function data_selector_cb(action,varargin);
%DATA_SELECTOR_CB - Callback function to setup and execute inverse techniques
% function data_selector_cb(action,varargin);
% Called with no action, it will build the GUI window using data_selector.fig
% Adds to the data structure the channel indexer called Selected_Channel
% In the UserData of AxisStudy are Data, StudySubject, and Channel
% 
% The key results of this gui are stored in the UserData of AxisStudy, a structure with
%  fields of StudySubject and the GUI structure of
% GUI = struct('DataName',Udata.Filename,'Segment',USV.Segment,'Rank',RANK,...
%   'ChannelFlag',Data.ChannelFlag);

%<autobegin> ---------------------- 26-May-2004 11:30:10 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: GUI and Related
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\bst_color_scheme.m
%   toolbox\bst_layout.m
%   toolbox\bst_static_taskbar.m
%   toolbox\data_selector_cb.m  NOTE: Routine calls itself explicitly
%   toolbox\get_user_directory.m
%   toolbox\good_channel.m
%   toolbox\least_squares_parameters_cb.m
%   toolbox\minnorm_parameters_cb.m
%   toolbox\norcol.m
%   toolbox\svd0.m
%
% Subfunctions in this file, in order of occurrence in file:
%   [StudySubject,GUI] = start_gui_structure(hf);
%
% Application data and their calls in this file:
%   'TileType'
%   
%   setappdata(DataSelectorFig,'TileType','T');
%   
%
% Figure Files opened by this function:
%   'data_selector.fig'
%   'dataplot.fig'
%
%   Format of strings below: Type:Style:Tag, "String", CallBack Type and Call
%   <automatic> callback is <Tag>_Callback by Matlab default
%
% Callbacks by figure data_selector.fig
%   axes::AxisNoiseSubspace "" uses ButtonDownFcn for data_selector_cb('set time')
%   axes::AxisSignalSubspace "" uses ButtonDownFcn for data_selector_cb('set time')
%   figure::Data Selector "" uses KeyPressFcn for dokeypress(gcbf)
%   figure::Data Selector "" uses ResizeFcn for doresize(gcbf)
%   uicontrol:edit:EditRank "0" uses Callback for data_selector_cb('set textrank')
%   uicontrol:popupmenu:PopupSVD "Log Y-Axis" uses Callback for data_selector_cb('plot svd')
%   uicontrol:pushbutton:OKpushbutton "Done" uses Callback for data_selector_cb Done
%   uicontrol:pushbutton:Qpushbutton "Close" uses Callback for close(gcbf)
%   uicontrol:slider:SliderRank "" uses Callback for data_selector_cb('set sliderrank')
%   uimenu::EEGData "" uses Callback for data_selector_cb('checkdata')
%   uimenu::Exit Window "" uses Callback for data_selector_cb('exit')
%   uimenu::LoadData "" uses Callback for data_selector_cb('load')
%   uimenu::MEGData "" uses Callback for data_selector_cb('checkdata')
%   uimenu::OtherData "" uses Callback for data_selector_cb('checkdata')
%   uimenu::Source EstimationLeast Square "" uses Callback for data_selector_cb('leastsquares')
%   uimenu::Source EstimationLinear Imaging "" uses Callback for data_selector_cb('minnorm')
%   uimenu::Source EstimationRAP-MUSIC "" uses Callback for data_selector_cb('rap-music')
%   uimenu::UimenuReset "" uses Callback for data_selector_cb('reset')
%
% Callbacks by figure dataplot.fig
%   figure::DATAPLOT "" uses DeleteFcn for clear global data
%   uicontrol:edit:current_time "0" uses Callback for dataplot_cb set_current_time
%   uicontrol:edit:step "''" uses Callback for dataplot_cb set_time_step
%   uicontrol:edit:time_max "" uses Callback for dataplot_cb set_time_max
%   uicontrol:edit:time_min "" uses Callback for dataplot_cb set_time_min
%   uicontrol:popupmenu:ChangeUnits "MKS" uses Callback for
%     dataplot_cb('ChangeUnits','reset'),dataplot_cb ChangeUnits
%   uicontrol:popupmenu:DataViewingDataType "Original Data" uses Callback for
%     dataplot_cb DataViewingDataType
%   uicontrol:popupmenu:DataViewingSpatialDisplay "<No Scalp Topography>" uses Callback for
%     dataplot_cb('DataViewingSpatialDisplay', 'reset'), dataplot_cb DataViewingSpatialDisplay
%   uicontrol:popupmenu:DataViewingTimeDisplay "<No Time Display>" uses Callback for
%     dataplot_cb DataViewingTimeDisplay
%   uicontrol:popupmenu:SourceEstimationMethod "-------- IMAGING " uses Callback for
%     dataplot_cb SourceImaging
%   uicontrol:popupmenu:SourceViewingSpatialDisplay "<No Spatial Topography>" uses Callback for
%     dataplot_cb SourceViewingSpatialDisplay
%   uicontrol:popupmenu:SourceViewingTimeDisplay "<No Time Display>" uses Callback for
%     dataplot_cb SourceViewingTimeDisplay
%   uicontrol:pushbutton:HPlot "Plot" uses Callback for dataplot_cb('Plot','Measures')
%   uicontrol:pushbutton:HPlotTimeSeries "Plot" uses Callback for dataplot_cb('Plot','RESULTS')
%   uicontrol:pushbutton:HSetDataViewing "Set" uses Callback for dataplot_cb SetDataViewing
%   uicontrol:pushbutton:HSetSourceViewing "Set" uses Callback for dataplot_cb SetSourceViewing
%   uicontrol:pushbutton:MSIndexSwitch "ms/index" uses Callback for dataplot_cb MSIndexSwitch
%   uicontrol:pushbutton:NoiseModel "Noise Model" uses Callback for dataplot_cb CallDataSelector
%   uicontrol:pushbutton:pushbutton6 "Save" uses Callback for dataplot_cb saveas
%   uicontrol:pushbutton:SourceModel "Source Model" uses Callback for
%     dummy_dynamic_viewer('pushbutton11_Callback',gcbo,[],guidata(gcbo))
%   uicontrol:slider:TimeSlider "" uses Callback for dataplot_cb mapping_slider
%
% At Check-in: $Author: Mosher $  $Revision: 18 $  $Date: 5/26/04 9:59a $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 24-May-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 26-May-2004 11:30:10 -----------------------

% See 'reset' for list of objects and actions
%
% /---Script Author--------------------------------------\
% | *** John C. Mosher, Ph.D.                            |
% |    Biophysics Group                                  |
% |    Los Alamos National Laboratory                    |
% |    Los Alamos, New Mexico, USA                       |
% |                                                      |
% | *** Sylvain Baillet, Ph.D.                           |
% | Cognitive Neuroscience & Brain Imaging Laboratory    |
% | CNRS UPR640 - LENA                                   | 
% | Hopital de la Salpetriere, Paris, France             |
% | sylvain.baillet@chups.jussieu.fr                     |
% \------------------------------------------------------/

% Date of creation: January 1999

% Script History--------------------------------------------------------------------------------------------------------------------
% JCM 11/4/99     updating .ChannelFlag convention
% JCM 2/15/00     massive rebuild from rapswitchyard function
% JCM 3/21/00     handling degenerate case of single time slice
% SB  8-Sep-2001  Major revamping of the I/O - Now sourceimaging (was bst_SourceImaging) has become the main generic GUI for inverse routines. 
% ..............  data_selector_cb is now used for RAP-MUSIC interfacing only 
% SB  10-May-2002 User.CurrentData.DataFile is now a referential file name
% SB  07-Aug-2202 Edited script history on bst_SourceImaging (no sourceimaging)
% SB  09-Jul-2002 Plugged it into new BST window layout and dialog with BST Viewer.
% JCM 19-May-2004 Comments cleaning
% ----------------------------------------------------------------------------------------------------------------------------------


linecolor = [.8 .8 .8]; % Line color for coordinates display

if(~exist('action')),
    DataSelectorFig = openfig('data_selector.fig','reuse');
    set(DataSelectorFig,'Visible','off');
    bst_color_scheme(DataSelectorFig)
    setappdata(DataSelectorFig,'TileType','T');
    bst_layout('align',DataSelectorFig,2,1,2);
    set(DataSelectorFig,'Visible','on')
    
    %drawnow
    %TASKBAR = findobj(0,'Tag','TASKBAR');
    Users = get_user_directory;
    %data_selector_cb('load',Users.CurrentData.StudyFile,Users.CurrentData.DataFile); % call the loading function for data
    % SB : call the data structure in memory
    data_selector_cb('load'); 
    return
end

action = deblank(lower(action)); % case insensitivity

hf = findobj('Tag','Data Selector'); % figure handle of data selector window
hf = hf(1); % only the first one found, others don't count
fighandles = guihandles(hf);

switch action
    % exit will close the window
    % reset will clear figures and return to a nominal baseline.
    %  if all else fails, close the window and try again
    % load will load a brainstorm file
    
case 'exit'
    close(hf); %close the calling window
    
case 'reset'
    % Reset all of the buttons to initial values, refresh the studies list
    % Objects:  AxisStudy, AxisSignal, AxisNoise, AxisSVD
    %  EditMinTime, EditMaxTime, EditRank, SliderRank, SliderCorr,
    %  PopupSVD
    
    % Set the menu action
    
    % make sure the menus are set appropriately
    % Load Data should execute the load routine
    % Source Estimation should have submenus for the various inverse techniques
    % Reset GUI should run this case
    % Exit should close the window
    
    
    % clear the strings, enable
    TAGS = {'EditRank'};
    for i = 1:length(TAGS),
        ht = findobj(hf,'Tag',TAGS{i});
        set(ht,'Enable','On','String',' ','Units','Normalized');
    end
    
    % set the initial value to zero on the sliders, enable
    TAGS = {'SliderRank'};
    for i = 1:length(TAGS),
        ht = findobj(hf,'Tag',TAGS{i});
        set(ht,'Enable','On','Value',0,'Units','Normalized');
    end
    
    % set the initial value of popups to one, enable
    TAGS = {'PopupSVD'};  
    for i = 1:length(TAGS),
        ht = findobj(hf,'Tag',TAGS{i});
        set(ht,'Enable','On','Value',1,'Units','Normalized');
    end
    
    % clear all of the axes
    TAGS = {'AxisSignalSubspace', 'AxisNoiseSubspace', 'AxisSVD'};
    for i = 1:length(TAGS),
        axes(findobj(hf,'Tag',TAGS{i}));
        cla reset
        % set tag back in
        set(gca,'Tag',TAGS{i},'Units','Normalized','Xcolor',linecolor,'Ycolor',linecolor);
        axis on
        grid off
        zoom on
    end
    
    % now set up custom actions for each important object. 
    % Should have been saved with the .fig,
    %  but caca pasa
    
    set(fighandles.SliderRank,'Value',0,'Min',0,'Max',1,'callback','data_selector_cb(''set sliderrank'')');
    set(fighandles.EditRank,'String','0','callback','data_selector_cb(''set textrank'')');

    ht = findobj(hf,'Tag','Source Estimation');
    set(ht,'Enable','off'); % can't do estimation without data
    % end of reset
    
case 'load'
    % load in a brainstorm data set
    % First get the StudySubject information from the brainstormstudy file.
    if (0) % deprecated code - SB 09-Jul-2003
        if nargin == 1 % Load files the old way 
            User = get_user_directory; % the default locations of files
            cd(User.STUDIES); % set to the studies tree
            [Filename,Pathname]= uigetfile('*brainstormstudy.mat','Select a BrainStorm Study'); 
            if(Filename == 0),
                % user selected nothing, do nothing
                return
            end
            Pathname = deblank((Pathname));
            % form a referential filename by removing the STUDIES prefix from pathname
            Filename = fullfile(strrep(Pathname,User.STUDIES,''),Filename);   
            
            % generate the StudySubject structure from this filename
            StudySubject = find_brainstorm_structure(Filename);
            
            % now have the user select one of the valide data names
            iData = menu('Select a data file from this study',StudySubject.Data);
            Dataname = StudySubject.Data{iData};
        else
            Filename = varargin{1};
            Dataname = varargin{2};
            
            [path,tmp] = fileparts(Filename);
            Dataname = fullfile(path,Dataname);
            
            % generate the StudySubject structure from this filename
            StudySubject = find_brainstorm_structure(Filename);
        end
        
    end

    if (0) % Deprecated code - SB
        Data = load_brainstorm_file(Dataname); % load the data structure
        Channel = load_brainstorm_file(StudySubject.Channel);
        Channel = Channel.Channel;
    end
    
    % Call data structure in memory from BST Viewer
    global data
    % Sanity checks ------------------------
    if length(data.F) > 1 % more than one data set selected
        errordlg('Please select only one data set for noise modelling.')
        return
    end
    
    [val,enable,h] = bst_static_taskbar('GET','MEG');
    MEG = ~isempty(data.SelectedChannels{1}) & val ;
    [val,enable,h] = bst_static_taskbar('GET','EEG');
    EEG = ~isempty(data.SelectedChannels{2}) & val;
    [val,enable,h] = bst_static_taskbar('GET','OTHER');
    Other= ~isempty(data.SelectedChannels{3}) & val;
    Test = [MEG,EEG,Other];
    Label = {'MEG','EEG','OTHER'};
    
    data.imod = find(Test);
    if length(data.imod) > 1 % More than one modality selected
        errordlg('Please select only either MEG or EEG for noise modelling.')
        return
    end
    % Sanity checks ----------DONE----------

    % Use Mosher Data structure: initialize and fill all fields
    Data.Time = data.TimePlot;
    Data.F = data.F{1};
    Channel = data.Channel;
    Data.ChannelFlag = data.ChannelFlag;
    
    % So now we have the Data and Channel structures.
    % Start by setting all ChannelFlags to zero, unless tagged as -1 (bad)
    
    ndx = find(Data.ChannelFlag >= 0);
    Data.ChannelFlag(ndx) = 1; % want all good channels
    
    %TBB: It seems there is a problem when original channel structure has EEG and MEG
    if 1  % deprecated code - SB
        GoodChannelMEG = good_channel(Channel,Data.ChannelFlag,'MEG');
        GoodChannelEEG = good_channel(Channel,Data.ChannelFlag,'EEG');
    end
    
    %GoodChannel = good_channel(Channel,Data.ChannelFlag,Label{data.imod});

    ht = findobj(hf,'Tag','MEGData');
    if data.imod == 1 %(~isempty(GoodChannelMEG)),
        % there is MEG data
        set(ht,'Checked','On');
    else
        set(ht,'Checked','Off'); % apparently there is no MEG data
    end
    ht = findobj(hf,'Tag','EEGData');
    if data.imod == 2 %(~isempty(GoodChannelEEG)),
        % there is EEG data
        set(ht,'Checked','On');
    else
        set(ht,'Checked','Off'); % apparently there is no EEG data
    end
    
    Data = setfield(Data,'Selected_Channel',[GoodChannelMEG GoodChannelEEG]);
    %Data = setfield(Data,'Selected_Channel',[GoodChannel]);
    
    hStudy = findobj(hf,'Tag','AxisStudy');
    guidata(hf,struct('Data',Data,'Channel',Channel));
    %set(hStudy,'UserData',struct('Data',Data,'Channel',Channel),...
        %'StudySubject',StudySubject,'Dataname',Dataname)); % save into the Study figure
    
    ht = findobj(hf,'Tag','Source Estimation');
    set(ht,'Enable','off'); % can't do estimation until decompose
    
    data_selector_cb('view')
    
case 'checkdata'
    status = get(gcbo,'checked');
    switch status
    case 'on'
        set(gcbo,'checked','off');
    case 'off'
        set(gcbo,'checked','on');
    end
    data_selector_cb('view') % go view it
    
case 'view'
    % based on the checkboxes set in the menu, view the available data sets
    %hStudy = findobj(hf,'Tag','AxisStudy');
    Udata = guidata(hf);%get(hStudy,'UserData');
    
    GoodChannel = []; %initially null
    TAGS = {'MEG','EEG','Other'}; % checked tags to process, must be valid Channel.Type
    
    %Udata.Data.ChannelFlag(56) = -1; %CHEAT - ICA
    
    
    for i = 1:length(TAGS)
        nextTag = [TAGS{i} 'Data']; % form valid tags used in the gui, e.g. MEGData
        hData = findobj(hf,'Tag',nextTag); % the menu item
        % get all good indices corresponding to this
        next_ndx = good_channel(Udata.Channel,Udata.Data.ChannelFlag,TAGS{i});
        switch get(hData,'Checked')
        case 'on' % user wants the data
            if(isempty(next_ndx)),
                % there isn't any
                set(hData,'Checked','off'); % turn back off
            else
                Udata.Data.ChannelFlag(next_ndx) = 1; % set all good channels for analysis
            end
            GoodChannel = [GoodChannel next_ndx]; % append the list
        case 'off' %user doesn't want the data
            Udata.Data.ChannelFlag(next_ndx) = 0; % set all channels to ignore
        end
    end
    % GoodChannel now contains the indices to all valid channels
    
    if (0) % Deprecated code - SB
        axes(hStudy);
        if(isempty(GoodChannel)),
            cla
        else
            plot(Udata.Data.Time*1000,Udata.Data.F(GoodChannel,:),...
                'ButtonDownFcn','data_selector_cb(''set time'')');
            
            set(findobj(hf,'Tag','DataName'),'String',Udata.Data.Comment);
            
            grid on
            
            V = axis;
            ht = findobj(hf,'Tag','EditMinTime');
            set(ht,'String',int2str(floor(V(1))));
            ht = findobj(hf,'Tag','EditMaxTime');
            set(ht,'String',int2str(ceil(V(2))));
        end
        
    else
        
        set(fighandles.AxisSignalSubspace,'Xlim',1000*[Udata.Data.Time(1),Udata.Data.Time(end)])
        set(fighandles.AxisNoiseSubspace,'Xlim',1000*[Udata.Data.Time(1),Udata.Data.Time(end)])
        
        
    end
        
    Udata.Data = setfield(Udata.Data,'Selected_Channel',GoodChannel);
    %     set(hStudy,'Tag','AxisStudy','UserData',Udata,...
    %         'ButtonDownFcn','data_selector_cb(''set time'')',...
    %         'Xcolor',linecolor,'Ycolor',linecolor); % reset these items, clear by 'plot'
    %     
    
    TAGS = {'AxisSignalSubspace', 'AxisNoiseSubspace', 'AxisSVD'};
    for i = 1:length(TAGS),
        ht = findobj(hf,'Tag',TAGS{i});
        axes(ht)
        cla
    end
    
    ht = findobj(hf,'Tag','Source Estimation');
    set(ht,'Enable','off'); % can't do estimation until decompose
    
    data_selector_cb('set time')
    
case 'set time'
    % called by buttondown in AxisStudy, sets the time labels to the values of the
    % axis, then executes a decomposition of the signal into the other windows
    
    
    set([fighandles.AxisSignalSubspace,fighandles.AxisNoiseSubspace],'ButtonDownFcn','data_selector_cb(''set time'')');
    
    if (0) % Deprecated code
        ha = findobj(hf,'Tag','AxisStudy');
        % redundant, but sometimes we lose the buttondown function
        set(ha,'ButtonDownFcn','data_selector_cb(''set time'')');
        axes(ha);
        V = axis; % present limits
        h = findobj(gcbf,'Tag','EditMinTime');
        set(h,'String',sprintf('%.1f',V(1)));
        h = findobj(gcbf,'Tag','EditMaxTime');
        set(h,'String',sprintf('%.1f',V(2)));
    end
    
    % now decompose the viewed data
    data_selector_cb('decompose');
    
case 'set mintime'
    % editable text
    str = get(gcbo,'String'); % what is entered
    ha = findobj(gcbf,'Tag','AxisStudy');
    axes(ha);
    V = axis; % current settings
    axis([str2num(str) V(2:end)]);  %set the new axis
    data_selector_cb('set time'); % check labels
    
case 'set maxtime'
    % editable text
    str = get(gcbo,'String'); % what is entered
    ha = findobj(gcbf,'Tag','AxisStudy');
    axes(ha);
    V = axis; % current settings
    axis([V(1) str2num(str) V(3:end)]);  %set the new axis
    data_selector_cb('set time'); % check labels
    
case 'decompose'
    % calculate svd and display. don't use gcbo
    hwait = waitbar(.5,'Decomposing selected data');
    drawnow
    hl = fighandles.PopupSVD;%findobj(hf,'Tag','PopupSVD');
    set(hl,'Value',1); % force a log state
    % retrieve the state
    iLogLin = get(hl,'Value'); % 1 is log, 2 is linear
    
    hr = fighandles.EditRank;%findobj(gcbf,'Tag','EditRank'); % rank setting
    hs = fighandles.SliderRank;%findobj(gcbf,'Tag','SliderRank');
    %hStudy = findobj(gcbf,'Tag','AxisStudy');
    % write the SVD of the data into AxisSignal
    hSubspace = fighandles.AxisSignalSubspace;%findobj(hf,'Tag','AxisSignalSubspace');
    hStudy = hSubspace;
    
    % generate data
    %axes(hStudy);
    axes(hSubspace)
    V = axis; % current limits
    UData = guidata(hf);%get(hStudy,'UserData');
    Data = UData.Data;
    F = Data.F;
    % get index to the good data
    GoodChannel = Data.Selected_Channel; %what user has selected
    Udata = guidata(hf);%get(hStudy,'UserData');
    TAGS = {'MEG','EEG','Other'}; % checked tags to process, must be valid Channel.Type
    next_ndx = [];
    for i = 1:length(TAGS)
        nextTag = [TAGS{i} 'Data']; % form valid tags used in the gui, e.g. MEGData
        hData = findobj(hf,'Tag',nextTag); % the menu item
        % get all good indices corresponding to this
        if strcmp(get(hData,'checked'),'on')
            next_ndx = [next_ndx,good_channel(Udata.Channel,Udata.Data.ChannelFlag,TAGS{i})];
        end
        
        
    end
    GoodChannel = next_ndx;
    
    F = F(GoodChannel,:);
    Time = Data.Time;
    mni = min(find(Time*1000 >= V(1))); % time index is in ms, set in display_data
    mxi = max(find(Time*1000 <= V(2)));
    F = F(:,mni:mxi);
    [U,S,V] = svd0(F); % economy SVD
    
    set(hSubspace,'UserData',struct('U',U,'S',S,'V',V,'Time',Time(mni:mxi),'Segment',[mni:mxi]),'Xcolor',linecolor,'Ycolor',linecolor);
    
    nS = length(S); % how many values
    if(nS > 1),
        S = diag(S);
    end  
    midS = [1:round(nS/3)]'; % third the data
    midS = midS + round(nS/2); % centered on the half
    if(length(midS) >= 2), % need two points to define a line
        eS = polyval(polyfit(midS,S(midS),1),[1:nS]'); % first order fit
    else
        % degenerate case, may be single time slice fitting
        eS = S(end)+zeros(nS,1); % set to last value
    end
    ndx = find(eS <= 0); % negative values
    if(~isempty(ndx)), % some values
        eS(ndx) = eS(ndx(1)-1); % set to smallest positive value
    end
    ha = fighandles.AxisSVD;%findobj(gcbf,'Tag','AxisSVD'); % where is the plot
    set(ha,'UserData',[S eS]); % set the userdata now
    % set the initial rank display to 10%
    RANK = max(floor(length(S)/10),1); % at least unity
    set(hr,'String',int2str(RANK)); % set the rank field
    MaxSlider = max(2,length(S)); % need a minimum of two
    set(hs,'Min',1,'Max',MaxSlider,'Value',RANK,'Enable','On',...
        'SliderStep',[1/MaxSlider max(.1,2/MaxSlider)]); % want unity steps
    
    axes(ha);
    plot([S eS],'*')
    switch iLogLin % which plot
    case 2 % linear
        set(gca,'yscale','linear');
    case 1 % log
        set(gca,'yscale','log')
    otherwise
        % what otherwise?
        msgbox(sprintf('Error in plotting SVD','Error','modal'))
        return
    end
    V = axis;
    hold on
    % plot the vertical bar between signal and noise subspace
    % plot works either case
    hplot = plot([RANK;RANK]+.5,V(3:4),'linewidth',2);
    set(hplot,'EraseMode','Xor');
    hold off
    zoom on
    set(hs,'UserData',hplot); % the plot handle to the line
    % reset these items
    set(ha,'Tag','AxisSVD','UserData',S,'Xcolor',linecolor,'Ycolor',linecolor); 
    he = findobj(gcbf,'Tag','ExecuteRAP');
    set(he,'Enable','On');
    
    %set(hStudy,'Tag','AxisStudy',...
        %'ButtonDownFcn','data_selector_cb(''set time'')'); % reset these items, clear by 'plot'
    
    waitbar(1,hwait); % update the waitbar
    drawnow
    
    % now recursively call to plot the signal and noise data
    data_selector_cb('plot signalnoise');
    drawnow
    close(hwait); % close the waitbar
    
    ht = findobj(hf,'Tag','Source Estimation');
    set(ht,'Enable','on'); % now can estimate
    
    
case 'plot signalnoise'
    
    global data % Useful to pick up line color properties defined in Viewer
    hr = fighandles.SliderRank;%findobj(hf,'Tag','SliderRank');
    RANK = get(hr,'Value'); % what is the rank
    hs = fighandles.AxisSignalSubspace;%findobj(hf,'Tag','AxisSignalSubspace');
    hn = fighandles.AxisNoiseSubspace;%findobj(hf,'Tag','AxisNoiseSubspace');
    set(hs,'Xcolor',linecolor,'Ycolor',linecolor)
    set(hn,'Xcolor',linecolor,'Ycolor',linecolor)
    
    USV = get(hs,'UserData'); % get the svd from AxisSignal
    %hStudy = findobj(hf,'Tag','AxisStudy');
    %set(hStudy,'Xcolor',linecolor,'Ycolor',linecolor)
    
    %axes(hs)
    
    axes(hs)
    cla
    % Plot in milliseconds & Compute Noise & Signal Power relative to Data
    SIGNAL = [USV.U(:,1:RANK)*(USV.S(1:RANK,1:RANK)*USV.V(:,1:RANK)')]';
    SIGpower = 100*norcol(SIGNAL)/norcol([USV.U*(USV.S*USV.V')]');
    
    set(hs,'fontunits','points')
    plot(USV.Time*1000, SIGNAL,'color',data.LineColor{1});
    clear SIGNAL
    %axis(V); 
    axis tight
    set(hs,'Tag','AxisSignalSubspace','UserData',USV,'Xcolor',linecolor,'Ycolor',linecolor,...
        'fontunits','point','fontsize',9,'Xtick',[])
    fighandles.AxisSignalSubspace = hs;
    
    % plot in milliseconds
    V = axis; % what is the current setting
    % the calculation of the two data sets could be more optimally 
    %  done using .* or sparse matrices. Just dumb multiplication here for now.
    
    axes(hn)
    cla
    set(hn,'fontunits','points')
    plot(USV.Time*1000, [USV.U(:,(RANK+1):end)*(USV.S((RANK+1):end,(RANK+1):end)*USV.V(:,(RANK+1):end)')]','color',data.LineColor{1});
    axis(V);
    set(hn,'Tag','AxisNoiseSubspace','Xcolor',linecolor,'Ycolor',linecolor,'fontunits','point','fontsize',9)
    fighandles.AxisNoiseSubspace = hn;
    
    set(fighandles.NoisePower,'String',num2str(100-SIGpower,'%6.2f %%'))
    set(fighandles.tSignalPower,'String',num2str(SIGpower,'%6.2f %%'))
    set([fighandles.AxisSignalSubspace,fighandles.AxisNoiseSubspace],'ButtonDownFcn','data_selector_cb(''set time'')');
    
case 'set textrank'
    str = get(gcbo,'String');
    RANK = floor(str2num(str));
    RANK = max(1,RANK); % at least rank one
    h = findobj(gcbf,'Tag','SliderRank');
    hplot = get(h,'UserData'); % the plot handle to the rank plot
    mx = get(h,'Max'); % max value
    RANK = min(mx,RANK); % can't exceed
    RANK = max(1,RANK); % can't be less than unity
    set(gcbo,'String',num2str(RANK));
    set(h,'Value',RANK);
    set(hplot,'Xdata',[1 1]*(RANK+.5)); % shift plot line
    data_selector_cb('plot signalnoise')
    
case 'set sliderrank'
    RANK = round(get(gcbo,'Value'));
    RANK = max(1,RANK); % at least rank one
    set(gcbo,'Value',RANK); % round off
    h = findobj(gcbf,'Tag','EditRank');
    set(h,'String',num2str(RANK));
    hplot = get(gcbo,'UserData'); % the plot handle to the rank plot
    set(hplot,'Xdata',[1 1]*(RANK+.5)); % shift plot line
    data_selector_cb('plot signalnoise')
    
case 'plot svd'
    ht = findobj(hf,'Tag','AxisSVD');
    switch get(gcbo,'Value')
    case 1
        set(ht,'Yscale','log');
    case 2
        set(ht,'Yscale','linear');
    end

case 'rap-music'
    % need to load its UserData with a structure containing the StudySubject
    %  and initial GUI.DataName, GUI.Segment, GUI.Rank are set
    
    [StudySubject,GUI] = start_gui_structure(hf); %local function call
    
    % call the rap music input parameters screen
    hf = rap_parameters_cb; %setup and get figure number
    
    rap_parameters_cb(StudySubject,GUI,hf); %set up the popup
    
    % user continues with the inverse operation at the new gui
case 'minnorm'
    % need to load its UserData with a structure containing the StudySubject
    %  and initial GUI.DataName, GUI.Segment, GUI.Rank are set
    
    [StudySubject,GUI] = start_gui_structure(hf); %local function call
    
    % call the input parameters screen
    hf = minnorm_parameters_cb; %setup and get figure number
    
    minnorm_parameters_cb(StudySubject,GUI,hf); %set up the popup
    
    % user continues with the inverse operation at the new gui   
case 'leastsquares'
    % need to load its UserData with a structure containing the StudySubject
    %  and initial GUI.DataName, GUI.Segment, GUI.Rank are set
    
    [StudySubject,GUI] = start_gui_structure(hf); %local function call
    
    % call the rap music input parameters screen
    hf = least_squares_parameters_cb; %setup and get figure number
    
    least_squares_parameters_cb(StudySubject,GUI,hf); %set up the popup
    
    % user continues with the inverse operation at the new gui

case 'done' % Send noise model paramters to Viewer prior to source localization

    global data
    [StudySubject,data.NoiseModelParam] = start_gui_structure(hf); %local function call
    DATAPLOT = openfig('dataplot.fig','reuse');
    if isempty(DATAPLOT), return, end
    
    DPhandles = guihandles(DATAPLOT);
    set(DPhandles.NoiseModelTag,'string','set')
        
    close(gcbf)
        
    
end % case switch of actions

return


function [StudySubject,GUI] = start_gui_structure(hf);
% begin the basic GUI parameter structure from this figure hf

%ht = findobj(hf,'Tag','AxisStudy'); % the main data plot
Udata = guidata(hf);%get(ht,'UserData'); %get the data there
ht = findobj(hf,'Tag','AxisSignalSubspace');
USV = get(ht,'UserData'); % want the segment information

ht = findobj(gcbf,'Tag','EditRank');
str = get(ht,'String');
RANK = floor(str2num(str));

global data
GUI = struct('DataName',data.FileName,'Segment',USV.Segment,'Rank',RANK,...
    'ChannelFlag',Udata.Data.ChannelFlag);
StudySubject = [];%Udata.StudySubject; - SB

return
