function varargout = rap_music_parameters(varargin)
%RAP_MUSIC_PARAMETERS - Application M-file for rap_music_parameters.fig
% function varargout = rap_music_parameters(varargin)
%    FIG = RAP_MUSIC_PARAMETERS launch rap_music_parameters GUI.
%    RAP_MUSIC_PARAMETERS('callback_name', ...) invoke the named callback.

%<autobegin> ---------------------- 08-Jun-2004 15:12:54 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Inverse Modeling
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\bst_color_scheme.m
%   toolbox\bst_layout.m
%   toolbox\bst_message_window.m
%   toolbox\bst_static_taskbar.m
%   toolbox\dataplot_cb.m
%   toolbox\get_user_directory.m
%   toolbox\rapmusic_gui.m
%
% Subfunctions in this file, in order of occurrence in file:
%   load_parameters(hf,StudySubject,GUI); % called from parametric_estimation
%   varargout = pushbutton_execute_Callback(h, eventdata, handles, varargin)
%   varargout = PopupReg_Callback(h, eventdata, handles, varargin)
%   varargout = PopupReg_ButtonDownFcn(h, eventdata, handles, varargin)
%   varargout = EditReg_Callback(h, eventdata, handles, varargin)
%   varargout = CheckboxColumnNorm_Callback(h, eventdata, handles, varargin)
%   varargout = pushbutton_quit_Callback(h, eventdata, handles, varargin)
%   varargout = slider_threshold_Callback(h, eventdata, handles, varargin)
%   varargout = edit_threshold_Callback(h, eventdata, handles, varargin)
%   varargout = CurrentDipole_Callback(h, eventdata, handles, varargin)
%   varargout = popup_cd_headmodel_Callback(h, eventdata, handles, varargin)
%   varargout = CurrentDipole2_Callback(h, eventdata, handles, varargin)
%   varargout = popup_cd2_headmodel_Callback(h, eventdata, handles, varargin)
%   varargout = Multipole_Callback(h, eventdata, handles, varargin)
%   varargout = popup_cme_headmodel_Callback(h, eventdata, handles, varargin)
%   varargout = Multipole2_Callback(h, eventdata, handles, varargin)
%   varargout = popup_cme2_headmodel_Callback(h, eventdata, handles, varargin)
%   varargout = HeadModel_Directory_Callback(h, eventdata, handles, varargin)
%   varargout = pushbutton_help_Callback(h, eventdata, handles, varargin)
%   varargout = popup_cd_headmodel_ButtonDownFcn(h, eventdata, handles, varargin)
%   varargout = popup_cd2_headmodel_ButtonDownFcn(h, eventdata, handles, varargin)
%   varargout = popup_cme_headmodel_ButtonDownFcn(h, eventdata, handles, varargin)
%   varargout = popup_cme2_headmodel_ButtonDownFcn(h, eventdata, handles, varargin)
%   varargout = menu_quit_Callback(h, eventdata, handles, varargin)
%   varargout = menu_help_correlation_Callback(h, eventdata, handles, varargin)
%   varargout = Untitled_5_Callback(h, eventdata, handles, varargin)
%   varargout = checkbox_interactive_graphs_Callback(h, eventdata, handles, varargin)
%   varargout = checkbox_final_graphs_Callback(h, eventdata, handles, varargin)
%
% Application data and their calls in this file:
%   'GUI'
%   'HeadModelNames'
%   'HeadModelRefNames'
%   'StudySubject'
%   'TileType'
%   
%   setappdata(fig,'GUI',GUI);
%   setappdata(fig,'HeadModelNames',HeadModelNames);
%   setappdata(fig,'HeadModelRefNames',HeadModelRefNames);
%   setappdata(fig,'StudySubject',StudySubject);
%   setappdata(fig,'TileType','D');
%   
%   GUI = getappdata(fig,'GUI');
%   HeadModelRefNames = getappdata(fig,'HeadModelRefNames');
%   RESULTS = getappdata(fig,'RESULTS');
%   StudySubject = getappdata(fig,'StudySubject');
%   fname = getappdata(fig,'RESULTS');
%
% Figure Files opened by this function:
%   mfilename
%
%   Format of strings below: Type:Style:Tag, "String", CallBack Type and Call
%   <automatic> callback is <Tag>_Callback by Matlab default
%
% Callbacks by figure rap_music_parameters.fig
%   uicontrol:checkbox:checkbox_final_graphs "Final" uses Callback for <automatic>
%   uicontrol:checkbox:checkbox_interactive_graphs "Interactive" uses Callback for <automatic>
%   uicontrol:checkbox:CheckboxColumnNorm "Column Normalization" uses Callback for <automatic>
%   uicontrol:checkbox:CurrentDipole "Current Dipoles" uses Callback for <automatic>
%   uicontrol:checkbox:CurrentDipole2 "Synchronous Pairs of Dipoles" uses Callback for <automatic>
%   uicontrol:checkbox:Multipole "1st-order Multipoles" uses Callback for <automatic>
%   uicontrol:checkbox:Multipole2 "Synchronous Pairs of Multipoles" uses Callback for <automatic>
%   uicontrol:edit:edit_threshold "0.95" uses Callback for <automatic>
%   uicontrol:edit:EditReg "100" uses Callback for <automatic>
%   uicontrol:edit:HeadModel_Directory "Head Model Directory" uses Callback for <automatic>
%   uicontrol:popupmenu:popup_cd2_headmodel "Popup Menu" uses ButtonDownFcn for <automatic>
%   uicontrol:popupmenu:popup_cd2_headmodel "Popup Menu" uses Callback for <automatic>
%   uicontrol:popupmenu:popup_cd_headmodel "Popup Menu" uses ButtonDownFcn for <automatic>
%   uicontrol:popupmenu:popup_cd_headmodel "Popup Menu" uses Callback for <automatic>
%   uicontrol:popupmenu:popup_cme2_headmodel "Popup Menu" uses ButtonDownFcn for <automatic>
%   uicontrol:popupmenu:popup_cme2_headmodel "Popup Menu" uses Callback for <automatic>
%   uicontrol:popupmenu:popup_cme_headmodel "Popup Menu" uses ButtonDownFcn for <automatic>
%   uicontrol:popupmenu:popup_cme_headmodel "Popup Menu" uses Callback for <automatic>
%   uicontrol:popupmenu:PopupReg "Regularization . . ." uses ButtonDownFcn for <automatic>
%   uicontrol:popupmenu:PopupReg "Regularization . . ." uses Callback for <automatic>
%   uicontrol:pushbutton:pushbutton_execute "Execute" uses Callback for <automatic>
%   uicontrol:slider:slider_threshold "" uses Callback for <automatic>
%   uimenu::menu_help_correlation "" uses Callback for <automatic>
%   uimenu::menu_quit "" uses Callback for <automatic>
%   uimenu::Untitled_5 "" uses Callback for <automatic>
%
% At Check-in: $Author: Mosher $  $Revision: 29 $  $Date: 6/08/04 1:39p $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 28-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> ------------------------ 08-Jun-2004 15:12:54 -----------------------

% ---------------- change history --------------------
%
% JCM 31-Oct-2002  handled popup error when no headmodel exists
% SB  11-Jul-2003  make it fit as a layout tile and modified access to current data set 
%                  (do not use .CurrentData anymore)
% ---------------------------------------------------------

% Last Modified by GUIDE v2.0 17-Nov-2003 09:17:09

if nargin == 0  % LAUNCH GUI

	fig = openfig(mfilename,'new');

	% Generate a structure of handles to pass to callbacks, and store it. 
	handles = guihandles(fig);
	guidata(fig, handles);
    
	if nargout > 0
		varargout{1} = fig;
	end

   % custom creations begin here
   bst_color_scheme(fig); % apply standard colorings
   setappdata(fig,'TileType','D');
   bst_layout('align',fig)
   set(fig,'visible','on')
   
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK

	try
		if (nargout)
			[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
		else
			feval(varargin{:}); % FEVAL switchyard
		end
	catch
		disp(lasterr);
	end

end


% ----------------------- Local Functions ---------------------------
% ------------------ INITIALIZE THE GUI WITH RAP MUSIC PARAMETERS -------
function load_parameters(hf,StudySubject,GUI); % called from parametric_estimation

handles = guidata(hf); % get the handles for this figure
fig = handles.RAPMUSICparameters; % convenient figure handle

% copy in the sent data
setappdata(fig,'StudySubject',StudySubject);
setappdata(fig,'GUI',GUI);

User = get_user_directory; % where everything is stored

% The head models are stored with the data set
% what is the referential path for the head models
refpath = fileparts(GUI.StudySubject.Study);%User.CurrentData.DataFile); SB

% what is the full path name to the head models
fullpath = fileparts(fullfile(User.STUDIES,GUI.StudySubject.Study));%User.CurrentData.DataFile)); SB

% now get all of the headmodel filenames in that directory
HeadModelNames = dir(fullfile(fullpath,'*headmodelVolGrid*.mat')); 
% SB 20-Nov-2002 / Look only for scan grid headmodels.

if isempty(HeadModelNames) % No such headmodel available
    errordlg({'No volume scan grid headmodel available',...
            'Please compute one with the HeadModeling tool'...
        })
end

HeadModelNames = {HeadModelNames.name}; % convert to cell array of names
% now make all names also referential
HeadModelRefNames = HeadModelNames; % initialize
for i= 1:length(HeadModelRefNames),
   HeadModelRefNames{i} = fullfile(refpath,HeadModelNames{i});
end

% HeadModelNames will be good for display, HeadModelRefNames for load
setappdata(fig,'HeadModelNames',HeadModelNames); % store
setappdata(fig,'HeadModelRefNames',HeadModelRefNames); % store

% Now load the popups with the head model names
% SourceOrder -1 is for dipoles, SourceOrder 1 is for multipoles

SourceOrder = zeros(length(HeadModelRefNames),1); % for each head model
for i= 1:length(HeadModelRefNames),
   temp = load(fullfile(User.STUDIES,HeadModelRefNames{i}),'SourceOrder');
   SourceOrder(i) = temp.SourceOrder;
end

% setup the dipole and multipole popups
% First initialize the source model checkboxes

Tags = {'CurrentDipole'}; % unique tag identifiers
for i = 1:length(Tags),
   eval(sprintf('ht = handles.%s;',Tags{i}));
   set(ht,'Val',1); % set default on
end

Tags = {'CurrentDipole2','Multipole','Multipole2'}; % unique tag identifiers
for i = 1:length(Tags),
   eval(sprintf('ht = handles.%s;',Tags{i}));
   set(ht,'Val',0); % set default off
end

% now setup popups and checkboxes based on identified head models
% cd is current dipole, cme is current multipole, suffix 2 indicates synchronous pair
Tags = {'cd','cd2','cme','cme2'}; % unique tag identifiers
TagCheckBox = {'CurrentDipole','CurrentDipole2','Multipole','Multipole2'}; % checkboxes
TagOrder = [-1 -1 1 1]; % source order, one-to-one with Tags
for i = 1:length(Tags),
   % create temporary handle to the appropriate popup
   eval(sprintf('ht = handles.popup_%s_headmodel;',Tags{i}));
   eval(sprintf('hc = handles.%s;',TagCheckBox{i})); % corresponding checkbox
   tmpndx = find(SourceOrder == TagOrder(i)); % appropriate headmodel
   if(length(tmpndx)), % there are such head models built
      set(ht,'Val',1,'String',HeadModelNames(tmpndx),'enable','on');
      set(hc,'enable','on');
   else
      set(ht,'Val',1,'String','None','enable','off');
      set(hc,'Val',0,'enable','off'); % disable checkbox
   end
end

set(handles.HeadModel_Directory,'String',refpath); % information for user


% initialize the regularization models
% The Literal Strings are not important, but the ordering is
RegStrings = {'Regularization . . .','Truncated Condition','Truncated Energy',...
      'Tikhonov Condition','None'};
% initialze to Tikhonov Regularization
set(handles.PopupReg,'Val',4,'String',RegStrings);
set(handles.EditReg,'String','10'); % default regularization

% In MMII, we need each head model to have the source order put into
%  the Params structure, rather than the separater Order parameter of
%  BST 2000. As an interim, CHEAT by manually guessing this parameter
%  setting it into each head model, if it's not there.

if(0),% deprecated, head model tool now does
   for i= 1:length(HeadModelRefNames),
      FullName = fullfile(User.STUDIES,HeadModelRefNames{i});
      L = load(FullName,'Param');
      LName = fieldnames(L.Param);
      if(isempty(strmatch('Order',LName))), % Order is missing
         HeadModel = load(FullName); % load the whole thing
         DIM = size(HeadModel.Gain{1},2)/size(HeadModel.GridLoc{1},2);
         switch DIM
         case 1
            Order = -1; % constrained dipoles
         case 3
            Order = -1; % unconstrained dipoles
         case 12
            Order = 1; % unconstrained multipoles
         otherwise
            Order = input(sprintf('Dim is %.0f, what order is this: '));
         end
         for i = 1:length(HeadModel.Param),
            HeadModel.Param(i).Order = Order;
         end
         save_fieldnames(HeadModel,FullName); % save back
      end % if no order present
   end
end

% ---------------------  The Callbacks ------------------------------

% ----------- EXECUTE THE RAP MUSIC FUNCTION ------------------------
function varargout = pushbutton_execute_Callback(h, eventdata, handles, varargin)
% Execute RAP MUSIC by gathering the data and calling
% collect the data
fig = handles.RAPMUSICparameters; % convenient tag
bst_fig = bst_message_window; % get handle to the message window
arrow_fig = [fig;bst_fig]; % figures to show busy mouse

set(arrow_fig,'pointer','watch'); % busy mouse

StudySubject = getappdata(fig,'StudySubject');
GUI = getappdata(fig,'GUI');
User = get_user_directory;

refpath = get(handles.HeadModel_Directory,'String');
% refpath to add to the headmodel names

% now set the Orders to search by checking which flags are set
GUI.Order = []; % set to none first
GUI.OrderHeadModel = [];

% the order in which GUI.Order is loaded determines the order in
%  which the source models will be sequenced. Should look like
%  GUI from top to bottom.

if(get(handles.CurrentDipole,'Value')),
   GUI.Order = [GUI.Order -1]; % add the current dipole order
   TheseStr = get(handles.popup_cd_headmodel,'string');
   GUI.OrderHeadModel{end+1} = ...
      fullfile(refpath,TheseStr{get(handles.popup_cd_headmodel,'val')});
end
if(get(handles.Multipole,'Value')),
   GUI.Order = [GUI.Order 1]; % add the current multipole order
   TheseStr = get(handles.popup_cme_headmodel,'string');
   GUI.OrderHeadModel{end+1} = ...
      fullfile(refpath,TheseStr{get(handles.popup_cme_headmodel,'val')});
end
if(get(handles.CurrentDipole2,'Value')),
   GUI.Order = [GUI.Order 2]; % add the 2 synchronous current dipole order
   TheseStr = get(handles.popup_cd2_headmodel,'string');
   GUI.OrderHeadModel{end+1} = ...
      fullfile(refpath,TheseStr{get(handles.popup_cd2_headmodel,'val')});
end
if(get(handles.Multipole2,'Value')),
   GUI.Order = [GUI.Order 4]; % add the 2 synchronous multipole order
   TheseStr = get(handles.popup_cme2_headmodel,'string');
   GUI.OrderHeadModel{end+1} = ...
      fullfile(refpath,TheseStr{get(handles.popup_cme2_headmodel,'val')});
end
% Orders 0 and 3 are for magnetic dipole and pairs of mag dipoles


if(isempty(GUI.Order)), % user didn't check anything
   bst_message_window('You must select a starting model order');
   set(arrow_fig,'pointer','arrow'); % normal mouse
   return
end

GUI.Corr = get(handles.slider_threshold,'Value');

Val = get(handles.PopupReg,'Value'); % which regularization
switch Val
case 1
   bst_message_window('You must select a regularization technique');
   set(arrow_fig,'pointer','arrow'); % normal mouse
   return
case 2
   % truncated svd
   GUI.Condition = str2num(get(handles.EditReg,'String'));
   GUI.Energy = [];
   GUI.Tikhonov = [];
case 3
   % energy svd
   GUI.Condition = [];
   GUI.Energy = str2num(get(handles.EditReg,'String'));
   GUI.Tikhonov = [];
case 4
   % Tikhonov Condition normalization
   GUI.Condition = [];
   GUI.Energy = [];
   GUI.Tikhonov = str2num(get(handles.EditReg,'String'));
case 5
   % none
   GUI.Condition = [];
   GUI.Energy = [];
   GUI.Tikhonov = [];
end

GUI.Column_norm = get(handles.CheckboxColumnNorm,'Value'); % 0 is no, 1 is yes

% now hash together a results name
[PATH,NAME,EXT,VER] = fileparts(strrep(GUI.DataName,User.STUDIES,''));
c = clock;
NAME = strrep(NAME,'data','results'); % replace
newname = fullfile(PATH,[NAME sprintf('_%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('_%02.0f%02.0f',c(4),c(5)) EXT VER]);
end
GUI.Results = newname;

more off % let the text flow freely

%For displaying graphics
if get(handles.checkbox_interactive_graphs,'val'),
   GUI.DisplayGraphics = 1; % display during the analysis
else
   GUI.DisplayGraphics = 0; % don't
end

if get(handles.checkbox_final_graphs,'val'),
   % when done, launch the MRI tool to view the results
   GUI.FinalDisplayGraphics = 1;
else
   GUI.FinalDisplayGraphics = 0; % don't
end


[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

rapmusic_gui(StudySubject,GUI);

% Now update result file list in STATIC_TASKBAR and load last result file into Viewer if open
%[fname,ResultsPopDown] = bst_static_taskbar('GET','RESULTS');
fig = findobj(get(0,'children'),'flat','tag','static_taskbar'); 
fname = getappdata(fig,'RESULTS');
[tmp,h] = bst_static_taskbar('GET','RESULTS');
fname{end+1} = GUI.Results;
bst_static_taskbar('SET','RESULTS',fname);
set(h,'Value',length(fname))
bst_static_taskbar('popupmenu_RESULTS_Callback',h, [],guihandles(fig), []);

val = get(h,'val'); % where are we in the popup
RESULTS = getappdata(fig,'RESULTS');

global DATAPLOT
if ~ishandle(DATAPLOT) % Viewer is not active
    % Load last result file into viewer
    bst_message_window('wrap',...
        {'Loading new results into Viewer',' '});
    tmp = bst_static_taskbar('GET','RESULTS');
    Users = get_user_directory;
    if ~isempty(tmp)
        dataplot_cb('loadfile',tmp);
    end
end

set(arrow_fig,'pointer','arrow'); % normal mouse



% --------------------------------------------------------------------
function varargout = PopupReg_Callback(h, eventdata, handles, varargin)
% change the regularization technique and set a default parameter for each
Val = get(h,'Val');
switch Val
case 1
   % Calls for Regularization
   set(handles.EditReg,'String','','Tooltipstring',...
      'Variable parameter dependent on method');
case 2
   % Truncated Condition
   set(handles.EditReg,'String','10','Tooltipstring',...
      'Condition number');
case 3
   % Truncated Energy
   set(handles.EditReg,'String','0.98','Tooltipstring',...
      'Percentage energy');
case 4
   % Tikhonov Condition
   set(handles.EditReg,'String','10','Tooltipstring',...
      'Relative regularization level');
case 5
   % None
   set(handles.EditReg,'String','','Tooltipstring',...
      '');
end





% --------------------------------------------------------------------
function varargout = PopupReg_ButtonDownFcn(h, eventdata, handles, varargin)
% Give help on the regularization method
Val = get(h,'Val');
switch Val
case 1
   bst_message_window(' ');
   msg_str = ['Left-click to select a regularization method, then right ',...
         'click on the method for more help.'];
   bst_message_window('wrap',msg_str);
   
case 2
   msg_str = ['Truncate the SVD of the forward model at the smallest singular ',...
         'value which still yields the desired condition. Condition is the ',...
         'largest singular value divided by the smallest. Condition of 100 ',...
         'is good for quality SNR, 10 for poorer.'];
   bst_message_window(' ');
   bst_message_window('wrap',msg_str);
   
case 3
   msg_str = ['Square each singular value and sum, which equals the total ',...
         'sum square of all data in the matrix. Truncate the SVD at the ',...
         'singular value whos sum is at least the percentage desired. ',...
         'Select percentage based on plausible signal energy.'];
   bst_message_window(' ');
   bst_message_window('wrap',msg_str);
   
case 4
   msg_str = ['When the singular value is equal to the Tikhonov parameter, ',...
         'the contribution of that component is suppressed from the inverse ',...
         'by a factor of 1/2, the "knee." Smaller singular values are ',...
         'therefore progressively suppressed as compared to truncation. ',...
         'The parameter here sets the knee as a condition number relative ',...
         'to the first singular value, i.e. 100 means set the knee at the ',...
         '1/100th of the largest singular value.'];
   bst_message_window(' ');
   bst_message_window('wrap',msg_str);
   
case 5
   msg_str = ['No regularization will be applied, other than to truncate ',...
         'any forward model at the numeric rank of the matrix. In double ',...
         'precision, this truncation can be equivalent to a condition of',...
         'of about 1e16 and is extremely numerically sensitive. ',...
         'The use of "none" is recommended only for ',...
         'simulated noiseless data. Even in this case, it may be better ',...
         'to use a truncated condition of 1e8 rather than to be so dependent ',...
         'on double precision noise floors.'];
   bst_message_window(' ');
   bst_message_window('wrap',msg_str);
end




% --------------------------------------------------------------------
function varargout = EditReg_Callback(h, eventdata, handles, varargin)
% parameter, no callback



% --------------------------------------------------------------------
function varargout = CheckboxColumnNorm_Callback(h, eventdata, handles, varargin)
set(h,'val',0,'enable','off','tooltipstring','Disabled in this version');
bst_message_window('Column normalization turned off in this version');




% --------------------------------------------------------------------
function varargout = pushbutton_quit_Callback(h, eventdata, handles, varargin)
close(handles.RAPMUSICparameters)




% --------------------------------------------------------------------
function varargout = slider_threshold_Callback(h, eventdata, handles, varargin)
Val = get(h,'Val');
% sanity check
Val = max(0,Val);
Val = min(1,Val);
set(handles.edit_threshold,'String',sprintf('%01.2f',Val));




% --------------------------------------------------------------------
function varargout = edit_threshold_Callback(h, eventdata, handles, varargin)
Val = str2num(get(h,'String'));
if(~isempty(Val)),
   % sanity check
   Val = max(0,Val);
   Val = min(1,Val);
   set(handles.slider_threshold,'Val',Val);
else
   % invalid input by user
   Val = get(handles.slider_threshold,'Val'); % get the slider value
end

% set the formatted display of the string
set(handles.edit_threshold,'String',sprintf('%01.2f',Val));




% --------------------------------------------------------------------
function varargout = CurrentDipole_Callback(h, eventdata, handles, varargin)
% Checkbox




% --------------------------------------------------------------------
function varargout = popup_cd_headmodel_Callback(h, eventdata, handles, varargin)
% changed head model
% make sure corresponding box is checked
set(handles.CurrentDipole,'Val',1);




% --------------------------------------------------------------------
function varargout = CurrentDipole2_Callback(h, eventdata, handles, varargin)
% Checkbox




% --------------------------------------------------------------------
function varargout = popup_cd2_headmodel_Callback(h, eventdata, handles, varargin)
% changed head model
% make sure corresponding box is checked
set(handles.CurrentDipole2,'Val',1);




% --------------------------------------------------------------------
function varargout = Multipole_Callback(h, eventdata, handles, varargin)
% Checkbox




% --------------------------------------------------------------------
function varargout = popup_cme_headmodel_Callback(h, eventdata, handles, varargin)
% changed head model
% make sure corresponding box is checked
set(handles.Multipole,'Val',1);




% --------------------------------------------------------------------
function varargout = Multipole2_Callback(h, eventdata, handles, varargin)
% Checkbox




% --------------------------------------------------------------------
function varargout = popup_cme2_headmodel_Callback(h, eventdata, handles, varargin)
% changed head model
% make sure corresponding box is checked
set(handles.Multipole2,'Val',1);



% --------------------------------------------------------------------
function varargout = HeadModel_Directory_Callback(h, eventdata, handles, varargin)
% a inactive edit window, used as inactive for visual purposes


% --------------------------------------------------------------------
function varargout = pushbutton_help_Callback(h, eventdata, handles, varargin)

msg_str = ['DRAFT Help: Right click on each regularization method displayed to ',...
      'read more about each technique. Correlation threshold is . ',...
      'Regularization Methods are: .',...
      'Source Models are: .'];

bst_message_window('wrap',msg_str)




% ----------- Right Click operations on the head models ----------------
% --------------------------------------------------------------------
function varargout = popup_cd_headmodel_ButtonDownFcn(h, eventdata, handles, varargin)
% show user some stats about this particular head model
fig = handles.RAPMUSICparameters; % convenient handle
HeadModelRefNames = getappdata(fig,'HeadModelRefNames'); % referential names
User = get_user_directory;

refpath = get(handles.HeadModel_Directory,'String');
% refpath to add to the headmodel names

Val = get(h,'Val'); % which name is displayed
TheseStr = get(h,'String'); % strings in this popup

fname = fullfile(User.STUDIES,refpath,TheseStr{Val});
[FullPath,NameOnly] = fileparts(fname); % informational

% let's obtain the names and size of grid
L1 = load(fname,'HeadModelName','HeadModelType','GridName','GridLoc','SourceOrder');

SourceType = {'Current Dipole','Magnetic Dipole','Current Multipole'};

% display to the message window
bst_message_window({'',sprintf('Database: %s',FullPath),...
      sprintf('Filename: %s',NameOnly),...
      sprintf('Head Model: %s, Source Type: %s',...
      L1.HeadModelName,SourceType{L1.SourceOrder+2}),...
      sprintf('Type of Grid: %s',L1.HeadModelType),...
      sprintf('Name of Grid: %s',L1.GridName{1}),...
      sprintf('Size of Grid: %.0f locations',size(L1.GridLoc{1},2))});



% --------------------------------------------------------------------
function varargout = popup_cd2_headmodel_ButtonDownFcn(h, eventdata, handles, varargin)
% simply use cd version
popup_cd_headmodel_ButtonDownFcn(h, eventdata, handles, varargin);



% --------------------------------------------------------------------
function varargout = popup_cme_headmodel_ButtonDownFcn(h, eventdata, handles, varargin)
% simply use cd version
popup_cd_headmodel_ButtonDownFcn(h, eventdata, handles, varargin);



% --------------------------------------------------------------------
function varargout = popup_cme2_headmodel_ButtonDownFcn(h, eventdata, handles, varargin)
% simply use cd version
popup_cd_headmodel_ButtonDownFcn(h, eventdata, handles, varargin);






% --------------------------------------------------------------------
function varargout = menu_quit_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = menu_help_correlation_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = Untitled_5_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = checkbox_interactive_graphs_Callback(h, eventdata, handles, varargin)
% if on, wants interactive graphs during the run



% --------------------------------------------------------------------
function varargout = checkbox_final_graphs_Callback(h, eventdata, handles, varargin)
% if on, wants final display graphs
