function[AnaFileMat]=Eeg2Spm(action,FileMat)
%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Markus Junghöfer & Peter Peyk. All Rights Reserved.                     
%                                                                                          
%   THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE        
%   NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO,    
%   WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE    
%   OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
%   TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT,       
%   INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE      
%   OR DOCUMENTATION.                                                                      

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<2; FileMat=[]; end
if nargin<1; action='InitializeMenu'; end

%================= global variables =============================================
global hEeg2SpmMenuFig AnaPathMat

if strcmp(action,'InitializeMenu'),
    
    %============================================================================
    %=========== INITIALIZE MENU ================================================
    %============================================================================
    
    %============== figure with graphs =========================		
    if strcmp(computer,'MAC2')	
        MenuFigPosVec=[.8 0 .2 1];
    elseif strcmp(computer,'PCWIN') 
        MenuFigPosVec=[.78 .05 .2 .82];
    elseif strcmp(computer,'SOL2')
        MenuFigPosVec=[.8 .01 .2 .91];		
    end
    
    %============== figure with menu ===========================		
    Eeg2SpmMenuFigString=['Eeg2Spm Menu:'];
    hEeg2SpmMenuFig=figure('Units','normal','Position',MenuFigPosVec,'Name',Eeg2SpmMenuFigString,'Color',[.99 .99 .99],'NumberTitle','off');
    
    % Information for all buttons (and menus)
    labelColor=[0.8 0.8 0.8];
    yInitPos=0.90;
    menutop=0.955;
    btnTop = 0.6;
    top=0.75;
    left=0.125;
    btnWid=0.8;
    btnHt=0.04;
    btnHt_edit=0.050;
    textWidth = 0.06;
    %Spacing between the button and the next command's label
    spacing=0.015;
    
    %====================================
    % The CONSOLE frame
    frmBorder=0.05; 
    frmLeft=left-frmBorder;
    frmBottom=0.010; 
    frmHeight = 1-3.*frmBottom; 
    frmWidth = btnWid+2*frmBorder;
    yPos=frmBottom-frmBorder;
    frmPos=[frmLeft frmBottom frmWidth frmHeight];
    ConsoleRGBColor=[0.4 0.25 0];
    hConsolFrame=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',frmPos, ...
        'BackgroundColor',ConsoleRGBColor);
    
    
    %==============================================================
    % OpenAppFiles (AppSCADS-Session-Format)==============================
    %==============================================================
    btnNumber=1;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
    callbackStr = 'Eeg2Spm(''OpenAppFiles'')';
    hOpenAppFilesMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Open App File(s) ', ...
        'Userdata',[], ...
        'Callback',callbackStr,...
        'Enable','on');
    if ~isempty(FileMat)
        set(hOpenAppFilesMenu,'Userdata',FileMat);
    end
    %==============================================================
    % Set Result Path =============================================
    % callback: SetResultPath =====================================
    %==============================================================
    btnNumber=1;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    callbackStr = 'Eeg2Spm(''SetResultPath'')';
    hSetResultPath=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Create Result Path', ...
        'Userdata',[], ...
        'Value',2,...
        'Callback',callbackStr,...
        'Enable','on');
    
    %======================================================
    % Run Eeg2Spm Analysis ======================================
    % callback: RunEeg2Spm ========================================
    %======================================================
    btnNumber=2;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
    callbackStr = 'Eeg2Spm(''RunEeg2Spm'')';
    hRunEeg2SpmMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Run Eeg2Spm', ...
        'Userdata',[], ...
        'Callback',callbackStr,...
        'Enable','off');
    if ~isempty(FileMat)
        set(hRunEeg2SpmMenu,'Enable','on');
    end
    
    %=====================================================
    % ReadIntMat =========================================
    % callback: ReadIntMat ===============================
    %=====================================================
    btnNumber=2;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    callbackStr = 'Eeg2Spm(''ReadIntMat'')';
    hReadIntMatMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Read IntMat', ...
        'Value',0, ...
        'Userdata',[], ...
        'Callback',callbackStr,...
        'Enable','on');
    
    %======================================================
    % Launch SpmBatch Analysis ============================
    % callback: LaunchSpmBatch ============================
    %======================================================
    btnNumber=3;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 btnWid btnHt./2];
    callbackStr = 'Eeg2Spm(''LaunchSpmBatch'')';
    hLaunchSpmBatchMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Launch BatfMEEG', ...
        'Value',1, ...
        'Userdata',[], ...
        'Callback',callbackStr,...
        'Enable','on');
    
    %===================================
    % BatfMEEGMoldelHandel
    %===================================
    btnNumber=3;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit btnWid./2 btnHt_edit./2];
    
    hBatfMEEGMoldelText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','BatfMEEG Model:',...
        'Enable','on');
    
    btnPos=[left+btnWid./2 yPos-btnHt_edit btnWid./2 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetBatfMEEGMoldel'')';
    
    labelStr='Fixed|One Sample|Paired|FaceCond|ValAro';
    hBatfMEEGMoldelMenu = uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String',labelStr, ...
        'Value',3, ...
        'callback',callbackStr,...
        'Enable','on');
    
    %===================================
    % MinPointHandle
    %===================================
    btnNumber=4;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 btnWid./2 btnHt_edit./2];
    
    hMinPointText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Minimum Point []',...
        'Enable','on');
    
    btnPos=[left+btnWid./2 yPos-btnHt_edit./2 btnWid./2 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetMinPoint'')';
    
    hMinPointMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',1, ...
        'callback',callbackStr,...
        'Enable','on');
    
    %===================================
    % MaxPointHandle
    %===================================
    btnNumber=4;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit btnWid./2 btnHt_edit./2];
    
    hMaxPointText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Maximum Point []',...
        'Enable','on');
    
    btnPos=[left+btnWid./2 yPos-btnHt_edit btnWid./2 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetMaxPoint'')';
    
    hMaxPointMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'callback',callbackStr,...
        'Enable','on');
    
    %====================================
    % CalcDistPoint text edit button=====
    % callback: setDistPoint ============
    %====================================
    % DistPoint text
    btnNumber=5;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 btnWid./2 btnHt_edit./2];
    
    hDistPointText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Delta Points []');
    
    % DistPoint menu
    btnPos=[left+btnWid./2 yPos-btnHt_edit./2 btnWid./2 1.*btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetDistPoint'')';
    DistPointVec=[0 0 0 0];
    
    hDistPointMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0',...
        'Userdata',DistPointVec, ...
        'callback',callbackStr);
    
    %====================================
    % NDistInt text edit button=====
    % callback: setNDistInt ============
    %====================================
    % NDistInt text
    btnNumber=5;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit btnWid./2 btnHt_edit./2];
    
    hNDistIntText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Number of Intervals');
    
    % NDistInt menu
    btnPos=[left+btnWid./2 yPos-btnHt_edit btnWid./2 1.*btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetNDistInt'')';
    
    hNDistIntMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','1','Value',1, ...
        'callback',callbackStr);
    
    %====================================
    % CalcDistPointMean radio button=====
    % callback: setCalcDistPointMean ====
    %====================================
    btnNumber=6;  
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt/2 btnWid/4 btnHt/2];
    callbackStr='Eeg2Spm(''SetCalcDistPointMean'')';
    
    hCalcDistPointMeanMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Mean', ...
        'Value',1,...
        'Callback',callbackStr);
    
    %====================================
    % CalcDistPointMNMean radio button=====
    % callback: setCalcDistPointMNMean ====
    %====================================
    btnNumber=6;  
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./4 yPos-btnHt/2 btnWid./3 btnHt./2];
    callbackStr='Eeg2Spm(''setCalcDistPointMNMean'')';
    
    hCalcDistPointMNMeanMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','MN Mean', ...
        'Userdata',1,...
        'Value',1,...
        'Callback',callbackStr);
    
    %====================================
    % SetTotalIntPoint pushbutton=====
    % callback: SetTotalIntPoint ====
    %====================================
    btnNumber=6;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+.58*btnWid yPos-btnHt/2 .42.*btnWid btnHt./2];
    callbackStr='Eeg2Spm(''SetTotalIntPoint'')';
    
    hTotalIntMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Total Interval', ...
        'Value',0,...
        'Callback',callbackStr,...
        'Enable','on');
    
    %===================================
    % MinBaseHandle
    %===================================
    btnNumber=7;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos 2.*btnWid./3 btnHt_edit./2];
    
    hMinBaseText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Minimum Baseline []',...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetMinBase'')';
    
    hMinBaseMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'callback',callbackStr,...
        'Enable','on');
    
    %===================================
    % MaxBaseHandle
    %===================================
    btnNumber=7;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
    hMaxBaseText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Maximum Baseline []',...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetMaxBase'')';
    
    hMaxBaseMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'callback',callbackStr,...
        'Enable','on');
    
    %====================================
    % CalcBase radio button=====
    % callback: SetCalcBase ====
    %====================================
    btnNumber=8;  
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid/2 btnHt/2];
    callbackStr='Eeg2Spm(''SetCalcBase'')';
    
    hSetCalcBaseMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Calc. Baseline', ...
        'Value',0,...
        'Enable','off',...
        'Callback',callbackStr);
    
    %====================================
    % SetTotalIntBase pushbutton=====
    % callback: setTotalIntBase ====
    %====================================
    btnNumber=8;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid/2 yPos btnWid/2 btnHt/2];
    callbackStr='Eeg2Spm(''SetTotalIntBase'')';
    
    hTotalIntBaseMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Total Interval', ...
        'Value',0,...
        'Callback',callbackStr,...
        'Enable','on');
    
    %===================================
    % SmoothFWHMmmHandle
    %===================================
    btnNumber=9;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos 2.*btnWid./3 btnHt_edit./2];
    
    hSmoothFWHMmmText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Smoothing FWHM [mm]',...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetSmoothFWHMmm'')';
    
    hSmoothFWHMmmMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','16','Value',16, ...
        'callback',callbackStr,...
        'Enable','on');
    
    %====================================
    % SetSmoothStatus pushbutton=====
    % callback: SetSmoothStatus ====
    %====================================
    btnNumber=9;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 btnWid/2 btnHt/2];
    callbackStr='Eeg2Spm(''SetSmoothStatus'')';
    
    hSetSmoothStatus=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Smooth', ...
        'Value',1,...
        'Callback',callbackStr,...
        'Enable','on');
    
    %====================================
    % SetDelUnsmoothStatus pushbutton=====
    % callback: SetDelUnsmoothStatus ====
    %====================================
    btnNumber=9;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid/3 yPos-btnHt_edit./2 2*btnWid/3 btnHt/2];
    labelStr='Do not delete any|Delete all|Delete unsmoothed only';
    callbackStr='Eeg2Spm(''SetDeleteFileStatus'')';
    
    hSetDeleteFileStatus=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Value',3,...
        'Callback',callbackStr,...
        'Enable','on');
   
    %===================================
    % LambdaHandle
    %===================================
    btnNumber=10;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos 2.*btnWid./3 btnHt_edit./2];
    
    hLambdaText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Lambda Approx. []',...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetLambda'')';
    
    hLambdaMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0.02','Value',0.02, ...
        'callback',callbackStr,...
        'Enable','on');
    
    %=================================================
    % SetNTrials (edit text)==================================
    % callback: SetNTrials ===================================
    %==================================================
    btnNumber=11;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos 2.*btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetFixNTrialsStatus'')';
     
    hSetFixNTrialsStatus = uicontrol( ...
        'Style','radio', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Fix Number of Trials:',...
        'Value',0, ...
        'callback',callbackStr,...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetFixNTrials'')';
    
    hSetFixNTrials = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'callback',callbackStr,...
        'Enable','on');
    
    %=================================================
    % SetNTrials (edit text)==================================
    % callback: SetNTrials ===================================
    %==================================================
    btnNumber=11;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
    hSetNTrialsText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Number of Trials:',...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetNTrials'')';
    
    hSetNTrialsMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'Callback',callbackStr,...
        'Enable','off');
    
    
    %=================================================
    % SetNChan (edit text)==================================
    % callback: SetNChan ===================================
    %==================================================
    btnNumber=12;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos 2.*btnWid./3 btnHt_edit./2];
    
    hSetNChanText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Number of Sensors:',...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetNChan")';
    
    hSetNChanMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'Callback',callbackStr,...
        'Enable','off');
    
    %=================================================
    % SetNChanExtra (edit text)=============================
    % callback: SetNChan =================================
    %==================================================
    btnNumber=12;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
    hSetNChanExtraText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Number of Ext. Sensors:',...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetNChanExtra")';
    
    hSetNChanExtraMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'Callback',callbackStr,...
        'Enable','off');
    
    %=================================================
    % SetNPoints (edit text)==================================
    % callback: SetNPoints ===================================
    %==================================================
    btnNumber=13;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos 2.*btnWid./3 btnHt_edit./2];
    
    hSetNPointsText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Number of Points:',...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetNPoints'')';
    
    hSetNPointsMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'Callback',callbackStr,...
        'Enable','off');
    
    
    %=================================================
    % SetSampRate (edit text)================================
    % callback: SetSampRate ================================
    %==================================================
    btnNumber=13;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
    hSetSampRateText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Sampling Rate [Hz]:',...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetSampRate'')';
    
    hSetSampRateMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'Callback',callbackStr,...
        'Enable','off');
    
    
    %=================================================
    % SetMaxExp10 (edit text)==================================
    % callback: SetMaxExp10 ===================================
    %==================================================
    btnNumber=13;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
    hSetMaxExp10Text = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Count String Zeros:',...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
    callbackStr = 'Eeg2Spm(''SetMaxExp10'')';
    
    hSetMaxExp10Menu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'Callback',callbackStr,...
        'Enable','off');
    
    %=======================================================
    % callback: SetEegMegStatus ============================
    %=======================================================
    btnNumber=14;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
    callbackStr = 'Eeg2Spm(''SetEegMegStatus'')';
    hSetEegMegStatus=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','EEG', ...
        'Value',1, ...
        'Callback',callbackStr,...
        'Enable','on');
    
    %====================================
    %===================================
    % Close All Figures push button 
    btnNumber=14;
   	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    callbackStr = 'Eeg2Spm(''CloseAllFigures'')';
    hCloseAllFigures=uicontrol( ...
    'Style','pushbutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','Close All', ...
    'Userdata','0', ...
    'Callback',callbackStr,...
    'Enable','on');

    %=======================================================
    %=======================================================
    %=======================================================
    btnNumber=15;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelPos=[left yPos-btnHt_edit./2 btnWid btnHt_edit./2];
    h = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','=== Avg. & Diff. Eeg2Spm Menu ===', ...
        'Interruptible','off', ...
        'Background',ConsoleRGBColor, ...
        'Foreground','black');
    
    %=======================================================
    % OpenAnaFiles ==========================================
    %========================================================
    
    btnNumber=16;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
    callbackStr = 'Eeg2Spm(''OpenAnaFiles'')';
    hOpenAnaFilesMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Open Ana File(s) ', ...
        'Userdata',[], ...
        'Callback',callbackStr,...
        'Enable','on');
    
    %==============================================================
    % AverageAnaFiles ===================================
    %==============================================================
    btnNumber=17;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
    callbackStr = 'Eeg2Spm(''AvgAnaFiles'')';
    hAvgAnaFilesMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Avg. Ana. Files', ...
        'Userdata',[], ...
        'Callback',callbackStr,...
        'Enable','off');
    
    %==============================================================
    %DifferenceAnaFiles ==============================
    %==============================================================
    btnNumber=17;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    callbackStr = 'Eeg2Spm(''DiffAnaFiles'')';
    hDiffAnaFilesMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Diff. Ana Files', ...
        'Userdata',[], ...
        'Callback',callbackStr,...
        'Enable','off');
    
    
    %=======================================================
    %=======================================================
    hAwaMat=uicontrol('Visible','off');
    hEeg2SpmMat=uicontrol('Visible','off');
    %=======================================================
    %=======================================================
    
    NonUse=0;
    hList=[hOpenAppFilesMenu hSetResultPath hRunEeg2SpmMenu hMinPointText hMinPointMenu ...		                    %5
        hMaxPointText hMaxPointMenu hDistPointText hDistPointMenu hNDistIntText ...					                %10
        hNDistIntMenu hMinBaseText hMinBaseMenu hMaxBaseText hMaxBaseMenu ...						                %15
        hSetCalcBaseMenu hTotalIntBaseMenu hLambdaText hLambdaMenu NonUse ...					                    %20
        hCalcDistPointMeanMenu hCalcDistPointMNMeanMenu hAvgAnaFilesMenu hDiffAnaFilesMenu hEeg2SpmMat ...			%25
        hSetNChanText hSetNChanMenu hSetNPointsText hSetNPointsMenu hSetNTrialsText ...				                %30
        hSetNTrialsMenu hSetSampRateText hSetSampRateMenu hSetMaxExp10Text hSetMaxExp10Menu ...		                %35
        hSmoothFWHMmmText hSmoothFWHMmmMenu hSetSmoothStatus hSetDeleteFileStatus NonUse ...					    %40
        hLaunchSpmBatchMenu hReadIntMatMenu hSetFixNTrialsStatus hSetFixNTrials NonUse ...							%45
        hSetNChanExtraText hSetNChanExtraMenu hSetEegMegStatus hBatfMEEGMoldelText hBatfMEEGMoldelMenu];		    %50															
        
        set(hEeg2SpmMenuFig,'UserData',hList);
        
        %============================================================================	
        %============ set EEG / MEG Status
        %============================================================================
        
    elseif strcmp(action,'SetEegMegStatus'),
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        hSetEegMegStatus=hList(48);
        EegMegStatusString=get(hSetEegMegStatus,'String');
        if strcmp(EegMegStatusString,'EEG')
            EegMegStatusString='MEG';
            EegMegStatusVal=2;
        else
            EegMegStatusString='EEG';
            EegMegStatusVal=1;
        end
        set(hSetEegMegStatus,'String',EegMegStatusString,'Value',EegMegStatusVal);
        
    elseif  strcmp(action,'AppFileMatrixInfo') | strcmp(action,'AnaFileMatrixInfo') 
        
        hList=get(hEeg2SpmMenuFig,'Userdata'); 
        if  strcmp(action,'AppFileMatrixInfo')
            hListNo=1;
        elseif strcmp(action,'AnaFileMatrixInfo') 
            hListNo=21;
        end
        FileMat=get(hList(hListNo),'Userdata')
        NFiles=size(FileMat,1);
        
        if NFiles>1
            fprintf(1,'\n'); clc;
            Message=char(['The actual file matrix contains the following ',int2str(NFiles),' files:']);
            fprintf(1,'The actual file matrix contains the following %g files:\n\n',NFiles);
        else
            return;
        end
        Message=char(Message,' ');
        Message=char(Message,FileMat);
        Message=char(Message,'');
        Message=char(Message,'');
        hmsgbox=msgbox(Message,'Info','help'); 
        disp(FileMat)
        
        
    elseif strcmp(action,'OpenAppFiles') | strcmp(action,'SetAppFiles'),
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        ResultPath=get(hList(2),'Userdata');
        if strcmp(action,'OpenAppFiles')
            FileExt='*.app*'; 
            String='Choose an App. file (*.app*):';
            DefFilePath=SetDefPath(1,FileExt);
            [NFiles,FileMat,VersionString,BatchFilePath]=ReadFileNames(FileMat,DefFilePath,String);
            if NFiles==0; return; end
            set(hList(1),'Userdata',FileMat);
            set(hList(3),'Enable','on');	%RunEeg2Spm
        elseif strcmp(action,'SetAppFiles')
            FileMat=get(hList(1),'Userdata');
        end
        Eeg2Spm('SetResultFilePath')
        Eeg2Spm('AppFileMatrixInfo')
        [File,Path,FilePath]=GetFileNameOfMat(FileMat,1);
        [DataMat,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,chAvgRef,File,Path,FilePath,EegMegStatus,NChanExtra]=ReadAppData(FilePath,0);
        MinPoint=get(hList(5),'Value');
        if MinPoint==0 | MinPoint>NPoints;
            MinPoint=1;
        end
        set(hList(5),'Value',MinPoint,'String',sprintf('%g',MinPoint));	%MinPoint
        MaxPoint=get(hList(7),'Value');
        if MaxPoint==0 | MaxPoint>NPoints;
            MaxPoint=NPoints;
        end
        set(hList(7),'Value',MaxPoint,'String',sprintf('%g',MaxPoint));	%MaxPoint
        DistPoint=get(hList(9),'Value');
        if DistPoint==0 | DistPoint>MaxPoint-MinPoint+1;
            DistPoint=NPoints;
        end
        set(hList(9),'Value',DistPoint,'String',sprintf('%g',DistPoint));	%DistPoint
        set(hList(27),'Value',NChan,'String',sprintf('%g',NChan));
        set(hList(47),'Value',NChanExtra,'String',sprintf('%g',NChanExtra));
        set(hList(29),'Value',NPoints,'String',sprintf('%g',NPoints));
        set(hList(31),'Value',NTrials,'String',sprintf('%g',NTrials));
        set(hList(33),'Value',SampRate,'String',sprintf('%g',SampRate));
        MaxExp10=ceil(log10(NTrials));
        set(hList(35),'Value',MaxExp10,'String',sprintf('%g',MaxExp10));
        EegMegStatusString=get(hList(48),'String');
        if (EegMegStatus==2 & strcmp(EegMegStatusString,'EEG')) | (EegMegStatus==1 & strcmp(EegMegStatusString,'MEG'))
            Eeg2Spm('SetEegMegStatus')
            EegMegStatusString=get(hList(48),'String');
        end
        Eeg2Spm('SetDistPoint')
        
    elseif strcmp(action,'OpenAnaFiles'),
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        ResultPath=get(hList(2),'Userdata');
        DefFilePath=SetDefPath(1,'*.img');
        [NFiles,FileMat,VersionString,BatchFilePath]=ReadFileNames(FileMat,DefFilePath,String);
        if NFiles==0; return; end
        set(hList(21),'Userdata',FileMat);
        Eeg2Spm('AnaFileMatrixInfo')
        if NFiles>1
            set(hList(23),'Enable','on');	%Avg
            set(hList(24),'Enable','on');	%Diff
        else
            set(hList(23),'Enable','off');
            set(hList(24),'Enable','off');
        end
        
    elseif strcmp(action,'AvgAnaFiles')
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        ResultPath=get(hList(2),'Userdata');
        FileMat=get(hList(21),'Userdata');
        [SaveFile,SavePath,SaveFilePath]=GetFileNameOfMat(FileMat,1);
        initFile='GrandMean.img';
        [SaveFile,SavePath,SaveFilePath]=WriteFilePath(initFile,'Choose avg. file name:');
        if ~isempty(ResultPath)
            SaveFilePath=[ResultPath,SaveFile];
        end
        % [DataMat,SaveFilePath,SizeDataMat,NDim,Version,SampRate,AvgRef,MinPoint,MaxPoint,DistPoint,NTap,SigmaM]=AvgEeg2SpmData(FileMat,SaveFilePath);
        
    elseif strcmp(action,'DiffAnaFiles')
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        ResultPath=get(hList(2),'Userdata');
        FileMat=get(hList(21),'Userdata');
        [SaveFile,SavePath,SaveFilePath]=GetFileNameOfMat(FileMat,1);
        initFile='Diff.img';
        [SaveFile,SavePath,SaveFilePath]=WriteFilePath(initFile,'Choose diff. file name:');
        if ~isempty(ResultPath)
            SaveFilePath=[ResultPath,SaveFile];
        end
        % [DataMat,SaveFilePath,SizeDataMat,NDim,Version,SampRate,AvgRef,MinPoint,MaxPoint,DistPoint,NTap,SigmaM]=DifEeg2Spm2SpmData(FileMat,SaveFilePath);
        
    elseif strcmp(action,'SetResultPath'),
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        ResultPathTypeStr=get(hList(2),'String');
        if isempty(findstr(ResultPathTypeStr,'Create'))
            set(hList(2),'Value',2);
            set(hList(2),'String','Create Result Path');
            set(hList(2),'Userdata',[]);
        else
            set(hList(2),'Value',1);
            set(hList(2),'String','Set Result Path');
            WriteDlgTitle = 'Save Path';
            WriteDef=SetDefPath(1);
            while strcmp(WriteDef(end),filesep)
                WriteDef=WriteDef(1:length(WriteDef)-1);
            end
            if isempty(WriteDef)
                WriteDef = {pwd};
            else
                WriteDef={WriteDef};
            end
            WritePrompt = {'Enter full path to save data:'};
            ResultPath=[];
            while isempty(ResultPath)
                WritePath=inputdlg(WritePrompt,WriteDlgTitle,1,WriteDef);
                if isempty(WritePath); return; end
                WritePath=char(WritePath);
                if ~strcmp(WritePath(length(WritePath)),filesep)
                    WritePath=[WritePath,filesep];
                end
                if exist(WritePath)
                    ResultPath=WritePath;
                end
            end
            disp(ResultPath)
            set(hList(2),'Userdata',ResultPath);
        end
        
    elseif strcmp(action,'SetLambda')   
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        Lambda=get(hList(19),'Value');
        LambdaStr=get(hList(19),'String');   
        [Lambda,LambdaStr]=String2Value(LambdaStr,Lambda,0,1,[],1);
        set(hList(19),'Value',Lambda,'String',sprintf('%g',Lambda));
     
    elseif strcmp(action,'SetFixNTrialsStatus')   
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        FixNTrialStatus=get(hList(43),'Value');
        FixNTrials=get(hList(44),'Value');
        if FixNTrialStatus & FixNTrials==0
            set(hList(44),'Value',1,'String','1');
        elseif ~FixNTrialStatus
            set(hList(44),'Value',0,'String','0');
        end
            
    elseif strcmp(action,'SetFixNTrials')   
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        FixNTrials=get(hList(44),'Value');
        FixNTrialsStr=get(hList(44),'String');   
        [FixNTrials,FixNTrialsStr]=String2Value(FixNTrialsStr,FixNTrials,0,[],1,1);
        %String2Value(StrIn,ValIn,MinLim,MaxLim,RoundStatus,MinMaxLimStatus);
        set(hList(44),'Value',FixNTrials,'String',FixNTrialsStr);
        if FixNTrials==0
            set(hList(43),'Value',0);
        else
            set(hList(43),'Value',1);
        end
            
    elseif strcmp(action,'SetSmoothFWHMmm')   
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        SmoothFWHMmm=get(hList(37),'Value');
        SmoothFWHMmmStr=get(hList(37),'String');   
        [SmoothFWHMmm,SmoothFWHMmmStr]=String2Value(SmoothFWHMmmStr,SmoothFWHMmm,0,[],[],1);
        set(hList(37),'Value',SmoothFWHMmm,'String',sprintf('%g',SmoothFWHMmm));
        if SmoothFWHMmm==0
            set(hList(38),'Value',0);%SetSmoothStatus
            set(hList(39),'Value',0);%SetDelUnsmoothStatus
        else
            set(hList(38),'Value',1);%SetSmoothStatus
            set(hList(39),'Value',1);%SetDelUnsmoothStatus
        end
        
    elseif strcmp(action,'SetSmoothStatus')   
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        SmoothStatus=get(hList(38),'Value');
        if SmoothStatus
            set(hList(37),'Enable','On'); 
            set(hList(39),'Enable','On');  
        else
            set(hList(37),'Enable','Off'); 
            set(hList(39),'Enable','Off');  
        end
        
    elseif strcmp(action,'SetDelUnsmoothStatus')   
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        DelUnsmoothStatus=get(hList(39),'Value');
        
    elseif strcmp(action,'SetMinBase') | ...
            strcmp(action,'SetMaxBase') | ... 
            strcmp(action,'SetCalcBase') | ... 
            strcmp(action,'SetTotalIntBase'),	
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        NPoints=get(hList(29),'Value');
        MinBase=get(hList(13),'Value');
        MaxBaseOld=MinBase;
        MinBaseStr=get(hList(13),'String');
        MaxBase=get(hList(15),'Value');
        MaxBaseOld=MaxBase;
        MaxBaseStr=get(hList(15),'String');
        CalcBaseStatus=get(hList(16),'Value');
        
        if strcmp(action,'SetMinBase')
            [MinBase,MinBaseStr]=String2Value(MinBaseStr,MinBase,1,MaxBase,[],1);
        elseif strcmp(action,'SetMaxBase')
            [MaxBase,MaxBaseStr]=String2Value(MaxBaseStr,MaxBase,MinBase,NPoints,[],1);
            if MaxBaseOld==0; 
                MinBase=1; 
            end
        elseif strcmp(action,'SetTotalIntBase')
            MinBase=1;
            MaxBase=NPoints;
        end
        MaxBase=MaxBase
        set(hList(13),'Value',MinBase,'String',sprintf('%g',MinBase));
        set(hList(15),'Value',MaxBase,'String',sprintf('%g',MaxBase));
        if MaxBaseOld==0 & MaxBase>0
            set(hList(16),'Value',1,'Enable','on');
        end
        if MaxBase==0
            set(hList(16),'Value',0,'Visible','off');
        else
            set(hList(16),'Enable','on');
        end
        
    elseif strcmp(action,'SetCalcDistPointMean') 
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        CalcDistPointMean=get(hList(21),'Value');
        NPoints=get(hList(29),'Value');
        if CalcDistPointMean
            set(hList(10),'String','Number of Intervals');
            set(hList(11),'String','1'); %NPointVec
            Eeg2Spm('SetNDistInt')
        else
            set(hList(10),'String','Number of Points');
            set(hList(9),'String','1'); %DistPoint
            Eeg2Spm('SetDistPoint')
        end
        
    elseif strcmp(action,'setCalcDistPointMNMean') 
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        CalcDistPointMNMean=get(hList(22),'Value');
        if CalcDistPointMNMean
            set(hList(21),'Value',1); %CalcDistPointMean
        end
        
    elseif strcmp(action,'SetMinPoint') | ...
            strcmp(action,'SetMaxPoint') | ...
            strcmp(action,'SetTotalIntPoint') | ...
            strcmp(action,'SetDistPoint') | ...
            strcmp(action,'SetNDistInt'),	
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        NPoints=get(hList(29),'Value');
        MinPoint=get(hList(5),'Value');
        MinPointStr=get(hList(5),'String');
        MaxPoint=get(hList(7),'Value');
        MaxPointStr=get(hList(7),'String');
        DistPoint=get(hList(9),'Value');
        DistPointStr=get(hList(9),'String');
        NPointVec=get(hList(11),'Value');
        NPointVecStr=get(hList(11),'String');
        CalcDistPointMean=get(hList(21),'Value');
        
        if strcmp(action,'SetMinPoint')
            [MinPoint,MinPointStr]=String2Value(MinPointStr,MinPoint,1,MaxPoint,[],1);
            set(hList(5),'Value',MinPoint,'String',MinPointStr);
            DistPoint=MaxPoint-MinPoint+1;
        elseif strcmp(action,'SetMaxPoint')
            [MaxPoint,MaxPointStr]=String2Value(MaxPointStr,MaxPoint,MinPoint,NPoints,[],1);
            set(hList(7),'Value',MaxPoint,'String',MaxPointStr);
            DistPoint=MaxPoint-MinPoint+1
        elseif strcmp(action,'SetTotalIntPoint')
            MinPoint=1;
            MaxPoint=NPoints;
            set(hList(5),'Value',MinPoint,'String',sprintf('%g',MinPoint));
            set(hList(7),'Value',MaxPoint,'String',sprintf('%g',MaxPoint));
            if CalcDistPointMean
                DistPoint=MaxPoint-MinPoint;
            else
                DistPoint=MaxPoint-MinPoint+1;
            end
        elseif strcmp(action,'SetDistPoint')
            [DistPoint,DistPointStr]=String2Value(DistPointStr,DistPoint,1,MaxPoint-MinPoint+1,[],1);
        elseif strcmp(action,'SetNDistInt')
            [NPointVec,NPointVecStr]=String2Value(NPointVecStr,NPointVec,1,MaxPoint-MinPoint+1,[],1);
            DistPoint=floor((MaxPoint-MinPoint)./(NPointVec));
        end
        PointVec=[MinPoint:DistPoint:MaxPoint];
        if CalcDistPointMean
            PointVec=PointVec(find(MaxPoint-PointVec>=DistPoint-1));
        end
        PointVec=PointVec;
        NPointVec=length(PointVec);
        
        set(hList(7),'Value',MaxPoint,'String',sprintf('%g',MaxPoint));
        set(hList(9),'Value',DistPoint,'String',sprintf('%g',DistPoint));
        set(hList(11),'Value',NPointVec,'String',sprintf('%g',NPointVec),'Userdata',PointVec);       
        set(hList(42),'Userdata',[MinPoint MaxPoint]');
        
    elseif strcmp(action,'ReadIntMat'),	
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        ReadIntMatStatus=get(hList(42),'Value');
        if ReadIntMatStatus
            DefIntFilePath=which('IntMat.txt');
            [DefIntFile,DefIntPath]=SepFilePath(DefIntFilePath);
            if ~isempty(DefIntPath)
                if DefIntPath(end)~=filesep
                    DefIntPath=[DefIntPath,filesep];
                end
            else
                DefIntPath=SetDefPath('r');
            end
            [IntFile,IntPath]=uigetfile([DefIntPath,'*.*'],'Read intervals from file:');
            IntFilePath=[IntPath,IntFile];
            if isempty(find(IntFilePath)); return; end;
            fid=fopen(IntFilePath,'r','b');
            [IntVec,Count]=fscanf(fid,'%g');
            fclose(fid);
            if (Count./2-round(Count./2))~=0;
                Message=char('Sorry,');
                Message=char(Message,' ');
                Message=char(Message,'the file');
                Message=char(Message,IntFilePath);
                Message=char(Message,'has to have an even number of elements !');
                hmsgbox=msgbox(Message,'Info','help');
                return;
            else
                NInt=Count./2;
            end
            IntMat=reshape(IntVec,2,NInt);
            IntMatSize=size(IntMat)            
            if IntMatSize(1)~=2 & IntMatSize(2)==2; 
                IntMat=IntMat';
            end
            IntMatSize=size(IntMat);
            if IntMatSize(1)~=2; 
                Message=char('Sorry,')
                Message=char(Message,' ')
                Message=char(Message,'bad size of interval matrix file.')
                msgbox(Message,'Info !','help')
                set(hList(42),'Value',0,'Userdata',[]);
                return; 
            end
            Message=char(' ');
            Message=char(Message,['Load ', int2str(NInt),' intervals !']);
            Message=char(Message,' ');
            for i=1:NInt
                Message=char(Message,['Interval #: ',int2str(i),';  ',int2str(IntMat(1,i)),' - ',int2str(IntMat(2,i))]);
            end
            Message=char(Message,' ');
            msgbox(Message,'Info:','help');
            MinPoint=IntMat(1,:);
            MaxPoint=IntMat(2,:);
            DistPoint=MaxPoint-MinPoint+1;
        else
            IntMat=[];
            MinPoint=0;
            MaxPoint=0;
            DistPoint=0;
            NInt=0;
        end
        
        set(hList(5),'Value',MinPoint,'String',int2str(MinPoint));
        set(hList(7),'Value',MaxPoint,'String',int2str(MaxPoint));
        set(hList(9),'Value',DistPoint,'String',int2str(DistPoint));
        set(hList(11),'Value',NInt,'String',int2str(NInt));  
        set(hList(42),'Userdata',IntMat);
        
    elseif strcmp(action,'LaunchSpmBatch'),	
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        LaunchSpmBatchStatus=get(hList(41),'Value');
        if LaunchSpmBatchStatus
            LaunchSpmBatchFile=which('BatfMEEG');
            if ~exist(LaunchSpmBatchFile)
                set(hList(41),'Value',0);
            end    
        else
            LaunchSpmBatchFile=[];
        end
        set(hList(41),'Userdata',LaunchSpmBatchFile); 
        
    elseif strcmp(action,'SetBatfMEEGMoldel'),	
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        BatfMEEGMoldel=get(hList(50),'Value');
        BatfMEEGMoldelStr=get(hList(50),'String');   
               
    elseif strcmp(action,'SetDeleteFileStatus'),   
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        DeleteFileStatus=get(hList(39),'Value');
        
    elseif strcmp(action,'RunEeg2Spm'),	
        
        hList=get(hEeg2SpmMenuFig,'Userdata');
        FileMat=get(hList(1),'Userdata');
        NFiles=size(FileMat,1);
        ResultPath=get(hList(2),'Userdata');
        AnaFileMat=get(hList(4),'Userdata');
        MinPoint=get(hList(5),'Value');
        MaxPoint=get(hList(7),'Value');
        DistPoint=get(hList(9),'Value');
        NInt=get(hList(11),'Value');
        IntMat=get(hList(42),'Userdata');
        DistPointMeanStatus=get(hList(21),'Value');
        CalcDistPointMNMeanStatus=get(hList(22),'Value');
        LaunchSpmBatchStatus=get(hList(41),'Value');
        LaunchSpmBatchFile=get(hList(41),'Userdata');
        MinBase=get(hList(13),'Value');
        MaxBase=get(hList(15),'Value');
        CalcBaseStatus=get(hList(16),'Value');
        EegMegStatus=get(hList(48),'Value');
        NChan=get(hList(27),'Value');
        MaxExp10=get(hList(35),'Value');
        MNLambdaApprox=get(hList(19),'Value');
        FWHMmm=get(hList(37),'Value');
        SmoothStatus=get(hList(38),'Value');
        DeleteFileStatus=get(hList(39),'Value');
        FixNTrialStatus=get(hList(43),'Value');
        FixNTrials=get(hList(44),'Value');
        BatfMEEGMoldel=get(hList(50),'Value');
        NDip=655;
        NShells=4;
        LeadLocInt=[1 655];	
        LeadLocCfg=[int2str(NDip),'_',int2str(NShells)]
        DLocFilePath=which(['DLoc_',LeadLocCfg,'_Cart.ascii']);
        LeadLoc=ReadData(DLocFilePath,1,[],'ascii','ascii')';
        [DipFile,DipPath]=SepFilePath(DLocFilePath);
        PathLFCoeff=DipPath;
        DipPos=ReadData(DLocFilePath,1,[],'ascii','ascii')';
        SensorVec=[];
        
        [FileSizeVec]=GetFileSize(FileMat);
        AnaPathMat=[];
        
        Message=char(zeros(12,1));
        hProgressMsgbox=msgbox(Message,'Progress Info:','help');
        hChildProgressMsgbox=get(hProgressMsgbox,'children');
        hChild2ProgressMsgbox=get(hChildProgressMsgbox(2),'children');
        set(hChildProgressMsgbox(length(hChildProgressMsgbox)),'Visible','off');
        
        for FileInd=1:NFiles
            [File,Path,FilePath]=GetFileNameOfMat(FileMat,FileInd);
            FileMessage=char('Calculate Eeg2Spm ...');
            FileMessage=char(FileMessage,'');
            FileMessage=char(FileMessage,['File ',int2str(FileInd),' of ',int2str(NFiles)]);
            FileMessage=char(FileMessage,File);
            FileMessage=char(FileMessage,'');
            DataMat=[];	
            if  FileSizeVec(FileInd)<10^6
                [DataMat,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,chAvgRef,...
                        NonUse,NonUse,NonUse,EegMegStatus,NChanExtra]=ReadAppData(FilePath,'all');		
                DataMat=DataMat(:,SensorVec,:);	
            else
                [NonUse,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,chAvgRef,...
                        NonUse,NonUse,NonUse,EegMegStatus,NChanExtra]=ReadAppData(FilePath,1);
            end
            if isempty(SensorVec)
                SensorVec=[1:NChan];  %Sensors to analyze
            end
            NChanAct=NChan+NChanExtra;
            set(hList(27),'String',sprintf('%g',NChan));
            set(hList(29),'String',sprintf('%g',NPoints));
            set(hList(31),'String',sprintf('%g',NTrials));
            set(hList(47),'String',sprintf('%g',NChanExtra));
            
            if ~isempty(ResultPath)
                AnaPath=ResultPath;
            else
                Tmp=findstr(File,'.app');
                Tmp=Tmp(end);
                if isempty(Tmp)
                    SubPath=[File,'.f'];
                else
                    if length(File)>Tmp+3;
                        SubPath=[File(1:Tmp-1),'.',File(Tmp+4:length(File))];
                    end
                end
                [MkDirStatus,MkDirMsg]=mkdir(Path,SubPath)
                AnaPath=[Path,SubPath,filesep];
            end
            [AnaPathMat]=AddFileName2Mat(AnaPathMat,AnaPath);
            %Calculate Eeg2Spm
            FileMessage=char(FileMessage,'Result Path:');
            FileMessage=char(FileMessage,SubPath);
            FileMessage=char(FileMessage,'');
            if CalcBaseStatus
                FileMessage=char(FileMessage,['Baseline interval: ',int2str(MinBase),' - ',int2str(MaxBase)]);
            else
                FileMessage=char(FileMessage,'No baseline subtraction ...');
            end
            FileMessage=char(FileMessage,'');
            Message=char(FileMessage,'Calculate Eeg2Spm ...');
            if strcmp(computer,'MAC2') 
                set(hChildProgressMsgbox(2),'String',Message);
            else
                set(hChild2ProgressMsgbox,'String',Message);
            end
            pause(.001);
            %=====================================================================
            %=====================================================================
            if EegMegStatus==1 %'EEG'
                EEGMEGStatusString='EEG';
                CoorStatusString='sph'; %spherical
                LFDim=3; 
                SensorCfg=int2str(NChan);
            elseif EegMegStatus==2 	%MEG 
                EEGMEGStatusString='MEG';
                CoorStatusString='sph'; %spherical
                LFDim=2;
                Tmp=findstr(File,'.app');
                SensorCfg=File(1:Tmp(length(Tmp))-1)
            end
            %=====================================================================
            PILFCoeffFile=[PathLFCoeff,'PILF',EEGMEGStatusString(1),'_',LeadLocCfg,'_',SensorCfg,'_',int2str(MNLambdaApprox.*10000)]
            %PILFE if EEG; PILFM if MEG
            PILFCoeffFid=exist(PILFCoeffFile);
            if PILFCoeffFid~=2
                LFCoeffFile=[PathLFCoeff,'LF',EEGMEGStatusString(1),'_',LeadLocCfg '_',SensorCfg];
                %LFE if EEG; LFM if MEG
                LFCoeffFid=exist(LFCoeffFile);
                if LFCoeffFid~=2
                    Message=['Calculate ',EEGMEGStatusString,' leadfield coefficients using ',CoorStatusString,' coordinates'];
                    Message=char(Message,'and save them to file:');
                    Message=char(Message,LFCoeffFile);
                    if 	EegMegStatus==1 
                        SensorFilePath=which([int2str(NChan),'.ecfg']);
                        [SensorFile,SensorPath]=SepFilePath(SensorFilePath);
                        [NChan,SpherRadius,SensorPosSpher]=ReadEConfig(SensorFilePath);
                        SensorMat=change_sphere_cart(SensorPosSpher,[],1);
                    else
                        SensorFile=[SensorCfg,'.pmg'];
                        SensorFilePath=[Path,SensorFile];
                        [SensorMat,NonUse,NonUse,Cot,FidMat,SfpMat]=ReadPmgCotSfpFiles(SensorFilePath,0,1,1);
                        [SensorMat,Cot,FidMat,SfpMat]=AdjustPmgCotSfp(SensorMat,Cot,FidMat,SfpMat);
                        SurfPmgCotSfp(SensorMat,FidMat,SfpMat,0,SensorFilePath);
                    end
                    [LFCoeff,Orientations,v]=compute_lfdmat(LeadLoc(:,1:3)',SensorMat',EEGMEGStatusString,CoorStatusString,[],Message);
                    SaveData(LFCoeff,LFCoeffFile,1);
                else
                    Message=char(['Read ' EEGMEGStatusString ' leadfield coefficients from file:']);
                    Message=char(Message,LFCoeffFile);
                    Message=char(Message,' ');
                    hmsgbox=msgbox(Message,'Info:','help'); 
                    hChildMsgbox=get(hmsgbox,'Children');
                    set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                    pause(.01);
                    LFCoeff=ReadData(LFCoeffFile,1,[],'int16','float32');
                    close(hmsgbox);
                end
                Message=char(['Calculate ' EEGMEGStatusString ' pseudo inverse leadfield coefficients']);
                Message=char(Message,'and save them to file:');
                Message=char(Message,PILFCoeffFile);
                hmsgbox=msgbox(Message,'Info:','help');
                hChildMsgbox=get(hmsgbox,'Children');
                hChild2Msgbox=get(hChildMsgbox(2),'Children');
                if strcmp(computer,'MAC2')
                    set(hChildMsgbox(2),'String',Message);
                else
                    set(hChild2Msgbox,'String',Message);
                end
                set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                pause(.01);	
                PILFCoeff=pinv_tikh(LFCoeff,MNLambdaApprox); %MNLambdaApprox=regpar
                SaveData(PILFCoeff,PILFCoeffFile,1);
                close(hmsgbox);
            else
                Message=char(['Read ',EEGMEGStatusString,' pseudo inverse leadfield coefficients from file:']);
                Message=char(Message,PILFCoeffFile);
                hmsgbox=msgbox(Message,'Info:','help'); 
                hChildMsgbox=get(hmsgbox,'Children');
                set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                pause(.1);
                PILFCoeff=ReadData(PILFCoeffFile,1,[],'int16','float32');
                close(hmsgbox)
            end
            if FixNTrialStatus
                NTrialsTmp=min([NTrials FixNTrials])
            else
                NTrialsTmp=NTrials;
            end
            %=====================================================================
            for TrialInd=1:NTrialsTmp
                if TrialInd==1 | floor(TrialInd./10)==TrialInd./10
                    fprintf(1,'\n')
                    fprintf(1,'Trial %g of %g\n',TrialInd,NTrialsTmp);
                else
                    fprintf(1,'.')
                end
                Message=char(FileMessage,['Trial ',int2str(TrialInd),' of ',int2str(NTrialsTmp)]);
                if strcmp(computer,'MAC2') 
                    set(hChildProgressMsgbox(2),'String',Message);
                else
                    set(hChild2ProgressMsgbox,'String',Message);
                end
                pause(.001);
                if isempty(DataMat);
                    TrialMat=ReadAppData(FilePath,TrialInd);
                    TrialMat=TrialMat(SensorVec,:);
                else
                    TrialMat=squeeze(DataMat(TrialInd,:,:));
                end
                if EegMegStatus==2 	%MEG 
                    TrialMat=TrialMat.*10.^18;		%fT x 1000
                end      
                SpecTrialStr=AddZeros2CountStr(TrialInd,MaxExp10);
                TrialMat=CalcBaseline(TrialMat,MinBase,MaxBase,CalcBaseStatus);
                
                if ~DistPointMeanStatus
                    IntMat(1,:)
                    pause
                    TrialMat=TrialMat(:,IntMat(1,:)); 
                else
                    if ~CalcDistPointMNMeanStatus
                        if NInt==1
                            IntMat(1,1)
                            IntMat(2,1)
                            pause
                            TrialMat=mean(TrialMat(:,IntMat(1,1):IntMat(2,1)),2);
                        else    
                            TrialMatTmp=zeros(NChan,NInt);
                            for Ind=1:NInt
                                IntMat(1,Ind)
                                IntMat(2,Ind)
                                pause
                                TrialMatTmp(:,Ind)=mean(TrialMat(:,IntMat(1,Ind):IntMat(2,Ind)),2);
                            end
                            TrialMat=TrialMatTmp; clear TrialMatTmp;
                        end
                    else %if CalcDistPointMNMeanStatus
                        if NInt==1
                            TrialMat=TrialMat(:,IntMat(1,1):IntMat(2,1));
                        else    
                            TrialMatTmp=zeros(NChan,sum(DistPoint));
                            CumSumPointVec=[0,cumsum(DistPoint)];
                            for Ind=1:NInt
                                TrialMatTmp(:,CumSumPointVec(Ind)+1:CumSumPointVec(Ind+1))=TrialMat(:,IntMat(1,Ind):IntMat(2,Ind));
                            end
                            TrialMat=TrialMatTmp; clear TrialMatTmp;
                        end
                    end
                end
                MNMat=inv_recon(PILFCoeff((LeadLocInt(1)-1).*LFDim+1:LeadLocInt(2).*LFDim,:),TrialMat,LFDim);
                [NDip,NMNPoints]=size(MNMat);
                if CalcDistPointMNMeanStatus
                    if NInt==1
                        MNMat=mean(MNMat,2);
                    else    
                        MNMatTmp=zeros(NDip,NInt);
                        for Ind=1:NInt
                            MNMatTmp(:,Ind)=mean(MNMat(:,CumSumPointVec(Ind)+1:CumSumPointVec(Ind+1)),2);
                        end
                        MNMat=MNMatTmp; clear MNMatTmp;
                    end                    
                end    
                [NDip,NMNPoints]=size(MNMat);
                for Ind=1:NMNPoints
                    AnaFilePath=[AnaPath,int2str(IntMat(1,Ind)),'.',int2str(IntMat(2,Ind)),'.',SpecTrialStr];
                    MinNorm2Analyse(MNMat(:,Ind),LeadLoc,AnaFilePath);
                end
            end   
        end %FileInd
        if SmoothStatus
            global SmoothWorkDir SmoothMFilePath SmoothImgPath SmoothFWHMmm SmoothMaskStr
            set(hProgressMsgbox,'Units','normal','Position',[.175 .6 .20 .25]);
            for FileInd=1:NFiles
                [NonUse,SmoothImgPath]=GetFileNameOfMat(AnaPathMat,FileInd);
                for Ind=1:NMNPoints
                    SmoothMaskStr=[int2str(IntMat(1,Ind)),'.',int2str(IntMat(2,Ind)),'*.img'];
                    DelMaskStr=[int2str(IntMat(1,Ind)),'.',int2str(IntMat(2,Ind)),'*.*'];
                    fprintf(1,'Smooth images of:\n')
                    disp(SmoothImgPath)
                    fprintf(1,'\n'); 
                    fprintf(1,'Interval %g of %g;  %g - %g \n',Ind,NMNPoints,IntMat(1,Ind),IntMat(2,Ind)); 
                    fprintf(1,'Smooth mask: ');
                    fprintf(1,SmoothMaskStr);
                    fprintf(1,'\n'); 
                    Message=char('Smooth images ...');
                    Message=char(Message,'');
                    Message=char(Message,['Folder ',int2str(FileInd),' of ',int2str(NFiles)]);
                    Message=char(Message,'');
                    Message=char(Message,Path);
                    Message=char(Message,'');
                    Message=char(Message,['Interval ',int2str(Ind),' of ',int2str(NMNPoints),'; ',int2str(IntMat(1,Ind)),' - ',int2str(IntMat(2,Ind))]);
                    Message=char(Message,'');
                    Message=char(Message,['Smoothing FWHM: ',int2str(FWHMmm),' mm']);
                    Message=char(Message,'');
                    if strcmp(computer,'MAC2')
                        set(hChildProgressMsgbox(2),'String',Message);
                    else
                        set(hChild2ProgressMsgbox,'String',Message);
                    end
                    fprintf(1,'Smoothing FWHM: %g mm\n\n',FWHMmm)
                    SmoothWorkDir=pwd;
                    SmoothMFilePath=which('BatchSmoothEEG2SPM')
                    SmoothFWHMmm=FWHMmm;
                    spm_bch('BatchAnaSmoothEEG2SPM')
                    if DeleteFileStatus==2 | DeleteFileStatus==3 %All; Unsmoothed only
                        fprintf(1,'Delete unsmoothed images within folder:\n')
                        disp(SmoothImgPath)
                        fprintf(1,'\n'); 
                        fprintf(1,'Interval %g of %g;  %g - %g \n',Ind,NMNPoints,IntMat(1,Ind),IntMat(2,Ind)); 
                        fprintf(1,'Delete mask: ');
                        fprintf(1,DelMaskStr);
                        fprintf(1,'\n'); 
                        Message=char('Delete images ...');
                        Message=char(Message,'');
                        Message=char(Message,['Folder ',int2str(FileInd),' of ',int2str(NFiles)]);
                        Message=char(Message,'');
                        Message=char(Message,Path);
                        Message=char(Message,'');
                        Message=char(Message,['Interval ',int2str(Ind),' of ',int2str(NMNPoints),'; ',int2str(IntMat(1,Ind)),' - ',int2str(IntMat(2,Ind))]);
                        Message=char(Message,'');
                        Message=char(Message,'');
                        Message=char(Message,'');
                        if strcmp(computer,'MAC2')
                            set(hChildProgressMsgbox(2),'String',Message);
                        else
                            set(hChild2ProgressMsgbox,'String',Message);
                        end   
                        FileMat=spm_get('Files',SmoothImgPath,DelMaskStr);
                        DeleteFileMat(FileMat);
                        pause(1)     
                    end
                end
            end    
        end
        if LaunchSpmBatchStatus
            for Ind=1:NMNPoints
                MaskStrIn=['s',int2str(IntMat(1,Ind)),'.',int2str(IntMat(2,Ind))];
                Message=char('Launch BatfMEEG ...');
                Message=char(Message,'');
                Message=char(Message,['Interval ',int2str(Ind),' of ',int2str(NMNPoints),'; ',int2str(IntMat(1,Ind)),' - ',int2str(IntMat(2,Ind))]);
                Message=char(Message,'');
                Message=char(Message,'');
                Message=char(Message,'');
                if strcmp(computer,'MAC2')
                    set(hChildProgressMsgbox(2),'String',Message);
                else
                    set(hChild2ProgressMsgbox,'String',Message);
                end  
                pause(.01)
                BatfMEEG(AnaPathMat,MaskStrIn,SmoothFWHMmm,BatfMEEGMoldel);
            end
        end
        if DeleteFileStatus==2 %All
            for FileInd=1:NFiles
                [NonUse,AnaPath]=GetFileNameOfMat(AnaPathMat,FileInd);
                for Ind=1:NMNPoints
                    AnaFileMask=['s',int2str(IntMat(1,Ind)),'.',int2str(IntMat(2,Ind)),'*.*']
                    FileMat=spm_get('Files',AnaPath,AnaFileMask)
                    DeleteFileMat(FileMat);
                    fprintf(1,'Delete unsmoothed images within folder:\n')
                    disp(SmoothImgPath)
                    fprintf(1,'\n'); 
                    Message=char('Delete images ...');
                    Message=char(Message,'');
                    Message=char(Message,['Folder ',int2str(FileInd),' of ',int2str(NFiles)]);
                    Message=char(Message,'');
                    Message=char(Message,Path);
                    Message=char(Message,'');
                    Message=char(Message,['Interval ',int2str(Ind),' of ',int2str(NMNPoints)]);
                    Message=char(Message,'');
                    if strcmp(computer,'MAC2')
                        set(hChildProgressMsgbox(2),'String',Message);
                    else
                        set(hChild2ProgressMsgbox,'String',Message);
                    end
                    pause(2)
                end   
            end
        end
        Message=char('');
        Message=char(Message,'EEG2SPM calculation done ...');
        Message=char(Message,'');
        Message=char(Message,'');
        Message=char(Message,'');
        Message=char(Message,'');
        Message=char(Message,'');
        Message=char(Message,'');
        if strcmp(computer,'MAC2')
            set(hChildProgressMsgbox(2),'String',Message);
        else
            set(hChild2ProgressMsgbox,'String',Message);
        end
        set(hChildProgressMsgbox(length(hChildProgressMsgbox)),'Visible','on');
        Tmp=get(0,'children');
        for i=length(Tmp):-1:1
           if ~isempty(findstr(get(Tmp(i),'Name'),'SPM99'))
             close(Tmp(i))
           end
        end
    elseif strcmp(action,'CloseAllFigures'),
        delete(get(0,'children'))
        clc;
    else
        disp(sprintf('EEG2SPM: action string ''%s'' not recognized, no action taken.',action))
    end	
    
    return;
