function hf = minnorm_parameters_cb(action,GUI,hf);
%MINNORM_PARAMETERS_CB - Minimum Norm GUI setup and execution
% function hf = minnorm_parameters_cb(action,GUI,hf);
% function hf = minnorm_parameters_cb; % Build and return handle to figure
% function minnorm_parameters_cb(action); % switchyard
% function minnorm_parameters_cb(StudySubject,GUI,hf); % initialize
% Called with no action, it will build the GUI window using rap_parameters.fig
% action may be either a string or a StudySubject structure
% StudySubject must be a proper find_brainstorm_structure
% In the initialization, GUI must contain the fields
%  GUI.Segment, vector of column indices to process in the data matrix
%  GUI.Rank, the rank of the signal subspace to use
%  GUI.DataName, the referentially qualified filename of the data set
%  GUI.ChannelFlag, +1 for each channel to be used

%<autobegin> ---------------------- 26-May-2004 11:30:59 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Inverse Modeling
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\get_user_directory.m
%
% Figure Files opened by this function:
%   'minnorm_parameters.fig'
%
%   Format of strings below: Type:Style:Tag, "String", CallBack Type and Call
%   <automatic> callback is <Tag>_Callback by Matlab default
%
% Callbacks by figure minnorm_parameters.fig
%   figure::MinNorm Gui "" uses KeyPressFcn for dokeypress(gcbf)
%   figure::MinNorm Gui "" uses ResizeFcn for doresize(gcbf)
%   uicontrol:popupmenu:PopupReg "Regularization . . ." uses Callback for
%     minnorm_parameters_cb ('set reg');
%   uicontrol:pushbutton:ExecuteRAP "Execute" uses Callback for minnorm_parameters_cb('execute rap');
%   uicontrol:pushbutton:Pushbutton1 "Quit" uses Callback for delete(gcbf)
%   uimenu::                       "" uses Callback for
%     filemenufcn(gcbf,'FilePost')                                                    
%   uimenu::                       "" uses Callback for
%     figure                                                                          
%   uimenu::                       "" uses Callback for
%     filemenufcn(gcbf,'FileOpen')                                                    
%   uimenu::                       "" uses Callback for
%     close(gcbf)                                                                     
%   uimenu::                       "" uses Callback for
%     filemenufcn(gcbf,'FileExport')                                                  
%   uimenu::                       "" uses Callback for
%     propedit(gcbf)                                                                  
%   uimenu::                       "" uses Callback for
%     filemenufcn(gcbf,'FilePreferences')                                             
%   uimenu::                       "" uses Callback for
%     pagesetupdlg(gcbf)                                                              
%   uimenu::                       "" uses Callback for
%     filemenufcn(gcbf,'FilePrintSetup')                                              
%   uimenu::                       "" uses Callback for
%     printpreview(gcbf)                                                              
%   uimenu::                       "" uses Callback for
%     printdlg                                                                        
%   uimenu::                       "" uses Callback for
%     editmenufcn(gcbf,'EditCopyFigure')                                              
%   uimenu::                       "" uses Callback for
%     editmenufcn(gcbf,'EditCopyOptions')                                             
%   uimenu::                       "" uses Callback for
%     domymenu('menubar','toggletoolbar',gcbf)                                        
%   uimenu::                       "" uses Callback for
%     %<noop>                                                                         
%   uimenu::                       "" uses Callback for
%     domymenu menubar addaxes                                                        
%   uimenu::                       "" uses Callback for
%     domymenu menubar addarrow                                                       
%   uimenu::                       "" uses Callback for
%     domymenu menubar addline                                                        
%   uimenu::                       "" uses Callback for
%     domymenu menubar addtext                                                        
%   uimenu::                       "" uses Callback for
%     domymenu menubar zoomin                                                         
%   uimenu::                       "" uses Callback for
%     domymenu menubar zoomout                                                        
%   uimenu::                       "" uses Callback for
%     domymenu menubar rotate3d                                                       
%   uimenu::                       "" uses Callback for
%     winmenu(gcbo)                                                                   
%   uimenu::                       "" uses Callback for
%     %<noop>                                                                         
%   uimenu::                       "" uses Callback for
%     helpview([docroot '/mapfiles/plotedit.map'], 'plot_editor','PlotEditCollection')
%   uimenu::                       "" uses Callback for
%     web([docroot '/techdoc/umg/umg.html']);                                         
%   uimenu::                       "" uses Callback for
%     helpwin                                                                         
%   uimenu::                       "" uses Callback for
%     helpwin helpinfo                                                                
%   uimenu::                       "" uses Callback for
%     helpdesk                                                                        
%   uimenu::                       "" uses Callback for
%     demo                                                                            
%   uimenu::                       "" uses Callback for
%     uimenufcn(gcbf,'HelpAbout')                                                     
%   uimenu::                       "" uses Callback for
%     doc subscribe                                                                   
%   uimenu::figMenuEdit "" uses Callback for
%     editmenufcn(gcbf,'EditPost')                                                    
%   uimenu::figMenuEditClear "" uses Callback for
%     uimenufcn(gcbf,'EditClear')                                                     
%   uimenu::figMenuEditCopy "" uses Callback for
%     uimenufcn(gcbf,'EditCopy')                                                      
%   uimenu::figMenuEditCut "" uses Callback for
%     uimenufcn(gcbf,'EditCut')                                                       
%   uimenu::figMenuEditPaste "" uses Callback for
%     uimenufcn(gcbf,'EditPaste')                                                     
%   uimenu::figMenuEditSelectAll "" uses Callback for
%     uimenufcn(gcbf,'EditSelectAll')                                                 
%   uimenu::figMenuEditUndo "" uses Callback for
%     editmenufcn(gcbf,'EditUndo')                                                    
%   uimenu::figMenuFileSave "" uses Callback for
%     filemenufcn(gcbf,'FileSave')                                                    
%   uimenu::figMenuFileSaveAs "" uses Callback for
%     filemenufcn(gcbf,'FileSaveAs')                                                  
%   uimenu::figMenuTools "" uses Callback for
%     domymenu('menubar','updatetools',gcbf)                                          
%   uimenu::figMenuToolsAxesProps "" uses Callback for
%     domymenu menubar axesprop                                                       
%   uimenu::figMenuToolsLineProps "" uses Callback for
%     domymenu menubar lineprop                                                       
%   uimenu::figMenuToolsLockAxes "" uses Callback for
%     domymenu menubar lockaxes                                                       
%   uimenu::figMenuToolsPlotedit "" uses Callback for
%     plotedit(gcbf)                                                                  
%   uimenu::figMenuToolsShowLegend "" uses Callback for
%     domymenu menubar legend                                                         
%   uimenu::figMenuToolsTextProps "" uses Callback for
%     domymenu menubar textprop                                                       
%   uitoggletool::ScribeSelectToolBtn "" uses DeleteFcn for plotedit(gcbf,'off')
%
% At Check-in: $Author: Mosher $  $Revision: 13 $  $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:59 -----------------------

% ----------------------------- Script History ---------------------------------
% John C. Mosher, Ph.D.
% Sylvain Baillet, Ph.D.
% 19-May-2004 JCM Comments Cleaning
% ----------------------------- Script History ---------------------------------

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

if(~exist('action')),
   open('minnorm_parameters.fig');
   hf = gcf; %the new figure handle
   return   
end

if(isstruct(action)), % call is rap_parameters_cb(StudySubject,GUI)
   StudySubject = action;
   action = 'initialize';
else
   hf = gcbf; % the figure that called this
end

switch deblank(lower(action))
   
case 'initialize'
   Names = fieldnames(GUI); % what did the user provide
   temp = GUI; % will now overwrite
   GUI = struct('DataName',[],'Results',[],'Segment',[],'Order',[],'Rank',[],...
      'Corr',[],'ChannelFlag',[],'DisplayGraphics',[],'Tikhonov',[],'Column_norm',[]);
   for i = 1:length(Names),
      %map data in temp to data in GUI
      GUI = setfield(GUI,Names{i},getfield(temp,Names{i}));
   end
   % is there a slicker way to do this? JCM 2/17/00
   
   % so now I have the initial GUI parameters I need for RAP-MUSIC.
   % Map into the uicontrols
   
   ht = findobj(hf,'Tag','TextBrainStormStudy');
   set(ht,'String',StudySubject.Study);
   ht = findobj(hf,'Tag','TextBrainStormData');
   set(ht,'String',GUI.DataName);
   ht = findobj(hf,'Tag','TextBrainStormComment');
   set(ht,'String',sprintf('Rank: %.0f, From index %.0f to %.0f',...
      GUI.Rank,GUI.Segment(1),GUI.Segment(end)));
   
   User = get_user_directory;
   cd(User.STUDIES)

   HeadModel = load(StudySubject.HeadModel);
   ht = findobj(hf,'Tag','PopupImageGrid');
   set(ht,'String',HeadModel.ImageGridName); % available names
   set(ht,'Min',1,'Max',length(HeadModel.ImageGridName),'Value',1);
   
      
   % store in the window user data
   set(hf,'UserData',struct('StudySubject',StudySubject,'GUI',GUI));
   
   
case 'set textcorr'
   str = get(gcbo,'String');
   CORR = str2num(str);
   CORR = max(0,CORR);
   CORR = min(1,CORR);
   h = findobj(gcbf,'Tag','SliderCorr');
   set(h,'Value',CORR);
   
case 'set slidercorr'
   CORR = get(gcbo,'Value');
   h = findobj(gcbf,'Tag','EditCorr');
   set(h,'String',sprintf('%.2f',CORR));
   
case 'set reg'
   i = get(gcbo,'Value');
   ht = findobj(hf,'Tag','EditReg'); % the edit field
   switch i
   case 1
      set(ht,'String',' ')
      str = get(gcbo,'String');
      set(gcbo,'String','Select Method');
      pause(1)
      set(gcbo,'String',str)
   case 2
      % truncated SVD
      set(ht,'String','100')
   case 3
      % energy truncation
      set(ht,'String','.98')
   case 4
      % Tikhonov Condition
      set(ht,'String','100')
   case 5
      % none, do nothing
      set(ht,'String',' ')
   end
case 'execute rap'
   % collect up the stats
   UD = get(hf,'UserData');
   StudySubject = UD.StudySubject; %stored there
   GUI = UD.GUI;
   clear UD
   
   ht = findobj(hf,'Tag','PopupImageGrid');
   tmp = get(ht,'Value'); % which grid will we use
   strtmp = get(ht,'String');
   %GUI.iGrid = strmatch(lower(HeadModel.ImageGridName),lower(Comment));
   User = get_user_directory;
   cd(User.SUBJECTS)
   load(StudySubject.SubjectTess);
   GUI.iGrid = find(strcmp(lower(strtmp{tmp}),lower(Comment)));
   
   ht = findobj(hf,'Tag','PopupReg');
   hs = findobj(hf,'Tag','EditReg');
   i = get(ht,'Value');
   switch i
   case 1
      msgbox('You must select a regularization technique','Notice','modal');
      return
   case 2
      % truncated svd
      GUI.Condition = str2num(get(hs,'String'));
      GUI.Energy = [];
      GUI.Tikhonov = [];
   case 3
      % energy svd
      GUI.Condition = [];
      GUI.Energy = str2num(get(hs,'String'));
      GUI.Tikhonov = [];
   case 4
      % Tikhonov Condition normalization
      GUI.Condition = [];
      GUI.Energy = [];
      GUI.Tikhonov = str2num(get(hs,'String'));
   case 5
      % none
      GUI.Condition = [];
      GUI.Energy = [];
      GUI.Tikhonov = [];
   end
   
   hcn = findobj(hf,'Tag','CheckboxColumnNorm');
   GUI.Column_norm = get(hcn,'Value'); % 0 is no, 1 is yes
   
   % now hash together a results name
   [PATH,NAME,EXT,VER] = fileparts(GUI.DataName);
   c = clock;
   newname = fullfile(PATH,[NAME sprintf('_results_%02.0f%02.0f',c(4:5)) EXT VER]);
   i = 0;
   while(exist(newname,'file')),
      i = i+1; % subtract another minute
      c(5) = mod(c(5) - 1,60);
      newname = fullfile(PATH,[NAME sprintf('_results_%02.0f%02.0f',c(4),c(5)) EXT VER]);
   end
   GUI.Results = newname;
   
   more off % let the text flow freely
   
   %% CHEAT %% for displaying graphic
   GUI.DisplayGraphics = 1; % always display
   [PATH,NAME,EXT,VER] = fileparts(StudySubject.SubjectTess);
   
   TessRap = fullfile(PATH,[[NAME '_rap'] EXT VER]); % possible tesselation file
   if(exist(TessRap,'file')), % there is a reduce one for rap
      StudySubject.SubjectTess = TessRap; % map it in
   end
   
   minnorm_gui(StudySubject,GUI);
   
end

return
