function [varargout]=emegs3d(action,varargin);

%   emegs3d 
%
%   emegs3d opens a userinterface for 3d plotting. It is an extension
%   of the emegs2d console, and cannot be run without it.
%   Do not call 'emegs3d' separately.
%
%   See '3d-visualization' in the documentation for detailed descriptions
%   of functions and plotting styles.
%
%   See also EMEGS2D.

%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Markus Junghöfer, Peter Peyk, Andreas Keil, Olaf Hauk,                  
%   Thomas Gruber & Andrea de Cesarei.  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<1; action='Initialize'; end;	 

global hPlot3dMenuFig hPlot2dMenuFig hGlobalMsgbox ForSensorMat SensorMat View2d3d CutRealBotVal...
    matlabversion
if isempty(hPlot2dMenuFig);emegs2d;emegs2d('OpenAvgFile');end
matlabversionstring = version;
matlabversion= str2num(matlabversionstring(1:3));

%============================================================================
%=========== Initialize  ====================================================
%============================================================================
if strcmp(action,'Initialize'),
    
    TmpAddyPos=-.015;
    if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
        MenuFigPosVec=[.8 0 .2 1];
    elseif strcmp(computer,'PCWIN') 
        MenuFigPosVec=[.8 .02 0.2 .9];
    elseif strcmp(computer,'SOL2') | strcmp(computer,'LNX86') | strcmp(computer,'GLNX86')    	
        MenuFigPosVec=[0.8 0.00 0.2 0.89];			
    end
    
    %======================================
    % open emegs3d menu figure
    %=======================================
    set(0,'DefaultFigureCreateFcn','emegs3dopenmenu;');	
	CloseRequestFcnStr='emegs3d(''Closeemegs3dMenuFig'')';
    hPlot3dMenuFig=figure('Units','normal',...
        'Position',MenuFigPosVec, ...
        'Name','emegs3d Menu:', ...
        'Color',[.99 .99 .99], ...
        'NumberTitle','off',...
        'tag','emegs3dmenufig',...
	    'CloseRequestFcn',CloseRequestFcnStr,...
        'menubar','none','handlevisibility','on');
    set(0,'DefaultFigureCreateFcn',';');	
    
    hPlot2dList=get(hPlot2dMenuFig,'Userdata');
    SpherStatus=get(hPlot2dList(3),'Value');
    Domain=get(hPlot2dList(20),'value');
    EEGMEGStatusString=get(hPlot2dList(110),'String');
    if strcmp(EEGMEGStatusString,'EEG')
        if Domain<3
            EEGMEGString='µV';
        elseif Domain>2 & Domain<5
            EEGMEGString='µV/sqrt(Hz)';
        elseif Domain==5
            EEGMEGString='%';
        end
    else
        if Domain<3
            EEGMEGString='fT';
        elseif Domain>2 & Domain<5
            EEGMEGString='fT/sqrt(Hz)';
        elseif Domain==5
            EGMEGString='%';   
        end
    end
    
    % 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;
    textHeight = 0.05;	% not used !!!!!!!!!!!
    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 .3 0];
    hConsolFrame=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',frmPos, ...
        'BackgroundColor',ConsoleRGBColor);
    
    %====================================
    % CortMap Routine text label 
    %=======================================
    btnNumber=1;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./2;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hCortMapMethodText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Scalp, Lap, Cort', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    if SpherStatus==0; 
        set(hCortMapMethodText,'String','CalcMagFieldNorm'); 
    end
    
    %====================================
    % The CortMap Routine Selection Menu
    %=======================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
    labelStr='Scalp|Laplacian|Cortical Mapping|Perrin Scalp|Perrin Laplacian';
    callbackStr='emegs3d(''CalcCortMap'');';
    tooltipstring = 'selects the method of electric field display';
    
    hCortMapMethodMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Value',1,...
        'Userdata',1,...
        'Interruptible','on', ...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    if SpherStatus==0; 
        labelStr='Standard positions; 8 cm single shell|Standard positions; 6 cm single shell|Mean positions; 8 cm single shell|Mean positions; 6 cm single shell';
        callbackStr='emegs3d(''CalcMagFieldNorm'');';
        set(hCortMapMethodMenu,'String',labelStr,'Callback',callbackStr); 
    end
    
    %====================================
    %===============Special Task========
    %====================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./2;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+btnWid./2;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hSpecTaskText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Special Tasks', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    %=======================================
    % TheSpecial Tasks Routine Selection Menu
    %=======================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    labelStr1='SLC; Back & Front|MN; Back & Front|SLC & MN; Back & Front|SLC; Left & Right|MN; Left & Right|SLC & MN; Left & Right|All Sets SLC|All Sets MN|';
    labelStr2='BackHeadHv|BackBrainHv|BackBrainNcHv|BackHeadRc|BackBrainRc|BackBrainNcRc';
    labelStr=[labelStr1,labelStr2];
    callbackStr='emegs3d(''setSpecTask'');'; 
    tooltipstring = 'shortcuts to often used plotting tasks';
    
    hSpecTaskMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Value',3, ...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %====================================
    %  L2- Minimum Norm text label 
    %=======================================
    btnNumber=2;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./2;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hMinNormMethodText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','L2 Min.-Norm', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    %====================================
    %  L2- Minimum Norm Routine Selection Menu
    %=======================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
    labelStr='L2, Shell 8 cm, 4 Shells|L2, Shell 6 cm, 4 Shells|L2, Shell 4 cm, 4 Shells |L2, Shell 2 cm, 4 Shells|L2, Shell 8 cm, 1 Shell|L2, Shell 6 cm, 1 Shell|L2, All Shells, 4 Shells';
    callbackStr='emegs3d(''CalcMinimumNorm'');'; 
    tooltipstring = 'selects method of source localization';
    hMinNormMethodMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Value',1,...
        'Userdata',1,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %====================================
    %  Quiver text label 
    %====================================
    
    btnNumber=2;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./2;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+btnWid./2;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    
    hQuiverText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','L2 Min. Norm View', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white',...
        'Visible','on');
    
    %====================================
    % Quiver Selection Menu
    %====================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt./2 btnWid./2 btnHt./2];
    callbackStr='emegs3d(''SetQuiverStatus'')';
    tooltipstring = 'activates/deactivates plotting of dipole orientation';
    
    hQuiverMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Orientation', ...
        'Interruptible','on',...
        'Callback',callbackStr,...
        'Value',0,...
        'Enable','on',...
        'ToolTipString',tooltipstring,...
        'Visible','on');
    EEGMEGStatusString=get(hPlot2dList(110),'String');
    if strcmp(EEGMEGStatusString,'MEG')
        set(hQuiverMenu,'Value',0,'Enable','off');
    end
    
    %====================================
    % AbsMinNormSurf Selection Menu
    %====================================
    btnNumber=2;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt./2];
    callbackStr='emegs3d(''SetAbsMinNormSurfStatus'')';
    tooltipstring = 'activates/deactivates plotting of dipole strengths';
    
    hAbsMinNormSurfMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Absolute Value', ...
        'Interruptible','on',...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Value',1,...
        'Enable','on',...
        'Visible','on');
    
    %===================================
    % Save Data Routine text label 
    %===================================   
    btnNumber=5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    labelWidth = btnWid./4;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hSaveDataText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Save Data', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    %===================================
    % The Save Data Routine Selection Menu
    %===================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    btnPos=[left yPos-btnHt btnWid./4 btnHt];
    labelStr1='Values at scalp locations [ascii] | Values at scalp locations [float32] |';
    labelStr2='Values at sensor locations [ascii] | Values at sensor locations [float32] |';
    labelStr3='Values at special scalp locations [ascii] | Values at special scalp locations [float32] |';
    labelStr4='Values at special sensor locations [ascii] | Values at special sensor locations [float32] |';
    labelStr5='Scalp locations [ascii] | Scalp locations [float32] |';
    labelStr6='Sensor locations [ascii] | Sensor locations [float32] |';
    labelStr7='Special scalp locations [ascii] | Special scalp locations [float32] |';
    labelStr8='Special sensor locations [ascii] | Special sensor locations [float32]';
    
    labelStr=[labelStr1 labelStr2 labelStr3 labelStr4 labelStr5 labelStr6 labelStr7 labelStr8];
    callbackStr='emegs3d(''SaveData'');';
    tooltipstring = '';
    
    hSaveDataMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'ToolTipString',tooltipstring,...
        'Enable','off', ...
        'Callback',callbackStr);
    
    %===================================
    % CutRealBotText label 
    %===================================   
    btnNumber=5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    labelWidth = btnWid./4;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+2.*btnWid./4;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hCutRealBotText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','CutRealBot', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    %===================================
    % CutRealBot Selection Menu
    %===================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    btnPos=[left+2.*btnWid./4 yPos-btnHt btnWid./4 btnHt]; 
    callbackStr='emegs3d(''CutRealBot'');';
    tooltipstring = 'sets the size of the bottom gray edge on textured models';
    
    hCutRealBotMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','0|1|2|3|4|5|6|7|8|9', ...
        'Interruptible','on', ...
        'ToolTipString',tooltipstring,...
        'Enable','off', ...
        'Value',4, ...
        'Callback',callbackStr);
    
    %===================================
    % PotContourText label 
    %===================================   
    btnNumber=5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    labelWidth = btnWid./4;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+3.*btnWid./4;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hPotContourText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','PotCont', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    %===================================
    % PotContour Selection Menu
    %===================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    btnPos=[left+3.*btnWid./4 yPos-btnHt btnWid./4 btnHt]; 
    callbackStr='emegs3d(''setPotContour'');';
    tooltipstring = 'sets the texture type for textured models';
    
    hPotContourMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',{'Areas';'Smooth';'Contour'},...
        'Interruptible','on', ...
        'Enable','off', ...
        'tag','potcontourpopup',...
        'ToolTipString',tooltipstring,...
        'Value',3, ...
        'Callback',callbackStr);
    
    %====================================
    %===============2d3dView=============
    %====================================
    btnNumber=3;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./3;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    h2d3dViewText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Surf View', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    %====================================
    % The 2d3d View Routine Selection Menu
    %===================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./3 btnHt];
    labelStr='Spec. Surf (3d)|All Surf I (3d)|All Surf II (3d)|Plot (2d)|Head View|Cols & Rows';
    callbackStr='emegs3d(''set2d3dView'');';
    tooltipstring = 'performs plotting tasks in different sizes, views and formats';
    
    h2d3dViewMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'ToolTipString',tooltipstring,...
        'Value',4, ...
        'Callback',callbackStr);
    
    %====================================
    %===============HeadView=============
    %===================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./3;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+btnWid./3;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hHeadViewText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Head View', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    %===================================
    % The Head View Routine Selection Menu
    %===================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./3 yPos-btnHt btnWid./3 btnHt];
    labelStr='Back     [0, 0]|Front    [180, 0]|Top  [0, 90]|Bottom  [180, -90]|Left       [-90, 0]|Right     [90, 0]|Special';
    callbackStr='emegs3d(''setHeadView'');';
    tooltipstring = 'sets view direction on surface plots';
    
    hHeadViewMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'ToolTipString',tooltipstring,...
        'Value',3, ...
        'Callback',callbackStr);
    %===================================
    %===============HeadModel===========
    %===================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./3;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+2*btnWid./3;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hHeadModelText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Render Model', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    %===================================
    % The Head View Routine Selection Menu
    %===================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+2*btnWid./3 yPos-btnHt btnWid./3 btnHt];
    labelStr={'Sphere';'Head';'Head Smooth';'Brain';'Brain Low Smooth';'Brain High Smooth';'BrainNC Low Smooth';'BrainNC High Smooth';'Custom'};
    %labelStr={'Sphere';'Realistic';'Brain';'Transparent';'Brain_smooth1';'Brain_smooth2';'Realist.2'};
    callbackStr='emegs3d(''setHeadModel'');';
    tooltipstring = 'selects the active surface model';
    
    hHeadModelMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Value',1, ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Userdata',1);
    
    if matlabversion<6
        set(hHeadModelMenu,'Enable','off');
    end
    
    %====================================
    % ThetaViewHandle
    %===================================
    
    btnNumber=4;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid./6 btnHt_edit./2];
    hThetaViewText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Theta');
    
    btnPos=[left+btnWid./6 yPos btnWid./6 btnHt_edit./2];
    callbackStr = 'emegs3d(''setThetaView'')';
    tooltipstring = 'sets the horizontal view angle';
    hThetaViewMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Userdata',0, ...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    %===================================
    % PhiViewHandle
    %===================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./3 yPos btnWid./6 btnHt_edit./2];
    hPhiViewText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Phi');
    
    btnPos=[left+3.*btnWid./6 yPos btnWid./6 btnHt_edit./2];
    callbackStr = 'emegs3d(''setPhiView'')';
    tooltipstring = 'sets the vertical view angle';
    hPhiViewMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','90','Userdata',90, ...
        'ToolTipString',tooltipstring,...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    %==============================================================
    % =============================================================
    % callback: setAllFigView =====================================
    %==============================================================  
    btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
    callbackStr = 'emegs3d(''setHeadView'')';
    tooltipstring = 'activates/deactivates view angle yoking of all figures';
    hAllFigViewMenu = uicontrol( ...
        'Style','radio', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'String','All Figures', ...
        'Value',0, ...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    %==============================================================
    % Plot Sensors (popupmenu)==================================
    % callback: setPlotEPos =======================================
    %==============================================================
    
    btnNumber=4;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    labelWidth = btnWid./3;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    
    hPlotEPosText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Plot Sensors', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    btnPos=[left yPos-btnHt btnWid./3 btnHt];
    labelStr='Just in first view|In all views|Do not plot sensor positions';
    callbackStr='emegs3d(''setPlotEPos'')';
    tooltipstring = 'enables/disables plotting of sensor positions';
    
    hPlotEPosMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Userdata',2,...
        'Value',2,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==============================================================
    % Plot Contours (popupmenu)====================================
    % callback: setPlotContour ====================================
    %==============================================================
    
    % The Plot Contour Routine Selection Text
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    labelWidth = btnWid./3;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+labelWidth;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    
    hPlotContourText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Contour', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    %===================================
    % The Plot Contour Routine Selection Menu
    %===================================
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    btnPos=[labelLeft yPos-btnHt btnWid./3 btnHt];
    labelStr='Just in first view|In all views|Do not plot head contours|3d contour';
    callbackStr='emegs3d(''setPlotContour'');';
    tooltipstring = 'enables/disables plotting of head contours';
    
    hPlotContourMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Value',2, ...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==============================================================
    % Plot Latency (popupmenu)====================================
    % callback: setPlotLatency ====================================
    %==============================================================
    
    %===================================
    % The Plot Latency Routine Selection Text
    %===================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    labelWidth = btnWid./3;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+2.*labelWidth;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    
    hPlotLatencyText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Latency', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    %===================================
    % The Plot Latency Routine Selection Menu
    %===================================
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    btnPos=[labelLeft yPos-btnHt btnWid./3 btnHt];
    labelStr='Plot latency|Do not plot latency';
    callbackStr='emegs3d(''setPlotLatency'');';
    tooltipstring = 'enables/disables plotting of latencies';
    
    hPlotLatencyMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Value',1, ...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==============================================================
    % ColorMap (popupmenu)=========================================
    % callback: setColorMap =======================================
    %==============================================================   
    btnNumber=5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    labelWidth = btnWid./4;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+btnWid./4;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    
    hColorMapText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Color Map', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    %===================================
    % The ColorMap Routine Selection Menu
    %===================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    btnPos=[left+btnWid./4 yPos-btnHt btnWid./4 btnHt];
    labelStr='hsv|hot|cool|jet|pink|flag|copper|gray';
    callbackStr='emegs3d(''setColorMap'');';
    tooltipstring = 'chooses the active colormap';
    
    hColorMapMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Value',4, ...
        'tag','colormappopup',...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %============================================================
    % Flip Colormap (radio button)===========================
    % callback: FlipColormap ====================================
    %============================================================
    
    btnNumber=6;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt./2 btnWid btnHt./2];
    callbackStr='emegs3d(''FlipColormap'')';
    tooltipstring = 'enables/disables inverted colormapping';
    
    hFlipColormap=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Flip colormap', ...
        'Value',0,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==============================================================
    % No white ========================================
    % callback: setGrayFit ====================================
    %==============================================================
    
    btnNumber=6;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit btnWid./3 btnHt_edit./2];
    
    hGrayFitText = uicontrol( ...
        'Style','text', ...
        'String','Gray Fit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black');
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+1.5*btnWid./6 yPos-btnHt_edit 1.5.*btnWid./6 btnHt_edit./2];
    callbackStr='emegs3d(''setGrayFit'')';
    tooltipstring = '';
    
    hGrayFitMenu=uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %===================================
    % NRowColorMapHandle
    %===================================
    
    btnNumber=6;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
    
    hNRowColorMapText = uicontrol( ...
        'Style','text', ...
        'String','N-Color', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black');
    
    btnPos=[left+4.5*btnWid./6 yPos-btnHt_edit./2 1.5.*btnWid./6 btnHt_edit./2];
    callbackStr = 'emegs3d(''setNRowColorMap'')';
    tooltipstring = 'forces n colors (min-max) / forces one color per n units (amplitude)';
    
    hNRowColorMapMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','256','Value',256, ...
        'Userdata',[256 1], ...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    %==============================================================
    % ColorAmpTot (push button)======================================
    % callback: setColorAmpTot ======================================
    %==============================================================
    
    btnNumber=6;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-6.*btnHt./5 btnWid./2 btnHt./2];
    callbackStr='emegs3d(''setColorAmpTot'')';
    tooltipstring = 'toggles between amplitude dependent and min-max-dependent colormapping';
    
    hColorAmpTot=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','N-Color ', ...
        'Userdata',1,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %===================================
    % MinAmpHandle
    %===================================
    
    btnNumber=7;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
    hMinAmpText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 1.*btnHt_edit./2];
    callbackStr = 'emegs3d(''setMinAmp'')';
    tooltipstring = 'sets amplitude value of minimum color';
    
    hMinAmpMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Userdata',0, ...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    %===================================
    % MaxAmpHandle
    %===================================
    
    btnPos=[left yPos-btnHt_edit 2.*btnWid./3 btnHt_edit./2];
    hMaxAmpText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black');
    
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
    callbackStr = 'emegs3d(''setMaxAmp'')';
    tooltipstring = 'sets amplitude value of maximum color';
    
    hMaxAmpMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Userdata',0, ...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    %==============================================================
    % MinMaxAmpCentralize (radio button)===========================
    % callback: setCenterAmp =========================================
    %==============================================================  
    btnNumber=8;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt./2 .3.*btnWid btnHt./2];
    callbackStr='emegs3d(''setCenterAmp'')';
    tooltipstring = 'enables/disables zero-symmetrical colormapping';
    
    hCenterAmp=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Center', ...
        'Userdata',0,...
        'Value',0,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %=============================================================
    % SpecAmp (radio button)======================================
    % callback: setSpecAmp =======================================
    %=============================================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+.3.*btnWid yPos-btnHt./2 .35.*btnWid btnHt./2];
    callbackStr='emegs3d(''setSpecAmp'')';
    tooltipstring = '';
    
    hSpecAmp=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Special', ...
        'Userdata',1,...
        'Value',1,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %=============================================================
    % AutoAmp (radio button)======================================
    % callback: setAutoAmp =======================================
    %=============================================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+.6.*btnWid yPos-btnHt./2 .4.*btnWid btnHt./2];
    callbackStr='emegs3d(''setAutoAmp'')';
    tooltipstring = 'enables/disables automatic min-max-amplitude scaling';
    
    hAutoAmp=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Auto. Amp.', ...
        'Userdata',1,...
        'Value',1,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %=======================================================
    % hPPlusMinusAmp (radio button)=========================
    % callback: setPPlusMinusAmp ===========================
    %=======================================================
    btnNumber=8.5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt./2 .33.*btnWid btnHt./2];
    callbackStr='emegs3d(''setPPlusMinusAmp'')';
    tooltipstring = 'enables/disables probability scaling';
    
    hPPlusMinusAmp=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Stats', ...
        'Userdata',[0 0.9], ...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %=======================================================
    % MinMaxAmpP90 (pushbutton)===========================
    % callback: setP90Amp ===============================
    %=======================================================
    btnNumber=8.5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+.33.*btnWid yPos-btnHt./2 .11.*btnWid btnHt./2];
    callbackStr='emegs3d(''setP90Amp'')';
    tooltipstring = 'sets probability threshold to 90%';
    
    hP90Amp=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','90', ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','Off');
    
    %=======================================================
    % MinMaxAmpP95 (radio button)===========================
    % callback: setP95Amp ==================================
    %=======================================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+.44.*btnWid yPos-btnHt./2 .11.*btnWid btnHt./2];
    callbackStr='emegs3d(''setP95Amp'')';
    tooltipstring = 'sets probability threshold to 95%';
    
    hP95Amp=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','95', ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
         'Enable','Off');
    
    %=======================================================
    % MinMaxAmpP99 (radio button)===========================
    % callback: setP99Amp ==================================
    %=======================================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+.55.*btnWid yPos-btnHt./2 .11.*btnWid btnHt./2];
    callbackStr='emegs3d(''setP99Amp'')';
    tooltipstring = 'sets probability threshold to 99%';
    
    hP99Amp=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','99', ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
         'Enable','Off');
    
    %=======================================================
    % setPEditAmp (edit)====================================
    % callback: setPEditAmp ================================
    %=======================================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+.66.*btnWid yPos-btnHt./2 .33.*btnWid btnHt./2];
    callbackStr='emegs3d(''setPEditAmp'')';
    tooltipstring = 'sets probability threshold to n%';
    
    hPEditAmp = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Userdata',0, ...
        'callback',callbackStr,...
        'ToolTipString',tooltipstring,...
         'Enable','Off');
    
    %===================================
    % MinPointHandle
    %===================================
    
    btnNumber=9;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
    hPlot2dMinMaxText=get(hPlot2dList(21),'Userdata');
    hMinPointText=get(hPlot2dMinMaxText(3),'String');
    
    hMinPointText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String',hMinPointText,...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
    callbackStr = 'emegs3d(''setMinPoint'')';
    tooltipstring = 'sets the first time point to be plotted';
    
    hMinPointMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',1, ...
        'callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','on');
    
    %===================================
    % MaxPointHandle
    %===================================
    
    btnNumber=9;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit 2.*btnWid./3 btnHt_edit./2];
    
    hPlot2dMinMaxText=get(hPlot2dList(21),'Userdata');
    hMaxPointText=get(hPlot2dMinMaxText(4),'String');
    
    hMaxPointText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String',hMaxPointText,...
        'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
    callbackStr = 'emegs3d(''setMaxPoint'')';
    tooltipstring = 'sets the last time point to be plotted';
    
    hMaxPointMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','on');
    
    %====================================
    % CalcDistPoint text edit button=====
    % callback: setDistPoint ============
    %====================================
    % DistPoint text
    btnNumber=10;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
    hDistPointText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Dist. time [ms]');
    
    % DistPoint menu
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 1.*btnHt_edit./2];
    callbackStr = 'emegs3d(''setDistPoint'')';
    tooltipstring = 'sets time distance between plots in a series';
    SampRate=get(hPlot2dList(60),'Userdata'); 
    MsPerPoint=1000./SampRate;
    DistPointVec=[1 MsPerPoint SampRate MsPerPoint];
    
    hDistPointMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String',int2str(MsPerPoint),'Userdata',DistPointVec, ...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    %====================================
    % NDistInt text edit button=====
    % callback: setNDistInt ============
    %====================================
    % NDistInt text
    btnNumber=10;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit 2.*btnWid./3 btnHt_edit./2];
    
    hNDistIntText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Number of intervals');
    
    % NDistInt menu
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 1.*btnHt_edit./2];
    callbackStr = 'emegs3d(''setNDistInt'')';
    tooltipstring = 'sets number of plots in a series';
    
    hNDistIntMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','1','Value',1, ...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    %====================================
    % CalcDistPointMean radio button=====
    % callback: setCalcDistPointMean ====
    %====================================
    btnNumber=11.4;  
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid./3 btnHt./2];
    callbackStr='emegs3d(''setCalcDistPointMean'')';
    tooltipstring = 'enables/diables averaging across time windows';
    
    hCalcDistPointMeanMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Mean', ...
        'Userdata',1,...
        'Value',1,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %====================================
    % CalcDistPointMinNormMean radio button=====
    % callback: setCalcDistPointMNMean ====
    %====================================
    btnNumber=11.4;  
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./4 yPos btnWid./3 btnHt./2];
    callbackStr='emegs3d(''setCalcDistPointMNMean'')';
    tooltipstring = 'sets Minimum Norm Calculation sequence (MN(MeanPotential) vs. Mean(MN))';
    
    hCalcDistPointMNMeanMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','MN Mean', ...
        'Userdata',1,...
        'Value',1,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
   
    %====================================
    % SetTotalInt pushbutton=====
    % callback: setTotalInt ====
    %====================================
    btnNumber=11.4;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+.58*btnWid yPos .42.*btnWid btnHt./2];
    callbackStr='emegs3d(''setTotalInt'')';
    tooltipstring = 'forces plot distance of 1 one time point';
    
    hTotalInt=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Total Interval', ...
        'Value',0,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr,...
        'Enable','on');
    
    %============================================================
    % Use Approximation (radio button)===========================
    % callback: setUseApprox ====================================
    %============================================================
    btnNumber=13.5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt./2 btnWid btnHt./2];
    callbackStr='emegs3d(''setUseApprox'')';
    tooltipstring = 'enables/disables ...???';
    
    hUseApprox=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Use Approximation/Normalization', ...
        'Userdata',1,...
        'Value',1,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==============================================================
    % Use Approximation (radio button)===========================
    % callback: setUseApproxVec ===================================
    %============================================================== 
    btnNumber=13.5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt./2];
    callbackStr='emegs3d(''setUseApproxVec'')';
    tooltipstring = 'enables/disables ...???';
    
    hUseApproxVec=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Use app. Vector', ...
        'Userdata',0,...
        'Value',0,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==============================================================
    % Use Matrix Approximation (radio button)======================
    % callback: setUseApproxMat ===================================
    %==============================================================
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt./2];
    callbackStr='emegs3d(''setUseApproxMat'')';
    tooltipstring = 'enables/disables ...???';
    
    hUseApproxMat=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Use app. Matrix', ...
        'Userdata',0,...
        'Value',0,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==============================================================
    % Lambda Approx (edit button)=================================
    % callback: setSLCLambdaApprox ===================================
    %==============================================================
    
    btnNumber=11.5;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
    hSLCLambdaApproxText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','SLC Lambda:');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
    callbackStr = 'emegs3d(''setSLCLambdaApprox'')';
    tooltipstring = 'sets the smoothness of spherical spline interpolation';
    
    hSLCLambdaApproxMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0.02','Value',.02, ...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    
    btnPos=[left yPos-btnHt_edit btnWid./3 btnHt_edit./2];
    callbackStr = 'emegs3d(''CalcMNLambdaApprox'')';
    tooltipstring = '';
    
    hCalcMNLambdaApproxMenu = uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Evaluate', ...
        'ToolTipString',tooltipstring,...
        'Value',0, ...
        'callback',callbackStr);
    
    btnPos=[left+btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
    
    hMNLambdaApproxText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','MN Lambda:');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
    callbackStr = 'emegs3d(''setMNLambdaApprox'')';
    tooltipstring = 'sets the smoothness of spherical spline interpolation';
    
    hMNLambdaApproxMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0.02','Value',.02, ...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    %==========================================================
    % Min. Beta Approx (edit button)==============================
    % callback: setMinBetaApprox ================================
    %==========================================================
    
    btnNumber=12.5;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
    hMinBetaApproxText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Min. Beta Approx:');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
    callbackStr = 'emegs3d(''setMinBetaApprox'')';
    tooltipstring = 'sets the minimun beta approximation';
    
    hMinBetaApproxMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0.8','Userdata',.8, ...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    
    %============================================================
    % Beta Wheigt Kind (popupmenu button)==========================
    % callback: setBetaWeightMethod ===============================
    %============================================================
    
    btnNumber=13;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 btnWid./2 btnHt_edit./2];
    
    hBetaWeightMethodText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Beta Weight:');
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    btnPos=[left+btnWid./2 yPos-3.*btnHt./4 btnWid./2 btnHt];
    labelStr='Square Root|Linear|Square|Cubic';
    callbackStr='emegs3d(''setBetaWeightMethod'');';
    tooltipstring = 'sets the beta weighting method';
    
    hBetaWeightMethodMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==============================================================
    % Print to file Kind (popupmenu button)========================
    % callback: setPrint2FileMethod ===============================
    %==============================================================
    
    btnNumber=14.5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    labelPos = [left+btnWid./2 yPos-textHeight./1.5 btnWid./2 textHeight];
    hPrint2FileMethodText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Print Format', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    labelStr='EPS|EPS & Tiff preview|JPEG|TIFF';
    callbackStr='emegs3d(''setPrint2FileMethod'');';
    tooltipstring = 'chooses method used for printing to file';
    
    hPrint2FileMethod=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Userdata','JPEG',...
        'Value',3,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==========================================================
    % Movie Status (radiobutton)===============================
    % callback: setPrint2FileStatus ===========================
    %==========================================================
    
    btnNumber=14.5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
    callbackStr='emegs3d(''setPrint2FileStatus'')';
    tooltipstring = 'enables/disables printing to file';
    
    hPrint2FileStatus=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Print to file', ...
        'Userdata',0,...
        'Value',0,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==========================================================
    % Movie Pause Status (radiobutton)=========================
    % callback: setMoviePause =================================
    %==========================================================
    btnNumber=16;   
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-2.*btnHt./3 btnWid./2 btnHt./2];
    callbackStr='emegs3d(''setMoviePause'')';
    tooltipstring = 'enables pausing between series plots';
    
    hMoviePause=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Movie Pause', ...
        'Userdata',1,...
        'Value',1,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==========================================================
    % Plot and Surf Status (radiobutton)=======================
    % callback: setPlotSurfStatus =============================
    %==========================================================
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-2.*btnHt./3 btnWid./2 btnHt./2];
    callbackStr='emegs3d(''setPlotSurfStatus'')';
    tooltipstring = '';
    
    hPlotSurfStatus=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Plot Data', ...
        'Userdata',1,...
        'Value',1,...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==============================================================
    % Print Compression Value (edit button)========================
    % callback: setPrintFileComp ==================================
    %==============================================================
    
    btnNumber=15.5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
    hPrintFileCompText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Print file compression:');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
    callbackStr = 'emegs3d(''setPrintFileComp'')';
    tooltipstring = '';
    
    hPrintFileCompMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','80','Userdata',80, ...
        'ToolTipString',tooltipstring,...
        'callback',callbackStr);
    
    %====================================
    
    btnNumber=19;
    
    % Save to plot Routine text label 
    %yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    %labelWidth = btnWid./2;
    %labelBottom=yPos-textHeight./1.5;
    %labelLeft = left;
    %labelPos = [labelLeft labelBottom labelWidth textHeight];
    %hSave2PlotText = uicontrol( ...
    %    'Style','text', ...
    %    'Units','normalized', ...
    %	'Position',labelPos, ...
    %    'Horiz','center', ...
    %    'String','Save to plot', ...
    %    'Interruptible','off', ...
    %    'BackgroundColor',ConsoleRGBColor, ...
    %    'ForegroundColor','white');
    hSave2PlotText=0;
    %====================================
    
    % The Save to Plot Selection Menu
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
    labelStr='Save to plot';
    callbackStr='emegs3d(''Save2Plot'');';
    tooltipstring = '';
    
    hSave2PlotMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','off');
    
    %====================================
    
    % Read and Plot Routine text label 
    %yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    %labelWidth = btnWid./2;
    %labelBottom=yPos-textHeight./1.5;
    %labelLeft = left+btnWid./2;
    %labelPos = [labelLeft labelBottom labelWidth textHeight];
    %hReadPlotText = uicontrol( ...
    %    'Style','text', ...
    %    'Units','normalized', ...
    %	'Position',labelPos, ...
    %   'Horiz','center', ...
    %   'String','Read and plot', ...
    %    'Interruptible','off', ...
    %    'BackgroundColor',ConsoleRGBColor, ...
    %    'ForegroundColor','white');
    hReadPlotText=0;
    %====================================
    
    % The Read and Plot Selection Menu
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    labelStr='Read and plot';
    callbackStr='emegs3d(''ReadPlotData'');';
    tooltipstring = '';
    
    hReadPlotMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','off');
    
    %====================================
    
    btnNumber=17;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-4.*btnHt./5 btnWid./2 btnHt];
    callbackStr = 'emegs3d(''Apply'')';
    tooltipstring = 'runs last SLC or MinMorm choice / recalculates if necessary';
    hApply=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Apply', ...
        'Userdata',[1 1 1], ...         &[Recalculate Yes=1 No=0,SLC=1 MN=2,Scalp or MN8=1 Lap or MN6=2 etc.]
        'Enable','on', ...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);
    
    %==============================================================
    % Selection of actual file (popupmenu) ========================
    % callback: setActFileNo ======================================
    %==============================================================
    
    btnNumber=17;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;;
    labelWidth = btnWid./2;
    labelBottom=yPos-textHeight./5;
    labelLeft = left+btnWid./2;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    
    hActFileNoText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','Actual data set:', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white',...
        'Enable','on');
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-4.*btnHt./5 btnWid./2 btnHt];
    callbackStr='emegs3d(''setActFileNo'')';
    tooltipstring = 'selects the active dataset';
    ActFileNo2d=get(hPlot2dList(1),'Value');
    FileNoVec=get(hPlot2dList(56),'Userdata'); 
    ActFileNo3d=find(FileNoVec==ActFileNo2d);
    hActFileNoMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',' ', ...
        'Interruptible','on', ...
        'Value',ActFileNo3d, ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','on');
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-4.*btnHt./5 btnWid./2 btnHt./2];
    callbackStr = 'emegs3d(''setActFileNo'')';
    tooltipstring = 'reloads emegs2d datasets';
    hActualize=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Reload', ...
        'Enable','on', ...
        'ToolTipString',tooltipstring,...
        'Callback',callbackStr);

    %==============================================================
    % Selection of actual file (pushbuttons 1-6) ==================
    % callback: setActFileNo1 - setActFileNo6 =====================
    %==============================================================
    btnNumber=18;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid./6 btnHt./2];
    callbackStr='emegs3d(''setActFileNo1'')';
    tooltipstring = 'selects emegs2d dataset 1 as active';
    
    hSetActFileNo1=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','1', ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','On');
    if ~any(FileNoVec==1); set(hSetActFileNo1,'Enable','Off'); end
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./6 yPos btnWid./6 btnHt./2];
    callbackStr='emegs3d(''setActFileNo2'')';
    tooltipstring = 'selects emegs2d dataset 2 as active';
    
    hSetActFileNo2=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','2', ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','On');
    if ~any(FileNoVec==2); set(hSetActFileNo2,'Enable','Off'); end
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+2.*btnWid./6 yPos btnWid./6 btnHt./2];
    callbackStr='emegs3d(''setActFileNo3'')';
    tooltipstring = 'selects emegs2d dataset 3 as active';
    
    hSetActFileNo3=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','3', ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','On');
    if ~any(FileNoVec==3); set(hSetActFileNo3,'Enable','Off'); end
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+3.*btnWid./6 yPos btnWid./6 btnHt./2];
    callbackStr='emegs3d(''setActFileNo4'')';
    tooltipstring = 'selects emegs2d dataset 4 as active';
    
    hSetActFileNo4=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','4', ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','On');
    if ~any(FileNoVec==4); set(hSetActFileNo4,'Enable','Off'); end
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+4.*btnWid./6 yPos btnWid./6 btnHt./2];
    callbackStr='emegs3d(''setActFileNo5'')';
    tooltipstring = 'selects emegs2d dataset 5 as active';
    
    hSetActFileNo5=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','5', ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','On');
    if ~any(FileNoVec==5); set(hSetActFileNo5,'Enable','Off'); end
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+5.*btnWid./6 yPos btnWid./6 btnHt./2];
    callbackStr='emegs3d(''setActFileNo6'')';
    tooltipstring = 'selects emegs2d dataset 6 as active';
    
    hSetActFileNo6=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','6', ...
        'Callback',callbackStr,...
        'ToolTipString',tooltipstring,...
        'Enable','On');
    if ~any(FileNoVec==6); set(hSetActFileNo6,'Enable','Off'); end
    
    %=======================================================
    %===========UIMENUES====================================
    %=======================================================
    
    %==============================================================
    % Menu: File ==================================================
    %==============================================================
    hFileMenu=uimenu('Label','File','ForegroundColor',[0 0 1],'Enable','on');
    
    hSetActFileNoMenu=uimenu(hFileMenu,'Label','Choose Data Set');
    callbackStr = 'emegs3d(''setActFileNo1'')';
    uimenu(hSetActFileNoMenu,'Label','Actual Data Set 1','Callback',callbackStr,'Accelerator','1');
    callbackStr = 'emegs3d(''setActFileNo2'')';
    uimenu(hSetActFileNoMenu,'Label','Actual Data Set 2','Callback',callbackStr,'Accelerator','2');
    callbackStr = 'emegs3d(''setActFileNo3'')';
    uimenu(hSetActFileNoMenu,'Label','Actual Data Set 3','Callback',callbackStr,'Accelerator','3');
    callbackStr = 'emegs3d(''setActFileNo4'')';
    uimenu(hSetActFileNoMenu,'Label','Actual Data Set 4','Callback',callbackStr,'Accelerator','4');
    callbackStr = 'emegs3d(''setActFileNo5'')';
    uimenu(hSetActFileNoMenu,'Label','Actual Data Set 5','Callback',callbackStr,'Accelerator','5');
    callbackStr = 'emegs3d(''setActFileNo6'')';
    uimenu(hSetActFileNoMenu,'Label','Actual Data Set 6','Callback',callbackStr,'Accelerator','6');
    callbackStr = 'emegs3d(''PlotSurfData'')';
    uimenu(hSetActFileNoMenu,'Label','Apply','Callback',callbackStr,'Accelerator','a','Separator','on');
    callbackStr = 'emegs3d(''setActFileNo'')';
    uimenu(hSetActFileNoMenu,'Label','Reload','Callback',callbackStr,'Accelerator','r');
    
    hFileMatrixMenu=uimenu(hFileMenu,'Label','File matrix');
    callbackStr='emegs3d(''OpenFileMatrix'')';
    hFileOpenFileMatrixMenu=uimenu(hFileMatrixMenu,'Label','Open Batch File','Callback',callbackStr,'Accelerator','b');
    callbackStr='emegs3d(''SaveFileMatrix'')';
    hFileSaveFileMatrixMenu=uimenu(hFileMatrixMenu,'Label','Save Batch File','Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''AddFile2FileMatrix'')';
    hFileAddFile2FileMatrixMenu=uimenu(hFileMatrixMenu,'Label','Add File to Batch','Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''UseFileMatrix'')';
    hFileUseFileMatrixMenu=uimenu(hFileMatrixMenu,'Label','Use Batch File','Callback',callbackStr,'Enable','off','Userdata',0);
       
    %============ save/open view default file =====================
	hDefFileMenu=uimenu(hFileMenu,'Label','Default File','Separator','on');
	callbackStr = 'emegs3d(''AutoViewDefaultFile'')';
	hAutoDefFileMenu=uimenu(hDefFileMenu,'Label','Auto','Callback',callbackStr,'Userdata',0);
	callbackStr = 'emegs3d(''ReadViewDefaultFile'')';
	hOpenDefFileMenu=uimenu(hDefFileMenu,'Label','Open','Callback',callbackStr,'Accelerator','y');
	callbackStr = 'emegs3d(''SaveViewDefaultFile'')';
	hSaveDefFileMenu=uimenu(hDefFileMenu,'Label','Save','Callback',callbackStr,'Enable','on','Accelerator','x');
	hInfoDefFileMenu=uimenu(hDefFileMenu,'Label','Info','Callback',callbackStr,'Separator','on','Enable','on');
	uimenu(hInfoDefFileMenu,'Label','No view def. file opened','Enable','on');
	%-------------------------------------------------------------------------------------------
    
    %==============================================================
    % Menu: Style =================================================
    %==============================================================
    hStyleMenu=uimenu('Label','Style','ForegroundColor',[0 0 1],'Enable','on');
    
    %============ Colormap ========================================
    hStyleColormapMenu=uimenu(hStyleMenu,'Label','Colormap','Enable','on');
    callbackStr='emegs3d(''FlipColormap'')';
    hFlipColormapMenu=uimenu(hStyleColormapMenu,'Label','Flip Colormap   ','Userdata',16,'Callback',callbackStr);
    
    %============ Text ========================================
    hStyleTextMenu=uimenu(hStyleMenu,'Label','Text','Enable','on');
    hDispSensorMenu=uimenu(hStyleTextMenu,'Label','Sensors');
    callbackStr='emegs3d(''DispSensorName'')';
    hDispSensorNameMenu=uimenu(hDispSensorMenu,'Userdata',0,'Label','Names','Callback',callbackStr);
    callbackStr='emegs3d(''DispSensorCircle'')';
    hDispSensorCircleMenu=uimenu(hDispSensorMenu,'Userdata',1,'Label','Circle','Callback',callbackStr);
    callbackStr='emegs3d(''DispSensorAsterisk'')';
    hDispSensorAsteriskMenu=uimenu(hDispSensorMenu,'Userdata',0,'Label','Asterisk','Callback',callbackStr);
    
    %==============================================================
    % Menu: Export ================================================
    %==============================================================
    
    
    hExportMenu=uimenu('Label','Export','ForegroundColor',[0 0 1],'Enable','on');
   

    callbackStr='emegs3d(''ExportCalcPot'')';
    hExportCalcPotMenu=uimenu(hExportMenu,'Label','Calculated distribution','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    hExportSaveDataMenu=uimenu(hExportMenu,'Label','Save Data','ForegroundColor',[0 0 1],'Enable','on');
    callbackStr='emegs3d(''SaveDataMet1 '')';
    uimenu(hExportSaveDataMenu,'Label','Values at scalp locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet2 '')';
    uimenu(hExportSaveDataMenu,'Label','Values at scalp locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet3 '')';
    uimenu(hExportSaveDataMenu,'Label','Values at sensor locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet4 '')';
    uimenu(hExportSaveDataMenu,'Label','Values at sensor locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet5 '')';
    uimenu(hExportSaveDataMenu,'Label','Values at special scalp locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet6 '')';
    uimenu(hExportSaveDataMenu,'Label','Values at special scalp locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet7 '')';
    uimenu(hExportSaveDataMenu,'Label','Values at special sensor locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet8 '')';
    uimenu(hExportSaveDataMenu,'Label','Values at special sensor locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet9 '')';
    uimenu(hExportSaveDataMenu,'Label','Scalp locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet10'')';
    uimenu(hExportSaveDataMenu,'Label','Scalp locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet11'')';
    uimenu(hExportSaveDataMenu,'Label','Sensor locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet12'')';
    uimenu(hExportSaveDataMenu,'Label','Sensor locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet13'')';
    uimenu(hExportSaveDataMenu,'Label','Special scalp locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet14'')';
    uimenu(hExportSaveDataMenu,'Label','Special scalp locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet15'')';
    uimenu(hExportSaveDataMenu,'Label','Special sensor locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    callbackStr='emegs3d(''SaveDataMet16'')';
    uimenu(hExportSaveDataMenu,'Label','Special sensor locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    
    %==============================================================
    % Menu: Calculate =============================================
    %==============================================================
    hCalcMenu=uimenu('Label','Calculate','ForeGroundColor',[0 0 1],'Enable','on');
    
    %===============ScalpLapCort2Pic==========================
    hCalcSLC2FileMenu=uimenu(hCalcMenu,'Label','Scalp, Lap., Cort. => Pic','Enable','on','Callback', 'emegs3d(''CalcSLC2Pic'')');
    %=============================================
    %===============ScalpLapCort2File==========================
    hCalcSLC2FileMenu=uimenu(hCalcMenu,'Label','Scalp, Lap., Cort. => File','Enable','on','separator','on');
    callbackStr = 'emegs3d(''CalcSLC2FileAll'')';
    hCalcSLC2FileAllMenu=uimenu(hCalcSLC2FileMenu,'Label','Use all original sensors','Callback',callbackStr,'Enable','on');
    callbackStr = 'emegs3d(''CalcSLC2FileGroups'')';
    hCalcSLC2FileGroupsMenu=uimenu(hCalcSLC2FileMenu,'Label','Use predefined sensor groups','Callback',callbackStr,'Enable','on');
    hCalcSLC2FileROIMenu=uimenu(hCalcSLC2FileMenu,'Label','Regions/indices of interest','Enable','off');
    callbackStr = 'emegs3d(''CalcSLC2FileROI'')';
    hCalcSLC2FileUseROIMenu=uimenu(hCalcSLC2FileROIMenu,'Label','Use regions/indices of interest','Callback',callbackStr,'Enable','off');
    callbackStr = 'emegs3d(''ReadROIFile'')';
    hCalcSLCReadROIFileMenu=uimenu(hCalcSLC2FileROIMenu,'Label','Read regions of interest file (*ROI.txt)','Callback',callbackStr,'Enable','off');
    callbackStr = 'emegs3d(''ReadIOIFile'')';
    hCalcSLCReadIOIFileMenu=uimenu(hCalcSLC2FileROIMenu,'Label','Read indices of interest file (*IOI.txt)','Callback',callbackStr,'Enable','off');

    %=============================================
    %===============MinNorm2File==========================
    hCalcMinNorm2FileMenu=uimenu(hCalcMenu,'Label','Minimum Norm  => File','Enable','on');
    if strcmp(EEGMEGStatusString,'MEG')
        callbackStr = 'emegs3d(''CalcNormMagField2File'')';
        hCalcNormMagField2FileMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Save field to sensor configuration','Callback',callbackStr,'Enable','on');
    end
    callbackStr = 'emegs3d(''CalcMinNorm2FileEcfg'')';
    hCalcMinNorm2FileRawMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Save MN to sensor configuration','Callback',callbackStr,'Enable','on','Separator','on');
    callbackStr = 'emegs3d(''CalcMinNorm2FileShell'')';
    hCalcMinNorm2FileShellMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Save MN to actual shell','Callback',callbackStr,'Enable','on');
    callbackStr = 'emegs3d(''CalcMinNorm2FileAnalyse'')';
    hCalcMinNorm2FileShellMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Save MN to Analyse','Callback',callbackStr,'Enable','on');
    callbackStr = 'emegs3d(''CalcMinNorm2FileAll'')';
    hCalcMinNorm2FileAllMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Use all original sensors','Callback',callbackStr,'Enable','on','Separator','on');
    callbackStr = 'emegs3d(''CalcMinNorm2FileGroups'')';
    hCalcMinNorm2FileGroupsMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Use predefined sensor groups','Callback',callbackStr,'Enable','on');
    hCalcMinNorm2FileROIMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Regions/indices of interest','Enable','on','Separator','on');
    callbackStr = 'emegs3d(''CalcMinNorm2FileROI'')';
    hCalcMinNorm2FileUseROIMenu=uimenu(hCalcMinNorm2FileROIMenu,'Label','Use regions/indices of interest','Callback',callbackStr,'Enable','on');
    callbackStr = 'emegs3d(''ReadROIFile'')';
    hCalcMinNormReadROIFileMenu=uimenu(hCalcMinNorm2FileROIMenu,'Label','Read regions of interest file (*ROI.txt)','Callback',callbackStr,'Enable','on');
    callbackStr = 'emegs3d(''ReadIOIFile'')';
    hCalcMinNormReadIOIFileMenu=uimenu(hCalcMinNorm2FileROIMenu,'Label','Read indices of interest file (*IOI.txt)','Callback',callbackStr,'Enable','on');

    %=============================================
    %===============ABSOLUTE=======================
    callbackStr = 'emegs3d(''CalcAbs'')';
    hCalcAbsMenu=uimenu(hCalcMenu,'Label','Absolute','Callback',callbackStr,'Separator','on','Enable','off');
    
    %=============================================
    %===============INVERT=======================+
    callbackStr = 'emegs3d(''CalcInvert'')';
    hCalcInvertMenu=uimenu(hCalcMenu,'Label','Invert','Callback',callbackStr,'Separator','on','Enable','off');
    
    %=============================================
    %===============DIFFERENCE====================
    hCalcDifferenceMenu=uimenu(hCalcMenu,'Label','Difference','Callback',callbackStr,'Separator','on','Enable','off');
    callbackStr = 'emegs3d(''CalcDifference1'')';
    uimenu(hCalcDifferenceMenu,'Label','Actual - File','Callback',callbackStr,'Separator','on','Enable','on');
    callbackStr = 'emegs3d(''CalcDifference2'')';
    uimenu(hCalcDifferenceMenu,'Label','File - Actual','Callback',callbackStr,'Separator','on','Enable','on');
    
     %=============================================
    %===============Repetead Measures Anvoa====================
    hCalcRepMeasAnovaMenu=uimenu(hCalcMenu,'Label','Repeated Measures Anova','Separator','on','Enable','on');
    callbackStr = 'emegs3d(''RepeatedMeasuresDefine'')';
    uimenu(hCalcRepMeasAnovaMenu,'Label','Define','Callback',callbackStr,'Enable','on');
    callbackStr = 'emegs3d(''RepeatedMeasuresReset'')';
    uimenu(hCalcRepMeasAnovaMenu,'Label','Reset','Callback',callbackStr,'Enable','on');
    callbackStr = 'emegs3d(''RepeatedMeasuresCalculate'')';
    hRunAnova=uimenu(hCalcRepMeasAnovaMenu,'Label','Run ANOVA','Callback',callbackStr,'Separator','on','Enable','on','userdata',0);
    callbackStr = 'emegs3d(''ImportAnovaData'')';
    uimenu(hCalcRepMeasAnovaMenu,'Label','Import foreign data','Callback',callbackStr,'Separator','on','Enable','on');
    callbackStr = 'emegs3d(''ExportPointwiseAnova'')';
    uimenu(hCalcRepMeasAnovaMenu,'Label','Write pointwise results to file','Callback',callbackStr,'Separator','on','Enable','on');
    %===============================================
    %============GlobalPower========================
     hCalcRepMeasAnovaMenu=uimenu(hCalcMenu,'Label','Global Power','Separator','on','Enable','on');
    callbackStr = 'emegs3d(''CalcGPGradient'')';
    uimenu(hCalcRepMeasAnovaMenu,'Label','Gradient','Callback',callbackStr,'Enable','on');
    
    
    
    %==============================================================
    % Menu: View ==================================================
    %==============================================================
    hViewMenu=uimenu('Label','View','ForegroundColor',[0 0 1],'Enable','on');
    
    
    %=========== 3d figure navigator=====================
    h3dnavigator=uimenu(hViewMenu,'Label','3d navigator','Enable','on','Callback','fignavigator');
    
    hPlotViewMenu=uimenu(hViewMenu,'Label','2d3d View','ForegroundColor',[0 0 1],'Enable','on');
    callbackStr='emegs3d(''set2d3dView'');';
    uimenu(hPlotViewMenu,'Label','Spec. Surf (3d)','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hPlotViewMenu,'Label','All Surf I (3d)','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hPlotViewMenu,'Label','All Surf II (3d)','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hPlotViewMenu,'Label','Plot (2d)','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hPlotViewMenu,'Label','Spec Right','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    
    hViewHeadViewMenu=uimenu(hViewMenu,'Label','Head View','ForegroundColor',[0 0 1],'Enable','on');
    callbackStr='emegs3d(''setHeadView'');';
    uimenu(hViewHeadViewMenu,'Label','Back     [0, 0]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewHeadViewMenu,'Label','Front    [180, 0]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewHeadViewMenu,'Label','Top      [0, 90]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewHeadViewMenu,'Label','Bottom   [180, -90]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewHeadViewMenu,'Label','Left     [-90, 0]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewHeadViewMenu,'Label','Right    [90, 0]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewHeadViewMenu,'Label','Special','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    
    hPlotSensorsMenu=uimenu(hViewMenu,'Label','Plot Sensors','ForegroundColor',[0 0 1],'Enable','on');
    callbackStr='emegs3d(''setPlotEPos'')';
    uimenu(hPlotSensorsMenu,'Label','Just in the first view','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hPlotSensorsMenu,'Label','In all views','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hPlotSensorsMenu,'Label','Do not plot sensors','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    
    hViewPlotContourMenu=uimenu(hViewMenu,'Label','Plot Contour','ForegroundColor',[0 0 1],'Enable','on');
    callbackStr='emegs3d(''setPlotContour'');';	
    uimenu(hViewPlotContourMenu,'Label','Just in the first view','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewPlotContourMenu,'Label','In all views','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewPlotContourMenu,'Label','Do not plot sensors','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    
    hViewColorMapMenu=uimenu(hViewMenu,'Label','Color Map','ForegroundColor',[0 0 1],'Enable','on');
    callbackStr='emegs3d(''setColorMap'');';
    uimenu(hViewColorMapMenu,'Label','hsv','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewColorMapMenu,'Label','hot','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewColorMapMenu,'Label','cool','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewColorMapMenu,'Label','jet','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewColorMapMenu,'Label','pink','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewColorMapMenu,'Label','flag','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewColorMapMenu,'Label','copper','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    uimenu(hViewColorMapMenu,'Label','gray','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
    
    %==============================================================
    
    
    %==============================================================
    %============================================
    % hPlot3dList(83)
    hTopMenu=[hFileMenu hStyleMenu hExportMenu hCalcMenu hViewMenu];
    
    %==============================================================
    %==============================================================  
    hPlot2dList=get(hPlot2dMenuFig,'Userdata');
    BasePath=get(hPlot2dList(18),'Userdata');
    ActFileNo2d=get(hPlot2dList(1),'Userdata');
    Plot2dNListHdr=get(hPlot2dList(51),'Userdata');
    ActFilePath=get(hPlot2dList(Plot2dNListHdr+(ActFileNo2d-1).*50+4),'Userdata');
    MinAmp=get(hPlot2dList(52),'Value');	MinAmp=round(MinAmp.*1000)./1000;
    set(hMinAmpMenu,'Userdata',MinAmp,'String',sprintf('%2g',MinAmp));
    MaxAmp=get(hPlot2dList(53),'Value');	MaxAmp=round(MaxAmp.*1000)./1000;
    set(hMaxAmpMenu,'Userdata',MaxAmp,'String',sprintf('%2g',MaxAmp));	
    MinPoint=get(hPlot2dList(54),'Value');
    MinPointString=get(hPlot2dList(54),'String');
    set(hMinPointMenu,'Value',MinPoint,'String',MinPointString);
    MaxPoint=get(hPlot2dList(55),'Value');
    MaxPointString=get(hPlot2dList(55),'String');
    set(hMaxPointMenu,'Value',MaxPoint,'String',MaxPointString);
    NPoints=get(hPlot2dList(50),'Userdata');
    NPoints3d=MaxPoint-MinPoint+1;
    NPoints2Plot=NPoints3d;
    CalcAvgMat=get(hPlot2dList(Plot2dNListHdr+(ActFileNo2d-1).*50+1),'Userdata');
    NTrialAvgVec=get(hPlot2dList(Plot2dNListHdr+(ActFileNo2d-1).*50+5),'Userdata');
    StdChanTimeMat=get(hPlot2dList(Plot2dNListHdr+(ActFileNo2d-1).*50+6),'Userdata');
    hDataVec=get(hPlot2dList(Plot2dNListHdr+(ActFileNo2d-1).*50+25),'Userdata');
    NChan=get(hPlot2dList(Plot2dNListHdr+(ActFileNo2d-1).*50+2),'Userdata');
    
    hCustomModel = uicontrol('Visible','off');
    hCalcPotChan=uicontrol('Visible','off');							%50
    hActMethod=uicontrol('Visible','off');								%51
    hTitleNum=uicontrol('Visible','off');								%52
    hCalcPot=uicontrol('Visible','off','Userdata',[]);					%53	
    hData2Analyse=uicontrol('Userdata',CalcAvgMat,'Visible','off');		%54
    hActFilePath=uicontrol('Userdata',ActFilePath,'Visible','off');		%55
    EPosSpher=get(hPlot2dList(3),'Userdata');
    hEPosSpher=uicontrol('Userdata',EPosSpher,'Visible','off');			%56
    [EPosCart]=change_sphere_cart(EPosSpher,1,1);
    hEPosCart=uicontrol('Userdata',EPosCart,'Visible','off');			%57
    set(hCalcMinNorm2FileRawMenu,'Label',['Save MN to sensor configuration (',GetDefEcfgFile(NChan),')']);
    if strcmp(EEGMEGStatusString,'MEG')
        set(hCalcNormMagField2FileMenu,'Label',['Save field to sensor configuration (',int2str(NChan),'.pmg)']);
    end
    %DEFINE RADII OF SHELLS 
    CortRadius = 0.0815; 		%radius of shell 1 (brain or cort)
    CsfRadius=0.0836;			%radius of shell 2 (cerebro-spinal fluid)
    SkullRadius=0.0878; 		%radius of shell 3 (skull)
    ScalpRadius=0.092; 			%radius of shell 4 (scalp)
    
    %SubjRadius=0.094;
    %RadiusFac=SubjRadius/ScalpRadius;
    
    % DEFINE CONDUCTIVITY VARIABLES (ohms * meters)
    ocort=1/3;  				%sigma1 of shell 1 (brain or cort)   = 0.333
    ocsf=3 * ocort;   			%sigma2 of shell 2 (cerebro-spinal fluid)  =1.0
    oskull= ocort / 80;   		%sigma3 of shell 3 (skull) = 1/240 = 0.0042
    oscalp = ocort; 			% sigma4 of shell 4 (scalp) = 0.333
    
    NSqrtScalpLoc=32;
    NScalpLoc=NSqrtScalpLoc.^2;
    [XScalp,YScalp,ZScalp]=sphere(NSqrtScalpLoc-1);
    XScalp=XScalp.*ScalpRadius;
    YScalp=YScalp.*ScalpRadius;
    ZScalp=ZScalp.*ScalpRadius;
    [ScalpLoc]=change_nn_n3(XScalp,YScalp,ZScalp);
    hScalpLoc=uicontrol('Userdata',ScalpLoc,'Visible','off');			%58
    PathLeg=[BasePath 'emegs3dLegCoeff'];
    DipoleRadius=0.04;
    
    hPathLeg=uicontrol('Userdata',PathLeg,'Visible','off');				%59
    PathCoeff=[BasePath 'emegs3dCoeff' int2str(DipoleRadius.*1000)];
    hPathCoeff=uicontrol('Userdata',PathCoeff,'Visible','off');			%60
    ECfgFilePath=get(hPlot2dList(2),'Userdata');
    hECfgFilePath=uicontrol('Userdata',ECfgFilePath,'Visible','off');	%61
    
    ChanVisVec=get(hDataVec,'Visible');
    for ChanInd=1:length(ChanVisVec)
        if strcmp(ChanVisVec(ChanInd,:),'on')
            ChanStatusVec(ChanInd)=1;
        else
            ChanStatusVec(ChanInd)=0;
        end
    end
    hChanStatusVec=uicontrol('Userdata',ChanStatusVec,'Visible','off');		%63
    NUsedChan=length(find(ChanStatusVec==1));
    
    if NUsedChan>200
        InvIter=18;
        ForIter=18;
        PIter=18;
        MSpherical=1;
    elseif NUsedChan>100
        InvIter=15;
        ForIter=15;
        PIter=15;
        MSpherical=2;
    elseif NUsedChan<100 & NUsedChan>60
        InvIter=12;
        ForIter=12;
        PIter=12;
        MSpherical=3;
    else
        InvIter=9;
        ForIter=9;
        PIter=9;
        MSpherical=4;
    end
    
    LengthLegVec=5001;
    
    % DEFINE PARAMETER VECTOR
    
    ParaVec =[CortRadius ocort CsfRadius ocsf SkullRadius, ...
            oskull ScalpRadius oscalp DipoleRadius InvIter, ...
            ForIter PIter MSpherical NSqrtScalpLoc LengthLegVec ...
        NChan NUsedChan NPoints NPoints3d SampRate NPoints2Plot];
        
        hParaVec=uicontrol('Userdata',ParaVec,'Visible','off');						%62
        
        
        hStdChanTimeMat=uicontrol('Userdata',StdChanTimeMat,'Visible','off');	%64
        hStdChanVec=uicontrol('Userdata',sum(StdChanTimeMat')','Visible','off');%65
        
        
        hNTrialAvgVec=uicontrol('Userdata',NTrialAvgVec,'Visible','off');		%70
        PathLFCoeff=[BasePath 'emegs3dInvCoeff'];
        hPathLFCoeff=uicontrol('Userdata',PathLFCoeff,'Visible','off');			%71
        %hUseApprox 															%72
        %hMinBetaApproxText 													%73
        %hMinBetaApproxMenu 													%74
        %hBetaWeightMethodText													%75
        
        %hBetaWeightMethodMenu												%76
        hInvData2Analyse=uicontrol('Userdata',0,'Visible','off');			%77
        hTimePotVec=uicontrol('Userdata',0,'Visible','off');				%78
        %'Back     [0, 0]|Front    [180, 0]|Top  [0, 90]|Bottom  [180, -90]|Left       [-90, 0]|Right     [90, 0]';
        ViewVec=[0 0;180 0;0 90;180 -90;-90 0;90 0;45 70;0 0;0 0;0 0;0 0;180 0;0 90;180 -90;-90 0;90 0;45 70;0 0];
        hViewVec=uicontrol('Userdata',ViewVec,'Visible','off');				%79
        hInverseRadiusVec=uicontrol('Userdata',[.08 .06 .04],'Visible','off');	%80
        
        hLeadLoc=uicontrol('Userdata',0,'Visible','off');					%81
        hLeadLocShell=uicontrol('Userdata',0,'Visible','off');				%82
        hhTopMenu=uicontrol('Userdata',hTopMenu,'Visible','off'); 			%83
        hChanStatusVecOld=uicontrol('Userdata',ChanStatusVec,'Visible','off');%90
        
        hMinNormXMat=uicontrol('Userdata',[],'Visible','off'); 				%91
        hMinNormYMat=uicontrol('Userdata',[],'Visible','off'); 				%92
        hMinNormZMat=uicontrol('Userdata',[],'Visible','off'); 				%93
        
        hCalcMinNorm2File=uicontrol('Value',0,'Visible','off'); 			%96
        hMNPILFCoeff=uicontrol('Visible','off'); 							%97
        hMNInvCoeff=uicontrol('Visible','off'); 							%98
        hMNForCoeff=uicontrol('Visible','off'); 							%99
        hFileMat=uicontrol('Visible','off'); 								%100
        
        hCalcSLC2File=uicontrol('Value',0,'Visible','off'); 				%101
        hSLCInvCoeff=uicontrol('Visible','off'); 							%102
        hSLCForCoeff=uicontrol('Visible','off'); 							%103
        hSLCForChanCoeff=uicontrol('Visible','off'); 						%104
        %NoUse													            %105
        
        hScalpLocIndVec=uicontrol('Visible','off'); 						%106
        hROIFile=uicontrol('Visible','off'); 								%107
        
        
        hSaveStatsDefPath=uicontrol('Visible','off'); 						%110
        hNWinText=0;
        hNWinMenu=uicontrol('Visible','off','Userdata',[1 1]); 				%114
        hBatchFileDefPath=uicontrol('Visible','off'); 						%115
        
        hAnovaData = uicontrol('Visible','off');                            %133
        
        
        %CalcCoeffs for all cases
        %===============================
        InvIter=18;
        ForIter=18;
        PIter=18;
        MSpherical=1;
        ExistCalcCoeff(InvIter,0,PIter,MSpherical,LengthLegVec,PathLeg,ParaVec);
        InvIter=15;
        ForIter=15;
        PIter=15;
        MSpherical=2;
        ExistCalcCoeff(InvIter,0,PIter,MSpherical,LengthLegVec,PathLeg,ParaVec);
        InvIter=12;
        ForIter=12;
        PIter=12;
        MSpherical=3;
        ExistCalcCoeff(InvIter,0,PIter,MSpherical,LengthLegVec,PathLeg,ParaVec);
        InvIter=9;
        ForIter=9;
        PIter=9;
        MSpherical=4;
        ExistCalcCoeff(InvIter,0,PIter,MSpherical,LengthLegVec,PathLeg,ParaVec);
         
        if NUsedChan>200
            InvIter=18;
            ForIter=18;
            PIter=18;
            MSpherical=1;
        elseif NUsedChan>100
            InvIter=15;
            ForIter=15;
            PIter=15;
            MSpherical=2;
        elseif NUsedChan<100 & NUsedChan>60
            InvIter=12;
            ForIter=12;
            PIter=12;
            MSpherical=3;
        else
            InvIter=9;
            ForIter=9;
            PIter=9;
            MSpherical=4;
        end
    
        %====================================
        NoUse=0;
        
        hPlot3dList=[hCortMapMethodText hCortMapMethodMenu NoUse NoUse hSaveDataText ... 
            hSaveDataMenu hAllFigViewMenu NoUse hReadPlotText hReadPlotMenu ...
            h2d3dViewText h2d3dViewMenu hHeadViewText hHeadViewMenu hThetaViewText ...
            hThetaViewMenu hPhiViewText hPhiViewMenu hColorMapText hColorMapMenu ...
            hMinAmpText hMinAmpMenu hMaxAmpText hMaxAmpMenu hCenterAmp ...								%25
            hSpecAmp hPrint2FileStatus hMoviePause hPlotEPosText hPlotEPosMenu ...							
            hMinNormMethodText hMinNormMethodMenu hApply hPlotContourText hPlotContourMenu ...
            hPrintFileCompText hPrintFileCompMenu hSave2PlotText hSave2PlotMenu hDistPointText ...
            hDistPointMenu hPlotLatencyText hPlotLatencyMenu hCalcDistPointMeanMenu hAutoAmp ...
            hMinPointText hMinPointMenu hMaxPointText hMaxPointMenu hCalcPotChan ...					%50
            hActMethod hTitleNum hCalcPot hData2Analyse hActFilePath ...
            hEPosSpher hEPosCart hScalpLoc hPathLeg hPathCoeff ...
            hECfgFilePath hParaVec hChanStatusVec hStdChanTimeMat hStdChanVec ...
            hUseApproxVec hUseApproxMat hSLCLambdaApproxText hSLCLambdaApproxMenu hNTrialAvgVec ...
            hPathLFCoeff hUseApprox hMinBetaApproxText hMinBetaApproxMenu hBetaWeightMethodText ...		%75
            hBetaWeightMethodMenu hInvData2Analyse hTimePotVec hViewVec hInverseRadiusVec ...
            hLeadLoc hLeadLocShell hhTopMenu hPlotSurfStatus hChanStatusVecOld ...
            hActFileNoText hActFileNoMenu hPrint2FileMethodText hPrint2FileMethod hCalcDistPointMNMeanMenu ...
            hMinNormXMat hMinNormYMat hMinNormZMat hQuiverText hQuiverMenu ...
            hCalcMinNorm2File hMNPILFCoeff hMNInvCoeff hMNForCoeff hFileMat ...							%100
            hCalcSLC2File hSLCInvCoeff hSLCForCoeff hSLCForChanCoeff hAbsMinNormSurfMenu  ...
            hScalpLocIndVec hROIFile hMNLambdaApproxText hMNLambdaApproxMenu hSaveStatsDefPath ...
            hSpecTaskText hSpecTaskMenu hNWinText hNWinMenu hBatchFileDefPath ...
            hNRowColorMapText hNRowColorMapMenu hFlipColormap hGrayFitMenu hColorAmpTot ...             %120
            hNDistIntText hNDistIntMenu hGrayFitText hCalcMNLambdaApproxMenu NoUse ...	                %125
            hCutRealBotText hCutRealBotMenu hHeadModelText hHeadModelMenu hPotContourText ...           %130
            hPotContourMenu hCalcRepMeasAnovaMenu hAnovaData NoUse hPEditAmp ...
            hP90Amp hP95Amp hP99Amp hPPlusMinusAmp hCustomModel ...                                     %140
            hSetActFileNo1 hSetActFileNo2 hSetActFileNo3 hSetActFileNo4 hSetActFileNo5 ...
            hSetActFileNo6 hRunAnova  NoUse NoUse NoUse];                      %150                                 %150
            
            set(hPlot3dMenuFig,'Visible','on','UserData',hPlot3dList);
            emegs3d('setHandleActFileNo')
            emegs3d('setActFileNo')
            emegs3d('setMinMaxAmpString')
            if NPoints3d>10
                set(hNDistIntMenu,'String',10);
            else
                set(hNDistIntMenu,'String',int2str(NPoints3d));
                set(h2d3dViewMenu,'Value',3); %All Surf II (3d)
            end
            emegs3d('setNDistInt')
            pause(1)
            %close(hPlot3dStartMsg);
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        
        elseif  strcmp(action,'set2d3dView')
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            View2d3d=get(hPlot3dList(12),'Value');
            if View2d3d<4
                set(hPlot3dList(30),'Value',2);			%hPlotEPosMenu In all views
                set(hPlot3dList(122),'String','1');	    %hNDistIntMenu
                emegs3d('setNDistInt');
            elseif View2d3d==6 %Columns & Rows
                set(hPlot3dList(30),'Value',1);			%hPlotEPosMenu Just in first view
                emegs3d('setNDistInt');
            end
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif  strcmp(action,'setSpecTask')
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            SpecTaskNo=get(hPlot3dList(112),'Value');
            
            if SpecTaskNo<4
                if SpecTaskNo==1 | SpecTaskNo==3
                    set(hPlot3dList(114),'Userdata',[4 1]);	%hNWinMenu
                    set(hPlot3dList(14),'Value',1);			%hHeadViewMenu %Back
                    emegs3d('setHeadView');
                    emegs3d('CalcCortMap');pause(.1);
                    set(hPlot3dList(114),'Userdata',[4 2]);	%hNWinMenu
                    set(hPlot3dList(14),'Value',2);			%hHeadViewMenu %Front
                    emegs3d('setHeadView');
                    emegs3d('PlotSurfData');pause(.1);
                end
                if SpecTaskNo==2 | SpecTaskNo==3
                    set(hPlot3dList(114),'Userdata',[4 3]);	%hNWinMenu
                    set(hPlot3dList(14),'Value',1);			%hHeadViewMenu %Back
                    emegs3d('setHeadView');
                    emegs3d('CalcMinimumNorm');pause(.1);
                    set(hPlot3dList(114),'Userdata',[4 4]);	%hNWinMenu
                    set(hPlot3dList(14),'Value',2);			%hHeadViewMenu %Front
                    emegs3d('setHeadView');
                    emegs3d('PlotSurfData');pause(.1); 	
                end
                set(hPlot3dList(114),'Userdata',[1 1]);		%hNWinMenu
            elseif SpecTaskNo>3 &  SpecTaskNo<7
                if SpecTaskNo==4 | SpecTaskNo==6
                    set(hPlot3dList(114),'Userdata',[4 1]);	%hNWinMenu
                    set(hPlot3dList(14),'Value',5);			%hHeadViewMenu %Left
                    emegs3d('setHeadView');
                    emegs3d('CalcCortMap');pause(.1);
                    set(hPlot3dList(114),'Userdata',[4 2]);	%hNWinMenu
                    set(hPlot3dList(14),'Value',6);			%hHeadViewMenu %Right
                    emegs3d('setHeadView');
                    emegs3d('PlotSurfData');pause(.1);
                end
                if SpecTaskNo==5 | SpecTaskNo==6
                    set(hPlot3dList(114),'Userdata',[4 3]);	%hNWinMenu
                    set(hPlot3dList(14),'Value',5);			%hHeadViewMenu %Left
                    emegs3d('setHeadView');
                    emegs3d('CalcMinimumNorm');pause(.1);
                    set(hPlot3dList(114),'Userdata',[4 4]);	%hNWinMenu
                    set(hPlot3dList(14),'Value',6);			%hHeadViewMenu %Right
                    emegs3d('setHeadView');
                    emegs3d('PlotSurfData');pause(.1); 	
                end
                set(hPlot3dList(114),'Userdata',[1 1]);		%hNWinMenu
            elseif SpecTaskNo>6 &  SpecTaskNo<9
                hPlot2dList=get(hPlot2dMenuFig,'Userdata'); 
                FileNoVec=get(hPlot2dList(56),'Userdata');
                NFileNoVec=length(FileNoVec);	
                for Index=1:NFileNoVec
                    set(hPlot3dList(114),'Userdata',[NFileNoVec Index]);	%hNWinMenu
                    set(hPlot3dList(87),'Value',Index);					%ActFileNo3d
                    emegs3d('setActFileNo');
                    if SpecTaskNo==7
                        emegs3d('CalcCortMap');
                    elseif SpecTaskNo==8
                        emegs3d('CalcMinimumNorm');
                    end
                    pause(.1); 
                end
                set(hPlot3dList(114),'Userdata',[1 1]);		%hNWinMenu          
           elseif SpecTaskNo==9 | SpecTaskNo==10 | SpecTaskNo==11 | SpecTaskNo==12  | SpecTaskNo==13  | SpecTaskNo==14
                if SpecTaskNo==9 | SpecTaskNo==12
                    set(hPlot3dList(129),'Value',2); %HeadModel Realistic
                elseif SpecTaskNo==10 | SpecTaskNo==13
                    set(hPlot3dList(129),'Value',5); %HeadModel Brain Low Smooth
                elseif SpecTaskNo==11 | SpecTaskNo==14
                    set(hPlot3dList(129),'Value',7); %HeadModel Brain Low Smooth
                end
                emegs3d('setHeadModel');
                set(hPlot3dList(14),'Value',1);  %HeadView Back
                emegs3d('setHeadView');
                if SpecTaskNo==9 | SpecTaskNo==10 | SpecTaskNo==11
                    set(hPlot3dList(12),'Value',5);  %View2d3d Head View
                elseif SpecTaskNo==12 | SpecTaskNo==13 | SpecTaskNo==14
                    set(hPlot3dList(12),'Value',6);  %View2d3d Cols and Rows
                end
                emegs3d('setView2d3d');
                set(hPlot3dList(30),'Value',3); %Do not plot Sensors
            else
                return;
            end 
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif  strcmp(action,'SetQuiverStatus') | strcmp(action,'SetAbsMinNormSurfStatus') 
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            QuiverStatus=get(hPlot3dList(95),'Value');
            AbsMinNormSurfStatus=get(hPlot3dList(105),'Value');
            if QuiverStatus==0 & AbsMinNormSurfStatus==0
                if strcmp(action,'SetQuiverStatus')
                    set(hPlot3dList(105),'Value',1);
                else
                    set(hPlot3dList(95),'Value',1);
                end
            end
   
       %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
       elseif  strcmp(action,'Closeemegs3dMenuFig')

            try
                figposition = get(hPlot3dMenuFig,'position');
                utilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs3dfigpos.mat');
                save(utilpath,'figposition');
                delete(hPlot3dMenuFig);
            catch
                delete(gcf);
            end  

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif  strcmp(action,'OpenFileMatrix') 
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            hTopMenu=get(hPlot3dList(83),'Userdata');
            hFileMenuVec=get(hTopMenu(1),'children');
            hFileMenu = get(hFileMenuVec(2),'children');
            UseFileMatStatus=get(hFileMenu(1),'Userdata');
            BatchFileDefPath=get(hPlot3dList(115),'Userdata');
            if isempty(BatchFileDefPath)
                [BatchFileDefPath]=SetDefPath(1);
            end	
            BatchFileDefPath=SwitchGrandBatch(BatchFileDefPath,'Grand2Batch',1);
            FileMask=['*.rep'];
            [NFiles,FileMat,NonUse,BatchFilePath]=ReadFileNames([],[BatchFileDefPath,FileMask],'Please choose file(s):');
            if NFiles==0; return; end
            [BatchFile,BatchPath]=SepFilePath(BatchFilePath);
            set(hPlot3dList(115),'Userdata',BatchPath);
            set(hPlot3dList(100), 'Value',NFiles,'Userdata',FileMat);
            set(hFileMenu(3),'Enable','on'); %SaveFileMat
            set(hFileMenu(2),'Enable','on')	%AddFileName2FileMat
            set(hFileMenu(1),'Enable','on')	%UseFileMat
            if UseFileMatStatus==0; 
                emegs3d('UseFileMatrix')
                Message=char('Set "Use File Matrix" status "on".');
                hPlot3dStartMsg=msgbox(Message,'Info','help'); 
                hPlot3dStartMsgChild=get(hPlot3dStartMsg,'Children');
                set(hPlot3dStartMsgChild(length(hPlot3dStartMsgChild)),'Visible','off');
                pause(1)
                close(hPlot3dStartMsg)
            else
                emegs3d('FileMatrixInfo')
            end
            
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif  strcmp(action,'SaveFileMatrix') 
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            FileMat=get(hPlot3dList(100),'Userdata')
            NFiles=get(hPlot3dList(100),'Value');
            emegs3d('FileMatrixInfo')
            [SaveFile,SavePath,SaveFilePath]=WriteFilePath('FileMatrix.txt','Save file matrix to file:');
            if SaveFile==0; return; end
            fid=fopen(SaveFilePath,'w','b');
            for FileIndex=1:NFiles
                fprintf(fid,[FileMat(FileIndex,:),'\n']);
            end
            fclose(fid);
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif  strcmp(action,'AddFile2FileMatrix') 
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            FileMatOld=get(hPlot3dList(100),'Userdata')
            NFilesOld=get(hPlot3dList(100),'Value');
            [NFiles,FileMat]=ReadFileNames([],'*','Please choose file(s) to add:');
            if NFiles==0; return; end
            NFiles=NFiles+NFilesOld;
            FileMat=char(FileMatOld,FileMat);
            set(hPlot3dList(100),'Userdata',FileMat,'Value',NFiles);
            emegs3d('FileMatrixInfo')
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif  strcmp(action,'UseFileMatrix') 
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata'); 
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            hTopMenu=get(hPlot3dList(83),'Userdata');
            hFileMenu=get(hTopMenu(1),'children');
            Pointer=get(hPlot2dList(83),'Userdata');
            UseFileMatrixLabel=get(hFileMenu(1),'Label');
            UseFileMatStatus=get(hFileMenu(1),'Userdata');
            if UseFileMatStatus==1; 
                UseFileMatStatus=0;
                PointPosEnd=length(UseFileMatrixLabel)-3;
                UseFileMatrixLabel=UseFileMatrixLabel(1:PointPosEnd);
            else
                UseFileMatStatus=1;
                UseFileMatrixLabel=[UseFileMatrixLabel,'  ',setstr(Pointer)];
                emegs3d('FileMatrixInfo')
            end
            set(hFileMenu(1),'Label',UseFileMatrixLabel,'Userdata',UseFileMatStatus)
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif  strcmp(action,'FileMatrixInfo') 
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            FileMat=get(hPlot3dList(100),'Userdata')
            NFiles=get(hPlot3dList(100),'Value');
            fprintf(1,'\n'); clc;
            if NFiles==1
                Message=char(['The actual file matrix contains the following file:']);
                fprintf(1,'The actual file matrix contains the following file:\n\n');
            else
                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);
            end
            Message=char(Message,' ');
            Message=char(Message,FileMat);
            Message=char(Message,'');
            Message=char(Message,['Total number of files: ',int2str(NFiles)]);
            hmsgbox=msgbox(Message,'Info','help'); 
            set(hmsgbox,'Units','Normal');
            MsgBoxPos=get(hmsgbox,'Position');
            MsgBoxPos(1:2)=[0.1 0]
            set(hmsgbox,'Position',MsgBoxPos);
	        pause(.001)
            disp(FileMat)
    
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'ReadROIFile') | strcmp(action,'ReadIOIFile')
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            if strcmp(action,'ReadROIFile')
                OIDefPath=which('LB-RB-LF-RF-ROI.txt')
                OIStr='ROI';
            elseif strcmp(action,'ReadIOIFile')
                OIDefPath=which('LB-RB-LF-RF-MN7-IOI.txt')
                OIStr='IOI';
            end
            IndSepPathVec=findstr(OIDefPath,filesep);
            if ~isempty(IndSepPathVec)	
                OIDefPath=OIDefPath(1:IndSepPathVec(length(IndSepPathVec)));
                OIDef=[OIDefPath,'*',OIStr,'.txt'];
            else
                OIDef=['*',OIStr,'.txt'];
            end
            [OIFile,OIPath]=uigetfile(OIDef,['Open ',OIStr,' file (*',OIStr,'.txt):']);
            OIFilePath=[OIPath,OIFile];
            if OIFile==0; return; end
            OIMat=ReadAscii(OIFilePath);
            [NOI,Def4]=size(OIMat);
            if strcmp(action,'ReadROIFile') 
                if Def4~=4
                    Message=char('Sorry,wrong ROI file format !');
                    Message=char(Message,'');
                    Message=char(Message,'Please use ');
                    Message=char(Message,'"LB-RB-LF-RF-ROI.txt"');
                    Message=char(Message,'as an example.');
                    hmsgbox=msgbox(Message,'Info','help'); 
                    return
                end
                Message=char(['Read the following ',int2str(NROI),' regions of interest:']);
                Message=char(Message,'');
                for OIInd=1:NOI
                   Message=char(Message,['Region # ',int2str(OIInd)]);
                   Message=char(Message,['Theta: ', sprintf('%g',OIMat(OIInd,1)),'; Phi: ', sprintf('%g',OIMat(OIInd,2)),'; Radius: ', sprintf('%g',ROIMatSpherDeg(ROIInd,3)),'; Extension: ', sprintf('%g',ROIMatSpherDeg(ROIInd,4))]);
                    Message=char(Message,'');
                end
            elseif strcmp(action,'ReadIOIFile')
                for OIInd=1:NOI
                    OIVec=find(OIMat(OIInd,:)~=0);
                    OIVec=OIMat(OIInd,OIVec);
                    Message=char(Message,['Region # ',int2str(OIInd),'; Number of Sensors/Dipoles: ',int2str(length(OIVec))]);
                    Message=char(Message,['Sensor/Dipole #: ',int2str(OIVec)]);
                    Message=char(Message,'');
                end
            end
            hmsgbox=msgbox(Message,'Info','help'); 
            set(hPlot3dList(107),'Value',NOI,'Userdata',OIMat,'String',OIStr);
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif	strcmp(action,'CalcSLC2FileAll') | ...
                strcmp(action,'CalcSLC2FileGroups') | ...
                strcmp(action,'CalcSLC4AnovaGroups') | ...
                strcmp(action,'CalcSLC4AnovaAll') | ...
                strcmp(action,'CalcSLC2FileROI') | ...
                strcmp(action,'CalcNormMagField2File') | ...
                strcmp(action,'CalcMinNorm2FileEcfg') | ...
                strcmp(action,'CalcMinNorm2FileShell') | ...
                strcmp(action,'CalcMinNorm2FileAnalyse') | ...
                strcmp(action,'CalcMinNorm2FileAll') | ...
                strcmp(action,'CalcMinNorm2FileGroups') | ...
                strcmp(action,'CalcMinNorm2FileROI') | ...
                strcmp(action,'CalcSLC2Pic')
            
           
            hPlot2dList=get(hPlot2dMenuFig,'Userdata'); 
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            
%             try
                
                if  strcmp(action,'CalcSLC4AnovaGroups') | strcmp(action,'CalcSLC4AnovaAll')
                    set(hPlot3dList(132),'Userdata',1);
                end

                if strcmp(action,'CalcSLC2Pic')
                       prompt={'Enter the number of subjects:','Enter the number of conditions:'};
                       name='Input for batch plotting';
                       numlines=1;
                       defaultanswer={'20','3'};
                       batchplotdefaultspath = strrep(which('emegs3d.m'),'emegs3d.m','batchplotdefaults.mat');
                       if exist(batchplotdefaultspath)==2
                            load(batchplotdefaultspath,'answer');
                            defaultanswer = answer;
                       end
                       try
                            answer=inputdlg(prompt,name,numlines,defaultanswer);
                       catch
                            defaultanswer={'20','3'};
                            answer=inputdlg(prompt,name,numlines,defaultanswer);
                       end
                       if isempty(answer)
                           return
                       end
                       try
                           versionstring = version;
                           if str2num(versionstring(1))>6
                                save(batchplotdefaultspath,'answer','-V6');
                           else
                                save(batchplotdefaultspath,'answer');
                           end
                       catch
                       end
                        
                       BatchPlotNSubjects = str2num(answer{1});
                       BatchPlotNConditions = str2num(answer{2});
                       ScaleOpt = questdlg('Do you wish global scaling or subject scaling (maximal 6 conditions)?','Scaling:','global','subject','subject');
                       ScaleCount = BatchPlotNConditions;
                end


                EEGMEGStatusString=get(hPlot2dList(110),'String');
                if strcmp(EEGMEGStatusString,'EEG'); EegMegStatus=1; elseif strcmp(EEGMEGStatusString,'MEG'); EegMegStatus=2; end
                if strcmp(action,'CalcMinNorm2FileROI') | strcmp(action,'CalcSLC2FileROI')
                    ROIMatSpherDeg=get(hPlot3dList(107),'Userdata');
                    NROI=get(hPlot3dList(107),'Value');
                    OIStr=get(hPlot3dList(107),'String');
                    if isempty(ROIMatSpherDeg)
                        emegs3d('ReadROIFile');
                        ROIMatSpherDeg=get(hPlot3dList(107),'Userdata');
                        NROI=get(hPlot3dList(107),'Value');
                    end
                end
                hTopMenu=get(hPlot3dList(83),'Userdata');
                hFileMenuVec=get(hTopMenu(1),'children');
                hFileMenu = get(hFileMenuVec(2),'children');
                if strcmp(get(hFileMenu(2),'Enable'),'on')
                    UseFileMatStatus=1;
                else
                    UseFileMatStatus=0;
                end

                PicCell = cell(1);
                MinPoint=get(hPlot3dList(47),'Value');
                MaxPoint=get(hPlot3dList(49),'Value');
                CalcBaseStatus=get(hPlot2dList(57),'Value'); 
                MinBase=get(hPlot2dList(58),'Value');
                MaxBase=get(hPlot2dList(59),'Value');
                ParaVec=get(hPlot3dList(62),'Userdata');
                ScalpRadius=ParaVec(7);
                NChan=ParaVec(16);
                NPoints2d=ParaVec(18);
                SampRate=ParaVec(20);
                DistPointMsString=get(hPlot3dList(41),'String');
                DistPointMeanStatus=get(hPlot3dList(44),'Value');
                MsHzMinPointString = get(hPlot3dList(47),'String');
                MsHzMaxPointString = get(hPlot3dList(49),'String');
                TrigPoint=get(hPlot2dList(22),'Value');
                SLCLambdaApprox=get(hPlot3dList(69),'Value');
                MNLambdaApprox=get(hPlot3dList(109),'Value');
                Plot2dActFileNo=get(hPlot2dList(1),'Userdata');
                Plot2dNListHdr=get(hPlot2dList(51),'Userdata');
                Plot2dFileNoVec=get(hPlot2dList(56),'Userdata');
                Plot2dAvgFileFormat=get(hPlot2dList(Plot2dNListHdr+(Plot2dActFileNo-1).*50+22),'Userdata');
                UseApp=get(hPlot3dList(72),'Value');
                DistPointVec=get(hPlot3dList(41),'Userdata');
                DistPoint=DistPointVec(1);
                MsPerPoint=DistPointVec(2);
                SaveStatsDefPath=get(hPlot3dList(110),'Userdata');

                TempFiltStruc=get(hPlot2dList(134),'Userdata');
                SpatFiltStruc=get(hPlot2dList(135),'Userdata');
                if isempty(TempFiltStruc); TempFiltStatus=0; else; TempFiltStatus=1; end
                if isempty(SpatFiltStruc); SpatFiltStatus=0; else; SpatFiltStatus=1; end
                CalcGradStatus=get(findobj('Tag','CalcGradClear'),'Userdata');
                CalcAbsStatus=get(findobj('Tag','CalcAbsClear'),'Userdata');

                if strcmp(action,'CalcMinNorm2FileAnalyse')
                    set(hPlot3dList(32),'Value',7); %4 Shells, All Shells
                end   
                if strcmp(action,'CalcMinNorm2FileEcfg') | ...
                        strcmp(action,'CalcMinNorm2FileShell') | ...
                        strcmp(action,'CalcMinNorm2FileAnalyse') | ...
                        strcmp(action,'CalcMinNorm2FileAll') | ...
                        strcmp(action,'CalcMinNorm2FileGroups') | ...
                        strcmp(action,'CalcMinNorm2FileROI')


                    ShellNumber = get(hPlot3dList(32),'Value');
                    SLCMethodShellNumber=ShellNumber;
                    set(hPlot3dList(97),'Userdata',[]);
                    set(hPlot3dList(98),'Userdata',[]);
                    set(hPlot3dList(99),'Userdata',[]);
                    if strcmp(action,'CalcMinNorm2FileEcfg') | strcmp(action,'CalcMinNorm2FileShell')
                        set(hPlot3dList(47),'Value',1);			  %MinPoint
                        emegs3d('setMinPointString');
                        set(hPlot3dList(49),'Value',NPoints2d);   %MaxPoint 
                        emegs3d('setMaxPointString');
                    end                
                else
                    SLCMethod = get(hPlot3dList(2),'Value');  	  %'Scalp|Lap|Cort|Perrin Scalp|Perrin Lap';
                    SLCMethodShellNumber=SLCMethod;
                    set(hPlot3dList(102),'Userdata',[]);
                    set(hPlot3dList(103),'Userdata',[]);
                end
                if strcmp(action,'CalcSLC2FileGroups') | strcmp(action,'CalcMinNorm2FileGroups') | strcmp(action,'CalcSLC4AnovaGroups')

                    hTopMenu=get(hPlot2dList(65),'Userdata');
                    hCalcMenu=get(hTopMenu(4),'children');	
                    hCalcChanGroup=hCalcMenu(17);
                    GroupMat=get(hCalcChanGroup,'Userdata');
                    if isempty(GroupMat)
                        Message=char('Sorry, no groups selected !');
                        Message=char(Message,'');
                        Message=char(Message,'Please select them using the Plot2d top menu !');
                        Message=char(Message,'(Calculate : Channel groups : OpenGroup file)');
                        hmsgbox=msgbox(Message,'Info','help'); 
                        return;
                    end
                    if any(GroupMat(2,:)>NChan) | any(GroupMat(2,:)<1)
                        Message=char('Sorry, ');
                        Message=char(Message,'the selected groups contain sensor numbers');
                        Message=char(Message,'which are inconsistent with the data set !');
                        hmsgbox=msgbox(Message,'Info','help'); 
                        return;
                    end
                    NGroup=0;
                    GroupIndVec=[];
                    for GroupInd=min(GroupMat(1,:)):max(GroupMat(1,:))
                        GroupIndVec=find(GroupMat(1,:)==GroupInd);
                        if ~isempty(GroupIndVec)
                            NGroup=NGroup+1;
                            GroupNoVec(NGroup)=GroupInd;
                        end
                    end
                end
                if UseFileMatStatus
                    FileMat=get(hPlot3dList(100),'Userdata');
                    NFiles=get(hPlot3dList(100),'Value')
                else
                    NFiles=length(Plot2dFileNoVec);
                end
                if strcmp(action,'CalcMinNorm2FileEcfg') | ...
                        strcmp(action,'CalcMinNorm2FileShell') | ...
                        strcmp(action,'CalcMinNorm2FileAnalyse') | ...
                        strcmp(action,'CalcMinNorm2FileAll') | ...
                        strcmp(action,'CalcMinNorm2FileGroups') | ...
                        strcmp(action,'CalcMinNorm2FileROI')

                    Message=char('');
                    Message=char(Message,'');
                    Message=char(Message,'Please remember: Calculation of L2-Minimum-Norm,');
                    Message=char(Message,'depends on the chosen shell(s) and the lambda approximation value(s) ! ');
                    Message=char(Message,'');
                    Message=char(Message,'The actual values are:');
                    Message=char(Message,['Shell:                ',int2str(ShellNumber)]);
                    if UseApp
                        Message=char(Message,['SLC Lambda:  ',num2str(SLCLambdaApprox)]);
                        Message=char(Message,['Min. Norm Lambda:  ',num2str(MNLambdaApprox)]);
                    else
                        Message=char(Message,'No approximation used.');
                    end
                    Message=char(Message,' ');
                    if UseFileMatStatus
                        Message=char(Message,'Calculate L2-Minimum-Norm using files given in file matrix.');
                    else
                        Message=char(Message,'Calculate L2-Minimum-Norm using data sets given in Plot2d.');	
                    end
                else
                    Message=char(' ');
                    if SLCMethod==1
                        SLCString='Scalp';
                        Message=char(Message,'Please remember: Calculation of the "Scalp Potential"');
                    elseif SLCMethod==2
                        SLCString='Laplacian';
                        Message=char(Message,'Please remember: Calculation of the "Laplacian"');
                    elseif SLCMethod==3
                        SLCString='Cort';
                        Message=char(Message,'Please remember: Calculation of the "Intracranial Potential Estimation"');
                    elseif SLCMethod==4
                        SLCString='PerrinScalp';
                        Message=char(Message,'Please remember: Calculation of the "Perrin Scalp Potential"');
                    elseif SLCMethod==5
                        SLCString='PerrinLaplacian';
                        Message=char(Message,'Please remember: Calculation of the "Perrin Laplacian"');
                    end
                    Message=char(Message,'depends on the chosen lambda approximation value ! ');
                    Message=char(Message,' ');
                    if UseApp
                        Message=char(Message,['The actual lambda approximation value is:  ',num2str(SLCLambdaApprox)]);
                    else
                        Message=char(Message,'No approximation used.');
                    end
                    Message=char(Message,' ');
                    if DistPoint>1 	& DistPointMeanStatus
                        Message=char(Message,'You calculate the mean across intervals !');
                        Message=char(Message,'Please remember that this calculation acts');
                        Message=char(Message,'prior to the root mean square calculation !');
                        Message=char(Message,' ');
                    end
                    if UseFileMatStatus
                        Message=char(Message,['Files of file matrix.']);
                    else
                        Message=char(Message,['Data sets of Plot2d.']);
                    end
                end
                Message=char(Message,' ');
                if ~strcmp(action,'CalcMinNorm2FileAnalyse')
                    Message=char(Message,'Please choose a file name to export the calculated data.');
                end
                Message=char(Message,' ');
                hGlobalMsgbox=msgbox(Message,'Info','help'); 
                hReminderMsgbox = hGlobalMsgbox;
                set(hGlobalMsgbox,'Units','Normal','Position',[.325 .175 .35 .225]);
                hChildMsgbox=get(hGlobalMsgbox,'Children');
                set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                if NFiles==0; return; end
                if strcmp(action,'CalcMinNorm2FileEcfg') | ...
                        strcmp(action,'CalcMinNorm2FileShell') | ...
                        strcmp(action,'CalcMinNorm2FileAnalyse') | ...
                        strcmp(action,'CalcMinNorm2FileAll') | ...
                        strcmp(action,'CalcMinNorm2FileGroups') | ...
                        strcmp(action,'CalcMinNorm2FileROI')

                    if strcmp(action,'CalcMinNorm2FileAll')	| strcmp(action,'CalcMinNorm2FileGroups')	
                        set(hPlot3dList(96),'Value',1);			
                    elseif strcmp(action,'CalcMinNorm2FileROI')
                        set(hPlot3dList(96),'Value',2);			
                    elseif strcmp(action,'CalcMinNorm2FileEcfg')
                        set(hPlot3dList(96),'Value',3);		
                    elseif strcmp(action,'CalcMinNorm2FileShell')
                        set(hPlot3dList(96),'Value',4);	
                    elseif strcmp(action,'CalcMinNorm2FileAnalyse')
                        set(hPlot3dList(96),'Value',5);	
                    end
                    if ~strcmp(action,'CalcMinNorm2FileEcfg') & ~strcmp(action,'CalcMinNorm2FileShell') & ~strcmp(action,'CalcMinNorm2FileAnalyse')
                        [SaveFile,SavePath,SaveFilePath]=WriteFilePath('MN.txt','Export calculated data to file:');
                    end


                else
                    if  strcmp(action,'CalcSLC2Pic')
                        set(hPlot3dList(101),'Value',1);	%CalcSLC2File
                        [SaveFile,SavePath,SaveFilePath]=WriteFilePath(['SubjectsPlot.jpg'],'Export calculated data to image:');
                    elseif ~strcmp(action,'CalcSLC4AnovaGroups') & ~strcmp(action,'CalcSLC4AnovaAll')
                        set(hPlot3dList(101),'Value',1);	%CalcSLC2File
                        [SaveFile,SavePath,SaveFilePath]=WriteFilePath([SLCString '.txt'],'Export calculated data to file:');
                    elseif strcmp(action,'CalcSLC4AnovaGroups') 
                        SavePath = which('emegs3d.m');
                        SaveFile = 'anovaexporttmp.txt';
                        SaveFilePath =[SavePath(1:end-9) SaveFile];
                    elseif strcmp(action,'CalcSLC4AnovaAll')
                        AnovaData = [];
                        SavePath = which('emegs3d.m');
                        SaveFile = 'anovaexporttmp.mat';
                        DesignFilePath = [SavePath(1:end-9),'anovaexportdesign.mat']
                        SaveFilePath =[SavePath(1:end-9) SaveFile];
                    end
                end

                %close(hmsgbox);
                if ~strcmp(action,'CalcMinNorm2FileEcfg') &...
                        ~strcmp(action,'CalcMinNorm2FileShell') &...
                        ~strcmp(action,'CalcMinNorm2FileAnalyse') &...
                        ~strcmp(action,'CalcSLC4AnovaGroups') &...
                        ~strcmp(action,'CalcSLC4AnovaAll') & ...
                        ~strcmp(action,'CalcSLC2Pic')
                    if SaveFile==0; return; end
                    Fid1=fopen(SaveFilePath,'w','b');
                    Fid2=fopen([SaveFilePath '.rms'],'w','b');
                    Fid3=fopen([SaveFilePath '.dat'],'w','b');
                    Fid4=fopen([SaveFilePath '.rms.dat'],'w','b');
                    if strcmp(action,'CalcMinNorm2FileROI') | strcmp(action,'CalcSLC2FileROI')
                        Fid5=fopen([SaveFilePath '.roi'],'w','b');
                        Fid6=fopen([SaveFilePath '.roi.dat'],'w','b');
                    end
                    Fid7=fopen([SaveFilePath '.mmx'],'w','b');
                end		

                if strcmp(action,'CalcSLC4AnovaGroups')
                    Fid1=fopen(SaveFilePath,'w','b');
                elseif strcmp(action,'CalcSLC4AnovaAll')
                    Fid1=fopen(SaveFilePath,'w','b');
                    TotDataMat =[];
                end
                TmpString='File_Name; Condition; Subject_Number; Cell_Number; ';

                if strcmp(action,'CalcMinNorm2FileAll') | ...
                        strcmp(action,'CalcMinNorm2FileGroups') | ...
                        strcmp(action,'CalcMinNorm2FileROI')

                    LambdaApprox=MNLambdaApprox;
                    TmpString=[TmpString 'Shell_Number; MN_Lambda; '];		
                else
                    LambdaApprox=SLCLambdaApprox;
                    TmpString=[TmpString 'Method; '];	
                end
                if ~strcmp(action,'CalcMinNorm2FileEcfg') & ~strcmp(action,'CalcMinNorm2FileShell') & ~strcmp(action,'CalcMinNorm2FileAnalyse') & ~strcmp(action,'CalcSLC4AnovaAll') &  ~strcmp(action,'CalcSLC2Pic')
                    TmpString=[TmpString 'SLC_Lambda; Trigger_Point_[];  Min._Time_[ms];  Max._Time_[ms]; Dist._Time_[ms]; Mean_Status; '];
                    fprintf(Fid1,TmpString);
                    if  ~strcmp(action,'CalcSLC4AnovaGroups') & ~strcmp(action,'CalcSLC4AnovaAll')
                        fprintf(Fid2,TmpString);
                    end
                end
                if strcmp(action,'CalcMinNorm2FileAll') | strcmp(action,'CalcSLC2FileAll')
                    fprintf(Fid1,'Channel_Number; '); 	
                    if  ~strcmp(action,'CalcSLC4AnovaGroups')
                          fprintf(Fid2,'Number_of_channels; ');
                    end
                elseif strcmp(action,'CalcSLC2Pic')

                elseif strcmp(action,'CalcMinNorm2FileGroups') | strcmp(action,'CalcSLC2FileGroups')
                    fprintf(Fid1,'Group_Number; '); 
                    if  ~strcmp(action,'CalcSLC4AnovaGroups')
                        fprintf(Fid2,'Group_Number; '); 
                    end
                elseif strcmp(action,'CalcMinNorm2FileROI') | strcmp(action,'CalcSLC2FileROI')
                    if  ~strcmp(action,'CalcSLC4AnovaGroups')
                        fprintf(Fid5,TmpString);
                    end
                    fprintf(Fid1,'ROI_Number; '); 
                    if  ~strcmp(action,'CalcSLC4AnovaGroups')
                        fprintf(Fid2,'ROI_Number; '); 
                        fprintf(Fid5,'ROI_Number; '); 
                        fprintf(Fid5,'Time point (interval) ; Location of absolute maximum (x,y,z) [m] (polar, azimute, radius) [rad,rad,m]; Amplitude of absolute maximum: ; Mean of ROI: ; RMS of ROI: \n\n');
                    end      
                    global ScalpLeadLocCart ScalpLeadLocSpher ROIIndMat ScalpLeadLocSpherGrad

                    if strcmp(action,'CalcSLC2FileROI')
                        if strcmp(OIStr,'ROI')
                            ROIMatSpherRad(:,[1 2 4])=pi.*ROIMatSpherDeg(:,[1 2 4])./180;
                            ROIMatCart=ROIMatSpherRad;
                            ROIMatCart(:,1:3)=change_sphere_cart(ROIMatSpherRad(:,1:2),ScalpRadius,1);
                        end
                        ScalpLocCart=get(hPlot3dList(58),'Userdata');
                        ScalpLocSpher=change_sphere_cart(ScalpLocCart,[],-1);     
                        ScalpLocIndVec=get(hPlot3dList(106),'Userdata'); %Dont take all 1024 scalp positions because not all scalp positions are unique:
                        if isempty(ScalpLocIndVec)
                            emegs3d('ReadOrCalcScalpLocIndFile');
                            ScalpLocIndVec=get(hPlot3dList(106),'Userdata');
                        end
                        ScalpLocCart=ScalpLocCart(ScalpLocIndVec,:);
                        ScalpLocSpher=ScalpLocSpher(ScalpLocIndVec,:);
                        ScalpLeadLocCart=ScalpLocCart;
                        ScalpLeadLocSpher=ScalpLocSpher;
                        DiffLoc=ScalpLeadLocCart;
                    elseif strcmp(action,'CalcMinNorm2FileROI')
                        if strcmp(OIStr,'ROI')
                            ROIMatSpherDeg(:,3)=ones(4,1).*0.092;
                            ROIMatSpherDeg(:,4)=ones(4,1).*0.046;
                            ROIMatSpherRad=ROIMatSpherDeg;
                            ROIMatSpherRad(:,[1 2])=pi.*ROIMatSpherDeg(:,[1 2])./180;
                            ROIMatCart=ROIMatSpherRad;
                            ROIMatCart(:,1:3)=change_sphere_cart(ROIMatSpherRad(:,1:3),[],1);
                        end
                        LeadLocShell=get(hPlot3dList(82),'Userdata');
                        ScalpLeadLocCart=LeadLocShell;     
                        ScalpLeadLocSpher=change_sphere_cart(LeadLocShell,[],-1); 
                        DiffLoc=ScalpLeadLocCart;
                    end
                    ScalpLeadLocSpherGrad=ScalpLeadLocSpher;
                    ScalpLeadLocSpherGrad(:,[1,2])=(ScalpLeadLocSpher(:,[1,2])./pi).*180;
                    MaxNROIIndVec=0;
                    for ROIInd=1:NROI
                        if strcmp(OIStr,'ROI')
                            CenterROILoc=ROIMatCart(ROIInd,1:3);
                            if strcmp(action,'CalcSLC2FileROI')
                                Tau=ROIMatCart(ROIInd,4);
                                MaxDist=sqrt((ScalpRadius.*sin(Tau)).^2+(ScalpRadius.*(cos(Tau)-1)).^2);
                            elseif strcmp(action,'CalcMinNorm2FileROI')
                                MaxDist=ROIMatCart(ROIInd,4);
                            end
                            for Ind=1:length(DiffLoc);
                                DiffLoc(Ind,:)=ScalpLeadLocCart(Ind,:)-CenterROILoc;
                            end
                            ROIIndVec=find(sqrt(sum(DiffLoc'.^2))<MaxDist);
                        elseif strcmp(OIStr,'IOI')
                            ROIIndVec=ROIMatSpherDeg(ROIInd,:);
                            IndVec=find(ROIIndVec~=0);
                            ROIIndVec=ROIIndVec(IndVec);
                        else
                            error('Unknown OIStr in Plot3d')
                        end
                        %================================
    %                     if ROIInd==1
    %                         ROIIndVec=find(ScalpLeadLocCart(:,1)>0 & ScalpLeadLocCart(:,2)>0 & ScalpLeadLocCart(:,3)>0)';
    %                     elseif ROIInd==2
    %                         ROIIndVec=find(ScalpLeadLocCart(:,1)<0 & ScalpLeadLocCart(:,2)>0 & ScalpLeadLocCart(:,3)>0)';
    %                     elseif ROIInd==3
    %                         ROIIndVec=find(ScalpLeadLocCart(:,1)<0 & ScalpLeadLocCart(:,2)<0 & ScalpLeadLocCart(:,3)>0)';
    %                     elseif ROIInd==4
    %                         ROIIndVec=find(ScalpLeadLocCart(:,1)>0 & ScalpLeadLocCart(:,2)<0 & ScalpLeadLocCart(:,3)>0)';
    %                     end
                        if ROIInd==1
                            ROIIndVec=find(ScalpLeadLocSpherGrad(:,2)>0 & ScalpLeadLocSpherGrad(:,2)<90)';
                        elseif ROIInd==2
                            ROIIndVec=find(ScalpLeadLocSpherGrad(:,2)>90 & ScalpLeadLocSpherGrad(:,2)<180)';
                        elseif ROIInd==3
                            ROIIndVec=find(ScalpLeadLocSpherGrad(:,2)>180 & ScalpLeadLocSpherGrad(:,2)<270)';
                        elseif ROIInd==4
                            ROIIndVec=find(ScalpLeadLocSpherGrad(:,2)>270 & ScalpLeadLocSpherGrad(:,2)<360)';
                        end
    %                     if ROIInd==1
    %                         ROIIndVec=find(ScalpLeadLocSpherGrad(:,2)>0 & ScalpLeadLocSpherGrad(:,2)<90 & ScalpLeadLocSpherGrad(:,1)<90)';
    %                     elseif ROIInd==2
    %                         ROIIndVec=find(ScalpLeadLocSpherGrad(:,2)>90 & ScalpLeadLocSpherGrad(:,2)<180 & ScalpLeadLocSpherGrad(:,1)<90)';
    %                     elseif ROIInd==3
    %                         ROIIndVec=find(ScalpLeadLocSpherGrad(:,2)>180 & ScalpLeadLocSpherGrad(:,2)<270 & ScalpLeadLocSpherGrad(:,1)<90)';
    %                     elseif ROIInd==4
    %                         ROIIndVec=find(ScalpLeadLocSpherGrad(:,2)>270 & ScalpLeadLocSpherGrad(:,2)<360 & ScalpLeadLocSpherGrad(:,1)<90)';
    %                     end
                        NROIIndVec=length(ROIIndVec);
                        fprintf('Region of interest # %g ;\n',ROIInd);
                        fprintf('Center of region: %g , %g ; (theta, phi);\n',ROIMatSpherDeg(ROIInd,1:2));
                        fprintf('Extention of region: %g ;\n',ROIMatSpherDeg(ROIInd,4));
                        fprintf('Number of locations within given region: %g ;\n\n',NROIIndVec);
                        fprintf('Cartesian locations:\n\n')
                        disp(ScalpLeadLocCart(ROIIndVec,:).*1000);
                        fprintf('Spherical locations:\n\n')
                        disp(180.*ScalpLeadLocSpher(ROIIndVec,1:2)./pi);
                        fprintf('\n\n\n\n')
                        MaxNROIIndVec=max([MaxNROIIndVec NROIIndVec]);
                        if ROIInd==1
                             ROIIndMatTmp1=ROIIndVec;
                        else
                            ROIIndMatTmp2=zeros(ROIInd,MaxNROIIndVec);
                            ROIIndMatTmp2(1:ROIInd-1,1:max(size(ROIIndMatTmp1)))=ROIIndMatTmp1;
                            ROIIndMatTmp2(ROIInd,1:NROIIndVec)=ROIIndVec;
                            ROIIndMatTmp1=ROIIndMatTmp2;
                        end      
                    end
                    ROIIndMat=ROIIndMatTmp1;
                    RejectOverlapStatus=1;
                    if RejectOverlapStatus
                        MaxMaxInd=max(max(ROIIndMat));
                        for i=1:MaxMaxInd
                            [a,b]=find(ROIIndMat==i);
                            if length(a)>1
                                for j=1:length(a)
                                    ROIIndMat(a(j),b(j))=0;
                                end
                            end
                        end
                    end
                    %==================================================================================
                    hRoiIoiFig=figure('Units','normal','Position',[.5 .5 .5 .45], ...
                    'Name','Sensor/Dipole positions of interest','Color',[1 1 1],'NumberTitle','off');
                    ColorStr='rgbcmykrgbcmykrgbcmykrgbcmykrgbcmykrgbcmykrgbcmykrgbcmykrgbcmykrgbcmykrgbcmyk';
                    x=ScalpLeadLocCart(:,1);
                    y=ScalpLeadLocCart(:,2);
                    z=ScalpLeadLocCart(:,3);
    %               plot3(x,y,z,'k*')
    %               hold on
                    for ROIInd=1:NROI 
                        ROIIndVec=ROIIndMat(ROIInd,:);
                        IndVec=find(ROIIndVec~=0);
                        ROIIndVec=ROIIndVec(IndVec);
                        a=length(ROIIndVec)
                        x=ScalpLeadLocCart(ROIIndVec,1);
                        y=ScalpLeadLocCart(ROIIndVec,2);
                        z=ScalpLeadLocCart(ROIIndVec,3);
                        plot3(x,y,z,[ColorStr(ROIInd),'*'])
                        hold on
                    end
                    hold off
                    pause(.1)
                    view([0 90])
                    title('Sensor/Dipole positions of interest; Top View');
                end
                if ~strcmp(action,'CalcMinNorm2FileEcfg') & ...
                        ~strcmp(action,'CalcMinNorm2FileShell') &...
                        ~strcmp(action,'CalcMinNorm2FileAnalyse') &...
                        ~strcmp(action,'CalcSLC4AnovaGroups') &...
                        ~strcmp(action,'CalcSLC4AnovaAll') &...
                        ~strcmp(action,'CalcSLC2Pic')
                    fprintf(Fid2,'\n');
                    fprintf(Fid2,'Sum of integral of root mean square [µV x ms]:\n');
                    fprintf(Fid2,'Integral of root mean square [µV x ms]:\n\n');
                end

                FirstFileAnova = 1;
                ScaleInd = 0;
                for FileIndex=1:NFiles
                    
                    if  strcmp(action,'CalcSLC2Pic')
                        ScaleInd = ScaleInd + 1;
                        if ScaleInd > ScaleCount
                            ScaleInd = 1;
                        end
                    end
                    
                    if UseFileMatStatus & ~strcmp(Plot2dAvgFileFormat,'SCADS')
                        [File,Path,FilePath]=GetFileNameOfMat(FileMat,FileIndex);
                        [AvgMat,File,Path,FilePath,SampRateVec,NCells,NSubjectsVec,NPointsVec,NChan,NTrialsVec,LHdr,ScaleBins]=ReadEGISAvgFile(FilePath,1,1,1);
                        NDataSets=sum(NSubjectsVec);
                        CellIndex=0;
                        SubjectIndex=1;
                    else
                        CellIndex=1;
                        SubjectIndex=1;
                        NDataSets=1;
                    end
                    DataSetIndex=0; 
                    NDataSetVec=1;
                    while DataSetIndex<NDataSets
                        DataSetIndex=DataSetIndex+1;
                        NTrialAvgVec=[];StdChanTimeMat=[];MedMedRawVec=[];MedMedAvgVec=[];
                        if UseFileMatStatus
                            [File,Path,FilePath]=GetFileNameOfMat(FileMat,FileIndex);	
                            set(hPlot3dList(55),'Userdata',FilePath); %ActFilePath
                            if strcmp(Plot2dAvgFileFormat,'SCADS')
                                [AvgMat,File,Path,FilePath,NTrialAvgVec,StdChanTimeMat,...
                                SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec]=ReadAvgFile(FilePath);
                                [NonUse,ActNPoints]=size(AvgMat);
                                if strcmp(EEGMEGStatusString,'MEG')
                                    AvgMat=AvgMat.*10.^15;
                                end
                                fprintf('Temporary CellIndex, CondNumber and SubjectIndex, line 2494 in Plot3d')
                                if length(File)>9
                                    CellIndex=str2num(File(6));
                                    CondNumber=str2num(File(10));
                                    SubjectIndex=str2num(File(1:2));
                                end
                            elseif strcmp(Plot2dAvgFileFormat,'AvgEgis') | strcmp(Plot2dAvgFileFormat,'GrandAvgEgis')
                                CellIndex=CellIndex+1
                                if CellIndex>NCells
                                    SubjectIndex=SubjectIndex+1
                                    CellIndex=1
                                end
                                [AvgMat,File,Path,FilePath,SampRateVec,NCells,NSubjectsVec,NPointsVec,NChan,NTrialsVec,LHdr,ScaleBins]= ...
                                ReadEGISAvgFile(FilePath,1,CellIndex,SubjectIndex);	
                                ActNPoints=NPointsVec(CellIndex);
                            else
                                Message=char('Sorry,');
                                Message=char(Message,'');
                                Message=char(Message,'this application is only available');
                                Message=char(Message,'using "SCADS", "Egis Average" or');
                                Message=char(Message,'"Egis Grand Average" data file format.');
                                hmsgbox=msgbox(Message,'Info','help'); 
                                break;
                            end	
                            if CalcBaseStatus
                                if MaxBase>ActNPoints;
                                    Message=char('Sorry, ');
                                    Message=char(Message,' ');
                                    Message=char(Message,'given baseline interval is');
                                    Message=char(Message,'inconsistent with the number of points in:');
                                    Message=char(Message,['File:    ' File]);
                                    if ~strcmp(Plot2dAvgFileFormat,'SCADS')
                                        if ~strcmp(Plot2dAvgFileFormat,'GrandAvgEgis')
                                            Message=char(Message,['Subject: ' SubjectIndex]);
                                        end
                                        Message=char(Message,['Cell:    ' CellIndex]);
                                    end
                                    hmsgbox=msgbox(Message,'Info','help'); 
                                    return;
                                end
                                [AvgMat]=CalcBaseline(AvgMat,MinBase,MaxBase,1,1); 
                            end
                            if CalcAbsStatus
                                fprintf('Calculate absolute values ...\n');
                                AvgMat=abs(AvgMat);
                            else
                                fprintf('No absolute values ...\n');
                            end
                            if TempFiltStatus 
                                LowFiltCoeff=TempFiltStruc.LowFiltCoeff;
                                HighFiltCoeff=TempFiltStruc.HighFiltCoeff;
                                if ~isempty(LowFiltCoeff)
                                    fprintf('Temporal lowpass filtering ...\n');
                                    for i=1:NChan
                                        AvgMat(i,:)=(filtfilt(LowFiltCoeff(1,:),LowFiltCoeff(2,:),AvgMat(i,:)'))';
                                    end
                                end
                                if ~isempty(HighFiltCoeff)
                                    fprintf('Temporal highpass filtering ...\n');
                                    for i=1:NChan
                                        AvgMat(i,:)=(filtfilt(HighFiltCoeff(1,:),HighFiltCoeff(2,:),AvgMat(i,:)'))';
                                    end
                                end
                            else
                                fprintf('No temporal filtering ...\n');
                            end
                            if SpatFiltStatus
                                fprintf('Apply spatial lowpass filter. Sigma: %g\n',SpatFiltStruc.Sigma./pi.*180);
                                AvgMat=SpatFilt(AvgMat,SpatFiltStruc.PhiMat,SpatFiltStruc.Sigma,1);
                            else
                                fprintf('No spatial filtering ...\n');
                            end 
                            if CalcGradStatus
                                fprintf('Calculate gradient\n');
                                AvgMat=gradient(AvgMat);
                            else
                                fprintf('No gradient ...\n');
                            end
                        else
                            if strcmp(Plot2dAvgFileFormat,'AvgEgis') | strcmp(Plot2dAvgFileFormat,'GrandAvgEgis')
                                EgisAvgVec=get(hPlot2dList(Plot2dNListHdr+(Plot2dFileNoVec(FileIndex)-1).*50+31),'Userdata');
                                CellIndex=EgisAvgVec(1)
                                SubjectIndex=EgisAvgVec(2)
                            end
                            FilePath=get(hPlot2dList(Plot2dNListHdr+(Plot2dFileNoVec(FileIndex)-1).*50+4),'Userdata');
                            [File,Path]=SepFilePath(FilePath);
                            AvgMat=get(hPlot2dList(Plot2dNListHdr+(Plot2dFileNoVec(FileIndex)-1).*50+1),'Userdata');
                            [NonUse,ActNPoints]=size(AvgMat);
                        end
                        
                        set(hPlot3dList(54),'Userdata',AvgMat);                                                   
                   
                                
                        if strcmp(action,'CalcMinNorm2FileEcfg') | strcmp(action,'CalcMinNorm2FileShell') | strcmp(action,'CalcMinNorm2FileAnalyse')
                            [File,Path]=SepFilePath(FilePath);
                            SaveFilePath=[Path,File(1:min(length(File),27)),'.MN',int2str(ShellNumber)];
                            if FileIndex==1
                                SaveFilePathMat=char(SaveFilePath);
                            else
                                SaveFilePathMat=char(SaveFilePathMat,SaveFilePath)
                            end						
                         end


                        %=====================================================================
                        %=====================================================================
                        if strcmp(action,'CalcMinNorm2FileEcfg') | ...
                                strcmp(action,'CalcMinNorm2FileShell') | ...
                                strcmp(action,'CalcMinNorm2FileAnalyse') | ...
                                strcmp(action,'CalcMinNorm2FileAll') | ...
                                strcmp(action,'CalcMinNorm2FileGroups') | ...
                                strcmp(action,'CalcMinNorm2FileROI')
                            emegs3d('CalcMinimumNorm')
                            DataMat=get(hPlot3dList(53),'Userdata'); 


                        elseif strcmp(action,'CalcSLC2Pic')  

                           set(hPlot3dList(149),'userdata',1); %figure visibility
                           set(hPlot3dList(101),'Value',0);	   %CalcSLC2File

                           if strcmp(ScaleOpt,'subject')
                               if ScaleInd == 1;
                                   set(hPlot3dList(45),'Value',1); %AutoAmp on
                                   emegs3d('setAutoAmp');
                               elseif ScaleInd == 2
                                   set(hPlot3dList(45),'Value',0); %AutoAmp off
                                   emegs3d('setAutoAmp');
                               end
                           end
                           
                           emegs3d('CalcCortMap')
                           DataMat=get(hPlot3dList(50),'Userdata');

                           
                           
                        
                           fig=findobj('tag','BatchPlotFig');
                           if isempty(fig)
                               uiwait(errordlg('Could not find figure to print! Picture export must be done with ''Head View''!!!'));
                               asdfasdf;
                           end
                           set(fig,'units','points','position',[400 400 200 200],'PaperPositionMode','auto','PaperSize',[200 200]);
                           print(fig,'-djpeg','-r0','contourplottmp.jpg');
                           close(fig);
                           contourpic=imread('contourplottmp.jpg','jpg');
                           PicCell{FileIndex} = contourpic;

                           set(hPlot3dList(101),'Value',0);		%CalcSLC2File
                           set(hPlot3dList(149),'userdata',0);  %figure visibility

                        elseif strcmp(action,'CalcMagFieldNorm2File')
                            emegs3d('CalcMagFieldNorm')
                            DataMat=get(hPlot3dList(53),'Userdata');
                        else
                            emegs3d('CalcCortMap')
                            DataMat=get(hPlot3dList(50),'Userdata');
                        end	

                        [NGroupChan,NPointsInt]=size(DataMat);
                        %=====================================================================
                        %===================================================================== 
                        %=======================Calculate Absolute Extreme Values=============
                        if NPointsInt>1
                            GradMat=gradient(DataMat);
                            BinGradMat=(GradMat>0);
                            DiffBinGradMat=diff(BinGradMat,1,2);
                            DataMatMax=0.*DataMat;
                            DataMatMin=0.*DataMat;

                            DiffBinGradMatTmp=abs((DiffBinGradMat<0));
                            DataMat1=DataMat(:,1:NPointsInt-1).*DiffBinGradMatTmp;
                            DataMat2=DataMat(:,2:NPointsInt).*DiffBinGradMatTmp;
                            Max1=(DataMat1>=DataMat2);
                            Max2=(DataMat1<=DataMat2);
                            DataMatMax(:,1:NPointsInt-1)=DataMat1.*Max1;
                            DataMatMax(:,2:NPointsInt)=DataMatMax(:,2:NPointsInt)+DataMat2.*Max2;

                            DiffBinGradMatTmp=(DiffBinGradMat>0);
                            DataMat1=DataMat(:,1:NPointsInt-1).*DiffBinGradMatTmp;
                            DataMat2=DataMat(:,2:NPointsInt).*DiffBinGradMatTmp;
                            Min1=(DataMat1<=DataMat2);
                            Min2=(DataMat1>=DataMat2);
                            DataMatMin(:,1:NPointsInt-1)=DataMat1.*Min1;
                            DataMatMin(:,2:NPointsInt)=DataMatMin(:,2:NPointsInt)+DataMat2.*Min2;

                            [MaxValVec,MaxIndVec]=max(DataMatMax,[],2);				
                            [MinValVec,MinIndVec]=min(DataMatMin,[],2);		
                        end				
                        %======================================================================
                        if FileIndex==1 & DataSetIndex==1 & ...
                                ~strcmp(action,'CalcMinNorm2FileEcfg') &...
                                ~strcmp(action,'CalcMinNorm2FileShell') & ...
                                ~strcmp(action,'CalcMinNorm2FileAnalyse') &...
                                ~strcmp(action,'CalcSLC4AnovaAll') &...
                                ~strcmp(action,'CalcSLC2Pic')

                            TmpString=[];
                            for Ind=1:NPointsInt
                                TmpString=[TmpString,'T',int2str(Ind),'; '];
                            end
                            fprintf(Fid1,[TmpString '\n\n']);
                            if  ~strcmp(action,'CalcSLC4AnovaGroups') & ~strcmp(action,'CalcSLC4AnovaAll')
                                fprintf(Fid2,[TmpString '\n']);
                            end
                        elseif FileIndex==1 & DataSetIndex==1 & strcmp(action,'CalcSLC2Pic')

                        elseif FileIndex==1 & DataSetIndex==1 & strcmp(action,'CalcSLC4AnovaAll')
                             TotDataMat = zeros([size(AvgMat),NFiles]);
                        end

                        if strcmp(action,'CalcMinNorm2FileGroups') | strcmp(action,'CalcSLC2FileGroups')
                            NGroupChan=NGroup; 
                        elseif strcmp(action,'CalcMinNorm2FileROI') | strcmp(action,'CalcSLC2FileRoi')
                            NGroupChan=NROI; 	
                        end
                        Message=char(' ');
                        Message=char(Message,' ');
                        Message=char(Message,['Save calculated values of ',int2str(NGroupChan),' sensors, groups, rois or iois']);
                        Message=char(Message,['and ',int2str(NPointsInt),' point(s) or interval(s) in file: ']);
                        Message=char(Message,' ');
                        Message=char(Message,' ');
                        if CalcBaseStatus
                            Message=char(Message,['Baseline interval: ',int2str(MinBase),' - ',int2str(MaxBase),' ...']);
                        else
                            Message=char(Message,'No baseline correction ... ');
                        end
                        if CalcAbsStatus
                            Message=char(Message,'Absolute values ...');
                        else
                            Message=char(Message,'No absolute values ...');
                        end
                        if TempFiltStatus
                            Message=char(Message,'Temporal filtering ...');
                        else
                            Message=char(Message,'No temporal filtering ...');
                        end
                        if SpatFiltStatus
                            Message=char(Message,'Spatial filtering ...');
                        else
                            Message=char(Message,'No spatial filtering ...');
                        end
                        if CalcGradStatus
                            Message=char(Message,'Calculate temporal gradient ...');
                        else
                            Message=char(Message,'No temporal gradient ...');
                        end
                        Message=char(Message,' ');
                        Message=char(Message,SaveFilePath);
                        Message=char(Message,' ');
                        Message=char(Message,['File #    ',int2str(FileIndex),' of ',int2str(NFiles)]);
                        Message=char(Message,['File:     ',File]);
                        Message=char(Message,['Subject:  ',int2str(SubjectIndex)]);
                        Message=char(Message,['Cell:     ',int2str(CellIndex)]);
                        Message=char(Message,' ');
                        if DataSetIndex==1 & FileIndex==1
                            hGlobalMsgbox=msgbox(Message,'Info:','help');
                            hChildMsgbox=get(hGlobalMsgbox,'Children');
                            set(hGlobalMsgbox,'Units','Normal','Position',[.325 .6 .35 .3])
                            set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                        else 
                            hChildMsgbox=get(hGlobalMsgbox,'Children');
                            if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
                                set(hChildMsgbox(2),'String',Message);
                            else
                                hChild2Msgbox=get(hChildMsgbox(2),'Children');
                                set(hChild2Msgbox,'String',Message);
                            end
                        end
                        pause(.01);
                        if  UseFileMatStatus & ...
                                ~strcmp(action,'CalcMinNorm2FileEcfg') & ...
                                ~strcmp(action,'CalcMinNorm2FileShell') & ...
                                ~strcmp(action,'CalcMinNorm2FileAnalyse')

                            TmpString=[File '\t' int2str(CondNumber) '\t' int2str(SubjectIndex) '\t' int2str(CellIndex) '\t' int2str(SLCMethodShellNumber) '\t' ];
                            if strcmp(action,'CalcMinNorm2FileAll') | strcmp(action,'CalcMinNorm2FileGroups') | strcmp(action,'CalcMinNorm2FileROI')
                                TmpString=[TmpString,num2str(MNLambdaApprox) '\t' ];
                            end
                            TmpString=[TmpString,num2str(SLCLambdaApprox) '\t' int2str(TrigPoint) '\t'  MsHzMinPointString '\t' MsHzMaxPointString '\t' DistPointMsString '\t' int2str(DistPointMeanStatus)  '\t' ];
                        end
                        if strcmp(action,'CalcMinNorm2FileEcfg') | strcmp(action,'CalcMinNorm2FileShell')
                            SaveAvgFile(SaveFilePath,DataMat,NTrialAvgVec,zeros(size(DataMat)),SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus);
                        elseif strcmp(action,'CalcMinNorm2FileAnalyse') 
                            LeadLoc=get(hPlot3dList(81),'Userdata');  
                            MinNorm2Analyse(DataMat,LeadLoc,SaveFilePath);
                        elseif strcmp(action,'CalcMinNorm2FileAll') | strcmp(action,'CalcSLC2FileAll') 
                            for ChanIndex=1:NChan
                                fprintf(Fid1,[TmpString,int2str(ChanIndex)]);	fprintf(Fid1,'\t');
                                fprintf(Fid1,'%g\t',DataMat(ChanIndex,:)); 		fprintf(Fid1,'\n');
                                if ~ strcmp(action,'CalcSLC4AnovaAll')
                                    fprintf(Fid3,'%g\t',DataMat(ChanIndex,:)); 		fprintf(Fid3,'\n');
                                end
                            end
                            if ~ strcmp(action,'CalcSLC4AnovaAll')
                                fprintf(Fid2,TmpString);						fprintf(Fid2,'\t');
                                Tmp=MsPerPoint.*sum(sqrt(sum((DataMat.^2))./NChan));
                                fprintf(Fid2,'%g\t',Tmp); 						fprintf(Fid2,'\n');
                                Tmp=MsPerPoint.*sqrt(sum((DataMat.^2))./NChan);
                                fprintf(Fid2,'%g\t',Tmp); 						fprintf(Fid2,'\n');
                                fprintf(Fid4,'%g\t',Tmp); 	
                                if NPointsInt>1
                                    fprintf(Fid7,'%g\t',MaxValVec); fprintf(Fid7,'\n');
                                    fprintf(Fid7,'%g\t',MaxIndVec);  fprintf(Fid7,'\n');
                                    fprintf(Fid7,'%g\t',MinValVec);  fprintf(Fid7,'\n');
                                    fprintf(Fid7,'%g\t',MinIndVec);  fprintf(Fid7,'\n');
                                end
                            end
                        elseif strcmp(action,'CalcSLC4AnovaAll')

                             TotDataMat(:,:,FileIndex)=DataMat;

                        elseif strcmp(action,'CalcMinNorm2FileGroups') | strcmp(action,'CalcSLC2FileGroups') | strcmp(action,'CalcSLC4AnovaGroups')
                            MaxValGroupVec=zeros(NGroup,1);
                            MinValGroupVec=zeros(NGroup,1);
                            MaxIndGroupVec=zeros(NGroup,1);
                            MinIndGroupVec=zeros(NGroup,1);
                            if strcmp(action,'CalcSLC4AnovaGroups') & (NGroup==0)
                                uiwait(errordlg('No channelgroups have been selected!'));
                                return;
                            end
                            for GroupIndex=1:NGroup
                                GroupNo=GroupNoVec(GroupIndex);
                                GroupIndVec=find(GroupMat(1,:)==GroupNo);
                                ChanIndVec=GroupMat(2,GroupIndVec);
                                DataVec=mean(DataMat(ChanIndVec,:),1);
                                fprintf(Fid1,[TmpString,int2str(GroupIndex)]);	fprintf(Fid1,'\t');
                                fprintf(Fid1,'%g\t',DataVec); 					fprintf(Fid1,'\n');
                                if  ~strcmp(action,'CalcSLC4AnovaGroups')
                                    fprintf(Fid3,'%g\t',DataVec); 
                                    Tmp=MsPerPoint.*sum(sqrt(sum((DataMat(ChanIndVec,:).^2))./NChan));
                                    fprintf(Fid2,[TmpString,int2str(GroupIndex)]);	fprintf(Fid2,'\t');
                                    fprintf(Fid2,'%g\t',Tmp); 						fprintf(Fid2,'\n'); 
                                    Tmp=MsPerPoint.*sqrt(sum((DataMat(ChanIndVec,:).^2))./NChan);
                                    fprintf(Fid2,'%g\t',Tmp); 						fprintf(Fid2,'\n');
                                    fprintf(Fid4,'%g\t',Tmp); 
                                end
                                if NPointsInt>1
                                    MaxValGroupVec(GroupIndex)=mean(MaxValVec(ChanIndVec));
                                    MaxIndGroupVec(GroupIndex)=mean(MaxIndVec(ChanIndVec));
                                    MinValGroupVec(GroupIndex)=mean(MinValVec(ChanIndVec));
                                    MinIndGroupVec(GroupIndex)=mean(MinIndVec(ChanIndVec));
                                end
                            end
                            if  ~strcmp(action,'CalcSLC4AnovaGroups') 
                                fprintf(Fid3,'\n'); 
                                fprintf(Fid4,'\n'); 

                                if NPointsInt>1
                                    fprintf(Fid7,'%g\t',MaxValGroupVec); fprintf(Fid7,'\n');
                                    fprintf(Fid7,'%g\t',MaxIndGroupVec);  fprintf(Fid7,'\n');
                                    fprintf(Fid7,'%g\t',MinValGroupVec);  fprintf(Fid7,'\n');
                                    fprintf(Fid7,'%g\t',MinIndGroupVec);  fprintf(Fid7,'\n');
                                end
                            end
                        elseif strcmp(action,'CalcMinNorm2FileROI') | strcmp(action,'CalcSLC2FileROI')
                            if strcmp(action,'CalcSLC2FileROI')
                                DataMat=DataMat(ScalpLocIndVec,:); %932 statt 1024
                            end
                            for ROIIndex=1:NROI
                                ROIIndVec=ROIIndMat(ROIIndex,:);
                                Tmp=find(ROIIndVec~=0);
                                if isempty(Tmp); 
                                    Message=char(Message,['No location in ' int2str(ROIIndex) ' region of interest.']);
                                    hmsgbox=msgbox(Message,'Info','help');
                                else
                                    ROIIndVec=ROIIndVec(Tmp);
                                    NROIIndVec=length(ROIIndVec);
                                    DataVec=sum(DataMat(ROIIndVec,:),1)./NROIIndVec;
                                    fprintf(Fid1,[TmpString,int2str(ROIIndex)]);	fprintf(Fid1,'\t');
                                    fprintf(Fid1,'%g\t',DataVec);				 	fprintf(Fid1,'\n'); 
                                    if  ~strcmp(action,'CalcSLC4AnovaGroups')
                                        fprintf(Fid3,'%g\t',DataVec); 
                                        Tmp=MsPerPoint.*sum(sqrt(sum((DataMat(ROIIndVec,:).^2))./length(ROIIndVec)));
                                        fprintf(Fid2,'%g\t',Tmp); 						fprintf(Fid2,'\n'); 
                                        Tmp=MsPerPoint.*sqrt(sum((DataMat(ROIIndVec,:).^2))./length(ROIIndVec));
                                        fprintf(Fid2,'%g\t',Tmp); 						fprintf(Fid2,'\n');
                                        fprintf(Fid4,'%g\t',Tmp);
                                        [NoUse,MaxAbsIndVec]=max(abs(DataMat(ROIIndVec,:)));
                                        fprintf(Fid5,[TmpString,int2str(ROIIndex) '\n\n']);
                                        for TimeInd=1:length(DataVec)
                                            MaxAbsVal=DataMat(ROIIndVec(MaxAbsIndVec(TimeInd)),TimeInd);
                                            MeanVal=mean(DataMat(ROIIndVec,TimeInd));
                                            RMSVal=sqrt(sum(DataMat(ROIIndVec,TimeInd).^2,1));
                                            MaxAbsCart=ScalpLeadLocCart(ROIIndVec(MaxAbsIndVec(TimeInd)),:);
                                            MaxAbsSpher=ScalpLeadLocSpher(ROIIndVec(MaxAbsIndVec(TimeInd)),:);
                                            fprintf(Fid5,'%g\t',TimeInd); fprintf(Fid5,'\n'); 
                                            fprintf(Fid5,'%g\t',MaxAbsCart); fprintf(Fid5,'\n'); 
                                            fprintf(Fid5,'%g\t',MaxAbsSpher); fprintf(Fid5,'\n'); 
                                            fprintf(Fid5,'%g\t',MaxAbsVal); fprintf(Fid5,'\n'); 
                                            fprintf(Fid5,'%g\t',MeanVal);  fprintf(Fid5,'\n'); 
                                            fprintf(Fid5,'%g\t',RMSVal);  fprintf(Fid5,'\n\n');
                                            fprintf(Fid6,'%g\t',TimeInd);
                                            fprintf(Fid6,'%g\t',MaxAbsCart); 
                                            fprintf(Fid6,'%g\t',MaxAbsSpher); 
                                            fprintf(Fid6,'%g\t',MaxAbsVal); 
                                            fprintf(Fid6,'%g\t',MeanVal); 
                                            fprintf(Fid6,'%g\t',RMSVal); 
                                        end
                                    end
                                end
                            end
                            if  ~strcmp(action,'CalcSLC4AnovaGroups')
                                fprintf(Fid3,'\n'); 
                                fprintf(Fid4,'\n'); 
                            end
                        end	
                    end
                end
                if ~strcmp(action,'CalcMinNorm2FileEcfg') & ...
                        ~strcmp(action,'CalcMinNorm2FileShell') & ...
                        ~strcmp(action,'CalcMinNorm2FileAnalyse')  & ...
                        ~strcmp(action,'CalcSLC4AnovaAll')& ...
                        ~strcmp(action,'CalcSLC2Pic')

                    fclose(Fid1);
                    if  ~strcmp(action,'CalcSLC4AnovaGroups')
                        fclose(Fid2);
                        fclose(Fid3);
                        fclose(Fid4);
                        fclose(Fid7);
                        if strcmp(action,'CalcMinNorm2FileROI') | strcmp(action,'CalcSLC2FileROI')
                            fclose(Fid5);
                            fclose(Fid6);
                        end
                    end
                end
                close(hGlobalMsgbox);
                if strcmp(action,'CalcMinNorm2FileEcfg') | strcmp(action,'CalcMinNorm2FileShell') | strcmp(action,'CalcMinNorm2FileAll') | strcmp(action,'CalcMinNorm2FileGroups')  | strcmp(action,'CalcMinNorm2FileROI') | strcmp(action,'CalcMinNorm2FileAnalyse') 
                    Message=char('Min. Norm => File ');
                    if strcmp(action,'CalcMinNorm2FileEcfg')
                        Message=char(Message,'');
                        Message=char(Message,'Write SaveFilePathMat to file:');
                        Message=char(Message,'');
                        Message=char(Message,SaveFilePathMat);
                        Message=char(Message,'');
                        Message=char(Message,[Path,'SaveFilePathMat']);
                        Fid=fopen([Path,'SaveFilePathMat'],'w','b');
                        fprintf(Fid,SaveFilePathMat');
                        fclose(Fid);
                        SaveFilePathMat=SaveFilePathMat
                    end
                    set(hPlot3dList(96),'Value',0);			%CalcMinNorm2File
                    set(hPlot3dList(97),'Userdata',[]);
                    set(hPlot3dList(98),'Userdata',[]);
                    set(hPlot3dList(99),'Userdata',[]);
                elseif strcmp(action,'CalcSLC2FileAll') | strcmp(action,'CalcSLC2FileGroups') | strcmp(action,'CalcSLC2FileROI') | strcmp(action,'CalcSLC4AnovaAll') | strcmp(action,'CalcSLC2Pic') 
                    Message=char('Scalp, Lap., Cort. => File ');
                    set(hPlot3dList(101),'Value',0);		%CalcSLC2File
                    set(hPlot3dList(102),'Userdata',[]);
                    set(hPlot3dList(103),'Userdata',[]);
                    set(hPlot3dList(104),'Userdata',[]);
                end
                Message=char(Message,'');
                Message=char(Message,'Calculation completed !');
                Message=char(Message,'');
                Message=char(Message,'');
                hmsgbox=msgbox(Message,'Info','help');
                pause(0.8);
    %             hChildMsgbox=get(hmsgbox,'Children');
    %             set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
    %             pause(2);
    %             if ~strcmp(action,'CalcMinNorm2FileEcfg') & ~strcmp(action,'CalcMinNorm2FileShell') & ~strcmp(action,'CalcMinNorm2FileAnalyse')
    %                 close(hmsgbox);
    %             end

                %set anovastatus = 0
                if  strcmp(action,'CalcSLC4AnovaGroups') 
                    set(hPlot3dList(132),'Userdata',0);
                    close(hReminderMsgbox);
                    close(hmsgbox);
                elseif strcmp(action,'CalcSLC4AnovaAll')
                    set(hPlot3dList(132),'Userdata',0);
                    save(SaveFilePath,'TotDataMat');
                    AnovaExportDesign = char(['NChan = ',num2str(size(TotDataMat,1))],['NPoints = ',num2str(size(TotDataMat,2))],['NFiles = ',num2str(size(TotDataMat,3))]);
                    save(DesignFilePath,'AnovaExportDesign');
                    close(hReminderMsgbox);
                    close(hmsgbox);
                end

                if strcmp(action,'CalcSLC2Pic')
                    if length(PicCell)~=BatchPlotNSubjects*BatchPlotNConditions
                        uiwait(errordlg('Number of exported pictures does not match SUBJECTS*CONDITIONS!'));
                        return
                    end
                    [height, width,depth] = size(PicCell{1});
                    AllPicMat = zeros(height*BatchPlotNSubjects,width*BatchPlotNConditions,depth);
                    allind = 1;
                    for r = 1:BatchPlotNSubjects
                        for s = 1: BatchPlotNConditions
                            AllPicMat((r-1)*height+1:r*height,(s-1)*width+1:s*width,:)=PicCell{allind};
                            allind = allind +1;
                        end
                    end
                    imwrite(AllPicMat./255,SaveFilePath,'jpg');
                    figure;
                    image(AllPicMat./255);
                    axis off;
                    close(hReminderMsgbox);
                    close(hmsgbox);
                end
                
%             catch
%                 uiwait(errordlg(char('Export error:',lasterr)));
%                 try
%                     close(hReminderMsgbox);
%                     close(hmsgbox);
%                 catch
%                 end
%             end
                
               
                
            %============================================================================	
            %============ set number of actual file 
            %============================================================================	
        elseif strcmp(action,'setMinMaxAmpString'),
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata'); 
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            Domain=get(hPlot2dList(20),'value');
            Method = get(hPlot3dList(2),'Value');  	  %'Scalp|Lap|Cort|Perrin Scalp|Perrin Lap';
            EEGMEGStatusString=get(hPlot2dList(110),'String');
            
            if Method==2 | Method==5;
                if Domain<3
                    if strcmp(EEGMEGStatusString,'EEG')
                        MinAmpString='Min. amp. [µV/rad^2]';
                        MaxAmpString='Max. amp. [µV/rad^2]';
                    else
                        MinAmpString='Min. amp. [fT/rad^2]';
                        MaxAmpString='Max. amp. [fT/rad^2]';
                    end
                elseif Domain>2 & Domain<5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        MinAmpString='Min. amp. [µV/(sqrt(Hz) x rad^2)]';
                        MaxAmpString='Max. amp. [µV/(sqrt(Hz) x rad^2)]';
                    else
                        MinAmpString='Min. amp. [fT/(sqrt(Hz) x rad^2)]';
                        MaxAmpString='Max. amp. [fT/(sqrt(Hz) x rad^2)]';
                    end
                elseif Domain==5
                    MinAmpString='Min. variance [%]';
                    MaxAmpString='Max. variance [%]';
                end
            else
                if Domain<3
                    if strcmp(EEGMEGStatusString,'EEG')
                        MinAmpString='Min. amplitude [µV]';
                        MaxAmpString='Max. amplitude [µV]';
                    else
                        MinAmpString='Min. amplitude [fT]';
                        MaxAmpString='Max. amplitude [fT]';
                    end
                elseif Domain>2 & Domain<5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        MinAmpString='Min. amp. [µV/sqrt(Hz)]';
                        MaxAmpString='Max. amp. [µV/sqrt(Hz)]';
                    else
                        MinAmpString='Min. amp. [fT/sqrt(Hz)]';
                        MaxAmpString='Max. amp. [fT/sqrt(Hz)]';
                    end
                elseif Domain==5
                    MinAmpString='Min. var. [%]';
                    MaxAmpString='Max. var. [%]';
                end
            end
            
            set(hPlot3dList(21),'String',MinAmpString)
            set(hPlot3dList(23),'String',MaxAmpString)
          
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif ~isempty(findstr(action,'setActFileNo')),
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata'); 
            ActFileNo2d=get(hPlot2dList(1),'Value');
            Plot2dNListHdr=get(hPlot2dList(51),'Userdata');
            MaxNFiles=hPlot2dList(140);
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            ActFileNo3d=get(hPlot3dList(87),'Value');
            FileNoVec=get(hPlot2dList(56),'Userdata');
            NFileNoVec=length(FileNoVec);
            for FileIndex=1:MaxNFiles
                if ~any(FileNoVec==FileIndex)
                    set(hPlot3dList(140+FileIndex),'Enable','Off');
                else
                    set(hPlot3dList(140+FileIndex),'Enable','On');
                end
            end
            if ~strcmp(action,'setActFileNo')
                ActFileNo2d=str2num(action(length(action)));
                ActFileNo3d=find(FileNoVec==ActFileNo2d);
                if isempty(ActFileNo3d); set(hPlot3dList(87),'Value',1); return; end;
            end
            LabelString=[];
            for FileIndex=1:NFileNoVec  
                FilePath=get(hPlot2dList(Plot2dNListHdr+(FileNoVec(FileIndex)-1).*50+4),'Userdata');
                [File,Path]=SepFilePath(FilePath);
                LabelString=[LabelString,int2str(FileNoVec(FileIndex)),': ',File];
                if FileIndex<NFileNoVec
                    LabelString=[LabelString,'|'];
                end
            end
            set(hPlot3dList(87),'String',LabelString,'Value',ActFileNo3d);
            ActFilePath=get(hPlot2dList(Plot2dNListHdr+(FileNoVec(ActFileNo3d)-1).*50+4),'Userdata');
            set(hPlot3dList(55),'Userdata',ActFilePath);
            Data2Analyse=get(hPlot2dList(Plot2dNListHdr+(FileNoVec(ActFileNo3d)-1).*50+1),'Userdata');
            set(hPlot3dList(54),'Userdata',Data2Analyse);
            set(hPlot3dList(78),'Userdata',sqrt(sum(Data2Analyse.^2)));
            ApplyVec=get(hPlot3dList(33),'Userdata');
            ApplyVec(1)=1; %Recalculate
            set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
            emegs3d('setChanStatusVec')
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'setChanStatusVec'),
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata'); 
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            Plot2dNListHdr=get(hPlot2dList(51),'Userdata');
            FileNoVec=get(hPlot2dList(56),'Userdata');
            NFileNoVec=length(FileNoVec);	
            ParaVec=get(hPlot3dList(62),'Userdata');
            ChanStatusVecOld=get(hPlot3dList(85),'Userdata');
            ActFileNo2d=get(hPlot2dList(1),'Value');
            ActFileNo3d=get(hPlot3dList(87),'Value');
            hDataVec=get(hPlot2dList(Plot2dNListHdr+(FileNoVec(ActFileNo3d)-1).*50+25),'Userdata');
            ChanVisVec=get(hDataVec,'Visible');
            for ChanInd=1:length(ChanVisVec)
                if strcmp(ChanVisVec(ChanInd,:),'on')
                    ChanStatusVec(ChanInd)=1;
                else
                    ChanStatusVec(ChanInd)=0;
                end
            end
            set(hPlot3dList(63),'Userdata',ChanStatusVec); 
            ChanStatusOnVec=find(ChanStatusVec==1);
            ParaVec(17)=length(ChanStatusOnVec);                %NUsedChan;
            set(hPlot3dList(62),'Userdata',ParaVec);
            if sum(abs(ChanStatusVec-ChanStatusVecOld))~=0
                ApplyVec=get(hPlot3dList(33),'Userdata');
                ApplyVec(1)=1; %Recalculate
                set(hPlot3dList(33),'Userdata',ApplyVec);			%hApply
                set(hPlot3dList(90),'Userdata',ChanStatusVec);  %ChanStatusVecOld
                set(hPlot3dList(50),'Userdata',[]); %hCalcPotChan
                set(hPlot3dList(53),'Userdata',[]); %hCalcPot
                set(hPlot3dList(91),'Userdata',[]); %hMinNormXMat
                set(hPlot3dList(92),'Userdata',[]); %hMinNormYMat
                set(hPlot3dList(93),'Userdata',[]); %hMinNormZMat
                set(hPlot3dList(97),'Userdata',[]); %hMNPILFCoeff
                set(hPlot3dList(98),'Userdata',[]); %hMNInvCoeff
                set(hPlot3dList(99),'Userdata',[]); %hMNForCoeff
                set(hPlot3dList(102),'Userdata',[]);%hSLCInvCoeff
                set(hPlot3dList(103),'Userdata',[]);%hSLCForCoeff
                set(hPlot3dList(104),'Userdata',[]);%hSLCForChanCoeff
            end
            set(hPlot3dList(85),'Userdata',ChanStatusVec); %ChanStatusVecOld
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'setDistPoint'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            MinPoint = get(hPlot3dList(47),'Value');
            MaxPoint = get(hPlot3dList(49),'Value');
            NDistInt=get(hPlot3dList(122),'Value');
            MaxDistPoint=MaxPoint-MinPoint+1;
            DistPointVec=get(hPlot3dList(41),'Userdata');
            DistPoint=DistPointVec(1);
            MsPerPoint=DistPointVec(4);
            DistPointMsString=get(hPlot3dList(41),'String');
            DistPointMeanStatus=get(hPlot3dList(44),'Value');
            ind = find(abs(DistPointMsString)<32);
            DistPointMsString(ind) = 32*ones(size(ind));
            DistPointMsString = DistPointMsString';	
            DistPointMsTmp = eval(['[' DistPointMsString(:)' ']'],'-1')';
            DistPointTmp=round(DistPointMsTmp./MsPerPoint);
            if length(DistPointTmp)~=1
                DistPointTmp = DistPoint;
            end
            if DistPointTmp<1
                DistPointTmp=1;
            end
            if DistPointTmp>MaxDistPoint & DistPointMeanStatus;
                DistPointTmp=MaxDistPoint;
            end
            if DistPointTmp~=DistPoint
                ApplyVec=get(hPlot3dList(33),'Userdata');
                ApplyVec(1)=1; %Recalculate
                set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
            end
            DistPoint=DistPointTmp;
            DistPointMs=DistPoint.*MsPerPoint;
            DistPointVec(1:2)=[DistPoint DistPointMs];
            set(hPlot3dList(41),'Userdata',DistPointVec,'String',sprintf('%g',DistPointMs));
            NDistInt=floor(MaxDistPoint./DistPoint);
            set(hPlot3dList(122),'Value',NDistInt,'String', sprintf('%g',NDistInt)); 
           
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
         
        elseif strcmp(action,'setTotalInt'),	
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata'); 
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            NPoints=get(hPlot2dList(50),'Userdata');
            DistPointVec=get(hPlot3dList(41),'Userdata');
            DistPoint=DistPointVec(1);
            MsPerPoint=DistPointVec(4);
            set(hPlot3dList(47),'Value',1); 		%MinPoint
            emegs3d('setMinPointString')
            set(hPlot3dList(49),'Value',NPoints);	%MaxPoint
            emegs3d('setMaxPointString')
            DistPointVec(1:2)=[1 MsPerPoint];
            set(hPlot3dList(41),'Userdata',DistPointVec,'String',sprintf('%g',MsPerPoint));
            emegs3d('setDistPoint')
          
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'setNDistInt'),	
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            NDistInt=get(hPlot3dList(122),'Value');
            NDistIntStr=get(hPlot3dList(122),'String');
            MinPoint = get(hPlot3dList(47),'Value');
            MaxPoint = get(hPlot3dList(49),'Value');
            MaxDistPoint=MaxPoint-MinPoint+1;
            DistPointVec=get(hPlot3dList(41),'Userdata');
            DistPoint=DistPointVec(1);
            MsPerPoint=DistPointVec(4);
            ind=find(abs(NDistIntStr)<22);
            NDistIntStr(ind) = 32*ones(size(ind));
            NDistIntStr = NDistIntStr';	
            NDistIntTmp = eval(['[' NDistIntStr(:)' ']'],'-1')';
            NDistIntTmp=round(NDistIntTmp);
            if length(NDistIntTmp)~=1
                NDistIntTmp=NDistInt;
            end
            if NDistIntTmp<1
                NDistIntTmp=1;
            end
            if NDistIntTmp>MaxDistPoint
                NDistIntTmp = MaxDistPoint;
            end
            DistPoint=ceil(MaxDistPoint./NDistIntTmp)
            DistPointMs=round(DistPoint.*MsPerPoint.*100)./100;
            DistPointVec(1:2)=[DistPoint DistPointMs];
            NDistIntTmp=max([length([MinPoint:DistPoint:MaxPoint])-1,1])
            set(hPlot3dList(122),'Value',NDistIntTmp,'String', sprintf('%g',NDistIntTmp));  
            set(hPlot3dList(41),'Userdata',DistPointVec,'String',sprintf('%g',DistPointMs));
            emegs3d('setDistPoint')   
            if NDistIntTmp==1
                set(hPlot3dList(12),'Value',5); %View2d3d HeadView
            end
            ApplyVec=get(hPlot3dList(33),'Userdata');
            ApplyVec(1)=1; %Recalculate
            set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'setCalcDistPointMean'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            DistPointMeanStatus=get(hPlot3dList(44),'Value');
            if ~DistPointMeanStatus
                set(hPlot3dList(90),'Value',0); %DistPointMNMeanStatus
            else
                set(hPlot3dList(90),'Value',1); %DistPointMNMeanStatus
            end
            ApplyVec=get(hPlot3dList(33),'Userdata');
            ApplyVec(1)=1; %Recalculate
            set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
        
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'setCalcDistPointMNMean'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            set(hPlot3dList(44),'Value',1); %DistPointMeanStatus
            ApplyVec=get(hPlot3dList(33),'Userdata');
            ApplyVec(1)=1; %Recalculate
            set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
          
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'setRealisticHeadView'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            ThetaView=get(hPlot3dList(16),'Userdata');
            PhiView=get(hPlot3dList(18),'Userdata');
            heads=findobj('tag','head3d');
            brains=findobj('tag','brain3d');
            
            for i=length(heads):-1:1
                    figure(get(get(heads(i),'Parent'),'Parent'));
                    axes(get(heads(i),'Parent'));
                    view(ThetaView,PhiView);
                    pause(.01)
            end
            for i=length(brains):-1:1
                    figure(get(get(brains(i),'Parent'),'Parent'));
                    axes(get(brains(i),'Parent'));
                    view(ThetaView,PhiView);
                    pause(.01)
            end
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'ReadViewDefaultFile'),
          
            basepath = strrep(which('emegs2d.m'),'emegs2d.m',['emegs2dUtil',filesep,'ViewDefault',filesep]);
            [viewdeffilename,viewdeffilepath] = uigetfile([basepath,'*.udef3'],'Please choose view default file:');
            if isequal(viewdeffilename,0)| isequal(viewdeffilepath,0)
                return
            end
            viewdeffile = [viewdeffilepath,viewdeffilename] ;
                         
            load(viewdeffile,'-mat','CutRealBotVal','MinPoint3d','MaxPoint3d','Dim2d3dViewVal','HeadModel',...
                'HeadView','ThetaView',...
                'PhiView','DistPoint','SensorNameStatus','SensorCircleStatus',...
                'SensorAsteriskStatus','FlipColormapStatus','ColorMapVal','MinAmp3d',...
                'MaxAmp3d','CenterAmpStatus3d','SpecAmpStatus3d','Print2FileStatus3d',...
                'NColor','PlotEPosStatus','PlotContourStatus','PlotLatencyStatus','GrayFitVal',...
                'UseApp','SLCLambdaApprox','MNLambdaApprox','PlusMinusStatusVec','PlusMinusStatus',...
                'ActMethod','PotContourVal');
            
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
		    hList=get(hPlot2dMenuFig,'Userdata');
            
            SampRate = get(hList(60),'Userdata');
            NPoints = get(hList(50),'Userdata');
            TrigPoint = get(hList(22),'Userdata');
            Domain = 1;
            
            global hPlot3dMenuFig;
            hPlot3dList = get(hPlot3dMenuFig,'userdata');
            %-- CutRealBot-----------------
            try
            set(hPlot3dList(127),'Value',CutRealBotVal);
            emegs3d('CutRealBot');
            catch;end
            %-- MinTime-----------------
            try
                disp(['settings minpoint to ',num2str(Point2Ms(MinPoint3d,Domain,SampRate,TrigPoint(Domain,1))),'...']);
                set(hPlot3dList(47),'String',num2str(Point2Ms(MinPoint3d,Domain,SampRate,TrigPoint(Domain,1),NPoints)));
                emegs3d('setMinPoint');
            catch;end
            %-- MaxTime-----------------
            try
                disp(['settings maxpoint to ',num2str(Point2Ms(MaxPoint3d,Domain,SampRate,TrigPoint(Domain,1))),'...']);
                set(hPlot3dList(49),'String',num2str(Point2Ms(MaxPoint3d,Domain,SampRate,TrigPoint(Domain,1),NPoints)));
                emegs3d('setMaxPoint');
            catch;end
            %--PlotStyle---------------
            try
            set(hPlot3dList(12),'Value',Dim2d3dViewVal);
            emegs3d('set2d3dView');
            catch;end
            %--HeadView-------------------
            try
            set(hPlot3dList(14),'Value',HeadView);
            emegs3d('setHeadView');
            catch;end
             %--HeadModel-------------------
            try
            set(hPlot3dList(129),'Value',HeadModel);
            emegs3d('setHeadModel');
            catch;end
            %--ThetaView-------------
            try
            set(hPlot3dList(20),'Value',ThetaView);
            emegs3d('setThetaView');
            catch;end
            %--PhiView-------------
            try
            set(hPlot3dList(21),'Value',PhiView);
            emegs3d('setPhiView');
            catch;end
            %--DistPoint-------------
            try
            set(hPlot3dList(41),'String',num2str(Point2Ms(DistPoint,Domain,SampRate,1)));
            emegs3d('setDistPoint');
            catch;end
            %--PotContour-------------
            try
            set(hPlot3dList(131),'Value',PotContourVal);
            emegs3d('setPotContour');
            catch;end
            
            %--PlotSensorStatus----
%             
%             
%             
            %--SensorNameStatus-------------
%             set(hPlot3dList(),'Value',);
%             emegs3d('');
%             %--SensorCircleStatus-------------
%             set(hPlot3dList(),'Value',);
%             emegs3d('');
%             %--SensorAsteriskStatus-------------
%             set(hPlot3dList(),'Value',);
%             emegs3d('');
            
            
            %--FlipColormapStatus-------------
            try
            set(hPlot3dList(118),'Value',FlipColormapStatus);
            emegs3d('FlipColormap');   
            catch;end         
            %--ColorMapVal-------------
            try
            set(hPlot3dList(20),'Value',ColorMapVal);
            emegs3d('setColorMap');   
            catch;end         
            %--MinAmp3d-------------
            try
            set(hPlot3dList(22),'String',num2str(MinAmp3d));
            emegs3d('setMinAmp');
            catch;end
            %--MaxAmp3d-------------
            try
            set(hPlot3dList(24),'String',num2str(MaxAmp3d));
            emegs3d('setMaxAmp');
            catch;end
            %--CenterAmpStatus3d-------------
            try
            set(hPlot3dList(25),'Value',CenterAmpStatus3d);
            catch;end
            %--SpecAmpStatus3d-------------
            try
            set(hPlot3dList(26),'Value',SpecAmpStatus3d);
            emegs3d('setMaxAmp');
            catch;end
            %--Print2FileStatus3d-------------
            try
            set(hPlot3dList(27),'Value',Print2FileStatus3d);
            emegs3d('setPrint2FileStatus');
            catch;end
            %--NColor-------------
            try
            set(hPlot3dList(117),'String',num2str(NColor));
            catch;end
            %--PlotEPosStatus-------------
            try
            set(hPlot3dList(30),'Value',PlotEPosStatus);
            catch;end
            %--PlotContourStatus-------------
            try
            set(hPlot3dList(35),'Value',PlotContourStatus);
            catch;end
            %--PlotLatencyStatus-------------
            try
            set(hPlot3dList(43),'Value',PlotLatencyStatus); 
            catch;end           
            %--GrayFitVal-------------
            try
            set(hPlot3dList(119),'Value',GrayFitVal);
            catch;end
            
            %--UseApp-------------
            try
            set(hPlot3dList(72),'Value',UseApp);
            emegs3d('setUseApprox');
            catch;end
            %--SLCLambdaApprox-------------
            try
            set(hPlot3dList(69),'String',num2str(SLCLambdaApprox));
            emegs3d('setSLCLambdaApprox');
            catch;end
            %--PlusMinusStatus-------------
%             set(hPlot3dList(41),'String',num2str(DistPoint));
%             emegs3d('setPPlusMinusAmp');
            %--ActMethod-------------
            try
            set(hPlot3dList(51),'Value',ActMethod);  
            catch;end   
            
           
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'SaveViewDefaultFile'),
          
               
            basepath = strrep(which('emegs2d.m'),'emegs2d.m',['emegs2dUtil',filesep,'ViewDefault',filesep]);
            [viewdeffilename,viewdeffilepath] = uiputfile([basepath,'*.udef3'],'Please name new view default file:');
              if isequal(viewdeffilename,0)| isequal(viewdeffilepath,0)
                return
            end
            viewdeffile = [viewdeffilepath,viewdeffilename] ;
            
            if isempty(findstr(viewdeffile,'.mat')) & isempty(findstr(viewdeffile,'.udef3'))
               viewdeffile =[viewdeffile,'.udef3'];
            end
            
            if ~isempty(findstr(viewdeffile,'.mat'))
               viewdeffile =strrep(viewdeffile,'.mat','.udef3');
            end
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            
            HeadModel=get(hPlot3dList(129),'Userdata');            
            CutRealBotVal=get(hPlot3dList(127),'Value');
            MinPoint3d=get(hPlot3dList(47),'Value');
            MaxPoint3d=get(hPlot3dList(49),'Value');
            Dim2d3dViewVal=get(hPlot3dList(12),'Value');	%'Spec. Surf (3d)|All Surf I (3d)|All Surf II (3d) |Plot (2d)|Spec. Right'|Columns & Rows;
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            View2d3d=get(hPlot3dList(12),'Value');
            PotContourVal =get(hPlot3dList(131),'Value');
            HeadView=get(hPlot3dList(14),'Value');          %labelStr='Back[0, 0]|Front[180, 0]|Top  [0, 90]|Bottom  [180, -90]|Left[-90, 0]|Right [90, 0]|Special';
            ThetaView=get(hPlot3dList(16),'Userdata');
            PhiView=get(hPlot3dList(18),'Userdata');
            DistPointVec=get(hPlot3dList(41),'Userdata');
            DistPoint=DistPointVec(1);
            hTopMenu=get(hPlot3dList(83),'Userdata');
            hStyleMenu=get(hTopMenu(2),'children');
            hStyleTextMenu=get(hStyleMenu(1),'children');
            hStyleTextSensorMenu=get(hStyleTextMenu(1),'children');
            SensorNameStatus=get(hStyleTextSensorMenu(1),'Userdata');
            SensorCircleStatus=get(hStyleTextSensorMenu(2),'Userdata');
            SensorAsteriskStatus=get(hStyleTextSensorMenu(3),'Userdata');
            FlipColormapStatus=get(hPlot3dList(118),'Value'); 
            ColorMapVal=get(hPlot3dList(20),'Value');
            MinAmp3d=get(hPlot3dList(22),'Userdata');
            MaxAmp3d=get(hPlot3dList(24),'Userdata');
            CenterAmpStatus3d=get(hPlot3dList(25),'Value');
            SpecAmpStatus3d=get(hPlot3dList(26),'Value');
            Print2FileStatus3d=get(hPlot3dList(27),'Value');
            NColor=str2num(get(hPlot3dList(117),'String'));
            MoviePauseStatus=get(hPlot3dList(28),'Value');
            PlotEPosStatus=get(hPlot3dList(30),'Value');
            PlotContourStatus=get(hPlot3dList(35),'Value');
            if HeadModel~=1
                PlotContourStatus=3;
            end
            PlotLatencyStatus=get(hPlot3dList(43),'Value');
            GrayFitVal = get(hPlot3dList(119),'Value');
            ColorAmpTotStatus = get(hPlot3dList(120),'Userdata');
            UseApp=get(hPlot3dList(72),'Value');
            SLCLambdaApprox=get(hPlot3dList(69),'Value');
            MNLambdaApprox=get(hPlot3dList(109),'Value');
            PlusMinusStatusVec=get(hPlot3dList(139),'Userdata');
            PlusMinusStatus=PlusMinusStatusVec(1);
            ActMethod=get(hPlot3dList(51),'Value');  
            
            
            save(viewdeffile,'CutRealBotVal','MinPoint3d','MaxPoint3d','Dim2d3dViewVal','HeadModel','HeadView','ThetaView',...
                'PhiView','DistPoint','SensorNameStatus','SensorCircleStatus',...
                'SensorAsteriskStatus','FlipColormapStatus','ColorMapVal','MinAmp3d',...
                'MaxAmp3d','CenterAmpStatus3d','SpecAmpStatus3d','Print2FileStatus3d',...
                'NColor','PlotEPosStatus','PlotContourStatus','PlotLatencyStatus','GrayFitVal',...
                'UseApp','SLCLambdaApprox','MNLambdaApprox','PlusMinusStatusVec','PlusMinusStatus',...
                'ActMethod','PotContourVal');
            
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'AutoViewDefaultFile'),    
               
            
       %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'loadCustomModel'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            plot2dpath = which('emegs2d.m');
            modelpath = strrep(plot2dpath,'emegs2d.m','emegs2dUtil\Models\');
            oldpath = pwd;
            try
                cd(modelpath);
            catch
            end
            [modelfilename,modelfilepath]= uigetfile('*.mat','Please choose model-file:');
            if isequal(modelfilename,0) | isequal(modelfilepath,0) 
                return
            end
            modelfile = [modelfilepath,modelfilename];
            try
                load(modelfile,'head3dx','head3dy','head3dz');
            catch
                uiwait(errordlg('Could not load model! Check permissions and file integrity!','Error:'));
                return
            end
            uiwait(errordlg('Model loaded!','Custom Model:'));
            modelcell = cell(3,1);
            modelcell{1}=head3dx;
            modelcell{2}=head3dy;
            modelcell{3}=head3dz;
            set(hPlot3dList(140),'userdata',modelcell);
            try
                cd(oldpath);
            catch
            end
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'setPotContour'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            PotCont=get(hPlot3dList(131),'Value');
            if PotCont == 1 | PotCont == 3
                set(hPlot3dList(117),'String','20');
            else
                set(hPlot3dList(117),'String','256');
            end
           
          
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'setHeadView'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            HeadView=get(hPlot3dList(14),'Value');
            AllFigViewStatus=get(hPlot3dList(7),'Value');
            ThetaView=get(hPlot3dList(16),'Userdata');
            PhiView=get(hPlot3dList(18),'Userdata');
            if HeadView~=7 %Special
                ViewVec=get(hPlot3dList(79),'Userdata');			
                ThetaView=ViewVec(HeadView,1);
                PhiView=ViewVec(HeadView,2);
                ThetaViewString = sprintf('%g',ThetaView);
                PhiViewString = sprintf('%g',PhiView);
                set(hPlot3dList(16),'Userdata',ThetaView,'String',ThetaViewString);
                set(hPlot3dList(18),'Userdata',PhiView,'String',PhiViewString);
            end	  
            if AllFigViewStatus
                emegs3d('setRealisticHeadView')
            end
        
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            
         
        elseif strcmp(action,'setHeadModel'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            HeadModel=get(hPlot3dList(129),'Value');
            set(hPlot3dList(129),'Userdata',HeadModel);
            ColorAmpTotStatus = get(hPlot3dList(120),'Userdata');
            PotCont=get(hPlot3dList(131),'Value');
            
            if HeadModel==2  | HeadModel==3 | HeadModel==5 | HeadModel==6 | HeadModel==7 | HeadModel==8 | HeadModel==9
                set(hPlot3dList(127),'Enable','on');   
                set(hPlot3dList(131),'Enable','on');
                set(hPlot3dList(30),'Value',3);
                
                %set n-color to 20
                if PotCont == 1 | PotCont == 3
                    set(hPlot3dList(117),'String',20);
                end
                
                %cutrealbot
                if HeadModel == 2 | HeadModel ==3
                    set(hPlot3dList(127),'Value',4);
                else 
                    set(hPlot3dList(127),'Value',1);
                end
            else
                set(hPlot3dList(127),'Enable','off');  
                set(hPlot3dList(131),'Enable','off');
                set(hPlot3dList(117),'String',256);
            end
                   
            if HeadModel == 4
                if ColorAmpTotStatus
                    set(hPlot3dList(117),'String','20');
                end
            end
                
            if HeadModel == 9
                emegs3d('loadCustomModel');
            end
            
         
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
           
        elseif strcmp(action,'setThetaView'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            ThetaView=get(hPlot3dList(16),'Userdata');
            PhiView=get(hPlot3dList(18),'Userdata');
            ViewVec=get(hPlot3dList(79),'Userdata');			
            AllFigViewStatus=get(hPlot3dList(7),'Value');
            ThetaViewString=get(hPlot3dList(16),'String');
            ind = find(abs(ThetaViewString)<32);
            ThetaViewString(ind) = 32*ones(size(ind));
            ThetaViewString = ThetaViewString';	
            ThetaViewTmp = eval(['[' ThetaViewString(:)' ']'],'-1')';
            if ThetaView<-180 | ThetaView>180 | length(ThetaView)~=1
                ThetaViewTmp = ThetaView;
            end
            ThetaViewString = sprintf('%g',ThetaViewTmp);
            set(hPlot3dList(16),'Userdata',ThetaViewTmp,'String',ThetaViewString);
            
            HeadView=1;
            while HeadView<7
                if ThetaViewTmp==ViewVec(HeadView,1) & PhiView==ViewVec(HeadView,2);
                    set(hPlot3dList(14),'Value',HeadView);
                    emegs3d('setHeadView')
                    return;
                end
                HeadView=HeadView+1;
            end
            set(hPlot3dList(14),'Value',7);
            if AllFigViewStatus
                emegs3d('setRealisticHeadView')
            end
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
           
            
        elseif strcmp(action,'setPhiView'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            ThetaView=get(hPlot3dList(16),'Userdata');
            PhiView=get(hPlot3dList(18),'Userdata');
            ViewVec=get(hPlot3dList(79),'Userdata');			
            AllFigViewStatus=get(hPlot3dList(7),'Value');
            PhiViewString=get(hPlot3dList(18),'String');
            ind = find(abs(PhiViewString)<32);
            PhiViewString(ind) = 32*ones(size(ind));
            PhiViewString = PhiViewString';	
            PhiViewTmp = eval(['[' PhiViewString(:)' ']'],'-1')';
            if PhiView<-180 | PhiView>180 | length(PhiView)~=1
                PhiViewTmp = PhiView;
            end
            PhiViewString = sprintf('%g',PhiViewTmp);
            set(hPlot3dList(18),'Userdata',PhiViewTmp,'String',PhiViewString);
            emegs3d('setRealisticHeadView')
            HeadView=1;
            while HeadView<7
                if ThetaView==ViewVec(HeadView,1) & PhiViewTmp==ViewVec(HeadView,2);
                    set(hPlot3dList(14),'Value',HeadView);
                    emegs3d('setHeadView')
                    return;
                end
                HeadView=HeadView+1;
            end
            set(hPlot3dList(14),'Value',7);
            if AllFigViewStatus
                emegs3d('setRealisticHeadView')
            end
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            
        elseif strcmp(action,'setMinPoint') | strcmp(action,'setMinPointString'),
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata');
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            Domain=get(hPlot2dList(20),'Value');
            TrigPoint=get(hPlot2dList(22),'Value');
            MinPoint = get(hPlot3dList(47),'Value');
            MsHzMinPointString = get(hPlot3dList(47),'String');
            MaxPoint = get(hPlot3dList(49),'Value');
            ParaVec=get(hPlot3dList(62),'Userdata');
            NPoints=ParaVec(18);
            NPoints2Plot=ParaVec(19);
            SampRate=ParaVec(20);
            if MinPoint==MaxPoint; MinMaxIdStatus=1; else; MinMaxIdStatus=0; end
            if strcmp(action,'setMinPoint')
                ind=find(abs(MsHzMinPointString)<32);
                MsHzMinPointString(ind) = 32*ones(size(ind));
                MsHzMinPointString = MsHzMinPointString';	
                MsHzMinPointTmp = eval(['[' MsHzMinPointString(:)' ']'],'-1')';
                if Domain<3 %Time, Std
                    MinPointTmp=round(MsHzMinPointTmp.*SampRate./1000+TrigPoint);
                elseif Domain>2 & Domain<5
                    MinPointTmp=round(MsHzMinPointTmp.*NPoints.*2./SampRate);
                elseif Domain==5	%PCA
                    MinPointTmp=MsHzMinPointTmp;
                end
            elseif strcmp(action,'setMinPointString')
                MinPointTmp=MinPoint;
            end
            if length(MinPointTmp)~=1
                MinPointTmp=MinPoint;
            end
            if MinPointTmp>MaxPoint	
                set(hPlot3dList(49),'Value',NPoints); %MaxPoint
                emegs3d('setMaxPointString')
            end
            if MinPointTmp>NPoints 
                MinPointTmp=NPoints;
            end
            if MinPointTmp<=0
                MinPointTmp=1;
            end
            if Domain<3 %Time, Std
                MsHzMinPoint=round((MinPointTmp-TrigPoint).*1000./SampRate);
            elseif Domain>2 & Domain<5
                MsHzMinPoint=round(MinPointTmp.*SampRate./(2.*NPoints));
            elseif Domain==5	%PCA
                MsHzMinPoint=MinPointTmp;
            end
            NPoints3d2Plot=MaxPoint-MinPointTmp+1;
            ParaVec(19)=NPoints3d2Plot;
            ParaVec(21)=NPoints3d2Plot;
            set(hPlot3dList(62),'Userdata',ParaVec);
            MinPointText=get(hPlot3dList(46),'String');
            Ind=findstr(MinPointText,'#')
	        if ~isempty(Ind)
		        MinPointText=[MinPointText(1:Ind),' ',int2str(MinPointTmp)];
	        else
		        MinPointText=[MinPointText,'; #',int2str(MinPointTmp)];
	        end
	        set(hPlot3dList(46),'String',MinPointText);
            set(hPlot3dList(47),'Value',MinPointTmp,'String',sprintf('%g',MsHzMinPoint));
            if MinMaxIdStatus
                set(hPlot3dList(48),'String',MinPointText);
                set(hPlot3dList(49),'Value',MinPointTmp,'String',sprintf('%g',MsHzMinPoint));
            end
            ApplyVec=get(hPlot3dList(33),'Userdata');
            ApplyVec(1)=1; %Recalculate
            set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
            emegs3d('setDistPoint')
            emegs3d('setNDistInt')
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'setMaxPoint') | strcmp(action,'setMaxPointString'),
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata');
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            Domain=get(hPlot2dList(20),'Value');
            TrigPoint=get(hPlot2dList(22),'Value');
            MinPoint = get(hPlot3dList(47),'Value');
            MaxPoint = get(hPlot3dList(49),'Value');
            MsHzMaxPointString = get(hPlot3dList(49),'String');
            ParaVec=get(hPlot3dList(62),'Userdata');
            NPoints=ParaVec(18);
            NPoints2Plot=ParaVec(19);
            SampRate=ParaVec(20);
            if strcmp(action,'setMaxPoint') 
                ind=find(abs(MsHzMaxPointString)<32);
                MsHzMaxPointString(ind) = 32*ones(size(ind));
                MsHzMaxPointString = MsHzMaxPointString';	
                MsHzMaxPointTmp = eval(['[' MsHzMaxPointString(:)' ']'],'-1')';
                if Domain<3 %Time, Std
                    MaxPointTmp=round(MsHzMaxPointTmp.*SampRate./1000+TrigPoint);
                elseif Domain>2 & Domain<5
                    MaxPointTmp=round(MsHzMaxPointTmp.*NPoints.*2./SampRate);
                elseif Domain==5 %PCA
                    MaxPointTmp=MsHzMaxPointTmp;
                end
            elseif strcmp(action,'setMaxPointString') 
                MaxPointTmp=MaxPoint;
            end
            if length(MaxPointTmp)~=1
                MaxPointTmp=MaxPoint;
            end
            if MaxPointTmp<MinPoint	
                set(hPlot3dList(47),'Value',1); %MinPoint
                emegs3d('setMinPointString')
            end
            if MaxPointTmp>NPoints 
                MaxPointTmp=NPoints;
            end
            if Domain<3 %Time, Std
                MsHzMaxPoint=round((MaxPointTmp-TrigPoint).*1000./SampRate);
            elseif Domain>2 & Domain<5
                MsHzMaxPoint=round(MaxPointTmp.*SampRate./(2.*NPoints));
            else	%PCA
                MsHzMaxPoint=MaxPointTmp;
            end
            NPoints3d2Plot=MaxPointTmp-MinPoint+1;
            ParaVec(19)=NPoints3d2Plot;
            ParaVec(21)=NPoints3d2Plot;
            set(hPlot3dList(62),'Userdata',ParaVec);
            MaxPointText=get(hPlot3dList(48),'String');
            Ind=findstr(MaxPointText,'#')
	        if ~isempty(Ind)
		        MaxPointText=[MaxPointText(1:Ind),' ',int2str(MaxPointTmp)];
	        else
		        MaxPointText=[MaxPointText,'; #',int2str(MaxPointTmp)];
	        end
	        set(hPlot3dList(48),'String',MaxPointText);
            set(hPlot3dList(49),'Value',MaxPointTmp,'String',sprintf('%g',MsHzMaxPoint));
            ApplyVec=get(hPlot3dList(33),'Userdata');
            ApplyVec(1)=1; %Recalculate
            set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
            emegs3d('setDistPoint')
            emegs3d('setNDistInt')
          
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'setMinAmp') | strcmp(action,'setMaxAmp'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            CenterStatus = get(hPlot3dList(25),'Value');
            if strcmp(action,'setMinAmp')
                ValInd1=22; ValInd2=24;
            else
                 ValInd1=24; ValInd2=22;
            end
            Val1=get(hPlot3dList(ValInd1),'Userdata');
            Val2=get(hPlot3dList(ValInd2),'Userdata');
            Str1=get(hPlot3dList(ValInd1),'String');
            [Val3,Str3]=String2Value(Str1,Val1);
            if strcmp(action,'setMinAmp')
                if Val3>=Val2
                    Val3=Val1;
                end
            else
                if Val3<=Val2
                    Val3=Val1;
                end
            end
            Val3=round(Val3*10000000000)/10000000000;
            Str3=sprintf('%g',Val3);
            set(hPlot3dList(ValInd1),'Userdata',Val3,'String',Str3);  
            if CenterStatus
                if (strcmp(action,'setMinAmp') & Val3>=0) | (strcmp(action,'setMaxAmp') & Val3<=0)
                    set(hPlot3dList(25),'Value',0); %CenterStatus
                else
                    Val3=-Val3;
                    Str3=sprintf('%g',Val3);
                    set(hPlot3dList(ValInd2),'Userdata',Val3,'String',Str3);
                end
            end
         
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
           
        elseif strcmp(action,'setGrayFit'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            ValIn = get(hPlot3dList(119),'Value');
            StrIn = get(hPlot3dList(119),'String');
            [ValOut,StrOut]=String2Value(StrIn,ValIn,0,[],1,1);
            set(hPlot3dList(119),'Value',ValOut,'String',StrOut);
          
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'setNRowColorMap')
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            v = get(hPlot3dList(117),'Value');
            vVec = get(hPlot3dList(117),'Userdata');
            str = get(hPlot3dList(117),'String');
            ColorAmpTotStatus = get(hPlot3dList(120),'Userdata');
            
            ind = find(abs(str)<32);
            str(ind) = 32*ones(size(ind));
            str = str';
            vv = eval(['[' str(:)' ']'],'-1')';
            if length(vv)~=1
                vv = v;
            end
            if ColorAmpTotStatus
                if vv<1
                    vv = v;
                end
                vv = ceil(vv);
                vvVec(1)=vv;
            else
                if vv<=0
                    vv = v;
                end
                vvVec(2)=vv;
            end
            set(hPlot3dList(117),'Value',vv,'Userdata',vVec,'String',sprintf('%g',vv));	
          
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'setColorAmpTot'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            ColorAmpTotStatus = get(hPlot3dList(120),'Userdata');
            vVec = get(hPlot3dList(117),'Userdata');
            if ColorAmpTotStatus
                set(hPlot3dList(120),'Userdata',0,'String','N-Color by Amp.');
                vv=vVec(2);
            else
                set(hPlot3dList(120),'Userdata',1,'String','N-Color');
                vv=vVec(1);
            end
            set(hPlot3dList(117),'Value',vv,'String',sprintf('%g',vv));
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'setCenterAmp'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            CenterStatus = get(hPlot3dList(25),'value');
            MinAmp=get(hPlot3dList(22),'Userdata');
            MaxAmp=get(hPlot3dList(24),'Userdata');
            if CenterStatus
                NewAmp=max(abs([MinAmp MaxAmp]));
                set(hPlot3dList(22),'Userdata',-1.*NewAmp,'String',sprintf('%g',-1.*NewAmp));
                set(hPlot3dList(24),'Userdata',NewAmp,'String',sprintf('%g',NewAmp));
                set(hPlot3dList(45),'Value',0); %AutoAmp
            end
           
           
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
         
        elseif strcmp(action,'setAutoAmp'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            AutoAmp=get(hPlot3dList(45),'Value');
            if AutoAmp
                set(hPlot3dList(136),'Value',0); 
                set(hPlot3dList(137),'Value',0); 
                set(hPlot3dList(138),'Value',0);     
                CalcPot=get(hPlot3dList(53),'Userdata'); 
                if ~isempty(CalcPot)
                    MinAmpTmp=min(min(CalcPot));
                    MaxAmpTmp=max(max(CalcPot));
                    MinAmpTmp = round(MinAmpTmp*1000)/1000;
                    MaxAmpTmp = round(MaxAmpTmp*1000)/1000;
                    MinAmpTmpStr = sprintf('%g',MinAmpTmp);
                    MaxAmpTmpStr = sprintf('%g',MaxAmpTmp);
                    set(hPlot3dList(22),'Userdata',MinAmpTmp,'String',MinAmpTmpStr);  
                    set(hPlot3dList(24),'Userdata',MaxAmpTmp,'String',MaxAmpTmpStr);  
                end
                set(hPlot3dList(136),'Enable','Off');
                set(hPlot3dList(137),'Enable','Off');
                set(hPlot3dList(138),'Enable','Off');
                set(hPlot3dList(139),'Userdata',[0 0],'String','Stats'); %PlusMinusStatusVec
            end
          
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'setPPlusMinusAmp') 
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            PlusMinusStatusVec=get(hPlot3dList(139),'Userdata');
            PlusMinusStatus=PlusMinusStatusVec(1);
            PlusMinusVal=PlusMinusStatusVec(2);
            if PlusMinusStatus==0
                PlusMinusStatusVec(1)=2;
                PlusMinusString='+/-'; 
                MaxAmp=1;
                MinAmp=-1; 
             elseif PlusMinusStatus==2   
                PlusMinusStatusVec(1)=+1;
                PlusMinusString='+';  
                MaxAmp=1;
                MinAmp=0;     
            elseif PlusMinusStatus==1
                PlusMinusStatusVec(1)=-1;
                PlusMinusString='-';  
                MaxAmp=0;
                MinAmp=-1;     
            elseif PlusMinusStatus==-1
                PlusMinusStatusVec(1)=0;
                PlusMinusStatusVec(2)=0;
                PlusMinusString='Stats';   
                MaxAmp=1;
                MinAmp=-1; 
            end
            PlusMinusStatus=PlusMinusStatusVec(1);
            PlusMinusVal=PlusMinusStatusVec(2);
            MinAmpStr = sprintf('%g',MinAmp);
            MaxAmpStr = sprintf('%g',MaxAmp);
            set(hPlot3dList(22),'Userdata',MinAmp,'String',MinAmpStr);  
            set(hPlot3dList(24),'Userdata',MaxAmp,'String',MaxAmpStr);  
            if PlusMinusStatus~=0
                set(hPlot3dList(135),'Enable','On');
                set(hPlot3dList(136),'Enable','On');
                set(hPlot3dList(137),'Enable','On');
                set(hPlot3dList(138),'Enable','On');
                PlusMinusString=[PlusMinusString,' ',int2str(PlusMinusVal.*100)]; 
                set(hPlot3dList(45),'Value',0); %AutoAmp
            else
                set(hPlot3dList(135),'Userdata',0,'String','0','Enable','Off');
                set(hPlot3dList(136),'Enable','Off');
                set(hPlot3dList(137),'Enable','Off');
                set(hPlot3dList(138),'Enable','Off');
                set(hPlot3dList(45),'Value',1); %AutoAmp
            end    
            set(hPlot3dList(139),'Userdata',PlusMinusStatusVec,'String',PlusMinusString);
           
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
         
        elseif strcmp(action,'setP90Amp') | strcmp(action,'setP95Amp') | strcmp(action,'setP99Amp') | strcmp(action,'setPEditAmp') ,
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            PlusMinusStatusVec=get(hPlot3dList(139),'Userdata');
            PlusMinusStatus=PlusMinusStatusVec(1);
            PlusMinusVal=PlusMinusStatusVec(2);
            if strcmp(action,'setP90Amp')
                PlusMinusVal=0.9;
                PlusMinusValStr='90';
            elseif strcmp(action,'setP95Amp')    
                PlusMinusVal=0.95;
                PlusMinusValStr='95';
            elseif strcmp(action,'setP99Amp')    
                PlusMinusVal=0.99;
                PlusMinusValStr='99';
            elseif strcmp(action,'setPEditAmp') 
                PlusMinusValStr=get(hPlot3dList(135),'String');
                PlusMinusVal=get(hPlot3dList(135),'Userdata');
                [PlusMinusVal,PlusMinusValStr]=String2Value(PlusMinusValStr,PlusMinusVal,0,100,0,1);
                PlusMinusVal=PlusMinusVal./100;
            end
            PlusMinusStatusVec(2)=PlusMinusVal;
            if PlusMinusStatus==1
                MaxAmp=1;
                MinAmp=0;     
                PlusMinusString='+';  
            elseif PlusMinusStatus==-1
                MinAmp=-1;
                MaxAmp=0;
                PlusMinusString='-';  
            elseif PlusMinusStatus==2
                MinAmp=-1;
                MaxAmp=+1;
                PlusMinusString='+/-';     
            end  
            PlusMinusString=[PlusMinusString,' ',int2str(PlusMinusVal.*100)]; 
            set(hPlot3dList(139),'Userdata',PlusMinusStatusVec,'String',PlusMinusString);
            set(hPlot3dList(135),'Userdata',PlusMinusVal,'String',PlusMinusValStr);
            MinAmpStr = sprintf('%g',MinAmp);
            MaxAmpStr = sprintf('%g',MaxAmp);
            set(hPlot3dList(22),'Userdata',MinAmp,'String',MinAmpStr);  
            set(hPlot3dList(24),'Userdata',MaxAmp,'String',MaxAmpStr);  
            set(hPlot3dList(45),'Value',0);  
            emegs3d('setAutoAmp')
            set(hPlot3dList(25),'Value',0);  %CenterAmp
            emegs3d('setCenterAmp')
           
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
         
        elseif strcmp(action,'setUseApprox'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            ApplyVec=get(hPlot3dList(33),'Userdata');
            ApplyVec(1)=1; %Recalculate
            set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
          
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'setSLCLambdaApprox') | strcmp(action,'setMNLambdaApprox'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            if strcmp(action,'setSLCLambdaApprox') 
                ListNo=69;
            elseif  strcmp(action,'setMNLambdaApprox')
                ListNo=109;
            end
            v=get(hPlot3dList(ListNo),'Value');
            str = get(hPlot3dList(ListNo),'String');
            
            ind = find(abs(str)<32);
            str(ind) = 32*ones(size(ind));
            str = str';
            vv = eval(['[' str(:)' ']'],'-1')';
            if vv<=0 | length(vv)~=1
                vv = v;
            else
                ApplyVec=get(hPlot3dList(33),'Userdata');
                ApplyVec(1)=1; %Recalculate
                set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
                set(hPlot3dList(97),'Userdata',[]);
                set(hPlot3dList(98),'Userdata',[]);
                set(hPlot3dList(99),'Userdata',[]);
                set(hPlot3dList(102),'Userdata',[]);
                set(hPlot3dList(103),'Userdata',[]);
                set(hPlot3dList(104),'Userdata',[]);
            end
            set(hPlot3dList(ListNo),'Value',vv,'String', sprintf('%g',vv));
          
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
        elseif strcmp(action,'setUseApproxVec'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            UseApproxVec=get(hPlot3dList(66),'Value');
            StdChanVec=get(hPlot3dList(65),'Userdata');
            if UseApproxVec & all(StdChanVec==1)
                set(hPlot3dList(66),'Value',0);
            else
                ApplyVec=get(hPlot3dList(33),'Userdata');
                ApplyVec(1)=1; %Recalculate
                set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
            end
           
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
         
        elseif strcmp(action,'setUseApproxMat'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            UseApproxMat=get(hPlot3dList(67),'Value');
            StdChanTimeMat=get(hPlot3dList(64),'Userdata');
            if UseApproxMat & all(StdChanTimeMat==1)
                set(hPlot3dList(67),'Value',0);
            else
                ApplyVec=get(hPlot3dList(33),'Userdata');
                ApplyVec(1)=1; %Recalculate
                set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
            end
           
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
         
        elseif strcmp(action,'setMinBetaApprox'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            v=get(hPlot3dList(74),'Userdata');
            str = get(hPlot3dList(74),'String');
            
            ind = find(abs(str)<32);
            str(ind) = 32*ones(size(ind));
            str = str';
            vv = eval(['[' str(:)' ']'],'-1')';
            if vv<=0 | vv>1 | length(vv)~=1
                vv = v;
            else
                ApplyVec=get(hPlot3dList(33),'Userdata');
                ApplyVec(1)=1; %Recalculate
                set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
            end
            str = sprintf('%g',vv);
            set(hPlot3dList(74),'Userdata',vv,'String',str);
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'setBetaWeightMethod'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            UseApproxStatus=get(hPlot3dList(72),'Userdata');
            if UseApproxStatus
                ApplyVec=get(hPlot3dList(33),'Userdata');
                ApplyVec(1)=1; %Recalculate
                set(hPlot3dList(33),'Userdata',ApplyVec);				%hApply
            end
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'setPrint2FileMethod'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            Print2FileMethod=get(hPlot3dList(89),'Value');
            if Print2FileMethod==1; 	Print2FileMethodString='EPS';
                Print2FileCompVal=100;
            elseif Print2FileMethod==2; Print2FileMethodString='EPSTIFF';
                Print2FileCompVal=100;
            elseif Print2FileMethod==3; Print2FileMethodString='JPEG';
                Print2FileCompVal=80;
            elseif Print2FileMethod==4; Print2FileMethodString='TIFF';
                Print2FileCompVal=150; 	
            end
            set(hPlot3dList(37),'Userdata',Print2FileCompVal,'String',sprintf('%g',Print2FileCompVal));
            set(hPlot3dList(89),'Userdata',Print2FileMethodString)
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'setPrint2FileStatus'),
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata'); 
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            Print2FileStatus=get(hPlot3dList(27),'Value');
            Print2FileMethodString=get(hPlot3dList(89),'Userdata');
            
            if Print2FileStatus		
                DefFilePath=which('emegs3dPrintFiles')
                if ~strcmp(DefFilePath,'')
                    FileSepVec=findstr(DefFilePath,filesep);
                    DefFilePath=[DefFilePath(1:FileSepVec(length(FileSepVec))),'PrintName']
                else
                    DefFilePath='PrintName';
                end
                [Print2File,Print2Path,Print2FilePath]=WriteFilePath(DefFilePath,['Please choose a file name without extension:']);
                if Print2File==0; 
                    set(hPlot3dList(27),'Value',0);
                    return;
                end
                BlankVec=findstr(Print2FilePath,' ');
                if ~isempty(BlankVec)
                    set(hPlot3dList(27),'Value',0);
                    Message=char('Sorry,');
                    Message=char(Message,'');
                    Message=char(Message,'your chosen path:');
                    Message=char(Message,Print2FilePath);
                    Message=char(Message,'contains one or more blanks.');
                    Message=char(Message,'');
                    Message=char(Message,'Using the Matlab function "print"');
                    Message=char(Message,'blanks in the path are not permitted.');
                    hmsgbox=msgbox(Message,'Info','help'); 
                    return;
                end	
                set(hPlot3dList(27),'Userdata',Print2FilePath); 
            end
            
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'setPrintFileComp'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            v=get(hPlot3dList(37),'Userdata');
            str = get(hPlot3dList(37),'String');
            
            ind = find(abs(str)<32);
            str(ind) = 32*ones(size(ind));
            str = str';
            vv = eval(['[' str(:)' ']'],'-1')';
            if vv<=0 | vv>100 | length(vv)~=1
                vv = v;
            end
            str = sprintf('%g',vv);
            set(hPlot3dList(37),'Userdata',vv,'String',str);
            
            %=============================================================================
            %============ DispSensorName: display number of sensor at sensor position
            %============ DispSensorCircle: display circle at sensor position
            %============ DispSensorAsterisk: display asterisk at sensor position
            %=============================================================================
        elseif strcmp(action,'DispSensorName') | strcmp(action,'DispSensorCircle') | strcmp(action,'DispSensorAsterisk')
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            hTopMenu=get(hPlot3dList(83),'Userdata');
            hStyleMenu=get(hTopMenu(2),'children');
            hStyleTextMenu=get(hStyleMenu(1),'children');
            hStyleTextSensorMenu=get(hStyleTextMenu(1),'children');
            if strcmp(action,'DispSensorName')
                hAct=hStyleTextSensorMenu(1);
                ActStatus=get(hAct,'Userdata');
            elseif strcmp(action,'DispSensorCircle')
                hAct=hStyleTextSensorMenu(2);
                ActStatus=get(hAct,'Userdata');
            elseif strcmp(action,'DispSensorAsterisk')
                hAct=hStyleTextSensorMenu(3);
                ActStatus=get(hAct,'Userdata');
            end
            if ActStatus==1
                ActStatus=0;
            elseif ActStatus==0
                ActStatus=1;
            end
            set(hAct,'Userdata',ActStatus);
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'FlipColormap')
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata');
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            FlipColormapStatus=get(hPlot3dList(118),'Value');
            hTopMenu=get(hPlot3dList(83),'Userdata');
            hStyleMenu=get(hTopMenu(2),'children');
            hStyleColormapMenu=get(hStyleMenu(2),'children');
            pointer=get(hPlot2dList(83),'Userdata');
            ColormapFlipLabel=get(hStyleColormapMenu(1),'Label');
            ColormapFlipPointPos=get(hStyleColormapMenu(1),'Userdata');
            if FlipColormapStatus
                ColormapFlipLabel(ColormapFlipPointPos)=setstr(pointer);  
            else
                ColormapFlipLabel(ColormapFlipPointPos)=' '; 
            end
            set(hStyleColormapMenu(1),'Label',ColormapFlipLabel);
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'CalcCortMap'),
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata');
            hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
            
            emegs3d('setChanStatusVec')
            Method = get(hPlot3dList(2),'Value');	  %'Scalp|Lap|Cort|Perrin Scalp|Perrin Lap';
            set(hPlot3dList(33),'Userdata',[1,1,Method]);%hApply [Recalculate, SLC, Method]
            MethodOld = get(hPlot3dList(2),'Userdata');
            if MethodOld~=Method
                set(hPlot3dList(2),'Userdata',Method);
                set(hPlot3dList(102),'Userdata',[]);
                set(hPlot3dList(103),'Userdata',[]);
                set(hPlot3dList(104),'Userdata',[]);
            end
            UseApp=get(hPlot3dList(72),'Value');
            Domain=get(hPlot2dList(20),'Value');
            EEGMEGStatusString=get(hPlot2dList(110),'String');
            
            if isempty(varargin)
                targetfig = [];
            else
                targetfig = varargin{1};
            end
            
            if  Method==1 & ~UseApp; 
                if Domain<3; 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=6; 
                    else
                        TitleNum=73; 
                    end
                elseif Domain>2 & Domain<5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=57; 
                    else
                        TitleNum=74; 
                    end
                elseif Domain==5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=93; 
                    else
                        TitleNum=94; 
                    end
                end
                CoeffStatus=2;
            elseif  Method==1 &  UseApp; 
                if Domain<3; 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=25; 
                    else
                        TitleNum=75; 
                    end
                elseif Domain>2 & Domain<5     
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=58; 
                    else
                        TitleNum=76; 
                    end
                elseif Domain==5     
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=95; 
                    else
                        TitleNum=96; 
                    end
                end
                CoeffStatus=2;
            elseif  Method==2 & ~UseApp; 
                if Domain<3; 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=17; 
                    else
                        TitleNum=77; 
                    end
                elseif Domain>2 & Domain<5      
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=59; 
                    else
                        TitleNum=78; 
                    end
                elseif Domain==5
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=97; 
                    else
                        TitleNum=98; 
                    end
                end
                CoeffStatus=3;
            elseif  Method==2 &  UseApp; 
                if Domain<3; 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=26; 
                    else
                        TitleNum=79; 
                    end
                elseif Domain>2 & Domain<5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=60; 
                    else
                        TitleNum=80; 
                    end
                elseif Domain==5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=99; 
                    else
                        TitleNum=100; 
                    end
                end
                CoeffStatus=3;
            elseif  Method==3 & ~UseApp; 
                if Domain<3; 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=2; 
                    elseif Domain>2 & Domain<5 
                        TitleNum=81; 
                    end
                elseif Domain>2 & Domain<5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=61; 
                    else
                        TitleNum=82; 
                    end
                elseif Domain==5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=101; 
                    else
                        TitleNum=102; 
                    end
                end
                CoeffStatus=4;
            elseif  Method==3 &  UseApp; 
                if Domain<3; 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=27; 
                    else
                        TitleNum=83; 
                    end
                elseif Domain>2 & Domain<5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=62; 
                    else
                        TitleNum=84; 
                    end
                elseif Domain==5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=103; 
                    else
                        TitleNum=104; 
                    end
                end
                CoeffStatus=4;
            elseif  Method==4 & ~UseApp; 
                if Domain<3; 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=7; 
                    else
                        TitleNum=85; 
                    end
                elseif Domain>2 & Domain<5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=63; 
                    else
                        TitleNum=86; 
                    end
                elseif Domain==5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=105; 
                    else
                        TitleNum=106; 
                    end
                end
                CoeffStatus=2;
            elseif  Method==4 &  UseApp; 
                if Domain<3; 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=32; 
                    else
                        TitleNum=87; 
                    end
                elseif Domain>2 & Domain<5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=64; 
                    else
                        TitleNum=88; 
                    end
                elseif Domain==5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=107; 
                    else
                        TitleNum=108; 
                    end
                end
                CoeffStatus=2;
            elseif  Method==5 & ~UseApp; 
                if Domain<3; 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=10; 
                    else
                        TitleNum=89; 
                    end
                elseif Domain>2 & Domain<5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=65; 
                    else
                        TitleNum=90; 
                    end
                elseif Domain==5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=109; 
                    else
                        TitleNum=110; 
                    end
                end
                CoeffStatus=3;
            elseif  Method==5 &  UseApp;
                if Domain<3; 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=33; 
                    else
                        TitleNum=91; 
                    end
                elseif Domain>2 & Domain<5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=66; 
                    else
                        TitleNum=92; 
                    end
                elseif Domain==5 
                    if strcmp(EEGMEGStatusString,'EEG')
                        TitleNum=111; 
                    else
                        TitleNum=112; 
                    end
                end
                CoeffStatus=3;
            end
            set(hPlot3dList(51),'Value',Method); 
            set(hPlot3dList(52),'Value',TitleNum); 
            MinPoint=get(hPlot3dList(47),'Value');
            MaxPoint=get(hPlot3dList(49),'Value');
            ChanStatusVec=get(hPlot3dList(63),'Userdata');
            ChanStatusOnVec=find(ChanStatusVec==1);
            Data2Analyse=get(hPlot3dList(54),'Userdata');
            Data2Analyse=Data2Analyse(ChanStatusOnVec,MinPoint:MaxPoint);
            ParaVec=get(hPlot3dList(62),'Userdata');
            NChan=ParaVec(16);
            NUsedChan=ParaVec(17);
            NPoints3d=ParaVec(19);
            EPosSpher=get(hPlot3dList(56),'Userdata'); 
            EPosCart=get(hPlot3dList(57),'Userdata');
            PathLeg=get(hPlot3dList(59),'Userdata');
            PathCoeff=get(hPlot3dList(60),'Userdata');
            ECfgFilePath=get(hPlot3dList(61),'Userdata');
            [ECfgFile,ECfgPath]=SepFilePath(ECfgFilePath);
            ParaVec=get(hPlot3dList(62),'Userdata');		
            NSqrtScalpLoc=ParaVec(14);
            InvIter=ParaVec(10);
            ForIter=ParaVec(11);
            PIter=ParaVec(12);
            MSpherical=ParaVec(13);
            LengthLegVec=ParaVec(15);
            ScalpLoc=get(hPlot3dList(58),'Userdata');
            StdChanTimeMat=get(hPlot3dList(64),'Userdata');
            StdChanVec=get(hPlot3dList(65),'Userdata');
            UseApproxVec=get(hPlot3dList(66),'Value');
            UseApproxMat=get(hPlot3dList(67),'Value');
            SLCLambdaApprox=get(hPlot3dList(69),'Value');
            NTrialAvgVec=get(hPlot3dList(70),'Userdata');
            MinBetaApprox=get(hPlot3dList(74),'Userdata');
            BetaWeightMethod=get(hPlot3dList(76),'Value');
            DistPointVec=get(hPlot3dList(41),'Userdata');
            DistPoint=DistPointVec(1);
            DistPointMeanStatus=get(hPlot3dList(44),'Value');
            AutoAmp=get(hPlot3dList(45),'Value');
            CalcSLC2FileStatus=get(hPlot3dList(101),'Value');			%CalcSLC2File
            InvCoeff=get(hPlot3dList(102),'Userdata');			
            ForCoeff=get(hPlot3dList(103),'Userdata');			
            ForChanCoeff=get(hPlot3dList(104),'Userdata');			
            
            if DistPoint>1
                if ~DistPointMeanStatus
                    TimeIndexVec=[1:DistPoint:NPoints3d];
                    NPoints2Plot=length(TimeIndexVec);
                    Data2Analyse=Data2Analyse(:,TimeIndexVec); 
                else
                    TimeIndexVec=[1:DistPoint:NPoints3d-DistPoint+1];
                    NPoints2Plot=length(TimeIndexVec);
                    NUsedChan=NUsedChan
                    size(Data2Analyse)
                    Data2AnalyseTmp=zeros(NUsedChan,NPoints2Plot);
                    for Ind=1:NPoints2Plot
                        Data2AnalyseTmp(:,Ind)=mean(Data2Analyse(:,(Ind-1).*DistPoint+1:Ind.*DistPoint),2);
                    end
                    Data2Analyse=Data2AnalyseTmp; clear Data2AnalyseTmp;
                end
            else
                NPoints2Plot=NPoints3d;
            end
            ParaVec(21)=NPoints2Plot;	%Number of points to plot
            set(hPlot3dList(62),'Userdata',ParaVec);
            
            %Subtract the mean part of Data2Analyse
            c0=mean(Data2Analyse);
            [C0Data2Analyse]=CalcValOfVecToMat(Data2Analyse,c0,['-']);
            
            if isempty(InvCoeff) | isempty(ForCoeff) | isempty(ForChanCoeff)
                if Method<4 
                    [InvCoeff] = ReadOrCalcCoeff(1,EPosCart,ScalpLoc,PathLeg,...
                        PathCoeff,ECfgFile,NSqrtScalpLoc,...
                        InvIter,0,LengthLegVec);
                    [ForCoeff] = ReadOrCalcCoeff(CoeffStatus,EPosCart,ScalpLoc,PathLeg,...
                        PathCoeff,ECfgFile,NSqrtScalpLoc,...
                        ForIter,0,LengthLegVec);			  
                elseif Method>=4
                    [InvCoeff] = ReadOrCalcPCoeff(1,EPosCart,ScalpLoc,PathLeg,...
                        PathCoeff,ECfgFile,NSqrtScalpLoc,...
                        PIter,MSpherical,LengthLegVec);
                    [ForCoeff] = ReadOrCalcPCoeff(CoeffStatus,EPosCart,ScalpLoc,PathLeg,...
                        PathCoeff,ECfgFile,NSqrtScalpLoc,...
                        PIter,MSpherical,LengthLegVec);
                end	
                if Method==1 | Method==4				  
                    ForChanCoeff=InvCoeff';
                else
                    if Method<4 
                        [ForChanCoeff] = ReadOrCalcCoeff(CoeffStatus,EPosCart,EPosCart,PathLeg,...
                            PathCoeff,ECfgFile,NChan,...
                            ForIter,0,LengthLegVec);
                    else
                        [ForChanCoeff] = ReadOrCalcPCoeff(CoeffStatus,EPosCart,EPosCart,PathLeg,...
                            PathCoeff,ECfgFile,NChan,...
                            PIter,MSpherical,LengthLegVec);
                    end
                end
                InvCoeff=InvCoeff(ChanStatusOnVec,ChanStatusOnVec);	
                TmpInvCoeff=InvCoeff;
                ForCoeff=ForCoeff(ChanStatusOnVec,:);
                ForChanCoeff=ForChanCoeff(ChanStatusOnVec,:);
                set(hPlot3dList(102),'Userdata',InvCoeff);
                set(hPlot3dList(103),'Userdata',ForCoeff);
                set(hPlot3dList(104),'Userdata',ForChanCoeff);
            end
            if UseApp & (UseApproxVec | UseApproxMat)
                if isempty(StdChanTimeMat)
                    UseApproxVec=0;
                    UseApproxMat=0;
                    set(hPlot3dList(66),'Value',UseApproxVec,'Userdata',UseApproxVec);
                    set(hPlot3dList(67),'Value',UseApproxMat,'Userdata',UseApproxMat);
                end
            else
                AppMat=[];	
            end
            if UseApp
                SLCLambdaApprox=SLCLambdaApprox.*InvCoeff(1,1);		% Achtung: Da InvCoeff anders berechnet wurde als unter CalcInverse (Min. Norm)
                if UseApproxMat		
                    CalcPot=zeros(NSqrtScalpLoc.^2,NPoints2Plot);
                    CalcPotChan=zeros(NChan,NPoints2Plot);
                    AppMat=StdChanTimeMat(ChanStatusOnVec,:).*SLCLambdaApprox;
                    for TimeInd=1:NPoints2Plot
                        TmpInvCoeff=InvCoeff;
                        TmpInvCoeff=InvCoeff+diag(AppMat(:,TimeInd));
                        DipStrength = TmpInvCoeff \ C0Data2Analyse(:,TimeInd);
                        CalcPot(:,TimeInd)=(DipStrength' * ForCoeff)';
                        CalcPotChan(:,TimeInd)=(DipStrength' * ForChanCoeff)';
                    end
                elseif UseApproxVec
                    BetaVec=StdChanVec(ChanStatusOnVec)';
                    k=find(BetaVec==0);
                    if ~isempty(k); BetaVec(k)=10.^(-6).*ones(length(k),1); end
                    BetaVec=1./BetaVec;
                    if BetaWeightMethod==1
                        BetaWeightPot=.5;
                    elseif BetaWeightMethod==2
                        BetaWeightPot=1;
                    elseif BetaWeightMethod==3
                        BetaWeightPot=2;
                    elseif BetaWeightMethod==4
                        BetaWeightPot=3;
                    end
                    BetaVec=BetaVec.^BetaWeightPot;
                    BetaVec=norm_1(BetaVec,4,[],MinBetaApprox,1);
                    AppVec=SLCLambdaApprox.*BetaVec;
                    TmpInvCoeff=InvCoeff;
                    TmpInvCoeff=InvCoeff+diag(AppVec);
                else
                    TmpInvCoeff=InvCoeff;
                    TmpInvCoeff=InvCoeff+SLCLambdaApprox.*eye(NUsedChan);
                end
            else
                TmpInvCoeff=InvCoeff;
            end
            if ~UseApp | (UseApp & ~UseApproxMat)
                DipStrength = TmpInvCoeff \ C0Data2Analyse;
                if ~CalcSLC2FileStatus
                    CalcPot=(DipStrength' * ForCoeff)';
                end
                CalcPotChan=(DipStrength' * ForChanCoeff)';
            end
            %Add the mean of Data2Analyse
            if  Method==1 |  Method==4
                if ~CalcSLC2FileStatus
                    [CalcPot]=CalcValOfVecToMat(CalcPot,c0,['+']);
                end
                [CalcPotChan]=CalcValOfVecToMat(CalcPotChan,c0,['+']);
            end
            set(hPlot3dList(50),'Userdata',CalcPotChan);
            if ~CalcSLC2FileStatus
                set(hPlot3dList(53),'Userdata',CalcPot); 
            else
                return; 
            end
            set(hPlot3dList(6),'Enable','on');  %SaveData
            
            emegs3d('setMinMaxAmpString')
            emegs3d('setAutoAmp')	
            emegs3d('chSaveDataLabelString')	
            emegs3d('EnableOnOff')	
            
            anovastatus = get(hPlot3dList(132),'Userdata');
            if isempty(anovastatus) | ~anovastatus
                if isempty(varargin)
                    emegs3d('PlotSurfData')
                else
                   emegs3d('PlotSurfData',targetfig);
                end
            end
            
        elseif strcmp(action,'CalcMagFieldNorm'), 
            
            %global InvLFCoeff ForLFCoeff Data2Analyse RadVec NormData ForSensorMat InvSensorMat DipStrength LeadLoc
            hPlot2dList=get(hPlot2dMenuFig,'Userdata');
            Plot2dNListHdr=get(hPlot2dList(51),'Userdata');
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            emegs3d('setChanStatusVec')
            MagFieldNormMethod=get(hPlot3dList(2),'Value');
            FileFormat=get(hPlot2dList(Plot2dNListHdr+(1-1).*50+22),'Userdata');
            if MagFieldNormMethod==1
                UseMeanSensorStatus=0; NLeadLoc=350;
            elseif MagFieldNormMethod==2
                UseMeanSensorStatus=0; NLeadLoc=197;
            elseif MagFieldNormMethod==3
                UseMeanSensorStatus=1; NLeadLoc=350;
            elseif MagFieldNormMethod==4
                UseMeanSensorStatus=1; NLeadLoc=197;
            end
            MinPoint=get(hPlot3dList(47),'Value');
            MaxPoint=get(hPlot3dList(49),'Value');
            SampRate=get(hPlot2dList(60),'Userdata'); 
            MNLambdaApprox=get(hPlot3dList(109),'Value'); 
            hTopMenu=get(hPlot3dList(83),'Userdata');
            hFileMenu=get(hTopMenu(1),'children');
            UseFileMatStatus=get(hFileMenu(1),'Userdata');
            if UseFileMatStatus
                FileMat=get(hPlot3dList(100),'Userdata'); 
                NFiles=get(hPlot3dList(100),'Value');
            else
                NFiles=0;
            end
            CalcBaseStatus=get(hPlot2dList(57),'Value'); 
            MinBase=get(hPlot2dList(58),'Value'); 
            MaxBase=get(hPlot2dList(59),'Value');
            PathLFCoeff=get(hPlot3dList(71),'Userdata');
            LeadLocFile=[PathLFCoeff,filesep,'DLoc_',int2str(NLeadLoc),'_1_Cart'];
            LeadLoc=ReadData(LeadLocFile,1,[],'int16','float32')';
            NChan=148;
            ECfgFilePath=which('148.pmg');
            %===================================================================
            if UseMeanSensorStatus
                cnt=1;
                for FileIndex=1:NFiles
                    FileIndex=FileIndex
                    ECfgFilePathOld=ECfgFilePath;
                    [File,Path,FilePath]=GetFileNameOfMat(FileMat,FileIndex);	
                    if strcmp(FileFormat,'SCADS')
                        Tmp=findstr(File,'.at');
                    elseif strcmp(FileFormat,'AppSCADS')
                        Tmp=findstr(File,'.app');
                    elseif strcmp(FileFormat,'AsciiBesaVec')
                        Tmp=findstr(File,'.avr');
                    end
                    ECfgFile=[File(1:Tmp(length(Tmp))-1),'.pmg'];
                    ECfgFilePath=[Path,ECfgFile];
                    if ~strcmp(ECfgFilePathOld,ECfgFilePath)
                        %===================================================================
                        %===================================================================
                        [SensorMat,NonUse,NonUse,Cot]=ReadPmgCotSfpFiles(ECfgFilePath,1,1,0);
                        [SensorMat]=AdjustPmgCotSfp(SensorMat,Cot);
                        if cnt==1
                            ForSensorMat=SensorMat;
                        else
                            ForSensorMat=ForSensorMat+SensorMat;
                            cnt=cnt+1;
                        end
                    end
                end
                [ECfgFileTmp,ECfgPathTmp]=SepFilePath(ECfgFilePath);
                if strcmp(ECfgPathTmp(length(ECfgPathTmp)),filesep)
                    ECfgFilePathTmp=[ECfgPathTmp,'M148.pmg'];
                else
                    ECfgFilePathTmp=[ECfgPathTmp,filesep,'M148.pmg'];
                end
                ForSensorMat=ForSensorMat./cnt;
                SaveData(ForSensorMat,ECfgFilePathTmp,1);
            else
                [ForSensorMat,NonUse,NonUse,ForCot]=ReadPmgCotSfpFiles(ECfgFilePath,1,1,0);
                [ForSensorMat]=AdjustPmgCotSfp(ForSensorMat,ForCot);
            end
            InvLFCoeff=zeros(NChan,NLeadLoc,3);
            ForLFCoeff=zeros(NChan,NLeadLoc,3);
            Message=char(' ');
            Message=char(Message,'Inverse calculation for MEG (homogenous sphere)');
            Message=char(Message,' ');
            MessageTmp=char(Message,['Calculate ',sprintf('%g',NChan),' sensors ...']);
            hmsgbox=msgbox(MessageTmp,'Progress Info:','help');
            hChildMsgbox=get(hmsgbox,'Children');
            hChild2Msgbox=get(hChildMsgbox(2),'Children');
            set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
            pause(.01);
            for ChanInd=1:NChan
                if round(ChanInd./25)==ChanInd./25
                    fprintf('\n');
                    fprintf('Sensor %g of %g sensors done ...  ',ChanInd,NChan);
                    MessageTmp=char(Message,'');
                    MessageTmp=char(Message,['Sensor ',sprintf('%g',ChanInd),' of ',sprintf('%g',NChan),' sensors done ...']);
                    if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
                        set(hChildMsgbox(2),'String',MessageTmp);
                    else
                        set(hChild2Msgbox,'String',MessageTmp);
                    end
                    pause(.01)
                else
                    fprintf('.');
                end
                for j=1:NLeadLoc
                    ForLFCoeff(ChanInd,j,:)=sphere_meg(ForSensorMat(1:3,ChanInd),ForSensorMat(4:6,ChanInd),LeadLoc(1:3,j));
                end
            end
            close(hmsgbox);
            hPmgCotFig=figure('Units','normal','NumberTitle','off','Position',[0 .4 .4 .6]);
            for FileIndex=1:NFiles
                ECfgFilePathOld=ECfgFilePath;
                [File,Path,FilePath]=GetFileNameOfMat(FileMat,FileIndex);
                Tmp=[];
                if strcmp(FileFormat,'SCADS')
                    [AvgMat,File,Path,FilePath,NTrialAvgVec,StdChanTimeMat,...
                            SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra]=ReadAvgFile(FilePath);
                    [NChan,NPoints]=size(AvgMat);
                    Tmp=findstr(File,'.at');
                elseif strcmp(FileFormat,'AsciiBesaVec')
                    [AvgMat,TSB,DI,SB,SC,NPoints,NChan,SampRate,TrigPoint,File,Path,FilePath,SensorNames]=ReadAsciiBesa(FilePath);
                    Tmp=findstr(File,'.avr');
                elseif  strcmp(FileFormat,'AppSCADS')
                    [AvgMat,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,AvgRefStatus,File,Path,FilePath,EegMegStatus,NChanExtra]=...
                        ReadAppData(FilePath,'all');
                    NChan=NChan-NChanExtra;
                    Tmp=findstr(File,'.app');
                end
                if CalcBaseStatus
                    [AvgMat]=CalcBaseline(AvgMat,MinBase,MaxBase,1,1);
                end
                if ~isempty(Tmp)
                    ECfgFile=[File(1:Tmp(length(Tmp))-1),'.pmg'];
                else
                    ECfgFile=[File,'.pmg'];
                end
                ECfgFilePath=[Path,ECfgFile];
                if ~exist(ECfgFilePath,'file')
                    ECfgFilePath=ECfgFilePath
                    return
                end
                ECfgFilePathOld=ECfgFilePathOld
                ECfgFilePath=ECfgFilePath
                
                if ~strcmp(ECfgFilePathOld,ECfgFilePath)
                    %===================================================================
                    %===================================================================
                    [InvSensorMat,NonUse,NonUse,InvCot]=ReadPmgCotSfpFiles(ECfgFilePath,0,1,1);
                    [InvSensorMat]=AdjustPmgCotSfp(InvSensorMat,InvCot);
                    figure(hPmgCotFig)
                    clf;
                    plot3(InvSensorMat(1,:),InvSensorMat(2,:),InvSensorMat(3,:),'bo')
                    hold on
                    quiver3(InvSensorMat(1,:),InvSensorMat(2,:),InvSensorMat(3,:),InvSensorMat(4,:),InvSensorMat(5,:),InvSensorMat(6,:),'b');
                    plot3(ForSensorMat(1,:),ForSensorMat(2,:),ForSensorMat(3,:),'ro')
                    quiver3(ForSensorMat(1,:),ForSensorMat(2,:),ForSensorMat(3,:),ForSensorMat(4,:),ForSensorMat(5,:),ForSensorMat(6,:),'r');
                    plot3(LeadLoc(1,:),LeadLoc(2,:),LeadLoc(3,:),'g*')
                    hold off
                    pause(.1)
                    Message=char(' ');
                    Message=char(Message,'Forward calculation for MEG (homogenous sphere)');
                    Message=char(Message,' ');
                    MessageTmp=char(Message,['Calculate ',sprintf('%g',NChan),' sensors ...']);
                    hmsgbox=msgbox(MessageTmp,'Progress Info:','help');
                    hChildMsgbox=get(hmsgbox,'Children');
                    hChild2Msgbox=get(hChildMsgbox(2),'Children');
                    set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                    pause(.01);
                    for ChanInd=1:NChan
                        fprintf(1,'%g of %g sensors done ...\n',i,NChan)
                        if round(ChanInd./25)==ChanInd./25
                            fprintf('\n');
                            fprintf('Sensor %g of %g sensors done ...  ',ChanInd,NChan);
                            MessageTmp=char(Message,'');
                            MessageTmp=char(Message,['Sensor ',sprintf('%g',ChanInd),' of ',sprintf('%g',NChan),' sensors done ...']);
                            if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
                                set(hChildMsgbox(2),'String',MessageTmp);
                            else
                                set(hChild2Msgbox,'String',MessageTmp);
                            end
                            pause(.01)
                        else
                            fprintf('.');
                        end
                        for j=1:NLeadLoc
                            InvLFCoeff(ChanInd,j,:)=sphere_meg(InvSensorMat(1:3,ChanInd),InvSensorMat(4:6,ChanInd),LeadLoc(1:3,j));
                        end
                    end
                    close(hmsgbox);
                    ReshInvLFCoeff=zeros(NChan,NLeadLoc.*3);
                    ReshInvLFCoeff(:,1:NLeadLoc)=squeeze(InvLFCoeff(:,:,1));
                    ReshInvLFCoeff(:,NLeadLoc+1:2.*NLeadLoc)=squeeze(InvLFCoeff(:,:,2));
                    ReshInvLFCoeff(:,2.*NLeadLoc+1:3.*NLeadLoc)=squeeze(InvLFCoeff(:,:,3));
                    ReshPinvLFCoeff=pinv_tikh(ReshInvLFCoeff,MNLambdaApprox);
                end
                if strcmp(FileFormat,'SCADS') 
                    Data2Analyse=AvgMat(1:NChan,:);
                    XMat=ReshPinvLFCoeff(1:NLeadLoc,:)*Data2Analyse;	
                    YMat=ReshPinvLFCoeff(NLeadLoc+1:2.*NLeadLoc,:)*Data2Analyse;	
                    ZMat=ReshPinvLFCoeff(2.*NLeadLoc+1:3.*NLeadLoc,:)*Data2Analyse;
                    
                    NormData=((XMat' * ForLFCoeff(:,:,1)')+(YMat' * ForLFCoeff(:,:,2)')+(ZMat' * ForLFCoeff(:,:,3)'))';
                    AvgMat(1:NChan,:)=NormData;
                    FilePath=[Path,'M.',File];
                    SaveAvgFile(FilePath,AvgMat,NTrialAvgVec,StdChanTimeMat,SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra);
                    NormData=sqrt(XMat.^2+YMat.^2+ZMat.^2);
                    FilePath=[FilePath,'.MN0'];
                    SaveAvgFile(FilePath,NormData,NTrialAvgVec,StdChanTimeMat,SampRate,MedMedRawVec,MedMedAvgVec,1);
                    pause(1)
                elseif strcmp(FileFormat,'AsciiBesaVec')
                    Data2Analyse=AvgMat;
                    XMat=ReshPinvLFCoeff(1:NLeadLoc,:)*Data2Analyse;	
                    YMat=ReshPinvLFCoeff(NLeadLoc+1:2.*NLeadLoc,:)*Data2Analyse;	
                    ZMat=ReshPinvLFCoeff(2.*NLeadLoc+1:3.*NLeadLoc,:)*Data2Analyse;
                    
                    NormData=((XMat' * ForLFCoeff(:,:,1)')+(YMat' * ForLFCoeff(:,:,2)')+(ZMat' * ForLFCoeff(:,:,3)'))';
                    FilePath=[Path,'M.',File];
                    SaveAsciiBesa(NormData,TSB,DI,SB,SC,FilePath);
                    NormData=sqrt(XMat.^2+YMat.^2+ZMat.^2);
                    FilePath=[FilePath,'.MN0'];
                    SaveAsciiBesa(NormData,TSB,DI,SB,SC,FilePath);
                    pause(1)
                elseif strcmp(FileFormat,'AppSCADS')
                    FileFid=[];
                    FilePath=[Path,'M.',File];
                    for ActTrial=1:NTrials
                        Data2Analyse=squeeze(AvgMat(1:NChan,:,ActTrial));
                        XMat=ReshPinvLFCoeff(1:NLeadLoc,:)*Data2Analyse;	
                        YMat=ReshPinvLFCoeff(NLeadLoc+1:2.*NLeadLoc,:)*Data2Analyse;	
                        ZMat=ReshPinvLFCoeff(2.*NLeadLoc+1:3.*NLeadLoc,:)*Data2Analyse;
                        
                        NormData=((XMat' * ForLFCoeff(:,:,1)')+(YMat' * ForLFCoeff(:,:,2)')+(ZMat' * ForLFCoeff(:,:,3)'))';
                        FileFid=SaveAppData(version,FileFid,FilePath,ScaleBins,NChan,NPoints,NTrials,ActTrial,NormData);
                        NormData=sqrt(XMat.^2+YMat.^2+ZMat.^2);
                        AvgMat(1:NChan,:,ActTrial)=NormData;
                    end
                    FilePath=[FilePath,'.MN0'];
                    SaveAppData(Version,[],FilePath,ScaleBins,NChan,NPoints,NTrials,'all',SampRate,AvgRefStatus,EegMegStatus,NChanExtra,AvgMat);
                end
            end
            
        elseif strcmp(action,'CalcMinimumNorm'),
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata');
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            
            emegs3d('setChanStatusVec')
            hTopMenu=get(hPlot3dList(83),'Userdata');
            hFileMenu=get(hTopMenu(1),'children');
            UseFileMatStatus=get(hFileMenu(1),'Userdata');
            Tmp = get(hPlot3dList(32),'Value');
            set(hPlot3dList(33),'Userdata',[1,2,Tmp]);%hApply [Recalculate, MinNorm, Method]
            TmpOld = get(hPlot3dList(32),'Userdata');
            if TmpOld~=Tmp
                set(hPlot3dList(32),'Userdata',Tmp);
                set(hPlot3dList(97),'Userdata',[]);
                set(hPlot3dList(98),'Userdata',[]);
                set(hPlot3dList(99),'Userdata',[]);
            end
            
            Domain=get(hPlot2dList(20),'Value');
            EEGMEGStatusString=get(hPlot2dList(110),'String');
            QuiverStatus=get(hPlot3dList(95),'Value');
            if Tmp==1; 			%4 Shells, Shell 8 cm
                ActMethod=6; 
                LeadLocCfgVal=1;
                ShellNo=1;
                if Domain<3; 
                    TitleNum=51; 
                elseif Domain>2 & Domain<5 
                    TitleNum=67; 
                elseif Domain==5
                    TitleNum=113; 
                end
            elseif Tmp==2; 		%4 Shells, Shell 6 cm
                ActMethod=6; 
                LeadLocCfgVal=1;
                ShellNo=2;
                if Domain<3; 
                    TitleNum=52; 
                elseif Domain>2 & Domain<5 
                    TitleNum=68; 
                elseif Domain==5
                    TitleNum=114; 
                end
            elseif Tmp==3;  	%4 Shells, Shell 4 cm
                ActMethod=6; 
                LeadLocCfgVal=1;
                ShellNo=3;
                if Domain<3; 
                    TitleNum=53; 
                elseif Domain>2 & Domain<5 
                    TitleNum=69; 
                elseif Domain==5
                    TitleNum=115; 
                end
            elseif Tmp==4;  	%4 Shells, Shell 2 cm
                ActMethod=6; 
                LeadLocCfgVal=1;
                ShellNo=4;
                if Domain<3; 
                    TitleNum=54; 
                elseif Domain>2 & Domain<5 
                    TitleNum=70; 
                elseif Domain==5
                    TitleNum=116; 
                end
            elseif 	Tmp==5;		%1 Shell, Shell 8 cm
                ActMethod=6; 
                LeadLocCfgVal=2;
                ShellNo=1;
                if Domain<3; 
                    TitleNum=55; 
                elseif Domain>2 & Domain<5 
                    TitleNum=71; 
                elseif Domain==5
                    TitleNum=117; 
                end
            elseif 	Tmp==6;		%1 Shell, Shell 6 cm
                ActMethod=6; 
                LeadLocCfgVal=3;
                ShellNo=1;
                if Domain<3; 
                    TitleNum=56; 
                elseif Domain>2 & Domain<5 
                    TitleNum=72; 
                elseif Domain==5
                    TitleNum=118; 
                end
            elseif 	Tmp==7;		%4 Shells, All Shells
                ActMethod=6; 
                LeadLocCfgVal=1;
                ShellNo=5;
                if Domain<3; 
                    TitleNum=56; 
                elseif Domain>2 & Domain<5 
                    TitleNum=72; 
                elseif Domain==5
                    TitleNum=118; 
                end
            end
            if ActMethod==6;
                set(hPlot3dList(21),'String','Min. Amp. [nA/mm]')
                set(hPlot3dList(23),'String','Max. Amp. [nA/mm]')
            end
            set(hPlot3dList(51),'Value',ActMethod);
            set(hPlot3dList(52),'Value',TitleNum); 
            
            MinPoint=get(hPlot3dList(47),'Value');
            MaxPoint=get(hPlot3dList(49),'Value');
            ChanStatusVec=get(hPlot3dList(63),'Userdata');
            ChanStatusOnVec=find(ChanStatusVec==1);
            Data2Analyse=get(hPlot3dList(54),'Userdata');
            Data2Analyse=Data2Analyse(ChanStatusOnVec,MinPoint:MaxPoint);
            EPosSpher=get(hPlot3dList(56),'Userdata');
            if strcmp(EEGMEGStatusString,'EEG')
                SensorMat=get(hPlot3dList(57),'Userdata');
                CoorStatusString='sph'; %spherical
                LFDim=3; %EEG
            elseif strcmp(EEGMEGStatusString,'MEG')
                SensorMat=get(hPlot2dList(111),'Userdata');
                CoorStatusString='sph'; %spherical
                LFDim=2; %MEG
            end
            ScalpLoc=get(hPlot3dList(58),'Userdata');
            PathLeg=get(hPlot3dList(59),'Userdata'); 
            PathCoeff=get(hPlot3dList(60),'Userdata');
            PathLFCoeff=get(hPlot3dList(71),'Userdata');
            ECfgFilePath=get(hPlot3dList(61),'Userdata');
            [ECfgFile,ECfgPath]=SepFilePath(ECfgFilePath);
            ParaVec=get(hPlot3dList(62),'Userdata');
            ScalpRadius=ParaVec(7);
            NSqrtScalpLoc=ParaVec(14);
            InvIter=ParaVec(10);
            ForIter=ParaVec(11);
            LengthLegVec=ParaVec(15);
            NChan=ParaVec(16);
            NUsedChan=ParaVec(17);
            NPoints3d=ParaVec(19);
            SLCLambdaApprox=get(hPlot3dList(69),'Value');
            MNLambdaApprox=get(hPlot3dList(109),'Value');
            CalcMNLambdaApproxStatus=get(hPlot3dList(124),'Value');
            DistPointVec=get(hPlot3dList(41),'Userdata');
            DistPoint=DistPointVec(1);
            DistPointMeanStatus=get(hPlot3dList(44),'Value');
            DistPointMNMeanStatus=get(hPlot3dList(90),'Value');
            AutoAmp=get(hPlot3dList(45),'Value');
            CalcMinNorm2FileStatus=get(hPlot3dList(96),'Value');
            
            if DistPoint>1
                if ~DistPointMeanStatus
                    TimeIndexVec=[1:DistPoint:NPoints3d];
                    NPoints2Plot=length(TimeIndexVec);
                    Data2Analyse=Data2Analyse(:,TimeIndexVec); 
                else
                    TimeIndexVec=[1:DistPoint:NPoints3d-DistPoint+1];
                    NPoints2Plot=length(TimeIndexVec);
                    if ~DistPointMNMeanStatus
                        Data2AnalyseTmp=zeros(NUsedChan,NPoints2Plot);
                        for Ind=1:NPoints2Plot
                            Data2AnalyseTmp(:,Ind)=mean(Data2Analyse(:,(Ind-1).*DistPoint+1:Ind.*DistPoint),2);
                        end
                        Data2Analyse=Data2AnalyseTmp; 
                        clear Data2AnalyseTmp;
                    end
                end
            else
                NPoints2Plot=NPoints3d;
            end
            ParaVec(21)=NPoints2Plot;	%Number of points to plot
            
            if  LeadLocCfgVal==1
                NShells=4;
                LeadLocCfg='655_4';
                NLeadLocVec=[350 197 87 21 655];
                LeadLocIntMat=[1 350;351 547;548 634;635 655;1 655];
            elseif  LeadLocCfgVal==2
                NShells=1;
                LeadLocCfg='350_1';
                NLeadLocVec=350;
                LeadLocIntMat=[1 350];
            elseif  LeadLocCfgVal==3
                NShells=1;
                LeadLocCfg='197_1';
                NLeadLocVec=197;
                LeadLocIntMat=[1 197];
            end
         
            NLeadLoc=NLeadLocVec(ShellNo);
            LeadLocInt=LeadLocIntMat(ShellNo,:);
            PILFCoeff=get(hPlot3dList(97),'Userdata');
            
            if CalcMinNorm2FileStatus~=0 & strcmp(EEGMEGStatusString,'MEG')		%Check for identical sensor config
                ECfgExt='.pmg';
                ActDataFilePath=get(hPlot3dList(55),'Userdata')
                [ActDataFile,ActDataPath]=SepFilePath(ActDataFilePath);
                Tmp=findstr(ActDataFile,'.at');
                if ~isempty(Tmp)
                    ActECfgFile=[ActDataFile(1:Tmp(length(Tmp))-1),ECfgExt];
                    ActECfgFilePath=[ActDataPath,ActECfgFile];
                else
                    ActECfgFile=[ActDataFile,ECfgExt];
                    ActECfgFilePath=[ActDataPath,ActECfgFile];
                end
                if ~strcmp(ECfgFile,ActECfgFile)
                    PILFCoeff=[];InvCoeff=[];ForCoeff=[];
                    ECfgFile=ActECfgFile;
                    ECfgFilePath=ActECfgFilePath;
                    set(hPlot3dList(61),'Userdata',ECfgFilePath);
                    ECfg=ECfgFile;
                    if 	strcmp(EEGMEGStatusString,'EEG') & strcmp(ECfgFile(length(ECfgFile)-4:length(ECfgFile)),'.ecfg')
                        ECfg=ECfgFile(1:length(ECfgFile)-5);
                    elseif 	strcmp(EEGMEGStatusString,'MEG') & strcmp(ECfgFile(length(ECfgFile)-3:length(ECfgFile)),'.pmg')
                        ECfg=ECfgFile(1:length(ECfgFile)-4);
                    end 
                    PILFCoeffFile=[PathLFCoeff,filesep,'PILF' EEGMEGStatusString(1) '_' LeadLocCfg '_' ECfg '_' int2str(MNLambdaApprox.*10000)];
                    %	PILFE if EEG; PILFM if MEG
                    PILFCoeffFid=exist(PILFCoeffFile);
                    if PILFCoeffFid==2
                        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');
                        PILFCoeff=ReadData(PILFCoeffFile,1,[],'int16','float32');
                        set(hPlot3dList(97),'Userdata',PILFCoeff);
                        pause(1)
                        close(hmsgbox)
                    else
                        [SensorPosNormMat,ENames,SensorNChan,Cot,SfpMat]=ReadPmgCotSfpFiles(ActECfgFilePath,1);
                        [SensorPosNormMat]=AdjustPmgCotSfp(SensorPosNormMat,Cot);
                        set(hPlot2dList(111),'Userdata',SensorMat);
                        EPosCart=SensorMat(:,1:3); 
                        [EPosSpher]=change_sphere_cart(EPosCart,[], -1);
                        set(hPlot3dList(57),'Userdata',EPosCart); 
                    end
                end
            end
            
            %==============================================================
            %============Calculate best MNLambdaApprox====================
            if CalcMNLambdaApproxStatus	
                ECfg=ECfgFile;
                if 	strcmp(EEGMEGStatusString,'EEG') & strcmp(ECfgFile(length(ECfgFile)-4:length(ECfgFile)),'.ecfg')
                    ECfg=ECfgFile(1:length(ECfgFile)-5);
                elseif 	strcmp(EEGMEGStatusString,'MEG') & strcmp(ECfgFile(length(ECfgFile)-3:length(ECfgFile)),'.pmg')
                    ECfg=ECfgFile(1:length(ECfgFile)-4);
                end
                LFCoeffFile = [PathLFCoeff,filesep,'LF' EEGMEGStatusString(1) '_' LeadLocCfg '_' ECfg];
                %LFE if EEG; LFM if MEG
                LFCoeffFid=exist(LFCoeffFile);
                if LFCoeffFid==0
                    [LFCoeff,Orientations,v]=compute_lfdmat(LeadLoc(:,1:3)',SensorMat',EEGMEGStatusString,CoorStatusString,[]);
                    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	
                MNLambdaApproxVec=10.^[-8:1];
                Message=char('Calculate L2-Min.-Norm residual variance:');
                Message=char(Message,'');
                Message=char(Message,'');
                Message=char(Message,'');
                Message=char(Message,'');
                if UseFileMatStatus
                    Message=char(Message,'');
                    Message=char(Message,'');
                    Message=char(Message,'');
                end
                hmsgbox=msgbox(Message,'Progress Info:','help');
                hChildMsgbox=get(hmsgbox,'Children');
                hChild2Msgbox=get(hChildMsgbox(2),'Children');
                clear Message
                set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                pause(.01);	
                MeanVar=zeros(size(MNLambdaApproxVec));
                for MNLambdaApproxInd=1:length(MNLambdaApproxVec)
                    MNLambdaApprox=MNLambdaApproxVec(MNLambdaApproxInd);
                    MessageTmp=char(['Calculate L2-Min.-Norm residual variance:']);
                    MessageTmp=char(MessageTmp,'');
                    MessageTmp=char(MessageTmp,['Regular. parameter (lambda) = ',num2str(MNLambdaApprox)]);
                    MessageTmp=char(MessageTmp,'');
                    MessageTmp=char(MessageTmp,['Calculate ',int2str(MNLambdaApproxInd),' of ',int2str(length(MNLambdaApproxVec)),' values ... ']);
                    if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
                        set(hChildMsgbox(2),'String',MessageTmp);
                    else
                        set(hChild2Msgbox,'String',MessageTmp);
                    end
                    if UseFileMatStatus
                        FileMat=get(hPlot3dList(100),'Userdata');
                        NFiles=get(hPlot3dList(100),'Value');
                        CalcBaseStatus=get(hPlot2dList(57),'Value'); 
                        MinBase=get(hPlot2dList(58),'Value');
                        MaxBase=get(hPlot2dList(59),'Value');
                        for FileIndex=1:NFiles
                            Message=char(MessageTmp,'');
                            Message=char(Message,['Calculate ',int2str(FileIndex),' of ',int2str(NFiles),' files ... ']);
                            if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
                                set(hChildMsgbox(2),'String',MessageTmp);
                            else
                                set(hChild2Msgbox,'String',MessageTmp);
                            end
                            PILFCoeff=pinv_tikh(LFCoeff,MNLambdaApprox); %MNLambdaApprox=regpar
                            [File,Path,FilePath]=GetFileNameOfMat(FileMat,FileIndex);	
                            [AvgMat,File,Path,FilePath,NTrialAvgVec,StdChanTimeMat,...
                                    SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra]=ReadAvgFile(FilePath);
                            [NonUse,ActNPoints]=size(AvgMat);
                            if CalcBaseStatus
                                [AvgMat]=CalcBaseline(AvgMat,MinBase,MaxBase,1,1);
                            end
                            Data2Analyse=AvgMat(ChanStatusOnVec,MinPoint:MaxPoint);
                            if DistPoint>1
                                if ~DistPointMeanStatus
                                    TimeIndexVec=[1:DistPoint:NPoints3d];
                                    NPoints2Plot=length(TimeIndexVec);
                                    Data2Analyse=Data2Analyse(:,TimeIndexVec); 
                                else
                                    TimeIndexVec=[1:DistPoint:NPoints3d-DistPoint+1];
                                    NPoints2Plot=length(TimeIndexVec);
                                    if ~DistPointMNMeanStatus
                                        Data2AnalyseTmp=zeros(NUsedChan,NPoints2Plot);
                                        for Ind=1:NPoints2Plot
                                            Data2AnalyseTmp(:,Ind)=mean(Data2Analyse(:,(Ind-1).*DistPoint+1:Ind.*DistPoint)')';
                                        end
                                        Data2Analyse=Data2AnalyseTmp; clear Data2AnalyseTmp;
                                    end
                                end
                            end
                            InvSol=PILFCoeff*Data2Analyse; 
                            Var(FileIndex)=mean(res_var(LFCoeff,InvSol,Data2Analyse));
                        end
                    else
                        PILFCoeff=pinv_tikh(LFCoeff,MNLambdaApprox); %MNLambdaApprox=regpar
                        InvSol=PILFCoeff*Data2Analyse; 
                        Var=mean(res_var(LFCoeff,InvSol,Data2Analyse));
                    end
                    MeanVar(MNLambdaApproxInd)=mean(Var);
                end
                close(hmsgbox);
                ResVarFig=figure('Units','normal',...
                    'Position',[0 .5 .5 .5],...
                    'NumberTitle','off',...
                    'Name','L2-Min.-Norm residual variance');
                loglog(MNLambdaApproxVec,MeanVar);
                hold on
                loglog(MNLambdaApproxVec,MeanVar,'r*');
                axis([min(MNLambdaApproxVec) max(MNLambdaApproxVec) min(MeanVar) max(MeanVar)]);
                title('L2-Min.-Norm residual variance')
                xlabel('Regular. parameter (lambda) [ ]')
                ylabel('Residual variance [ ]')
                return
            end
            %==============================================================
            %=============================================================
            if isempty(PILFCoeff)
                LeadLocFile=[PathLFCoeff,filesep,'DLoc_' LeadLocCfg '_Cart'];
                LeadLocFid=exist(LeadLocFile);
                if LeadLocFid==0
                    Message=char('Sorry,');
                    Message=char(Message,' ');	
                    Message=char(Message,'Can not find the file:');					
                    Message=char(Message,LeadLocFile);
                    Message=char(Message,' ');
                    Message=char(Message,'The path of this file containing')
                    Message=char(Message,'the leadfield locations has to be exact.');
                    hmsgbox=msgbox(Message,'Info:','help');
                    return;
                end
                LeadLoc=ReadData(LeadLocFile,1,[],'int16','float32');
                LeadRadius=sqrt(sum(LeadLoc(LeadLocInt(1),1:3).^2));
                fprintf(1,'Leadfield radius: %g cm\n\n',round(LeadRadius.*10000)./100);
                LeadLocShell=LeadLoc(LeadLocInt(1):LeadLocInt(2),1:3);
                LeadLocTmp=LeadLocShell.*ScalpRadius./LeadRadius;
                
                set(hPlot3dList(81),'Userdata',LeadLoc);
                set(hPlot3dList(82),'Userdata',LeadLocShell);
            end
            if isempty(PILFCoeff)	%if PILFCoeff is not in working memory
                ECfg=ECfgFile;
                if 	strcmp(EEGMEGStatusString,'EEG') & strcmp(ECfgFile(length(ECfgFile)-4:length(ECfgFile)),'.ecfg')
                    ECfg=ECfgFile(1:length(ECfgFile)-5);
                elseif 	strcmp(EEGMEGStatusString,'MEG') & strcmp(ECfgFile(length(ECfgFile)-3:length(ECfgFile)),'.pmg')
                    ECfg=ECfgFile(1:length(ECfgFile)-4);
                end 
                PILFCoeffFile=[PathLFCoeff,filesep,'PILF' EEGMEGStatusString(1) '_' LeadLocCfg '_' ECfg '_' int2str(MNLambdaApprox.*10000)];
                %	PILFE if EEG; PILFM if MEG
                PILFCoeffFid=exist(PILFCoeffFile);
                if PILFCoeffFid~=2
                    LFCoeffFile = [PathLFCoeff,filesep,'LF' EEGMEGStatusString(1) '_' LeadLocCfg '_' ECfg];
                    %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);
                        [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');
                        LFCoeff=ReadData(LFCoeffFile,1,[],'int16','float32');
                        pause(2)
                        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') | strcmp(computer,'MAC')	
                        set(hChildMsgbox(2),'String',Message);
                    else
                        set(hChild2Msgbox,'String',Message);
                    end
                    set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                    PILFCoeff=pinv_tikh(LFCoeff,MNLambdaApprox); %MNLambdaApprox=regpar
                    SaveData(PILFCoeff,PILFCoeffFile,1);
                    set(hPlot3dList(97),'Userdata',PILFCoeff);
                    pause(2)
                    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');
                    PILFCoeff=ReadData(PILFCoeffFile,1,[],'int16','float32');
                    set(hPlot3dList(97),'Userdata',PILFCoeff);
                    pause(2)
                    close(hmsgbox)
                end
            end	%if PILFCoeff 
            
            PILFCoeff=PILFCoeff(:,ChanStatusOnVec);
            if  ActMethod==6	%Inverse
                MNMat=inv_recon(PILFCoeff((LeadLocInt(1)-1).*LFDim+1:LeadLocInt(2).*LFDim,:),Data2Analyse,LFDim);	
                %=======================================================    
                %MNMat=MNMat.*10.^6; %nA/m^2 => nA/mm^2
                [NMNMat,NPoints]=size(MNMat);
                if DistPointMeanStatus & DistPointMNMeanStatus
                     MNMatTmp=zeros(NMNMat,NPoints2Plot);
                     for Ind=1:NPoints2Plot
                         MNMatTmp(:,Ind)=mean(MNMat(:,(Ind-1).*DistPoint+1:Ind.*DistPoint),2);
                     end
                     MNMat=MNMatTmp; clear MNMatTmp;
                end
                %=====Calculate spline interpolation==========
                c0M=mean(MNMat);	
                C0MNMat=MNMat-(c0M'*ones(1,NMNMat))';	
                if NLeadLoc>100
                    InvIter=15;
                    ForIter=15;
                elseif NLeadLoc<100 & NLeadLoc>60
                    InvIter=12;
                    ForIter=12;
                else
                    InvIter=9;
                    ForIter=9;
                end
                %========================================================================
                InvCoeff=get(hPlot3dList(98),'Userdata');
                ForCoeff=get(hPlot3dList(99),'Userdata');	
                
                if CalcMinNorm2FileStatus~=0
                    if CalcMinNorm2FileStatus==2
                        OIStr=get(hPlot3dList(107),'String');
                    end
                    if CalcMinNorm2FileStatus==4 | CalcMinNorm2FileStatus==5 | (CalcMinNorm2FileStatus==2 & strcmp(OIStr,'IOI')) %CalcMinNorm2FileShell | CalcMinNorm2FileAnalyse
                        MinNorm=MNMat;
                    else
                        EPosCart=get(hPlot3dList(57),'Userdata'); 
                        if isempty(InvCoeff) | isempty(ForCoeff)
                            if	 CalcMinNorm2FileStatus==1				%CalcMinNorm2FileAll; CalcMinNorm2FileGroups
                                InvPos=EPosCart;
                                ForPos=EPosCart;
                                ECfgFile=[ECfg '_' LeadLocCfg '_' int2str(ShellNo)];
                            elseif CalcMinNorm2FileStatus==2			%CalcMinNorm2FileROI
                                InvPos=EPosCart;
                                ForPos=ScalpLoc;
                                ECfgFile=[LeadLocCfg '_' int2str(ShellNo)];
                            elseif CalcMinNorm2FileStatus==3		    %CalcMinNorm2FileEcfg 
                                BasePath=get(hPlot2dList(18),'Userdata');
                                if CalcMinNorm2FileStatus==3
                                    ECfgTmpFilePath=[BasePath,'emegs2dUtil',filesep,'SensorCfg',filesep,GetDefEcfgFile(NChan)];
                                elseif CalcMinNorm2FileStatus==3
                                    ECfgTmpFilePath=[BasePath,'emegs2dUtil',filesep,'SensorCfg',filesep,GetDefEcfgFile(NLeadLoc)];
                                end
                                if exist(ECfgTmpFilePath)~=2
                                    Message=char('Sorry, but the the sensor configuration default file');
                                    Message=char(Message,ECfgTmpFilePath);
                                    Message=char(Message,'does not exist !');
                                    Message=char(Message,'');
                                    hmsgbox=msgbox(Message,'Info','help');
                                    return;
                                end
                                [NonUse,NonUse,EPosSpherTmp]=ReadEConfig(ECfgTmpFilePath);
                                [InvPos]=change_sphere_cart(EPosSpherTmp,[],1);
                                ForPos=InvPos;
                                ECfgFile=[int2str(NChan),'_',LeadLocCfg '_' int2str(ShellNo)];
                            end				
                        end
                        if isempty(InvCoeff)
                            [InvCoeff] = ReadOrCalcCoeff(1,LeadLocTmp,InvPos,PathLeg,PathCoeff,ECfgFile,NSqrtScalpLoc,InvIter,0,LengthLegVec);
                            set(hPlot3dList(98),'Userdata',InvCoeff);
                        end		
                        if isempty(ForCoeff)
                            [ForCoeff] = ReadOrCalcCoeff(2,LeadLocTmp,ForPos,PathLeg,PathCoeff,ECfgFile,NSqrtScalpLoc,ForIter,0,LengthLegVec);
                            set(hPlot3dList(99),'Userdata',ForCoeff);
                        end
                        TmpInvCoeff=InvCoeff+SLCLambdaApprox.*InvCoeff(1,1).*eye(NLeadLoc);	% Achtung: Da InvCoeff anders berechnet wurde als unter CalcMinimumNorm
                        DipStrength = TmpInvCoeff\C0MNMat;
                        MinNorm=(DipStrength' * ForCoeff)';
                        [NMinNorm,NoUse]=size(MinNorm);
                        MinNorm=MinNorm+(c0M'*ones(1,NMinNorm))';	
                    end
                    set(hPlot3dList(53),'Userdata',MinNorm); 
                    return;
                end %CalcMinNorm2FileStatus
                XYZMat=inv_recon(PILFCoeff((LeadLocInt(1)-1).*LFDim+1:LeadLocInt(2).*LFDim,:),Data2Analyse,1);
                clear PILFCoeff
                XMat=XYZMat([1:LFDim:LFDim.*NLeadLoc-LFDim+1],:);	
                c0X=mean(XMat);
                C0XMat=XMat-(c0X'*ones(1,NMNMat))';
                YMat=XYZMat([2:LFDim:LFDim.*NLeadLoc-LFDim+2],:);	
                c0Y=mean(YMat); 
                C0YMat=YMat-(c0Y'*ones(1,NMNMat))';
                if LFDim==3
                    ZMat=XYZMat([3:3:3.*NLeadLoc],:);	
                    c0Z=mean(ZMat); 
                    C0ZMat=ZMat-(c0Z'*ones(1,NMNMat))';
                else
                    ZMat=zeros(size(XMat));
                    c0Z=zeros(size(c0X));
                    C0ZMat=zeros(size(C0XMat));
                end
                %========================================================================
                if isempty(InvCoeff) | isempty(ForCoeff)
                    ECfgFile=[LeadLocCfg '_' int2str(ShellNo)];
                end
                if isempty(InvCoeff)
                    [InvCoeff] = ReadOrCalcCoeff(1,LeadLocTmp,ScalpLoc,PathLeg,...
                        PathCoeff,ECfgFile,NSqrtScalpLoc,...
                        InvIter,0,LengthLegVec);
                    set(hPlot3dList(98),'Userdata',InvCoeff);
                end
                if isempty(ForCoeff)
                    [ForCoeff] = ReadOrCalcCoeff(2,LeadLocTmp,ScalpLoc,PathLeg,...
                        PathCoeff,ECfgFile,NSqrtScalpLoc,...
                        ForIter,0,LengthLegVec);
                    set(hPlot3dList(99),'Userdata',ForCoeff);
                end				  
                TmpInvCoeff=InvCoeff+SLCLambdaApprox.*InvCoeff(1,1).*eye(NLeadLoc);	% Achtung: Da InvCoeff anders berechnet wurde als unter CalcMinimumNorm
                DipStrength=TmpInvCoeff \ C0MNMat;
                
                CalcPot=(DipStrength' * ForCoeff)';        
                
                [NCalcPot,NoUse]=size(CalcPot);
                CalcPot=CalcPot+(c0M'*ones(1,NCalcPot))';	
                set(hPlot3dList(53),'Userdata',CalcPot); 
                set(hPlot3dList(50),'Userdata',MNMat);
                
                DipStrength = TmpInvCoeff \ C0XMat;
                CalcPot=(DipStrength' * ForCoeff)';
                XMat=CalcPot+(c0X'*ones(1,NCalcPot))';	
                
                DipStrength = TmpInvCoeff \ C0YMat;
                CalcPot=(DipStrength' * ForCoeff)';
                YMat=CalcPot+(c0Y'*ones(1,NCalcPot))';	
                
                DipStrength = TmpInvCoeff \ C0ZMat;
                CalcPot=(DipStrength' * ForCoeff)';
                ZMat=CalcPot+(c0Z'*ones(1,NCalcPot))';		
                
                set(hPlot3dList(91),'Userdata',XMat);
                set(hPlot3dList(92),'Userdata',YMat);
                set(hPlot3dList(93),'Userdata',ZMat);
                set(hPlot3dList(6),'Enable','on');  %SaveData
                
            elseif ActMethod==7		%Forward
                
                MNMat=inv_recon(PILFCoeff((LeadLocInt(1)-1).*LFDim+1:LeadLocInt(2).*LFDim,:),Data2Analyse,LFDim);
                LFSCoeffFile = [PathLFCoeff,filesep,'LF_' LeadLocCfg '_' ECfg '_S' int2str(ShellNo)];
                LFSCoeffFid=exist(LFSCoeffFile);
                
                if LFSCoeffFid==0
                    Message=char(['Calculate ' EEGMEGStatusString ' forward leadfield coefficients']);
                    Message=char(Message,'and save them to file:');
                    Message=char(Message,LFSCoeffFile);
                    hmsgbox=msgbox(Message,'Info:','help');
                    hChildMsgbox=get(hmsgbox,'Children');
                    set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                    pause(.1);
                    [LFSCoeff, orientations, v]=compute_lfdmat(LeadLocTmp',ScalpLoc',EEGMEGStatusString,CoorStatusString);
                    SaveData(LFSCoeff,LFSCoeffFile,1);
                else
                    LFSCoeff=ReadData(LFSCoeffFile,1,[],'int16','float32');
                end
                close(hmsgbox)
                CalcPot=MNMat'*LFSCoeff';		
                set(hPlot3dList(53),'Userdata',CalcPot'); 
                if Method~=6; set(hPlot3dList(50),'Userdata',CalcPotChan); end
                set(hPlot3dList(6),'Enable','on');  %SaveData
                Method=1;
                set(hPlot3dList(51),'value',Method); 
            end
            
            emegs3d('setAutoAmp')	
            emegs3d('chSaveDataLabelString')	
            emegs3d('EnableOnOff')	
            emegs3d('PlotSurfData')
            
        elseif strcmp(action,'chSaveDataLabelString'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            ActMethod=get(hPlot3dList(51),'Value');
            hSaveDataMenu=hPlot3dList(6);
            
            labelStr1='Values at scalp locations [ascii] | Values at scalp locations [float32] |';
            labelStr3='Values at special scalp locations [ascii] | Values at special scalp locations [float32] |';
            labelStr5='Scalp locations [ascii] | Scalp locations [float32] |';
            labelStr7='Special scalp locations [ascii] | Special scalp locations [float32] |';
            
            if ActMethod<6
                labelStr2='Values at sensor locations [ascii] | Values at sensor locations [float32] |';
                labelStr4='Values at special sensor locations [ascii] | Values at special sensor locations [float32] |';
                labelStr6='Sensor locations [ascii] | Sensor locations [float32] |';
                labelStr8='Special sensor locations [ascii] | Special sensor locations [float32]';
            else
                labelStr2='Values at leadfield locations [ascii] | Values at leadfield locations [float32] |';
                labelStr4='Values at special leadfield locations [ascii] | Values at special leadfield locations [float32] |';
                labelStr6='Leadfield locations [ascii] | Leadfield locations [float32] |';
                labelStr8='Special leadfield locations [ascii] | Special leadfield locations [float32]';
            end
            labelStr=[labelStr1 labelStr2 labelStr3 labelStr4 labelStr5 labelStr6 labelStr7 labelStr8];
            
            set(hSaveDataMenu,'String',labelStr);
            
        elseif strcmp(action,'ExportCalcPot'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            CalcPot=get(hPlot3dList(53),'Userdata');
            CalcPotChan=get(hPlot3dList(50),'Userdata');
            ActMethod=get(hPlot3dList(51),'Value');
            if ActMethod==1;
                DefFileName='Untitled.Scalp';
            elseif ActMethod==2;
                DefFileName='Untitled.Lap';
            elseif ActMethod==3;
                DefFileName='Untitled.Cort';
            elseif ActMethod==4;
                DefFileName='Untitled.PScalp';
            elseif ActMethod==4;
                DefFileName='Untitled.PLap';
            elseif ActMethod==6;
                Tmp=get(hPlot3dList(32),'value');
                if Tmp<4
                    DefFileName=['Untitled.IMN',int2str(Tmp)];
                else
                    DefFileName=['Untitled.FMN',int2str(Tmp-3)];
                end		
            end
            %         [SaveFilePath,EndPos]=SaveData(CalcPot,[],1,[],[],[],[],[],[],[],[],[],DefFileName);
            %         SaveData(CalcPotChan,SaveFilePath,1,[],[],[],1,0,1);
            [SaveFilePath,EndPos]=SaveData(CalcPotChan,[],1,[],[],[],[],[],[],[],[],[],DefFileName);
            
        elseif strcmp(action,'ReadOrCalcScalpLocIndFile') 
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            PathCoeff=get(hPlot3dList(60),'Userdata');
            ParaVec=get(hPlot3dList(62),'Userdata');
            NSqrtScalpLoc=ParaVec(14);
            %Because not all scalp positions are unique:
            ScalpLocIndFile = [PathCoeff,filesep,'ScalpLocInd_' int2str(NSqrtScalpLoc)];
            ScalpLocIndFileFid=exist(ScalpLocIndFile);
            
            if ScalpLocIndFileFid==0
                [NScalpLoc,NoUse]=size(ScalpLoc);
                Index1=0;
                Index3=0;
                BadLocIndVec=0;
                while Index1<NScalpLoc
                    Index1=Index1+1;
                    Index2=Index1+1;
                    Tmp=ScalpLoc(Index1,:);
                    while Index2<=NScalpLoc
                        if sum(abs(Tmp-ScalpLoc(Index2,:)))==0;
                            NewBadVec=find(BadLocIndVec==Index2);
                            if isempty(NewBadVec)
                                Index3=Index3+1;
                                BadLocIndVec(Index3)=Index2;
                            end
                        end	
                        Index2=Index2+1;	
                    end
                end
                Index2=0;
                for Index1=1:NScalpLoc
                    if isempty(find(BadLocIndVec==Index1))
                        Index2=Index2+1;
                        ScalpLocIndVec(Index2)=Index1;
                    end
                end
                SaveData(ScalpLocIndVec,ScalpLocIndFile,1);
            else
                ScalpLocIndVec=ReadData(ScalpLocIndFile,1,[],'int16','float32');
            end
            set(hPlot3dList(106),'Userdata',ScalpLocIndVec);
            
            %============================================================================	
            %============ CutRealBot
            %============================================================================	
            
       elseif strcmp(action,'CutRealBot')    
            
             hPlot3dList=get(hPlot3dMenuFig,'Userdata');
             CutRealBotVal=get(hPlot3dList(127),'Value');
             
            %============================================================================	
            %============ Save Data
            %============================================================================	
        elseif strcmp(action,'SaveData') %| strcmp(action,'SaveDataMet',11)
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            PathCoeff=get(hPlot3dList(60),'Userdata');
            ParaVec=get(hPlot3dList(62),'Userdata');
            NSqrtScalpLoc=ParaVec(14);
            
            CalcPotSensLead=get(hPlot3dList(50),'Userdata');
            ActMethod=get(hPlot3dList(51),'Value');
            CalcPot=get(hPlot3dList(53),'Userdata');
            EPosSpher=get(hPlot3dList(56),'Userdata'); 
            EPosCart=get(hPlot3dList(57),'Userdata'); 
            ScalpLoc=get(hPlot3dList(58),'Userdata');
            ScalpLocIndVec=get(hPlot3dList(106),'Userdata');
            if isempty(ScalpLocIndVec)
                emegs3d('ReadOrCalcScalpLocIndFile');
                ScalpLocIndVec=get(hPlot3dList(106),'Userdata');
            end
            ChanStatusVec=get(hPlot3dList(63),'Userdata'); 
            ChanStatusOnVec=find(ChanStatusVec==1);
            
            ScalpLoc=ScalpLoc(ScalpLocIndVec,:);
            CalcPot=CalcPot(ScalpLocIndVec,:);
            
            %labelStr1='Values at scalp locations [ascii] | Values at scalp locations [float32] |'					%value 1-2
            %labelStr2='Values at sensor locations [ascii] | Values at sensor locations [float32] |'					%value 3-4
            %labelStr3='Values at special scalp locations [ascii] | Values at special scalp locations [float32] |'		%value 5-6
            %labelStr4='Values at special sensor locations [ascii] | Values at special sensor locations [float32] |'	%value 7-8
            %labelStr5='Scalp locations [ascii] | Scalp locations [float32] |'											%value 9-10
            %labelStr6='Sensor locations [ascii] | Sensor locations [float32] |'										%value 11-12
            %labelStr7='Special scalp locations [ascii] | Special scalp locations [float32] |'							%value 13-14
            %labelStr8='Special sensor locations [ascii] | Special sensor locations [float32]'							%value 15-16
            
            if strcmp(action,'SaveData')
                Method = get(gco,'value') 
            else
                Method=str2num(action(12:13));			% TopMenu: Export
            end;	
            if Method==5 | Method==6 | Method==7 | Method==8  | Method==13 | Method==14 | Method==15 | Method==16
                hMessFig=figure('Units','normal','Position',[.25 .4 .3 .2],'Name','Message Window','Color',[0 0 0],'NumberTitle','off');
                hMessAxes=axes('Position',[0 0 1 1],'Visible','off');
                text('Position',[.5 .66],'Color',[1 1 1],'FontSize',20,'FontWeight','bold','HorizontalAlignment','center','String','Please follow the instructions');	
                text('Position',[.5 .33],'Color',[1 1 1],'FontSize',20,'FontWeight','bold','HorizontalAlignment','center','String','in the command window !');	
                pause
                close(hMessFig);
            end
            
            if 	ActMethod>5; %Minimum Norm
                LeadLocShell=get(hPlot3dList(82),'Userdata');
                if Method==7
                    Method=17;
                elseif Method==8
                    Method=18;
                elseif Method==11
                    Method=19;
                elseif Method==12
                    Method=20;
                elseif Method==15
                    Method=21;
                elseif Method==16
                    Method=22;
                end
            end
            
            if  mod(Method,2)~=0
                DataFormat='ascii';
            else
                DataFormat='float32';
            end
            if Method==1 | Method==2														%Values at scalp locations
                Save2Bem(CalcPot,[],[],1,'Matrix',DataFormat,[],[],1,1,'Untitled.slv')
            elseif Method==3 | Method==4													%Values at sensor/leadfield locations
                Save2Bem(CalcPotSensLead,[],[],1,'Matrix',DataFormat,[],[],1,1,'Untitled.elv')
            elseif  Method==5 | Method==6 | Method==13 | Method==14 | Method==17 | Method==18 | Method==21 | Method==22	%Values at special scalp/leadfield locations
                if Method==5 | Method==6 | Method==13 | Method==14
                    Loc=ScalpLoc;
                elseif Method==17 | Method==18 | Method==21 | Method==22
                    Loc=LeadLocShell;
                end
                [NLoc,NoUse]=size(Loc);
                SaveLocVec=[1:NLoc];
                AddStatus=1;
                while AddStatus
                    [SpecLocMode,k]=IfEmptyInputSpecVal([],[0:5],1,...
                        'Do you want to save\n\n',...
                        'all                       [0]',...
                        'x>0    (right)            [1]',...
                        'x<0    (left)             [2]',...
                        'y>0    (front)            [3]',...
                        'y<0    (back)             [4]',...
                        'z>0    (top)              [5]');
                    if SpecLocMode==0
                        SaveLocVec=[1:NLoc];
                        Tmp=[];
                    elseif SpecLocMode==1
                        Tmp=find(Loc(:,1)>0);
                    elseif SpecLocMode==2
                        Tmp=find(Loc(:,1)<0);
                    elseif SpecLocMode==3
                        Tmp=find(Loc(:,2)>0);
                    elseif SpecLocMode==4
                        Tmp=find(Loc(:,2)<0);
                    elseif SpecLocMode==5
                        Tmp=find(Loc(:,3)>0);
                    end
                    if SpecLocMode>0
                        IndexTmp=0;
                        SaveLocVecTmp=[];
                        for Index=1:NLoc
                            if any(SaveLocVec==Index) & any(Tmp==Index)
                                IndexTmp=IndexTmp+1;
                                SaveLocVecTmp(IndexTmp)=Index;
                            end
                        end
                        SaveLocVec=SaveLocVecTmp;
                        SaveLocVecTmp=[];		
                    end
                    [AddStatus]=IfEmptyInputBo('Additional choice ?',[],[],0,1);
                end
                if  Method==5 | Method==6
                    Save2Bem(CalcPot(SaveLocVec,:),[],[],1,'Matrix',DataFormat,[],[],1,1,'Untitled.sslv');
                elseif Method==13 | Method==14
                    Save2Bem(ScalpLoc(SaveLocVec,:),[],[],1,'Matrix',DataFormat,[],[],1,1,'Untitled.ssl');
                elseif Method==17 | Method==18
                    Save2Bem(CalcPotSensLead(SaveLocVec,:),[],[],1,'Matrix',DataFormat,[],[],1,1,'Untitled.sllv');
                elseif Method==21 | Method==22
                    Save2Bem(LeadLocShell(SaveLocVec,:),[],[],1,'Matrix',DataFormat,[],[],1,1,'Untitled.sll');
                end
            elseif Method==7 | Method==8 | Method==15 | Method==16
                [SaveChanIndVec]=ChooseChanInd(length(ChanStatusOnVec),1,1,[],[],[],EPosSpher,[],ChanStatusVec);
                if Method==7 | Method==8
                    Save2Bem(CalcPotSensLead(SaveChanIndVec,:),[],[],1,'Matrix',DataFormat,[],[],1,1,'Untitled.selv');
                elseif Method==15 | Method==16
                    Save2Bem(EPosCart(SaveChanIndVec,:),[],[],1,'Matrix',DataFormat,[],[],1,1,'Untitled.sel');
                end
            elseif  Method==9 | Method==10
                Save2Bem(ScalpLoc,[],[],1,'Matrix',DataFormat,[],[],1,1,'Untitled.sl');
            elseif  Method==11 | Method==12
                Save2Bem(EPosCart,[],[],1,'Matrix',DataFormat,[],[],1,1,'Untitled.el');
            elseif  Method==19 | Method==20
                Save2Bem(LeadLocShell,[],[],1,'Matrix',DataFormat,[],[],1,1,'Untitled.ll');
            end
          
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
            
        elseif strcmp(action,'Save2Plot'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            
            %Hier sollen alle notwendigen Daten als Ascii file weggeschrieben werden um sie 
            %spaeter mittels "ReadPlotData" zu laden und damit Plot3d unabhaengig von Plot2d starten zu koennen
            
            %fprintf('\n');clc;
            %fprintf('The workspace file *.mat has to be placed on cort_map_analysis_2.0 !!')
            %[File,Path,FilePath]=ReadFilePath([],[],'Please choose a file name:');
            %eval(['load ' FilePath]);
            %PlotSurfNew(CalcPot,1,1);
        
       
      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
      
       elseif strcmp(action,'BatchSubjectPlot')
           
           emegs3d('CalcSLC2Pic');          
           
               
      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif strcmp(action,'ReadPlotData'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            %fprintf('\n');clc;
            %fprintf('The workspace file *.mat has to be placed on cort_map_analysis_2.0 !!')
            %[File,Path,FilePath]=ReadFilePath([],[],'Please choose a file name:');
            %eval(['load ' FilePath]);
            %PlotSurfNew(CalcPot,1,1);
            
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif  strcmp(action,'CalcInvert') | ...
                strcmp(action,'CalcAbs'),
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            CalcPot=get(hPlot3dList(53),'Userdata'); 
            CalcPotChan=get(hPlot3dList(50),'Userdata');
            
            if  strcmp(action,'CalcInvert') 
                CalcPot=-1.*CalcPot;
                CalcPotChan=-1.*CalcPotChan;
            elseif strcmp(action,'CalcAbs')
                CalcPot=abs(CalcPot);
                CalcPotChan=abs(CalcPotChan);
            end
            set(hPlot3dList(53),'Userdata',CalcPot); 
            set(hPlot3dList(50),'Userdata',CalcPotChan); 
            
            emegs3d('setAutoAmp')
            emegs3d('PlotSurfData')
        
            
            
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        elseif  strcmp(action,'CalcDifference1') | ...
                strcmp(action,'CalcDifference2')
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata');
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            CalcPot1=get(hPlot3dList(53),'Userdata'); 
            CalcPotChan1=get(hPlot3dList(50),'Userdata'); 
            [CalcPot2,File,Path,FilePath,EndPos]=ReadData([],1,[],'int16','float32',[],[],'Choose the data to subtract:');
            [CalcPotChan2]=ReadData(FilePath,1,[],'int16','float32',EndPos);
            [m1 n1]=size(CalcPot1);
            [m2 n2]=size(CalcPot2);
            [m3 n3]=size(CalcPotChan1);
            [m4 n4]=size(CalcPotChan2);
            fprintf('\n')
            clc;
            if m1==m2 & n1==n2 
                if  strcmp(action,'CalcDifference1')
                    fprintf('Calculate difference of distribution matrix "Actual minus File"')
                    CalcPotDiff=CalcPot1-CalcPot2;	
                elseif  strcmp(action,'CalcDifference2')
                    fprintf('Calculate difference of distribution matrix "File minus Actual"')
                    CalcPotDiff=CalcPot2-CalcPot1;
                end
                set(hPlot3dList(53),'Userdata',CalcPotDiff); 
                emegs3d('setAutoAmp')
                emegs3d('PlotSurfData')
            else
                Message=char('Sorry,');
                Message=char(Message,'');
                Message=char(Message,'bad size of imported data matrix.');
                Message=char(Message,' ');
                Message=char(Message,'The data matrix you are currently using in Plot3d');
                Message=char(Message,['contains ',int2str(m1),' sensors and ',int2str(n1),'  time points.']);
                Message=char(Message,' ');
                Message=char(Message,'The imported data matrix');
                Message=char(Message,['contains ',int2str(m2),' sensors and ',int2str(n2),'  time points.']);
                hmsgbox=msgbox(Message,'Info','help'); 
                return;
            end
            if m3==m4 & n3==n4 
                if  strcmp(action,'CalcDifference1')
                    fprintf('Calculate difference of electrode matrix "Actual minus File"')
                    CalcPotChanDiff=CalcPotChan1-CalcPotChan2;		
                elseif  strcmp(action,'CalcDifference2')
                    fprintf('Calculate difference of electrode matrix "File minus Actual"')
                    CalcPotChanDiff=CalcPotChan2-CalcPotChan1;		
                end
                set(hPlot3dList(50),'Userdata',CalcPotChanDiff); 
            else
                Message=char('Sorry,');
                Message=char(Message,'');
                Message=char(Message,'bad size of imported data matrix.');
                Message=char(Message,' ');
                Message=char(Message,'The data matrix you are currently using in Plot3d');
                Message=char(Message,['contains ',int2str(m3),' sensors and ',int2str(n3),'  time points.']);
                Message=char(Message,' ');
                Message=char(Message,'The imported data matrix');
                Message=char(Message,['contains ',int2str(m4),' sensors and ',int2str(n4),'  time points.']);
                hmsgbox=msgbox(Message,'Info','help'); 
                
                return;
            end
         
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
            elseif  strcmp(action,'RepeatedMeasuresReset') 
                
                try 
                    rmanovautilpath = strrep(which('emegs3d.m'),'emegs3d.m','rmanovautil.mat');
                    factor = [];
                    save(rmanovautilpath,'factor')
                    hPlot3dList=get(hPlot3dMenuFig,'Userdata');
                    set(hPlot3dList(131),'userdata',factor);
                catch
                end
             
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        
             elseif  strcmp(action,'ExportPointwiseAnova')
                 
                 AnovaToAvgFiles;
                 
                 
         %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
    
                
            elseif  strcmp(action,'RepeatedMeasuresDefine') 
                
                
                
                % factor =          1           2           3   
                %           1       nsubj       ninterv     nchgroups
                %           2       target      nbetween    nsubjlistcells
                %           3       custom1     c1ngrad     c1gradnames
                %           4       custom2     c2ngrad     c2gradnames
                %           5       custom3     c3ngrad     c3gradnames
                %           6       custom4     c4ngrad     c4gradnames


                hPlot2dList=get(hPlot2dMenuFig,'Userdata');
                hPlot3dList=get(hPlot3dMenuFig,'Userdata');
                hTopMenu=get(hPlot3dList(83),'Userdata');
                hFileMenu=get(hTopMenu(1),'children');
                hDefFileMenu=get(hFileMenu(2),'children');
                
                if strcmp(get(hDefFileMenu(3),'Enable'),'off') | strcmp(get(hDefFileMenu(2),'Enable'),'off') |strcmp(get(hDefFileMenu(1),'Enable'),'off') 
                   uiwait(errordlg('You have not loaded a filematrix! Repeated measures anova requires a filematrix!'));
                   emegs3d('OpenFileMatrix');
                   if strcmp(get(hDefFileMenu(3),'Enable'),'off') | strcmp(get(hDefFileMenu(2),'Enable'),'off') |strcmp(get(hDefFileMenu(1),'Enable'),'off') 
                       return
                   end
                end
                MinPoint=get(hPlot3dList(47),'Value');
                MaxPoint=get(hPlot3dList(49),'Value');;
                ParaVec=get(hPlot3dList(62),'Userdata');
                ScalpRadius=ParaVec(7);
                NSqrtScalpLoc=ParaVec(14);
                InvIter=ParaVec(10);
                ForIter=ParaVec(11);
                LengthLegVec=ParaVec(15);
                NChan=ParaVec(16);
                NUsedChan=ParaVec(17);
                NPoints = get(hPlot2dList(50),'userdata');
                NPoints3d=ParaVec(19);   
                NPoints2Plot=get(hPlot3dList(122),'Value');            
                versionstring = version;
                rmanovautilpath = strrep(which('emegs3d.m'),'emegs3d.m','rmanovautil.mat');

                if exist (rmanovautilpath)~=2
                    hPlot3dList=get(hPlot3dMenuFig,'Userdata');
                    factor = get(hPlot3dList(131),'userdata');
                else
                    try
                        load(rmanovautilpath,'factor')
                    catch
                        factor = [];
                    end
                end

                if str2num(versionstring(1))<7
                    if ~isempty(factor)
                        try 
                            nbetween = factor{2,2};
                            startstringcell = {['nrofsubjects: ',num2str(factor{1,1}),  ';'];...
                                           ['nrofintervalls: ',num2str(factor{1,2}),';'];...
                                           ['nrofchannelgroups: ',num2str(factor{1,3}),';']};
                            for i=3:size(factor,1)-nbetween
                                    startstringcell{i+1}=[factor{i,1},':',num2str(factor{i,2}),';'];
                                    startstringcell{i+1}=[startstringcell{i+1},factor{i,3}{1}];
                                    for j=2:factor{i,2}
                                        startstringcell{i+1}=[startstringcell{i+1},',',factor{i,3}{j}];
                                    end
                                    startstringcell{i+1}=[startstringcell{i+1},';'];
                            end  
                            if nbetween>0
                                i=size(factor,1)-nbetween+1;
                                linecounter = i + 1;
                                betweencounter = 1;
                                while 1
                                        startstringcell{linecounter}=['between ',factor{i,1},':',num2str(factor{i,2}),';'];
                                        startstringcell{linecounter}=[startstringcell{linecounter},factor{i,3}{1}];
                                        for j=2:factor{i,2}
                                            try
                                                startstringcell{linecounter}=[startstringcell{linecounter},',',factor{i,3}{j}];
                                            catch
                                            end
                                        end
                                        startstringcell{linecounter} = [startstringcell{linecounter},';'];
                                        linecounter = linecounter + 1 ;
                                        startstringcell{linecounter} = ['[',num2str(factor{2,3}{betweencounter}),'];'];
                                        betweencounter = betweencounter +1;
                                        linecounter = linecounter + 1 ;
                                        i = i + 1;
                                        if i>size(factor,1);
                                            break;
                                        end
                                end  
                            end
                            evalstring = ['''',startstringcell{1},''''];
                            for t=2:size(startstringcell,1)
                                evalstring = [evalstring,',','''',startstringcell{t},''''];
                            end
                            evalstring = ['startstring = char(',evalstring,');'];
                            eval(evalstring);
                        catch
                            uiwait(errordlg('There was an error reloading the anova design! Please check syntax!','Warning:'));
                            startstring = char('nrofsubjects: 16;','nrofintervalls: 1;','nrofchannelgroups: 2;','emo:3;pos,neg,neut;','task: 2; attend, passive; ','between factor3: 2;  deg1, deg2;','[0,1,1,1,0,0,0,1];');
                        end
                    else
                        startstring = char('nrofsubjects: 16;','nrofintervalls: 1;','nrofchannelgroups: 2;','emo:2;pos,neg,neut;','task: 2; attend, passive;','between factor3: 2;  deg1, deg2;','[0,1,1,1,0,0,0,1]; ');
                    end                                                                                           

                    runstatus = 0;
                    syntaxok = 0;
                    while syntaxok==0
                        syntaxok = 1;
                         message = char('Please enter nrofsubjects and factorial design!','');
                         message = char(message,'Please note that the number of subjects must be supplied first, the number of intervalls next,');
                         message = char(message,'followed by the number of channelgroups.  ');
                         message = char(message,'');
                         message = char(message,'Subsequent within-factor definitions (up to a maximum of 4) are to be listed in top-down ');
                         message = char(message,'hierarchical order corresponding the structure of the filematrix that is used. One factor');
                         message = char(message,'definitions can be  preceded by the ''between''-statement. For this definition,  a vector');
                         message = char(message,'definition is required, listing the group index for each subject  in the same order as');
                         message = char(message,'subjects are listed in the batch file.');
                         message = char(message,'If you want to run the anova for every point and channel and view  the results as waves,');
                         message = char(message,'set nrofchannelgroups to the number of channels you have, and nrofintervalls to the total');
                         message = char(message,'number of points in the dataset.');
                        
                        [designstring,runstatus]= uigettext(message,startstring);
                        startstring = designstring;
                        if isempty(designstring)
                            uigettextfigure = findobj('tag','uigettextfigure');
                            close(uigettextfigure);
                            break;
                        else
                            uigettextfigure = findobj('tag','uigettextfigure');
                            close(uigettextfigure);
                        end
                        nrofrows = size(designstring,1);

                        %factors(cell): vert: one factor per row;  horz: 1:name; 2:nrofgradations; 3:gradationtitles;
                        factor = cell(1);

                        factor{2,1} = 'no target';
                        factor{2,2} = 0;
                        factor{2,3} = 0;

                        betweencounter = 1;
                        withincounter = 1;
                        tmpbetweencell = cell(1);
                        celldefstatus = 0;

                        try

                            for row = 1:nrofrows
                                %structure data
                                actualline = designstring(row,:);
                                commata = findstr(actualline,',');
                                semicolon = findstr(actualline,';');
                                colon = findstr(actualline,':');

                                if celldefstatus
                                     factor{2,2} = factor{2,2}+1;
                                    if factor{2,2}==1
                                         factor{2,3} = cell(1);
                                    end
                                    factor{2,3} {betweencounter} = str2num(designstring(row,:));
                                    celldefstatus = 0;
                                    betweencounter = betweencounter +1;
                                    continue;
                                end

                                if ~isempty(findstr(designstring(row,:),'target'))
                                    targeteffectstring = strrep(designstring(row,:),'target','');
                                    factor{2,1}=targeteffectstring;
                                    continue;
                                end
                                if ~isempty(findstr(actualline,'between'))
                                    tmpbetweencell{betweencounter,1} = strrep(designstring(row,1:findstr(actualline,':')-1),'between ','');
                                    tmpbetweencell{betweencounter,2} = str2num(designstring(row,findstr(actualline,':')+1:semicolon(1)));
                                    if ~isempty(commata) & length(semicolon)==2
                                        tmpbetweencell{betweencounter,3} = cell(1);
                                        tmpbetweencell{betweencounter,3}{1}=designstring(row,semicolon(1)+1:commata(1)-1);
                                        for t=1:length(commata)-1
                                            tmpbetweencell{betweencounter,3}{t+1}=designstring(row,commata(t)+1:commata(t+1)-1);
                                        end
                                        tmpbetweencell{betweencounter,3}{length(commata)+1}=designstring(row,commata(end)+1:semicolon(2)-1);
                                    end
                                    celldefstatus = 1;
                                    continue;
                                end

                                if length(colon)>2
                                    uiwait(errordlg({['Syntax error in line ',num2str(row),': only 1 '':'' per line is permitted!']},'Syntax error:'));
                                    syntaxok = 0;
                                    continue;
                                end
                                if length(semicolon)>3
                                    uiwait(errordlg({['Syntax error in line ',num2str(row),': only 2 '';'' per line are permitted!']},'Syntax error:'));
                                    syntaxok = 0;
                                    continue;
                                end
                                if isempty(semicolon) & ~isempty(actualline)
                                    uiwait(errordlg({['Syntax error in line ',num2str(row),':  '';'' expected!']},'Syntax error:'));
                                    syntaxok = 0;
                                    continue;
                                end

                                %read lines
                                if row ==1
                                    nrofsubjects = str2num(designstring(row,findstr(actualline,'nrofsubjects:')+14:findstr(actualline,';')-1));
                                    factor{1,1}=nrofsubjects;
                                    continue;
                                end

                                if row ==2
                                    nrofintervalls = str2num(designstring(row,findstr(actualline,'nrofintervalls:')+16:findstr(actualline,';')-1));
                                    factor{1,2}=nrofintervalls;                                        
                                    continue;
                                end

                                if row ==3
                                    nrofchannelgroups = str2num(designstring(row,findstr(actualline,'nrofchannelgroups:')+18:findstr(actualline,';')-1));
                                    factor{1,3}=nrofchannelgroups;
                                    continue;
                                end


                                %factors
                                factor{2+withincounter,1} = designstring(row,1:findstr(actualline,':')-1);
                                %nrofgradations:
                                factor{2+withincounter,2}= str2num(designstring(row,findstr(actualline,':')+1:semicolon(1)));
                                if ~isempty(commata) & length(semicolon)==2
                                    factor{2+withincounter,3} = cell(1);
                                    factor{2+withincounter,3}{1}=designstring(row,semicolon(1)+1:commata(1)-1);
                                    for t=1:length(commata)-1
                                        factor{2+withincounter,3}{t+1}=designstring(row,commata(t)+1:commata(t+1)-1);
                                    end
                                    factor{2+withincounter,3}{length(commata)+1}=designstring(row,commata(end)+1:semicolon(2)-1);
                                end
                                withincounter = withincounter +1;

                            end

                            if factor{1,2}==NPoints & factor{1,3}==NChan
                                if NPoints2Plot~=NPoints3d
                                    emegs3d('setTotalInt');
                                end
                                factor{2,1}='target 1';
                            else
                                factor{2,1}='no target';
                            end
                                
                            
                            if ~isempty(tmpbetweencell)
                                if ~isempty(tmpbetweencell{1})
                                    factor = [factor;tmpbetweencell];
                                end
                            end

                            if isempty(findstr(factor{2,1},'no target'))
                                if NPoints2Plot~=NPoints3d
                                    emegs3d('setTotalInt');
                                end
                            end
                            
                            if factor{1,2}==NPoints & factor{1,3}==NChan
                                factor{2,1}='target 1';
                            end
                
                            if isempty(factor{1,1}) | factor{1,1}<2 | isempty(factor{1,2})  | isempty(factor{1,3}) 
                                syntaxok = 0;
                                asdfasdfasd;
                            end
                        catch
                            syntaxok = 0;
                            uiwait(errordlg('There was an error parsing the design string! Check syntax!','Parse error:'));
                        end
                    end



                    hPlot3dList=get(hPlot3dMenuFig,'Userdata');
                    set(hPlot3dList(131),'userdata',factor);
                    save(rmanovautilpath,'factor');
                    if runstatus
                        emegs3d('RepeatedMeasuresCalculate');
                    end
                    
                else
                    openfig('rmanovadesign.fig');
                    nrofsubjectsedit = findobj('tag','nrofsubjectsedit');
                    anovadesignfig = findobj('tag','anovadesignfig');
                    intervallsedit=findobj('tag','intervallsedit');
                    channelgroupsedit=findobj('tag','channelgroupsedit');
                    pointwisecheck=findobj('tag','pointwisecheck');
                    f4nameedit= findobj('tag','f4nameedit');
                    f4gradedit= findobj('tag','f4gradedit');
                    f3nameedit= findobj('tag','f3nameedit');
                    f3gradedit=findobj('tag','f3gradedit');
                    f2nameedit= findobj('tag','f2nameedit');
                    f2gradedit=findobj('tag','f2gradedit');
                    f1nameedit= findobj('tag','f1nameedit');
                    f1gradedit= findobj('tag','f1gradedit');
                    bf1nameedit= findobj('tag','bf1nameedit');
                    bf1gradedit= findobj('tag','bf1gradedit');
                    bf1subjectcelledit=findobj('tag','bf1subjectcelledit');
                    bf1check=findobj('tag','bf1check');
                    f4check= findobj('tag','f4check');
                    f3check= findobj('tag','f3check');
                    f2check= findobj('tag','f2check');
                    f1check= findobj('tag','f1check');
                    cancelbutton = findobj('tag','cancelbutton');
                    okbutton= findobj('tag','okbutton');
                    
                    if ~isempty(factor)
                        
                         % factor =          1           2           3   
                        %           1       nsubj       ninterv     nchgroups
                        %           2       target      nbetween    nsubjlistcells
                        %           3       custom1     c1ngrad     c1gradnames
                        %           4       custom2     c2ngrad     c2gradnames
                        %           5       custom3     c3ngrad     c3gradnames
                        %           6       custom4     c4ngrad     c4gradnames
                        
                     
                        try
                            set(nrofsubjectsedit,'String',num2str(factor{1,1}));
                            if isempty(findstr(factor{2,1},'no target'))
                                set(pointwisecheck,'Value',1);
                            else
                                set(pointwisecheck,'Value',0);
                            end
                            enablepointwise;

                            set(intervallsedit,'String',num2str(factor{1,2}));
                            set(channelgroupsedit,'String',num2str(factor{1,3}));
                            
                            
                            
                            
                            nrofwithinfactors = size(factor,1)-2-factor{2,2};
                            if size(factor,1)-factor{2,2}>2
                                set(f1check,'Value',1);
                                set(f1nameedit,'String',factor{3,1});
                                set(f1gradedit,'String',factor{3,2});
                            else
                                set(f1check,'Value',0);
                                set(f1nameedit,'String','');
                                set(f1gradedit,'String','');
                            end
                            enablewfac1;

                            if size(factor,1)-factor{2,2}>3
                                set(f2check,'Value',1);
                                set(f2nameedit,'String',factor{4,1});
                                set(f2gradedit,'String',factor{4,2});
                            else
                                set(f2check,'Value',0);
                                set(f2nameedit,'String','');
                                set(f2gradedit,'String','');
                            end
                            enablewfac2;

                            if size(factor,1)-factor{2,2}>4
                                set(f3check,'Value',1);
                                set(f3nameedit,'String',factor{5,1});
                                set(f3gradedit,'String',factor{5,2});
                            else
                                set(f3check,'Value',0);
                                set(f3nameedit,'String','');
                                set(f3gradedit,'String','');
                            end
                            enablewfac3;

                            if size(factor,1)-factor{2,2}>5
                                set(f4check,'Value',1);
                                set(f4nameedit,'String',factor{6,1});
                                set(f4gradedit,'String',factor{6,2});
                            else
                                set(f4check,'Value',0);
                                set(f4nameedit,'String','');
                                set(f4gradedit,'String','');
                            end
                            enablewfac4;
                            
                            
                            if factor{2,2}>0
                                set(bf1check,'Value',1);
                                set(bf1nameedit,'String',factor{2+nrofwithinfactors+1,1});
                                set(bf1gradedit,'String',factor{2+nrofwithinfactors+1,2});
                                set(bf1subjectcelledit,'String',num2str(factor{2,3}));
                            else
                                set(bf1check,'Value',0);
                                set(bf1nameedit,'String','');
                                set(bf1gradedit,'String','');
                                set(bf1subjectcelledit,'String','');
                            end
                            enablebfac1;
                        catch
                        end
                    end
                        
                    waitfor(anovadesignfig);
                    factor = get(hPlot3dList(131),'userdata');
                    if ~isempty(factor)
                        if isempty(findstr(factor{2,1},'no target'))
                            if NPoints2Plot~=NPoints3d
                                emegs3d('setTotalInt');
                            end
                        end
                    else
                        return
                    end
                    if get(hPlot3dList(147),'userdata');
                        set(hPlot3dList(147),'userdata',0);
                        save(rmanovautilpath,'factor');
                        emegs3d('RepeatedMeasuresCalculate');
                    else;
                        save(rmanovautilpath,'factor');
                    end 
                end
        
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
    
            elseif  strcmp(action,'ImportAnovaData')        
        
                importanovadata;
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
    
            elseif  strcmp(action,'RepeatedMeasuresCalculate') | strcmp(action,'RepeatedMeasuresReCalculate') 
        
                mversion = version;
                mvnr = str2num(mversion(1:3));  
                hPlot3dList=get(hPlot3dMenuFig,'Userdata');
                hTopMenu=get(hPlot3dList(83),'Userdata');
                hFileMenu=get(hTopMenu(1),'children');
                hDefFileMenu=get(hFileMenu(2),'children');
                
               if strcmp(get(hFileMenu(3),'Enable'),'off') | strcmp(get(hFileMenu(2),'Enable'),'off') |strcmp(get(hFileMenu(1),'Enable'),'off') 
                   uiwait(errordlg('You have not loaded a filematrix! Repeated measures anova requires a filematrix!'));
                   return
               end
            
				factor = get(hPlot3dList(131),'userdata');
				if isempty(factor)
                    uiwait(errordlg('No Model has been defined! Please define factors and number of subjects...','Model Specification:'));
                    emegs3d('RepeatedMeasuresDefine');
                    factor = get(hPlot3dList(131),'userdata');
                    if isempty(factor)
                        return
                    end
				end
   
                pointwisestatus = isempty(findstr(factor{2,1},'no target'));
                anovadataold = get(hPlot3dList(133),'userdata');
                keepolddata = 1;
                if ~isempty(anovadataold)
                    if strcmp(action,'RepeatedMeasuresReCalculate') 
                        uigettextfig = findobj('tag','uigettextfigure');
                        close(uigettextfig);
                    else
                        answer = questdlg('There is an old analysis on the clipboard! Do you want to continue and delete the old data, or recalculate the analysis with the old data?','Old analysis:','delete','reuse','delete');
                        if strcmp(answer,'delete')
                             if pointwisestatus
                                
                               if mvnr>6.1
                                    initpath = SetDefPath(1);
                                    [file,initpath] = SepFilePath(initpath);
                                    if isempty(initpath);initpath = '';end
                                    [outpath] = uigetdir(initpath,'Where do you wish to save your results:');
                                    if isequal(outpath,0)
                                       return
									end
                                    SetDefPath(2,[outpath,filesep]);
								else
                                    initpath = SetDefPath(1);
                                    [file,initpath] = SepFilePath(initpath);
                                    if isempty(initpath);initpath = '';end
                                    [filename, outpath] = uiputfile(initpath, 'Where do you wish to save your results:', 300, 300);
									if isequal(filename,0)| isequal(outpath,0)
                                       uiwait(errordlg('File not found!','Error:'));
                                       return
									end
                                    SetDefPath(2,[outpath,filesep]);
								end
    
                                emegs3d('CalcSLC4AnovaAll');
                                keepolddata = 0;
                            else
                                emegs3d('CalcSLC4AnovaGroups');
                                keepolddata = 0;
                                outpath = [];
                            end
                        else
                            if pointwisestatus
                                
                               if mvnr>6.1
                                    initpath = SetDefPath(1);
                                    [file,initpath] = SepFilePath(initpath);
                                    if isempty(initpath);initpath = '';end
                                    [outpath] = uigetdir(initpath,'Where do you wish to save your results:');
                                    if isequal(outpath,0)
                                       return
									end
                                    SetDefPath(2,[outpath,filesep]);
								else
                                    initpath = SetDefPath(1);
                                    [file,initpath] = SepFilePath(initpath);
                                    if isempty(initpath);initpath = '';end
                                    [filename, outpath] = uiputfile(initpath, 'Where do you wish to save your results:', 300, 300);
									if isequal(filename,0)| isequal(outpath,0)
                                       uiwait(errordlg('File not found!','Error:'));
                                       return
									end
                                    SetDefPath(2,[outpath,filesep]);
								end
                            else
                                outpath = [];
                            end
                            
                        end
                    end
                else 
                    if pointwisestatus
                        
                         if mvnr>6.1
                            initpath = SetDefPath(1);
                            [file,initpath] = SepFilePath(initpath);
                            if isempty(initpath);initpath = '';end
                            [outpath] = uigetdir(initpath,'Where do you wish to save your results:');
                            if isequal(outpath,0)
                               return
							end
                            SetDefPath(2,[outpath,filesep]);
						else
                            initpath = SetDefPath(1);
                            [file,initpath] = SepFilePath(initpath);
                            if isempty(initpath);initpath = '';end
                            [filename, outpath] = uiputfile(initpath, 'Where do you wish to save your results:', 300, 300);
							if isequal(filename,0)| isequal(outpath,0)
                               uiwait(errordlg('File not found!','Error:'));
                               return
							end
                            SetDefPath(2,[outpath,filesep]);
						end
                        
                        emegs3d('CalcSLC4AnovaAll');
                        keepolddata = 0;
                    else
                        emegs3d('CalcSLC4AnovaGroups');
                        outpath = [];
                        keepolddata = 0;
                    end
                end
                [results]= RmAnova(factor,keepolddata,pointwisestatus,outpath);
                
                %Fehler
                if isempty(results)
                    return
                end
              
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        
        elseif strcmp(action,'Apply'),   
                 
            if isempty(varargin)
                updatestatus=0;
            else
                updatestatus = varargin{2};
                targetfig = varargin{3};
            end
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata');
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            ApplyVec=get(hPlot3dList(33),'Userdata');
            if ApplyVec(1)==0 %Do not recalculate 
                if updatestatus
                    emegs3d('PlotSurfData',targetfig)
                else
                    emegs3d('PlotSurfData')
                end    
            elseif ApplyVec(1)==1; %Recalculate    
                if ApplyVec(2)==1; %SLC
                    set(hPlot3dList(2),'Value',ApplyVec(3));
                    if updatestatus
                        emegs3d('CalcCortMap',targetfig)
                    else
                        emegs3d('CalcCortMap')
                    end   
                elseif ApplyVec(2)==2; %MinNorm
                    set(hPlot3dList(32),'Value',ApplyVec(3));
                    if updatestatus
                        emegs3d('CalcMinimumNorm',targetfig)
                    else
                        emegs3d('CalcMinimumNorm')
                    end   
                end
            else
                error('Unknown value in ApplyVec')
            end
            
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
           
        elseif strcmp(action,'PlotSurfData'),
            
            hPlot2dList=get(hPlot2dMenuFig,'Userdata');
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            PlotSurfStatus=get(hPlot3dList(84),'Value');
            
            if isempty(varargin)
                targetfig = [];
            else
                targetfig = varargin{1};
                if isempty(targetfig)
                    updatestatus = 0;
                else
                    updatestatus = 1;
                end
            end
            
            if PlotSurfStatus==0; return; end
          
            HeadModel=get(hPlot3dList(129),'Userdata');
            CutRealBotVal=get(hPlot3dList(127),'Value');
            BatchPlotStatus = get(hPlot3dList(149),'userdata'); 
            if isempty(BatchPlotStatus);BatchPlotStatus = 0;end
            
            SensorNames=get(hPlot2dList(4),'Userdata');
            ActFileNo=get(hPlot3dList(87),'Value');
            Domain=get(hPlot2dList(20),'Value');
            EEGMEGStatusString=get(hPlot2dList(110),'String');
            if strcmp(EEGMEGStatusString,'EEG'); EEGMEGString='µV'; else; EEGMEGString='fT'; end
            Plot2dNListHdr=get(hPlot2dList(51),'Userdata');
            MinPoint=get(hPlot3dList(47),'Value');
            MaxPoint=get(hPlot3dList(49),'Value');
            NPoints=MaxPoint-MinPoint+1;
            TrigPoint=get(hPlot2dList(22),'Value');
            FileNoVec=get(hPlot2dList(56),'Userdata');	
            EPosCart=get(hPlot3dList(57),'Userdata');
            CalcAvgMat=get(hPlot2dList(Plot2dNListHdr+(FileNoVec(ActFileNo)-1).*50+1),'Userdata');
            NTrialAvgVec=get(hPlot2dList(Plot2dNListHdr+(ActFileNo-1).*50+5),'Userdata');
            StdChanTimeMat=get(hPlot2dList(Plot2dNListHdr+(ActFileNo-1).*50+6),'Userdata');
            
            SampRate=get(hPlot2dList(60),'Userdata'); 
            BackGroundColor=get(hPlot2dList(93),'Color');	%hChanFig
            FontSizeVec=get(hPlot2dList(112),'Userdata');
            
            ApplyVec=get(hPlot3dList(33),'Userdata');
            ApplyVec(1)=0; %Do not recalculate
            set(hPlot3dList(33),'Userdata',ApplyVec,'Enable','On');		%hApply
            Dim2d3dViewVal=get(hPlot3dList(12),'Value');	%'Spec. Surf (3d)|All Surf I (3d)|All Surf II (3d) |Plot (2d)|Spec. Right'|Columns & Rows;
            HeadView=get(hPlot3dList(14),'Value');          %labelStr='Back[0, 0]|Front[180, 0]|Top  [0, 90]|Bottom  [180, -90]|Left[-90, 0]|Right [90, 0]|Special';
            ChanStatusVec=get(hPlot3dList(63),'Userdata');
            ChanStatusOnVec=find(ChanStatusVec==1);
            SensorVisVecBack=find(EPosCart(ChanStatusOnVec,2)<=0);
            SensorVisVecFront=find(EPosCart(ChanStatusOnVec,2)>=0);
            SensorVisVecTop=find(EPosCart(ChanStatusOnVec,3)>=0);
            SensorVisVecBottom=find(EPosCart(ChanStatusOnVec,3)<=0);
            SensorVisVecLeft=find(EPosCart(ChanStatusOnVec,1)<=0);
            SensorVisVecRight=find(EPosCart(ChanStatusOnVec,1)>=0);
            SensorVisVecAll = [1:size(EPosCart,1)];
            if HeadView==1;
                HeadViewString='Back';	  
            elseif HeadView==2
                HeadViewString='Front';  
            elseif HeadView==3
                HeadViewString='Top';
            elseif HeadView==4
                HeadViewString='Bottom';        
            elseif HeadView==5
                HeadViewString='Left';		
            elseif HeadView==6
                HeadViewString='Right';		
            else
                HeadViewString=[];
            end
            ThetaView=get(hPlot3dList(16),'Userdata');
            PhiView=get(hPlot3dList(18),'Userdata');
            DistPointVec=get(hPlot3dList(41),'Userdata');
            DistPoint=DistPointVec(1);
            DistPointMeanStatus=get(hPlot3dList(44),'Value');
            
            hTopMenu=get(hPlot3dList(83),'Userdata');
            hStyleMenu=get(hTopMenu(2),'children');
            hStyleTextMenu=get(hStyleMenu(1),'children');
            hStyleTextSensorMenu=get(hStyleTextMenu(1),'children');
            SensorNameStatus=get(hStyleTextSensorMenu(1),'Userdata');
            SensorCircleStatus=get(hStyleTextSensorMenu(2),'Userdata');
            SensorAsteriskStatus=get(hStyleTextSensorMenu(3),'Userdata');
            hStyleColormapMenu=get(hStyleMenu(2),'children');
            pointer=get(hPlot2dList(83),'Userdata');
            ColormapFlipLabel=get(hStyleColormapMenu(1),'Label');
            ColormapFlipPointPos=get(hStyleColormapMenu(1),'Userdata');
            FlipColormapStatus=get(hPlot3dList(118),'Value'); 
            ColorMapVal=get(hPlot3dList(20),'Value');
            MinAmp=get(hPlot3dList(22),'Userdata');
            MaxAmp=get(hPlot3dList(24),'Userdata');
            CenterAmpStatus=get(hPlot3dList(25),'Value');
            SpecAmpStatus=get(hPlot3dList(26),'Value');
            Print2FileStatus=get(hPlot3dList(27),'Value');
            Print2FilePath=get(hPlot3dList(27),'Userdata');
            Print2FileCompVal=get(hPlot3dList(37),'Userdata');
            Print2FileMethodString=get(hPlot3dList(89),'Userdata');
            NColor=str2num(get(hPlot3dList(117),'String'));
            WinMat=get(hPlot3dList(114),'Userdata');
            NWin=WinMat(1);
            ActWin=WinMat(2);
            MoviePauseStatus=get(hPlot3dList(28),'Value');
            PlotEPosStatus=get(hPlot3dList(30),'Value');
            PlotContourStatus=get(hPlot3dList(35),'Value');
            if HeadModel~=1
                PlotContourStatus=3;
            end
            PlotLatencyStatus=get(hPlot3dList(43),'Value');
            ActFilePath=get(hPlot3dList(55),'Userdata');
            [ActFile,ActPath]=SepFilePath(ActFilePath);
            DiffSetStatus=0;
            if length(ActFile)>8
                if strcmp(ActFile(1:3),'Set') & strcmp(ActFile(5:8),'-Set')
                    DiffSetStatus=1;
                    SetNumber1=str2num(ActFile(4));
                    SetNumber2=str2num(ActFile(9));
                    DiffSetFilePath1=get(hPlot2dList(Plot2dNListHdr+(SetNumber1-1).*50+4),'Userdata');
                    [DiffSetFile1]=SepFilePath(DiffSetFilePath1);
                    DiffSetFilePath2=get(hPlot2dList(Plot2dNListHdr+(SetNumber2-1).*50+4),'Userdata');
                    [DiffSetFile2]=SepFilePath(DiffSetFilePath2);
                    DiffSetStr=[DiffSetFile1,' - ',DiffSetFile2];
                end	
            end
            EPosSpher=get(hPlot3dList(56),'Userdata'); 
            ECfgFilePath=get(hPlot3dList(61),'Userdata');
            [ECfgFile,ECfgPath]=SepFilePath(ECfgFilePath);
            ParaVec=get(hPlot3dList(62),'Userdata'); 
            LegIter=ParaVec(10);
            MSpherical=ParaVec(13);
            TimePotVec=get(hPlot3dList(78),'Userdata'); 
            NRowColorMap=get(hPlot3dList(117),'Value');
            GrayFitVal=get(hPlot3dList(119),'Value');
            ColorAmpTotStatus=get(hPlot3dList(120),'Userdata');
            
            if Domain<3; 
                xTimePotVec=[1-TrigPoint:length(TimePotVec)-TrigPoint].*1000./SampRate;
            elseif Domain>2 & Domain <5
                xTimePotVec=linspace(0,SampRate./2,length(TimePotVec));
            elseif Domain==5
                xTimePotVec=[1:length(TimePotVec)];
            end
            
            UseApp=get(hPlot3dList(72),'Value');
            SLCLambdaApprox=get(hPlot3dList(69),'Value');
            MNLambdaApprox=get(hPlot3dList(109),'Value');
            PlusMinusStatusVec=get(hPlot3dList(139),'Userdata');
            PlusMinusStatus=PlusMinusStatusVec(1);
            PlusMinusVal=PlusMinusStatusVec(2);
            
            ActMethod=get(hPlot3dList(51),'Value'); 
            if ActMethod~=3 &  ActMethod~=6
                ScalpCortStatus=1; Radius=ParaVec(7);
            elseif ActMethod==3
                ScalpCortStatus=2; Radius=ParaVec(1);
            elseif ActMethod==6		 % Inverse L2- Minimum Norm; %
                %ShellNo=get(hPlot3dList(32),'Value');
                %InverseRadiusVec=get(hPlot3dList(80),'Userdata'); 
                ScalpCortStatus=2; 
                %Radius=InverseRadiusVec(ShellNo);
                Radius=ParaVec(1);
            end
            if ActMethod==6
                QuiverStatus=get(hPlot3dList(95),'Value');
                AbsMinNormSurfStatus=get(hPlot3dList(105),'Value');
                if QuiverStatus
                    XMat=get(hPlot3dList(91),'Userdata');
                    YMat=get(hPlot3dList(92),'Userdata');
                    ZMat=get(hPlot3dList(93),'Userdata');
                end
                PotLapLabelString='Dipole Strength [nA/mm]';
                PotLapColorString='Used color versus value of dipole strength';
                PotLapEinheitString='nA/mm';
            elseif ActMethod==2 | ActMethod==5
                if Domain<3
                    PotLapLabelString=['Laplacian [',EEGMEGString,'/rad^2]'];
                    PotLapEinheitString=[EEGMEGString,'/rad^2'];
                    PotLapColorString='Used color versus value of laplacian';
                elseif Domain>2 & Domain <5
                    PotLapLabelString=['Laplacian of P-FFT [',EEGMEGString,'/(rad^2 x sqrt(Hz))]'];
                    PotLapEinheitString=[EEGMEGString,'/(rad^2 x sqrt(Hz))'];
                    PotLapColorString='Used color versus value of P-FFT laplacian';
                elseif Domain==5
                    PotLapLabelString=['Laplacian [1/rad^2]'];
                    PotLapEinheitString=['1/rad^2'];
                    PotLapColorString='Used color versus value of laplacian';
                end
            else
                if Domain<3
                    if strcmp(EEGMEGStatusString,'EEG')
                        PotLapLabelString=['Potential [',EEGMEGString,']'];	
                        PotLapColorString='Used color versus value of potential';
                    else
                        PotLapLabelString=['Field [',EEGMEGString,']'];	
                        PotLapColorString='Used color versus value of magnetic field';
                    end
                    PotLapEinheitString=EEGMEGString;
                elseif Domain>2 & Domain <5
                    PotLapLabelString=['P-FFT [',EEGMEGString,'/sqrt(Hz)]'];	
                    PotLapColorString='Used color versus value of P-FFT';
                    PotLapEinheitString=[EEGMEGString,'/sqrt(Hz)'];
                elseif Domain==5
                    PotLapLabelString=['Variance [%]'];	
                    PotLapColorString='Used color versus value of variance';
                    PotLapEinheitString=[' '];
                end
            end
            TitleNum=get(hPlot3dList(52),'Value');
            CalcPot=get(hPlot3dList(53),'Userdata'); 
            [NScalpLoc,NPoints]=size(CalcPot);
         
            if		BackGroundColor==[1 1 1]; BackGroundColorString='w'; ForeGroundColor=[0 0 0]; ForeGroundColorString='k';
            else	BackGroundColor==[0 0 0]; BackGroundColorString='k'; ForeGroundColor=[1 1 1]; ForeGroundColorString='w';
            end	
            if NWin>1
                FontSizeVec(1:3)=[8 12 18];
            else
                FontSizeVec(1:3)=[10 16 24];
            end
            
            if Dim2d3dViewVal<4			%2d
                SpecDimView=(Dim2d3dViewVal-1).*10+HeadView;
                NMovie=NPoints;
                [MovieFigPos,MovieAxesPos]=calc_fig_axes_mov(SpecDimView,1,NWin,ActWin);
                if Dim2d3dViewVal==1; MovieFigPos(3)=MovieFigPos(3)./2; end
            elseif Dim2d3dViewVal==4 	%3d
                NMovie=ceil(NPoints./10);
                if SpecAmpStatus
                    [MovieFigPos,MovieAxesPos]=calc_fig_axes_cou(1,1,NWin,ActWin);
                else
                    [MovieFigPos,MovieAxesPos]=calc_fig_axes_cou(2,1,NWin,ActWin);
                end
            elseif Dim2d3dViewVal==5	%Spec. Head View
                NMovie=NPoints;
                if NWin<5 & ActWin==1
                    MovieFigPos=[0 .5 .4 .5];
                elseif NWin<5 & ActWin==2
                    MovieFigPos=[.4 .5 .4 .5];
                elseif NWin<5 & ActWin==3
                    MovieFigPos=[0 0 .4 .5];
                elseif NWin<5 & ActWin==4
                    MovieFigPos=[.4 0 .4 .5];  
                elseif NWin>4 & ActWin==1
                    MovieFigPos=[0 .6 .33 .4]; 
                elseif NWin>4 & ActWin==2
                    MovieFigPos=[.33 .6 .33 .4];  
                elseif NWin>4 & ActWin==3
                    MovieFigPos=[.66 .6 .33 .4];  
                elseif NWin>4 & ActWin==4
                    MovieFigPos=[0 .1 .33 .4];  
                elseif NWin>4 & ActWin==5
                    MovieFigPos=[.33 .1 .33 .4]; 
                elseif NWin>4 & ActWin==6
                    MovieFigPos=[.66 .1 .33 .4]; 
                end
                MovieAxesPos=[0 0 0 0;...
                        0.87 0.095 0.06 0.825;...
                        0 0 0 0;...
                        0 0 0 0;...
                        0.05 0.05 0.7 0.9];
            elseif Dim2d3dViewVal==6 	%Columns & Rows
                if 	NPoints<61
                    NRow=10;
                    NCol=ceil(NPoints./NRow);
                elseif 	NPoints>60
                    NCol=5;
                    NRow=10;
                    while NRow.*NCol<NPoints
                        NCol=NCol+1;
                        RowColQuot=0.5;
                        while RowColQuot<0.6
                            RowColQuot=NRow/NCol;
                            NRow=NRow+1;
                        end
                    end
                end
                if NCol>=6
                    MovieFigPos=[0 0 1 1];
                else
%                     if NWin>1
%                         if ActWin==3; ActWin=1; end
%                         if ActWin==4; ActWin=2; end
%                     end
                    if .17.*NCol*ActWin<1
                        MovieFigPos=[0 1-.17.*NCol*ActWin 1 .17.*NCol];
                    else
                        MovieFigPos=[0 1-.17.*NCol 1 .17.*NCol];
                    end
                end
                MovieAxesPos=zeros(NPoints,4);
                for ActCol=1:NCol
                    for ActRow=1:NRow
                        MovieAxesPos((ActCol-1).*NRow+ActRow,:)=[(ActRow-1)./NRow,1-ActCol./NCol,.95/NRow,.925/NCol];
                    end
                end
            end	
            if strcmp(computer,'PCWIN') 
                MovieFigPos=MovieFigPos+[.05 -.05 -.05 0];
            end
            NSqrtScalpLoc=32;
            NScalpLoc=NSqrtScalpLoc.^2;
            [XScalp,YScalp,ZScalp]=sphere(NSqrtScalpLoc-1);
            XScalp=XScalp.*Radius;
            YScalp=YScalp.*Radius;
            ZScalp=ZScalp.*Radius;
            
            ViewVec=[0 0;180 0;0 90;180 -90;-90 0;90 0;45 70;0 0;0 0;0 0;0 0;180 0;0 90;180 -90;-90 0;90 0;45 70;0 0];
            
            [TitleString]=title_string_func(TitleNum,1);	
            if ~isempty(findstr(ActFile,'t-test'))
                TitleString=['t-Test'];
                PotLapLabelString=['t-value'];	
                PotLapColorString='Used color versus t-value';
                PotLapEinheitString=['t-value'];
            end
            if  (Dim2d3dViewVal==1 | Dim2d3dViewVal==4 | Dim2d3dViewVal==6 ) & ~isempty(HeadViewString)	
                if ~isempty(TitleString)
                    TitleString=[TitleString,'; '];
                end
                TitleString=[TitleString,HeadViewString,' View'];
            end
            if DiffSetStatus
                FigName=[TitleString,'; ',DiffSetStr];
            else
                FigName=[TitleString,'; ',ActFile];
            end
            if ~BatchPlotStatus
                 if isempty(varargin)
                    MovieFig=figure('Units','normal',...
                    'Position',MovieFigPos,...
                    'Color',BackGroundColor,...
                    'NumberTitle','off',...
                    'Name',FigName,...
                    'handlevisibility','on',...
                    'visible','on');
                else
                    if isempty(targetfig)
                        MovieFig=figure('Units','normal',...
                        'Position',MovieFigPos,...
                        'Color',BackGroundColor,...
                        'NumberTitle','off',...
                        'Name',FigName,...
                        'handlevisibility','on',...
                        'visible','on',...
                        'tag','GP2Emegs3dCursFig');
                    else
                        MovieFig = targetfig;
                        figure(MovieFig);
                    end
                end
            else
                MovieFig=figure('Units','normal',...
                'Position',MovieFigPos,...
                'Color',BackGroundColor,...
                'NumberTitle','off',...
                'Name',FigName,...
                'handlevisibility','on',...
                'visible','off');   
            end
            
            pause(.01)
            if ~ColorAmpTotStatus
                AmpDiff=MaxAmp-MinAmp;
                NRowColorMap=round(AmpDiff./NRowColorMap);
            end
            if ColorMapVal==8 & GrayFitVal>0
                NRowColorMap=NRowColorMap+GrayFitVal;
            end
            if ColorMapVal==1
                ColorMat=hsv(NRowColorMap);
            elseif ColorMapVal==2
                ColorMat=hot(NRowColorMap);
            elseif ColorMapVal==3
                ColorMat=cool(NRowColorMap);
            elseif ColorMapVal==4
                ColorMat=jet(NRowColorMap);
            elseif ColorMapVal==5
                ColorMat=pink(NRowColorMap);
            elseif ColorMapVal==6
                ColorMat=flag(NRowColorMap);
            elseif ColorMapVal==7
                ColorMat=copper(NRowColorMap);
            elseif ColorMapVal==8
                ColorMat=gray(NRowColorMap);
            end
            if ColorMapVal==8 & GrayFitVal>0
                ColorMat=ColorMat(GrayFitVal:size(ColorMat,1),:);
            end
            if FlipColormapStatus; ColorMat=flipud(ColorMat); end
            if PlusMinusStatus~=0;
                NRowColorMap=size(ColorMat,1);
                NRowColorMapTmp=floor(NRowColorMap.*1./(1-PlusMinusVal));
                ColorMatTmp=ones(NRowColorMapTmp,3);
                d=[.9 .9 .9];
                if PlusMinusStatus==-1
                    ColorMatTmp(1:NRowColorMap,:)=ColorMat(1:NRowColorMap,:);
                    c=[NRowColorMap+1:1:NRowColorMapTmp];
                end
                if PlusMinusStatus==1
                    ColorMatTmp(NRowColorMapTmp-NRowColorMap+1:NRowColorMapTmp,:)=ColorMat(1:NRowColorMap,:);
                    c=[1:1:NRowColorMapTmp-NRowColorMap-1];
                end
                if PlusMinusStatus==2
                    ColorMatTmp(1:floor(NRowColorMap./2),:)=ColorMat(1:floor(NRowColorMap./2),:);
                    ColorMatTmp(NRowColorMapTmp-floor(NRowColorMap./2)+1:NRowColorMapTmp,:)=ColorMat(floor(NRowColorMap./2)+1:NRowColorMap,:);
                    c=[floor(NRowColorMap./2)+1:1:NRowColorMapTmp-floor(NRowColorMap./2)];
                end   
                for i=1:length(c)
                    ColorMatTmp(c(i),:)=d;
                end          
                xi=linspace(1,NRowColorMapTmp,NRowColorMap);
                for i=1:3
             		ColorMat(:,i)=interp1([1:NRowColorMapTmp],ColorMatTmp(:,i),xi)';
                end
            end
            colormap(ColorMat);		
            
            if CenterAmpStatus
                MaxAmpTmp=max(abs([MaxAmp MinAmp]));
                MinAmpTmp=-1.*MaxAmpTmp;
            else
                MaxAmpTmp=MaxAmp;
                MinAmpTmp=MinAmp;
            end
            
            if SpecAmpStatus
                XPColor=linspace(MinAmpTmp,MaxAmpTmp);
            end
            
            CalcPotTmpcell=cell(1);
            
            %=========================================================================
            %   Head View & All Surf 1.
            %=========================================================================
            
            if Dim2d3dViewVal~=4 & Dim2d3dViewVal~=6 
                
                for MovieIndex=1:NMovie
                    [CalcPotTmp]=change_n_sqrt_n(CalcPot(:,MovieIndex));
                    if ActMethod==6 & QuiverStatus
                        [XMatTmp]=change_n_sqrt_n(XMat(:,MovieIndex));
                        [YMatTmp]=change_n_sqrt_n(YMat(:,MovieIndex));
                        [ZMatTmp]=change_n_sqrt_n(ZMat(:,MovieIndex));
                    end
                    if ~SpecAmpStatus
                        MinAmpTmp=min(min(CalcPotTmp));
                        MaxAmpTmp=max(max(CalcPotTmp));	
                        if CenterAmpStatus
                            MaxAmpTmp=max(abs([MaxAmpTmp MinAmpTmp]));
                            MinAmpTmp=-1.*MaxAmpTmp;
                        end
                    end
                    if MinAmpTmp==MaxAmpTmp
                        if MaxAmpTmp==0
                            MaxAmpTmp=.1;
                            MinAmpTmp=-.1;
                        elseif MaxAmpTmp>0
                            MaxAmpTmp=1.1.*MaxAmpTmp;
                            MinAmpTmp=.9.*MinAmpTmp;
                        elseif MaxAmpTmp<0
                            MaxAmpTmp=.9.*MaxAmpTmp;
                            MinAmpTmp=1.1.*MinAmpTmp;
                        end
                    end
                    if MovieIndex==1;
                        hAxes0=axes('Units','normal','Position',MovieAxesPos(5,:));
                    else
                        axes(hAxes0);
                        set(hAxes0,'NextPlot','Replace');
                    end
                    
                    %=========================================================================
                    %   Head View & All Surf 1.
                    %=========================================================================
                    
                    if HeadModel>1 & HeadModel~=4
                        %turn potential
                        %===============================
                        CalcPotTmp=[CalcPotTmp(:,18:32),CalcPotTmp(:,1:17)];
                         %To have a smooth fitting where the sides of the texture meet....
                        %============================================================
                        tmp = mean([CalcPotTmp(:,1),CalcPotTmp(:,32)],2);
                        CalcPotTmp(:,1)  = tmp;
                        CalcPotTmp(:,32) = tmp;
                        contourintvervall = str2num(get(hPlot3dList(117),'String'));
                        if HeadModel ~= 4
                            [contourpic]=surfcdata2contourpic(CalcPotTmp,ColorMat,MinAmp,MaxAmp,ColorAmpTotStatus,contourintvervall,NColor,CutRealBotVal);
                        end
                        if HeadModel == 2
                            load('head3dsurf2.mat','head3dx','head3dy','head3dz'); 
                        elseif HeadModel == 3
                            load('head3dsurf.mat','head3dx','head3dy','head3dz');  
                        elseif HeadModel == 5
                            load('brain3dsurf.mat','head3dx','head3dy','head3dz'); 
                        elseif HeadModel == 6
                            load('brain3dsurf2.mat','head3dx','head3dy','head3dz'); 
                        elseif HeadModel == 7
                            load('brainNC_lowsmooth_surf.mat','head3dx','head3dy','head3dz'); 
                        elseif HeadModel == 8
                            load('brainNC_highsmooth_surf.mat','head3dx','head3dy','head3dz'); 
                        elseif HeadModel == 9
                            modelcell = get(hPlot3dList(140),'Userdata');
                            if isempty(modelcell)
                                uiwait(errordlg('Failed to retrieve custom head model!','Warning:'));
                                return;
                            else
                                head3dx =  modelcell{1};
                                head3dy =  modelcell{2};
                                head3dz =  modelcell{3};
                            end
                        end
                        
                        hSurf0=surf(head3dx,head3dy,head3dz,'EdgeColor','none','CData',contourpic,'FaceColor','texturemap','tag','head3d');                            
                        
                        if BatchPlotStatus
                            set(gcf,'tag','BatchPlotFig','HandleVisibility','on','visible','on');
                        end
                        lighting phong;axis equal;material shiny;
                        light('Position',[30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                        light('Position',[-30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                        light('Position',[30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                        light('Position',[-30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                        if (PlotEPosStatus==1) | PlotEPosStatus==2
                            plotsensors3d(EPosSpher(ChanStatusOnVec,:),SensorNames(ChanStatusOnVec,:),0,SensorNameStatus,HeadModel);
                        end
                    elseif HeadModel==4  
                        contourintvervall = str2num(get(hPlot3dList(117),'String'));
                        hSurf0=plot3dbrain(XScalp,YScalp,ZScalp,CalcPotTmp,0,gca,HeadModel); 
                        if BatchPlotStatus
                            set(gcf,'tag','BatchPlotFig','HandleVisibility','on','visible','on');
                        end
                        set(gca,'PlotBoxAspectRatioMode','manual','CameraPositionMode','manual','CameraTargetMode','manual','DataAspectRatioMode','manual','CameraViewAngleMode','manual','CameraViewAngle',6,'CameraViewAngle',6,'CameraPosition',[2 2 2]);
                        if (PlotEPosStatus==1) | PlotEPosStatus==2
                            plotbrainsensors3d(EPosSpher(ChanStatusOnVec,:),SensorNames(ChanStatusOnVec,:),0,SensorNameStatus,HeadModel);
                        end
                    elseif HeadModel == 1
                        if BatchPlotStatus
                            set(gcf,'tag','BatchPlotFig','HandleVisibility','on','visible','on');
                        end
                        if isempty(varargin)
                            if PlotContourStatus==4
                                hSurf0=surf(XScalp,YScalp ,ZScalp,CalcPotTmp,'FaceLighting','gouraud'); %,'EdgeColor','none'
                                light('Position',[30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[-30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[-30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                            else
                                hSurf0=surf(XScalp,YScalp ,ZScalp,CalcPotTmp); %,'EdgeColor','none'
                            end
                            shading interp;
                            hold on;
                            %this only change the color rendering... 
                            plot3(0,0,0,'b*');
                        else
                            if isempty(targetfig)
                                hSurf0=surf(XScalp,YScalp ,ZScalp,CalcPotTmp,'tag','CursUpdateSurf','FaceLighting','gouraud'); %,'EdgeColor','none'
                                light('Position',[30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[-30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[-30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                shading interp;
                                hold on;
                                %this only change the color rendering... 
                                plot3(0,0,0,'b*');
                            else
                                hSurf0 = findobj('tag','CursUpdateSurf');
                                set(hSurf0,'CData',CalcPotTmp);
                            end
                        end
                    end  
       
                    if ActMethod==6  & ~AbsMinNormSurfStatus	
                        set(hSurf0,'Visible','off');
                    end
                    if Dim2d3dViewVal~=9
                        caxis([MinAmpTmp MaxAmpTmp]);
                        view(ThetaView,PhiView);
                    elseif (Dim2d3dViewVal==9 & MovieIndex==NMovie)
                        headaxes=get(hSurf0,'Parent');
                        axes(headaxes);
                        caxis([MinAmpTmp MaxAmpTmp]);
                        view(ThetaView,PhiView);
                    end      
                    if Dim2d3dViewVal<5
                        title(TitleString,'FontSize',FontSizeVec(3),'Color',ForeGroundColor);
                    end
                    axis('off')
                    hold on
                    if ActMethod==6 & QuiverStatus
                        quiver3(XScalp,YScalp,ZScalp,XMatTmp,YMatTmp,ZMatTmp,1.5);
                    end	
                    
                    if isempty(View2d3d) | (View2d3d~=7 & View2d3d~=8 & View2d3d~=9)
                        if PlotEPosStatus~=3
                            if HeadView==1;
                                SensorVisVec=SensorVisVecBack;	  
                            elseif HeadView==2
                                SensorVisVec=SensorVisVecFront;	  
                            elseif HeadView==3
                                SensorVisVec=SensorVisVecTop;	  
                            elseif HeadView==4
                                SensorVisVec=SensorVisVecBottom;	  
                            elseif HeadView==5
                                SensorVisVec=SensorVisVecLeft;	  	
                            elseif HeadView==6
                                SensorVisVec=SensorVisVecRight;	  
                            end
                            if isempty(varargin)
                                if PlotContourStatus==4
                                   PlotECPositions(ScalpCortStatus,3,0,ForeGroundColor,1,EPosSpher(ChanStatusOnVec(SensorVisVecAll),:),...
                                    Radius,SensorCircleStatus,SensorAsteriskStatus,SensorNameStatus,SensorNames(ChanStatusOnVec(SensorVisVecAll),:))
                                else
                                   PlotECPositions(ScalpCortStatus,3,0,ForeGroundColor,1,EPosSpher(ChanStatusOnVec(SensorVisVec),:),...
                                    Radius,SensorCircleStatus,SensorAsteriskStatus,SensorNameStatus,SensorNames(ChanStatusOnVec(SensorVisVec),:))
                                end
                            else
                                if isempty(targetfig)
                                    if PlotContourStatus==4
                                       PlotECPositions(ScalpCortStatus,3,0,ForeGroundColor,1,EPosSpher(ChanStatusOnVec(SensorVisVecAll),:),...
                                        Radius,SensorCircleStatus,SensorAsteriskStatus,SensorNameStatus,SensorNames(ChanStatusOnVec(SensorVisVecAll),:))
                                    else
                                       PlotECPositions(ScalpCortStatus,3,0,ForeGroundColor,1,EPosSpher(ChanStatusOnVec(SensorVisVec),:),...
                                        Radius,SensorCircleStatus,SensorAsteriskStatus,SensorNameStatus,SensorNames(ChanStatusOnVec(SensorVisVec),:))
                                    end
                                 end
                            end
                       end
                    end
                    
                    if isempty(View2d3d) | (View2d3d~=7 & View2d3d~=8 & View2d3d~=9)
                        if PlotContourStatus<3 & HeadView<7
                            if isempty(varargin)
                                plot_head_contour(MovieAxesPos(5,:),ScalpCortStatus,HeadView,ForeGroundColor,1)
                            else
                                if isempty(targetfig)
                                     plot_head_contour(MovieAxesPos(5,:),ScalpCortStatus,HeadView,ForeGroundColor,1)
                                end
                            end
                        elseif PlotContourStatus==4
                            PlotSpherBool;
                        end
                    end
                    hold off
                    if ((MovieIndex==1 | ~SpecAmpStatus) & Dim2d3dViewVal~=9) | (Dim2d3dViewVal==9 & MovieIndex==NMovie)
                        if MovieIndex>1 & Dim2d3dViewVal~=9
                            set(hPColorAxes,'XTickLabels',[]);
                        end
                        if isempty(varargin)
                            hPColorAxes=axes('Units','normal','Position',MovieAxesPos(2,:),'FontSize',FontSizeVec(1));
                        else
                            if isempty(targetfig)
                                hPColorAxes=axes('Units','normal','Position',MovieAxesPos(2,:),'FontSize',FontSizeVec(1),'tag','CursUpdateColorBar','handlevisibility','on');
                            else
                                hPColorAxes = findobj('tag','CursUpdateColorBar');
                                axes(hPColorAxes);
                            end
                        end
                        XPColor=linspace(MinAmpTmp,MaxAmpTmp);
                        if Dim2d3dViewVal<5
                            pcolor(XPColor,[0 1],ones(2,1)*XPColor);
                            set(gca,'YTick',[],'YTickLabel',[],'FontSize',FontSizeVec(1),...
                                'XColor',ForeGroundColor,'YColor',ForeGroundColor,'ZColor',ForeGroundColor);
                            hold off		
                        elseif Dim2d3dViewVal==5 | Dim2d3dViewVal==7 | Dim2d3dViewVal==8 | Dim2d3dViewVal==9
                             if isempty(varargin)
                                 pcolor([0 1],XPColor,(ones(2,1)*XPColor)'); 
                            else
                                if isempty(targetfig)
                                    pcolor([0 1],XPColor,(ones(2,1)*XPColor)'); 
                                end
                             end
                            set(gca,'XTick',[],'XTickLabel',[],'FontSize',FontSizeVec(1),...
                                'XColor',ForeGroundColor,'YColor',ForeGroundColor,'ZColor',ForeGroundColor,'FontWeight','Normal','tag','CursUpdateColorBar','handlevisibility','on');
                            hold off		
                        end
                        shading interp;
                    end
                    if Dim2d3dViewVal==5; 
                        TimeFrquString=[num2str(round(xTimePotVec(MinPoint).*10)./10)]; 
                        if DistPoint>1 
                            TimeFrquString=[TimeFrquString,' - ',num2str(round(xTimePotVec(MinPoint-1+DistPoint).*10)./10)]; 
                        end
                        if Domain<3; 
                            TimeFrquString=[TimeFrquString,' ms']; 
                        elseif Domain>2 & Domain <5 
                            TimeFrquString=[TimeFrquString,' ms'];                           
                        elseif Domain==5; 
                            TimeFrquString=['# ',TimeFrquString]; 
                        end
                        axes(hAxes0)
                        hPointText=text('Units','normal','Position',[.5,1.1],'Color',ForeGroundColor,'String',TimeFrquString,'FontSize',FontSizeVec(2),'HorizontalAlignment','center');
                        if PlotLatencyStatus~=1; set(hPointText,'Visible','off'); end
                        return; 
                    end
                    %========================================================================
                    if (MovieIndex==1 & Dim2d3dViewVal~=9) 
                        	
                        if Dim2d3dViewVal==7 | Dim2d3dViewVal==8 | Dim2d3dViewVal==9
                            ylabel(PotLapColorString,'Color',ForeGroundColor,'FontSize',FontSizeVec(1));
                        else
                            title(PotLapColorString,'Color',ForeGroundColor,'FontSize',FontSizeVec(1));
                        end
                        xlabel(PotLapLabelString,'Color',ForeGroundColor,'FontSize',FontSizeVec(1))	
                        
                        axes('Units','normal','Position',[MovieAxesPos(1,:)],'FontSize',FontSizeVec(1)); axis('off');
                        text('Units','normal','Position',[0,.01],'Color',ForeGroundColor,'String','Sensor config.:','FontSize',FontSizeVec(1))
                        text('Units','normal','Position',[.25,.01],'Color',ForeGroundColor,'String',ECfgFile,'FontSize',FontSizeVec(1))
                        if DiffSetStatus
                            text('Units','normal','Position',[.0,.2],'Color',ForeGroundColor,'String',DiffSetStr,'FontSize',FontSizeVec(1))
                        end
                        text('Units','normal','Position',[0,.4],'Color',ForeGroundColor,'String','Data from file:  ','FontSize',FontSizeVec(1));
                        text('Units','normal','Position',[.25,.4],'Color',ForeGroundColor,'String',ActFile,'FontSize',FontSizeVec(1))
                        if DistPointMeanStatus & DistPoint>1
                            if Domain<3; 
                                TimeFrquString='Time interval [ms]:  ';
                            elseif Domain>2 & Domain <5 
                                TimeFrquString='Frequency interval [Hz]:  '; 
                            elseif Domain==5 
                                TimeFrquString='Component interval [ ]:  '; 
                            end
                            text('Units','normal','Position',[0,.6],'Color',ForeGroundColor,'String',TimeFrquString,'FontSize',FontSizeVec(1))
                        else
                            if Domain<3; 
                                TimeFrquString='Point of time [ms]:  '; 
                            elseif Domain>2 & Domain <5 
                                TimeFrquString='Frequency [Hz]:  '; 
                            elseif Domain==5 
                                TimeFrquString='Component # :  '; 
                            end
                            text('Units','normal','Position',[0,.6],'Color',ForeGroundColor,'String',TimeFrquString,'FontSize',FontSizeVec(1))
                        end
                        if HeadModel == 1
                            hPointText=text('Units','normal','Position',[.25,.6],'Color',ForeGroundColor,'String',num2str(round(xTimePotVec(MinPoint+DistPoint.*(MovieIndex-1)).*10)/10),'FontSize',FontSizeVec(2),'HorizontalAlignment','left');
                        else
                            posvec = MovieAxesPos(1,:);
                            posvec = [posvec(1)+posvec(3)/4 posvec(2)+posvec(4)*0.85 posvec(3)/2 posvec(4)/10];
                            hPointText=uicontrol('style','text','Units','normal','Position',posvec,'ForegroundColor',ForeGroundColor,'BackgroundColor',[1 1 1],'String',num2str(round(xTimePotVec(MinPoint+DistPoint.*(MovieIndex-1)).*10)/10),'FontSize',FontSizeVec(2)*0.7,'HorizontalAlignment','left');
                       end
                        
                        if PlotLatencyStatus~=1; set(hPointText,'Visible','off'); end
                        text('Units','normal','Position',[0,.8],'Color',ForeGroundColor,'String','Leg. Iterations:  ','FontSize',FontSizeVec(1))
                        text('Units','normal','Position',[.25,.8],'Color',ForeGroundColor,'String',int2str(LegIter),'FontSize',FontSizeVec(1))
                        if UseApp
                            text('Units','normal','Position',[0,1],'Color',ForeGroundColor,'String','SLC. Lambda:  ','FontSize',FontSizeVec(1))
                            text('Units','normal','Position',[.25,1],'Color',ForeGroundColor,'String',num2str(SLCLambdaApprox),'FontSize',FontSizeVec(1))
                            if ActMethod==6	%L2 Min Norm
                                text('Units','normal','Position',[0,1.2],'Color',ForeGroundColor,'String','Min. Norm. Lambda:  ','FontSize',FontSizeVec(1))
                                text('Units','normal','Position',[.25,1.2],'Color',ForeGroundColor,'String',num2str(MNLambdaApprox),'FontSize',FontSizeVec(1))
                            end
                        end
                        if ActMethod==4 | ActMethod==5	%Perrin Scalp or Perrin CSD
                            text('Units','normal','Position',[0,1.2],'Color',ForeGroundColor,'String','Spherical m:  ','FontSize',FontSizeVec(1))
                            text('Units','normal','Position',[.25,1.2],'Color',ForeGroundColor,'String',num2str(MSpherical),'FontSize',FontSizeVec(1))
                        end
                    end	
                    if DistPointMeanStatus & DistPoint>1
                        if  Dim2d3dViewVal==9 & MovieIndex~=NMovie
                            if MovieIndex==1
                                timestringzaehler=1;
                                timestringcell=cell(1);
                            end
                            timestringcell{timestringzaehler}=[num2str(round(xTimePotVec(MinPoint+DistPoint.*(MovieIndex-1)).*10)/10),' - ',num2str(round(xTimePotVec(MinPoint-1+DistPoint.*MovieIndex).*10)/10)];
                            timestringzaehler=timestringzaehler+1;
                        elseif Dim2d3dViewVal==9 & MovieIndex==NMovie
                            timestringcell{timestringzaehler}=[num2str(round(xTimePotVec(MinPoint+DistPoint.*(MovieIndex-1)).*10)/10),' - ',num2str(round(xTimePotVec(MinPoint-1+DistPoint.*MovieIndex).*10)/10)];
                            set(hPointText,'userdata',timestringcell);
                            set(hPointText,'String',timestringcell{1});
                        else 
                             set(hPointText,'String',[num2str(round(xTimePotVec(MinPoint+DistPoint.*(MovieIndex-1)).*10)/10),' - ',num2str(round(xTimePotVec(MinPoint-1+DistPoint.*MovieIndex).*10)/10)]);
                        end
                    elseif Dim2d3dViewVal~=9
                        set(hPointText,'String',num2str(round(xTimePotVec(MinPoint+DistPoint.*(MovieIndex-1)).*10)./10));
                    end
                    %========================================================================
                    if (MovieIndex==1 & Dim2d3dViewVal~=9) | (MovieIndex==1 & Dim2d3dViewVal==9 & MovieIndex==NMovie)
                        hAxes1=axes('Units','normal',...
                            'Position',MovieAxesPos(3,:),...
                            'Color',BackGroundColor,...
                            'XColor',ForeGroundColor,...
                            'YColor',ForeGroundColor,...
                            'FontSize',FontSizeVec(1));
                    elseif Dim2d3dViewVal~=9
                        axes(hAxes1);
                        set(hAxes1,'NextPlot','Replace');
                    end
                    
                    if Dim2d3dViewVal~=9
                        MinPointTmp=MinPoint+DistPoint.*(MovieIndex-1);
                        MaxPointTmp=MinPoint+DistPoint.*MovieIndex-1;
                        
                        plot(xTimePotVec,TimePotVec,ForeGroundColorString)
                        hold on
                        plot(xTimePotVec(MinPoint:MaxPoint),TimePotVec(MinPoint:MaxPoint),'r--')
                        plot(xTimePotVec(MinPointTmp),TimePotVec(MinPointTmp),'b*')
                        if DistPointMeanStatus
                            plot(xTimePotVec(MinPointTmp:MaxPointTmp),TimePotVec(MinPointTmp:MaxPointTmp),'b');
                        end
                        if length(TimePotVec)>1
                            if Domain<3 | Domain==5;
                                if max(TimePotVec)~=min(TimePotVec)
                                    axis([min(xTimePotVec),max(xTimePotVec),min(TimePotVec),1.1*(max(TimePotVec)-min(TimePotVec))+min(TimePotVec)]);
                                else
                                    axis([min(xTimePotVec),max(xTimePotVec),.9.*min(TimePotVec),1.1.*min(TimePotVec)]);
                                end
                            else
                                axis([min(xTimePotVec),max(xTimePotVec),0,10.*median(TimePotVec)]);
                            end
                        else
                            axis([0,2,.9*min(TimePotVec), 1.1*max(TimePotVec)]);
                        end
                        if Domain<3; 
                            TimeFrquString='Time [ms]:'; 
                        elseif Domain>2 & Domain <5 
                            TimeFrquString='Frequency [Hz]:'; 
                        elseif Domain==5 
                            TimeFrquString='Component # :'; 
                        end
                        xlabel(TimeFrquString,'Color',ForeGroundColor);
                        ylabel(PotLapLabelString,'Color',ForeGroundColor)	
                        hold off
                    end
                    
                    %========================================================================
                    if (MovieIndex==1 & Dim2d3dViewVal~=9) | (MovieIndex==1 & Dim2d3dViewVal==9 & MovieIndex==NMovie)
                        hAxes2=axes('Units','normal',...
                            'Position',MovieAxesPos(4,:),...
                            'Color',BackGroundColor,...
                            'XColor',ForeGroundColor,...
                            'YColor',ForeGroundColor,...
                            'FontSize',FontSizeVec(1));
                    elseif Dim2d3dViewVal~=9
                        axes(hAxes2);
                        set(hAxes2,'NextPlot','Replace');
                    end
                    
                    if Dim2d3dViewVal~=9 
                        plot(xTimePotVec(MinPoint:MaxPoint),TimePotVec(MinPoint:MaxPoint),'r--')
                        hold on
                        plot(xTimePotVec(MinPointTmp),TimePotVec(MinPointTmp),'b*')
                        if DistPointMeanStatus
                            plot(xTimePotVec(MinPointTmp:MaxPointTmp),TimePotVec(MinPointTmp:MaxPointTmp),'b')
                        end
                        hold off 
                        MinTmp=min(TimePotVec(MinPoint:MaxPoint));
                        MaxTmp=max(TimePotVec(MinPoint:MaxPoint));
                        if MinTmp<MaxTmp & NPoints>1
                            axis([xTimePotVec(MinPoint) xTimePotVec(MaxPoint) MinTmp, 1.1*(MaxTmp-MinTmp)+MinTmp]);
                        elseif MinTmp>=MaxTmp & NPoints>1
                            axis([xTimePotVec(MinPoint) xTimePotVec(MaxPoint) .9*MinTmp 1.1*MaxTmp ]);
                        elseif MinTmp<MaxTmp & NPoints==1
                            axis([xTimePotVec(MinPoint)-1 xTimePotVec(MaxPoint)+1 MinTmp, 1.1*(MaxTmp-MinTmp)+MinTmp]);
                        elseif MinTmp>=MaxTmp & NPoints==1
                            axis([xTimePotVec(MinPoint)-1 xTimePotVec(MaxPoint)+1 .9*MinTmp 1.1*MaxTmp ]);
                        end
                    end
                    
                    %========================================================================
                    
                    if SpecDimView<=9
                        hold off
                    else		
                        if Dim2d3dViewVal==2
                            MovieAxesPosIndVec=[6:11];
                            ViewHeadIndVec=[1 2 5 6 3 4];
                        elseif Dim2d3dViewVal==3
                            MovieAxesPosIndVec=[6 7 8 9 11];
                            ViewHeadIndVec=[1 2 5 6 3];
                        end
                        NMovieAxes=length(MovieAxesPosIndVec);
                        for AxesInd=1:NMovieAxes
                            if MovieIndex==1;
                                hAxesTmp=axes('Units','normal',...
                                    'Position',MovieAxesPos(MovieAxesPosIndVec(AxesInd),:),...
                                    'FontSize',FontSizeVec(1),'NextPlot','Replace');
                                eval(['hAxes' int2str(AxesInd+3) '=hAxesTmp;']);
                            else
                                eval(['hAxesTmp=hAxes' int2str(AxesInd+3) ';']);
                                axes(hAxesTmp);
                                set(hAxesTmp,'NextPlot','Replace');
                            end
                            
                            %========================================================================
                            % All Surf II  2. -
                            %========================================================================
                            
                            if HeadModel>1 & HeadModel~=4   
                                %do not turn texture because it´s already happened for pic 1 in movie!!
                                %==================================================================
                                contourintvervall = str2num(get(hPlot3dList(117),'String'));
                                [contourpic]=surfcdata2contourpic(CalcPotTmp,ColorMat,MinAmp,MaxAmp,ColorAmpTotStatus,contourintvervall,NColor,CutRealBotVal);
                                if HeadModel == 2
                                    load('head3dsurf2.mat','head3dx','head3dy','head3dz');  
                                elseif HeadModel == 3
                                    load('head3dsurf.mat','head3dx','head3dy','head3dz');  
                                elseif HeadModel == 5
                                    load('brain3dsurf.mat','head3dx','head3dy','head3dz'); 
                                elseif HeadModel == 6
                                    load('brain3dsurf2.mat','head3dx','head3dy','head3dz');
                                elseif HeadModel == 7
                                    load('brainNC_lowsmooth_surf.mat','head3dx','head3dy','head3dz'); 
                                elseif HeadModel == 8
                                    load('brainNC_highsmooth_surf.mat','head3dx','head3dy','head3dz'); 
                                elseif HeadModel == 9
                                    modelcell = get(hPlot3dList(140),'Userdata');
                                    if isempty(modelcell)
                                        uiwait(errordlg('Failed to retrieve custom head model!','Warning:'));
                                        return;
                                    else
                                        head3dx =  modelcell{1};
                                        head3dy =  modelcell{2};
                                        head3dz =  modelcell{3};
                                    end
                                end
                                hSurf0=surf(head3dx,head3dy,head3dz,'EdgeColor','none','CData',contourpic,'FaceColor','texturemap','tag','head3d');
                                lighting phong;axis equal; material shiny;
                                light('Position',[30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[-30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[-30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                if (PlotEPosStatus==1 & AxesInd==1) | PlotEPosStatus==2
                                    plotsensors3d(EPosSpher(ChanStatusOnVec,:),SensorNames(ChanStatusOnVec,:),0,SensorNameStatus,HeadModel);
                                end
                            elseif HeadModel==4 
                                contourintvervall = str2num(get(hPlot3dList(117),'String'));
                                hSurf0=plot3dbrain(XScalp,YScalp,ZScalp,CalcPotTmp,0,gca,HeadModel);
                                if (PlotEPosStatus==1 & AxesInd==1) | PlotEPosStatus==2
                                    plotbrainsensors3d(EPosSpher(ChanStatusOnVec,:),SensorNames(ChanStatusOnVec,:),0,SensorNameStatus,HeadModel);
                                end
                            elseif HeadModel == 1
                                if PlotContourStatus==4
                                    hSurf0=surf(XScalp,YScalp ,ZScalp,CalcPotTmp,'FaceLighting','gouraud'); %,'EdgeColor','none'
                                    light('Position',[30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                    light('Position',[-30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                    light('Position',[30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                    light('Position',[-30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                    shading interp;
                                else
                                    hSurf0=surf(XScalp,YScalp ,ZScalp,CalcPotTmp); %,'EdgeColor','none'
                                    shading interp;
                                end
                            end  
         
                            
                            
                            if ActMethod==6  & ~AbsMinNormSurfStatus	
                                set(hSurfTmp,'Visible','off');
                            end		
                            caxis([MinAmpTmp MaxAmpTmp])
                            view(ViewVec(ViewHeadIndVec(AxesInd),:));	
                            [TitleString]=title_string_func(ViewHeadIndVec(AxesInd),2);
                            title(TitleString,'Color',ForeGroundColor,'FontSize',FontSizeVec(3));	
                            axis('off')
                            hold on
                            if ActMethod==6 & QuiverStatus
                                quiver3(XScalp,YScalp,ZScalp,XMatTmp,YMatTmp,ZMatTmp,1.5)
                            end
                            
                            if isempty(View2d3d) | (View2d3d~=7 & View2d3d~=8)
                                if PlotEPosStatus==2
                                    if ViewHeadIndVec(AxesInd)==1;
                                        SensorVisVec=SensorVisVecBack;	  
                                    elseif ViewHeadIndVec(AxesInd)==2
                                        SensorVisVec=SensorVisVecFront;	  
                                    elseif ViewHeadIndVec(AxesInd)==3
                                        SensorVisVec=SensorVisVecTop;	  
                                    elseif ViewHeadIndVec(AxesInd)==4
                                        SensorVisVec=SensorVisVecBottom;	  
                                    elseif ViewHeadIndVec(AxesInd)==5
                                        SensorVisVec=SensorVisVecLeft;	  	
                                    elseif ViewHeadIndVec(AxesInd)==6
                                        SensorVisVec=SensorVisVecRight;	  
                                    end
                                    PlotECPositions(ScalpCortStatus,3,0,ForeGroundColor,1,EPosSpher(ChanStatusOnVec(SensorVisVec),:),...
                                        Radius,SensorCircleStatus,SensorAsteriskStatus,SensorNameStatus,SensorNames(ChanStatusOnVec(SensorVisVec),:))
                                end
                            end
                            
                            if isempty(View2d3d) | (View2d3d~=7 & View2d3d~=8)
                                if PlotContourStatus<3
                                    plot_head_contour(MovieAxesPos(MovieAxesPosIndVec(AxesInd),:),ScalpCortStatus,ViewHeadIndVec(AxesInd),ForeGroundColor,1)
                                elseif PlotContourStatus==4
                                    PlotSpherBool;
                                end
                            end
                            hold off
                        end
                    end
                    hold off
                    if Print2FileStatus & Dim2d3dViewVal~=9
                        if strcmp(Print2FileMethodString,'EPS')
                            Print2FileString=['print -deps ' Print2FilePath,int2str(MovieIndex)];
                        elseif strcmp(Print2FileMethodString,'EPSTIFF')
                            Print2FileString=['print -deps -tiff ' Print2FilePath,int2str(MovieIndex)];
                        elseif strcmp(Print2FileMethodString,'JPEG')
                            Print2FileString=['print -djpeg',int2str(Print2FileCompVal),' ',Print2FilePath,int2str(MovieIndex)];
                        elseif strcmp(Print2FileMethodString,'TIFF')
                            Print2FileString=['print -dtiff -r',int2str(Print2FileCompVal),' ',Print2FilePath,int2str(MovieIndex)];
                        end
                        eval(Print2FileString)
                    end
                    
                    if NMovie>1 & MovieIndex<NMovie & View2d3d~=9
                        if MoviePauseStatus;
                            Message=char(['The current picture is the ',int2str(MovieIndex), ' of']);
                            Message=char(Message,['the ',int2str(NMovie),' pictures containing movie.']);
                            Message=char(Message,'');
                            Message=char(Message,'Please press "Return" or "O.k"');
                            Message=char(Message,'to continue or "Strg + C" to abort.');
                            hmsgbox=msgbox(Message,'Info !','help'); 
                            set(hmsgbox,'Units','Normal','Position',[.7 .05  .25 .125])
                            uiwait(hmsgbox);					
                        else
                            pause(.1); 
                        end
                    end     
                end
                
            %=========================================================================
            %   Plot2d 
            %=========================================================================
            elseif Dim2d3dViewVal==4 %Plot2d; 
                
                TimeInd=0;
                for MovieIndex=1:NMovie
                    axes('Units','normal','Position',[0 0 1 1]); axis('off');
                    text('Units','normal','Position',[.5 .97],'HorizontalAlignment','center','Color',ForeGroundColor,'String',TitleString,'FontSize',FontSizeVec(3))
                    AxesInd=0;
                    while AxesInd<10 & TimeInd<NPoints
                        AxesInd=AxesInd+1;
                        TimeInd=TimeInd+1;
                        [CalcPotTmp]=change_n_sqrt_n(CalcPot(:,TimeInd));
                        if ActMethod==6 & QuiverStatus
                            [XMatTmp]=change_n_sqrt_n(XMat(:,MovieIndex));
                            [YMatTmp]=change_n_sqrt_n(YMat(:,MovieIndex));
                            [ZMatTmp]=change_n_sqrt_n(ZMat(:,MovieIndex));
                        end
                        if ~SpecAmpStatus
                            MinAmpTmp=min(min(CalcPotTmp));
                            MaxAmpTmp=max(max(CalcPotTmp));	
                        end
                        if CenterAmpStatus
                            MaxAmpTmp=max(abs([MaxAmpTmp MinAmpTmp]));
                            MinAmpTmp=-1.*MaxAmpTmp;
                        end
                        if MinAmpTmp==MaxAmpTmp
                            if MaxAmpTmp==0
                                MaxAmpTmp=.1;
                                MinAmpTmp=-.1;
                            elseif MaxAmpTmp>0
                                MaxAmpTmp=1.1.*MaxAmpTmp;
                                MinAmpTmp=.9.*MinAmpTmp;
                            elseif MaxAmpTmp<0
                                MaxAmpTmp=.9.*MaxAmpTmp;
                                MinAmpTmp=1.1.*MinAmpTmp;
                            end
                        end       
                        
                        %=========================================================================
                        %   Plot2d 
                        %=========================================================================
                       contourintvervall = str2num(get(hPlot3dList(117),'String'));
                       if HeadModel>1 & HeadModel~=4         
                            %turn potential
                            %===============================
                            CalcPotTmp=[CalcPotTmp(:,18:32),CalcPotTmp(:,1:17)];
                             %To have a smooth fitting where the sides of the texture meet....
                            %============================================================
                            tmp = mean([CalcPotTmp(:,1),CalcPotTmp(:,32)],2);
                            CalcPotTmp(:,1)  = tmp;
                            CalcPotTmp(:,32) = tmp;
                        	[contourpic]=surfcdata2contourpic(CalcPotTmp,ColorMat,MinAmp,MaxAmp,ColorAmpTotStatus,contourintvervall,NColor,CutRealBotVal);
                            if HeadModel == 2
                                load('head3dsurf2.mat','head3dx','head3dy','head3dz');  
                            elseif HeadModel == 3
                                load('head3dsurf.mat','head3dx','head3dy','head3dz');  
                            elseif HeadModel == 5
                                load('brain3dsurf.mat','head3dx','head3dy','head3dz'); 
                            elseif HeadModel == 6
                                load('brain3dsurf2.mat','head3dx','head3dy','head3dz'); 
                            elseif HeadModel == 7
                                load('brainNC_lowsmooth_surf.mat','head3dx','head3dy','head3dz'); 
                            elseif HeadModel == 8
                                load('brainNC_highsmooth_surf.mat','head3dx','head3dy','head3dz'); 
                            elseif HeadModel == 9
                                modelcell = get(hPlot3dList(140),'Userdata');
                                if isempty(modelcell)
                                    uiwait(errordlg('Failed to retrieve custom head model!','Warning:'));
                                    return;
                                else
                                    head3dx =  modelcell{1};
                                    head3dy =  modelcell{2};
                                    head3dz =  modelcell{3};
                                end
                            end
                            axes('Units','normal','Position',MovieAxesPos(AxesInd,:));
                            hSurf0=surf(head3dx,head3dy,head3dz,'EdgeColor','none','CData',contourpic,'FaceColor','texturemap','tag','head3d');
                            lighting phong;axis equal;  material shiny;
                            light('Position',[30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                            light('Position',[-30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                            light('Position',[30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                            light('Position',[-30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                            if (PlotEPosStatus==1 & AxesInd==1) | PlotEPosStatus==2
                                plotsensors3d(EPosSpher,ENames,[],[],HeadModel);
                            end
                        elseif HeadModel==4
                            axes('Units','normal','Position',MovieAxesPos(AxesInd,:));
                            hSurf0=plot3dbrain(XScalp,YScalp,ZScalp,CalcPotTmp,0,gca,HeadModel);
                            if (PlotEPosStatus==1 & AxesInd==1) | PlotEPosStatus==2
                                plotbrainsensors3d(EPosSpher(ChanStatusOnVec,:),SensorNames(ChanStatusOnVec,:),0,SensorNameStatus,HeadModel);
                            end
                        elseif HeadModel==1  
							axes('Units','normal','Position',MovieAxesPos(AxesInd,:));
                            if PlotContourStatus==4
                                hSurfTmp=surf(XScalp,YScalp ,ZScalp,CalcPotTmp,'FaceLighting','gouraud'); %,'EdgeColor','none'
                                light('Position',[30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[-30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                light('Position',[-30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                                shading interp;
                            else
                                hSurfTmp=surf(XScalp,YScalp ,ZScalp,CalcPotTmp); %,'EdgeColor','none'
                                shading interp;
                            end
                        end
          
                        if ActMethod==6 & ~AbsMinNormSurfStatus; set(hSurf0,'Visible','off'); end
                        caxis([MinAmpTmp MaxAmpTmp])
                        view(ThetaView,PhiView);
                        axis('off')
                        hold on
                        if ActMethod==6 & QuiverStatus
                            quiver3(XScalp,YScalp,ZScalp,XMatTmp,YMatTmp,ZMatTmp,1.5)
                        end
                        hold off
                        if isempty(View2d3d) | (View2d3d~=7 & View2d3d~=8)
                            if (PlotEPosStatus==1 & AxesInd==1) | PlotEPosStatus==2
                                if HeadView==1;
                                    SensorVisVec=SensorVisVecBack;	  
                                elseif HeadView==2
                                    SensorVisVec=SensorVisVecFront;	  
                                elseif HeadView==3
                                    SensorVisVec=SensorVisVecTop;	  
                                elseif HeadView==4
                                    SensorVisVec=SensorVisVecBottom;	  
                                elseif HeadView==5
                                    SensorVisVec=SensorVisVecLeft;	  	
                                elseif HeadView==6
                                    SensorVisVec=SensorVisVecRight;	  
                                end
                                PlotECPositions(ScalpCortStatus,3,0,ForeGroundColor,1,EPosSpher(ChanStatusOnVec(SensorVisVec),:),...
                                    Radius,SensorCircleStatus,SensorAsteriskStatus,SensorNameStatus,SensorNames(ChanStatusOnVec(SensorVisVec),:))
                            end
                        end
                        
                        if isempty(View2d3d) |(View2d3d~=7 & View2d3d~=8)
                            if (PlotContourStatus==1 & AxesInd==1) | PlotContourStatus==2
                                plot_head_contour(MovieAxesPos(AxesInd,:),ScalpCortStatus,HeadView,ForeGroundColor,1)
                            elseif PlotContourStatus==4
                                PlotSpherBool;
                            end
                        end
                        
                        if Domain<3 
                            TimeFrquString=[num2str(round(xTimePotVec(MinPoint+DistPoint.*((MovieIndex-1).*10+AxesInd-1)).*10)./10),' ms']; 
                        elseif Domain>2 & Domain<5;
                            TimeFrquString=[num2str(round(xTimePotVec(MinPoint+DistPoint.*((MovieIndex-1).*10+AxesInd-1)).*10)./10),' Hz']; 
                        elseif Domain==5;
                            TimeFrquString=['# ',num2str(round(xTimePotVec(MinPoint+DistPoint.*((MovieIndex-1).*10+AxesInd-1)).*10)./10)]; 
                        end
                       if HeadModel == 1
                            hPointText=text('Units','normal','Position',[.5,1.02],'Color',ForeGroundColor,'String',TimeFrquString,'FontSize',FontSizeVec(2),'HorizontalAlignment','center','FontWeight','bold');
                        else
                            posvec = MovieAxesPos(AxesInd,:);
                            posvec = [posvec(1)+posvec(3)/4  posvec(2)+MovieAxesPos(1,4)*0.97 posvec(3)/2  MovieAxesPos(1,4)/10];
                            MovieAxesPos(1,4)*0.82;
                            hPointText=uicontrol('style','text','Units','normalized','Position',posvec,'ForegroundColor',ForeGroundColor,'BackgroundColor',[1 1 1],'String',TimeFrquString,'FontSize',FontSizeVec(2)*0.7,'HorizontalAlignment','center','FontWeight','bold');
                        end
                        
                    if PlotLatencyStatus~=1; set(hPointText,'Visible','off'); end
                        if DistPointMeanStatus & DistPoint>1
                            if Domain<3; 
                                TimeFrquString=[num2str(round(xTimePotVec(MinPoint+DistPoint.*((MovieIndex-1).*10+AxesInd-1)).*10)./10),' ms',' - ',num2str(round(xTimePotVec(MinPoint-1+DistPoint.*((MovieIndex-1).*10+AxesInd)).*10)./10),' ms']; 
                            elseif Domain>2 & Domain <5 
                                TimeFrquString=[num2str(round(xTimePotVec(MinPoint+DistPoint.*((MovieIndex-1).*10+AxesInd-1)).*10)./10),' Hz',' - ',num2str(round(xTimePotVec(MinPoint-1+DistPoint.*((MovieIndex-1).*10+AxesInd)).*10)./10),' Hz']; 
                            elseif Domain==5; 
                                TimeFrquString=['# ',num2str(round(xTimePotVec(MinPoint+DistPoint.*((MovieIndex-1).*10+AxesInd-1)).*10)./10),' - ',num2str(round(xTimePotVec(MinPoint-1+DistPoint.*((MovieIndex-1).*10+AxesInd)).*10)./10)]; 
                            end
                            if HeadModel == 1
                                set(hPointText,'Position',[.5,1.05],'String',TimeFrquString);
                            else
                                set(hPointText,'Position',posvec,'String',TimeFrquString);
                            end
                        end
                        hold off
                        if ~SpecAmpStatus
                            axes('Units','normal',...
                                'Position',MovieAxesPos(AxesInd,:)+[.02 -.02 -.04 -MovieAxesPos(AxesInd,4)+.02],...
                                'FontSize',FontSizeVec(1));	
                            XPColor=linspace(MinAmpTmp,MaxAmpTmp);
                            pcolor(XPColor,[0 1],ones(2,1)*XPColor); shading interp;
                            set(gca,'YTick',[],'YTickLabel',[],'FontSize',FontSizeVec(1),'XColor',ForeGroundColor,'YColor',ForeGroundColor,'ZColor',ForeGroundColor)
                            text('Units','normal','Position',[1.05 -0.5],'Color',ForeGroundColor,'String',PotLapEinheitString,'FontSize',FontSizeVec(1))
                        end
                    end
                    
                    %========================================================================
                    
                    axes('Units','normal',...
                        'Position',MovieAxesPos(11,:),...
                        'Color',BackGroundColor,...
                        'XColor',ForeGroundColor,...
                        'YColor',ForeGroundColor,...
                        'FontSize',FontSizeVec(1));
                    
                    plot(xTimePotVec,TimePotVec,ForeGroundColorString)
                    hold on
                    plot(xTimePotVec(MinPoint:MaxPoint),TimePotVec(MinPoint:MaxPoint),'r--')
                    MinPointTmp=MinPoint+DistPoint.*((MovieIndex-1).*10);
                    MaxPointTmp=MinPoint+DistPoint.*((MovieIndex-1).*10+AxesInd)-1;
                    plot(xTimePotVec(MinPointTmp:DistPoint:MaxPointTmp),TimePotVec(MinPointTmp:DistPoint:MaxPointTmp),'b*')	
                    if DistPointMeanStatus
                        plot(xTimePotVec(MinPointTmp:MaxPointTmp),TimePotVec(MinPointTmp:MaxPointTmp),'b')
                    end
                    if length(TimePotVec)>1
                        axis([min(xTimePotVec),max(xTimePotVec),min(TimePotVec),11*(max(TimePotVec)-min(TimePotVec))/10+min(TimePotVec)]);
                    else
                        axis([0,2,9*min(TimePotVec)./10, 11*max(TimePotVec)/10]);
                    end
                    if Domain<3; 
                        TimeFrquString='Time [ms]:'; 
                    elseif Domain>2 & Domain <5 
                        TimeFrquString='Frequency [Hz]:'; 
                    elseif Domain==5
                        TimeFrquString='Component #:'; 
                    end
                    xlabel(TimeFrquString,'Color',ForeGroundColor,'FontSize',FontSizeVec(1));
                    ylabel(PotLapLabelString,'Color',ForeGroundColor,'FontSize',FontSizeVec(1))	
                    hold off
                    
                    %========================================================================
                    
                    axes(	'Units','normal',...
                        'Position',MovieAxesPos(12,:),...
                        'Color',BackGroundColor,...
                        'XColor',ForeGroundColor,...
                        'YColor',ForeGroundColor,...
                        'FontSize',FontSizeVec(1));
                    
                    plot(xTimePotVec(MinPoint:MaxPoint),TimePotVec(MinPoint:MaxPoint),'r--')
                    hold on
                    plot(xTimePotVec(MinPointTmp:DistPoint:MaxPointTmp),TimePotVec(MinPointTmp:DistPoint:MaxPointTmp),'b*')
                    if DistPointMeanStatus
                        plot(xTimePotVec(MinPointTmp:MaxPointTmp),TimePotVec(MinPointTmp:MaxPointTmp),'b')
                    end
                    MinTmp=min(TimePotVec(MinPoint:MaxPoint));
                    MaxTmp=max(TimePotVec(MinPoint:MaxPoint));
                    if MinTmp<MaxTmp & NPoints>1
                        axis([xTimePotVec(MinPoint) xTimePotVec(MaxPoint) MinTmp, 1.1*(MaxTmp-MinTmp)+MinTmp]);
                    elseif MinTmp>=MaxTmp & NPoints>1
                        axis([xTimePotVec(MinPoint) xTimePotVec(MaxPoint) .9*MinTmp 1.1*MaxTmp ]);
                    elseif MinTmp<MaxTmp & NPoints==1
                        axis([xTimePotVec(MinPoint)-1 xTimePotVec(MaxPoint)+1 MinTmp, 1.1*(MaxTmp-MinTmp)+MinTmp]);
                    elseif MinTmp>=MaxTmp & NPoints==1
                        axis([xTimePotVec(MinPoint)-1 xTimePotVec(MaxPoint)+1 .9*MinTmp 1.1*MaxTmp ]);
                    end
                    if Domain<3; 
                        TimeFrquString='Time [ms]:'; 
                    elseif Domain>2 & Domain <5 
                        TimeFrquString='Frequency [Hz]:';
                    elseif Domain==5 
                        TimeFrquString='Component # :'; 
                    end
                    xlabel(TimeFrquString,'Color',ForeGroundColor,'FontSize',FontSizeVec(1));
                    ylabel(PotLapLabelString,'Color',ForeGroundColor,'FontSize',FontSizeVec(1))	
                    hold off
                    
                    %========================================================================
                    if SpecAmpStatus
                        h=axes(	'Units','normal',...
                            'Position',MovieAxesPos(13,:)-[.02 -.02 -.04 .02],...
                            'FontSize',FontSizeVec(1));	
                        XPColor=linspace(MinAmpTmp,MaxAmpTmp);
                        pcolor(XPColor,[0 1],ones(2,1)*XPColor); shading interp;
                        set(gca,'YTick',[],'YTickLabel',[],'FontSize',FontSizeVec(1),'XColor',ForeGroundColor,...
                            'YColor',ForeGroundColor,'ZColor',ForeGroundColor)
                        title(PotLapColorString,'Color',ForeGroundColor,'FontSize',FontSizeVec(1));	
                        xlabel(PotLapLabelString,'Color',ForeGroundColor,'FontSize',FontSizeVec(1));
                    end
                    %========================================================================
                    axes(	'Units','normal',...
                        'Position',MovieAxesPos(14,:)-[0 -.04 0 .04],...
                        'FontSize',FontSizeVec(1));	
                    axis('off');
                    
                    text('Units','normal','Position',[0,.01],'Color',ForeGroundColor,'String','Sensor config.:','FontSize',FontSizeVec(1))
                    text('Units','normal','Position',[.6,.01],'Color',ForeGroundColor,'String',ECfgFile,'FontSize',FontSizeVec(1))
                    if DiffSetStatus
                        text('Units','normal','Position',[.0,.2],'Color',ForeGroundColor,'String',DiffSetStr,'FontSize',FontSizeVec(1))
                    end
                    text('Units','normal','Position',[0,.4],'Color',ForeGroundColor,'String','Data from file:  ','FontSize',FontSizeVec(1))
                    text('Units','normal','Position',[.6,.4],'Color',ForeGroundColor,'String',ActFile,'FontSize',FontSizeVec(1))
                    text('Units','normal','Position',[0,.6],'Color',ForeGroundColor,'String','Leg. Iterations:  ','FontSize',FontSizeVec(1))
                    text('Units','normal','Position',[.6,.6],'Color',ForeGroundColor,'String',int2str(LegIter),'FontSize',FontSizeVec(1))
                    
                    if UseApp
                        text('Units','normal','Position',[0,.8],'Color',ForeGroundColor,'String','SLC Lambda:  ','FontSize',FontSizeVec(1))
                        text('Units','normal','Position',[.6,.8],'Color',ForeGroundColor,'String',num2str(SLCLambdaApprox),'FontSize',FontSizeVec(1))
                        if ActMethod==6
                            text('Units','normal','Position',[0,1],'Color',ForeGroundColor,'String','Min. Norm Lambda:  ','FontSize',FontSizeVec(1))
                            text('Units','normal','Position',[.6,1],'Color',ForeGroundColor,'String',num2str(MNLambdaApprox),'FontSize',FontSizeVec(1))
                        end
                    end
                    if ActMethod==4 | ActMethod==5	%Perrin Scalp or Perrin CSD
                        text('Units','normal','Position',[0,1],'Color',ForeGroundColor,'String','Spherical m:  ','FontSize',FontSizeVec(1))
                        text('Units','normal','Position',[.6,1],'Color',ForeGroundColor,'String',num2str(MSpherical),'FontSize',FontSizeVec(1))
                    end
                    %========================================================================
                    if Print2FileStatus
                        if strcmp(Print2FileMethodString,'EPS')
                            Print2FileString=['print -deps ' Print2FilePath,int2str(MovieIndex)];
                        elseif strcmp(Print2FileMethodString,'EPSTIFF')
                            Print2FileString=['print -deps -tiff ' Print2FilePath,int2str(MovieIndex)];
                        elseif strcmp(Print2FileMethodString,'JPEG')
                            Print2FileString=['print -djpeg',int2str(Print2FileCompVal),' ',Print2FilePath,int2str(MovieIndex)];
                        elseif strcmp(Print2FileMethodString,'TIFF')
                            Print2FileString=['print -dtiff -r',int2str(Print2FileCompVal),' ',Print2FilePath,int2str(MovieIndex)];
                        end
                        eval(Print2FileString)
                    end
                    if NMovie>1 & MovieIndex<NMovie
                        if MoviePauseStatus; 
                            Message=char(['The current picture is the ',int2str(MovieIndex), ' of']);
                            Message=char(Message,['the ',int2str(NMovie),' pictures containing movie.']);
                            Message=char(Message,'');
                            Message=char(Message,'Please press "Return" or "O.k"');
                            Message=char(Message,'to continue or "Strg + C" to abort.');
                            hmsgbox=msgbox(Message,'Info !','help'); 
                            set(hmsgbox,'Units','Normal','Position',[.7 .05  .25 .125])
                            uiwait(hmsgbox);					
                        else 
                            pause(.01); 
                        end
                    end
                    if MovieIndex<NMovie; clf; end
                end
              
            %=========================================================================
            %   %Columns & Rows
            %=========================================================================
            elseif Dim2d3dViewVal==6	
                
                ActFontSize=min([10,round(600/NPoints)]);
                for TimeInd=1:NPoints
                    [CalcPotTmp]=change_n_sqrt_n(CalcPot(:,TimeInd));
                    %           	if ActMethod==6 & QuiverStatus
                    %        	  		[XMatTmp]=change_n_sqrt_n(XMat(:,MovieIndex));
                    %         			[YMatTmp]=change_n_sqrt_n(YMat(:,MovieIndex));
                    % 					[ZMatTmp]=change_n_sqrt_n(ZMat(:,MovieIndex));
                    % 				end
                    if ~SpecAmpStatus
                        MinAmpTmp=min(min(CalcPotTmp));
                        MaxAmpTmp=max(max(CalcPotTmp));	
                    end
                    if CenterAmpStatus
                        MaxAmpTmp=max(abs([MaxAmpTmp MinAmpTmp]));
                        MinAmpTmp=-1.*MaxAmpTmp;
                    end
                    if MinAmpTmp==MaxAmpTmp
                        if MaxAmpTmp==0
                            MaxAmpTmp=.1;
                            MinAmpTmp=-.1;
                        elseif MaxAmpTmp>0
                            MaxAmpTmp=1.1.*MaxAmpTmp;
                            MinAmpTmp=.9.*MinAmpTmp;
                        elseif MaxAmpTmp<0
                            MaxAmpTmp=.9.*MaxAmpTmp;
                            MinAmpTmp=1.1.*MinAmpTmp;
                        end
                    end
        
                    %=========================================================================
                    %   %Columns & Rows
                    %=========================================================================
                     if HeadModel>1 & HeadModel~=4
                        %turn potential
                        %===============================
                        CalcPotTmp=[CalcPotTmp(:,18:32),CalcPotTmp(:,1:17)];
                         %To have a smooth fitting where the sides of the texture meet....
                        %============================================================
                        tmp = mean([CalcPotTmp(:,1),CalcPotTmp(:,32)],2);
                        CalcPotTmp(:,1)  = tmp;
                        CalcPotTmp(:,32) = tmp;
                        contourintvervall = str2num(get(hPlot3dList(117),'String'));
                        [contourpic]=surfcdata2contourpic(CalcPotTmp,ColorMat,MinAmp,MaxAmp,ColorAmpTotStatus,contourintvervall,NColor,CutRealBotVal);
                        if HeadModel == 2
                            load('head3dsurf2.mat','head3dx','head3dy','head3dz'); 
                        elseif HeadModel == 3
                            load('head3dsurf.mat','head3dx','head3dy','head3dz');  
                        elseif HeadModel == 5
                            load('brain3dsurf.mat','head3dx','head3dy','head3dz');  
                        elseif HeadModel == 6
                            load('brain3dsurf2.mat','head3dx','head3dy','head3dz');
                        elseif HeadModel == 7
                            load('brainNC_lowsmooth_surf.mat','head3dx','head3dy','head3dz'); 
                        elseif HeadModel == 8
                            load('brainNC_highsmooth_surf.mat','head3dx','head3dy','head3dz'); 
                        elseif HeadModel == 9
                            modelcell = get(hPlot3dList(140),'Userdata');
                            if isempty(modelcell)
                                uiwait(errordlg('Failed to retrieve custom head model!','Warning:'));
                                return;
                            else
                                head3dx =  modelcell{1};
                                head3dy =  modelcell{2};
                                head3dz =  modelcell{3};
                            end
                        end
                        axes('Units','normal','Position',MovieAxesPos(TimeInd,:));
                        hSurf0=surf(head3dx,head3dy,head3dz,'EdgeColor','none','CData',contourpic,'FaceColor','texturemap','tag','head3d');
                        if (PlotEPosStatus==1 & TimeInd==1) | PlotEPosStatus==2
                           plotsensors3d(EPosSpher(ChanStatusOnVec,:),SensorNames(ChanStatusOnVec,:),0,SensorNameStatus,HeadModel);
                        end
                        lighting phong;axis equal;material shiny;
                        light('Position',[30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                        light('Position',[-30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                        light('Position',[30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                        light('Position',[-30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                    elseif HeadModel==4 
                        contourintvervall = str2num(get(hPlot3dList(117),'String'));
                        axes('Units','normal','Position',MovieAxesPos(TimeInd,:));
                        hSurf0=plot3dbrain(XScalp,YScalp,ZScalp,CalcPotTmp,0,gca,HeadModel);
                        if (PlotEPosStatus==1 & TimeInd==1) | PlotEPosStatus==2
                            plotbrainsensors3d(EPosSpher(ChanStatusOnVec,:),SensorNames(ChanStatusOnVec,:),0,SensorNameStatus,HeadModel);
                        end
                    elseif HeadModel==1
                        %axes that only serve to change the color rendering
                        %to nice areas. How this works,.... i don't know
                        axes('Units','normal','position',[1 1 0.1 0.1]);
                        plot(1,1,'b*');	
						axes('Units','normal','Position',MovieAxesPos(TimeInd,:));
                        if PlotContourStatus==4
                            hSurfTmp=surf(XScalp,YScalp ,ZScalp,CalcPotTmp,'FaceLighting','gouraud'); %,'EdgeColor','none'
                            light('Position',[30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                            light('Position',[-30 30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                            light('Position',[30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                            light('Position',[-30 -30 30],'Style','infinite','Color',[0.5 0.5 0.5]);
                            shading interp;
                        else
                            hSurfTmp=surf(XScalp,YScalp ,ZScalp,CalcPotTmp); %,'EdgeColor','none'
                            shading interp;
                        end
                        
                    end
                    
   
                    if ActMethod==6 & ~AbsMinNormSurfStatus; set(hSurf0,'Visible','off'); end
                    caxis([MinAmpTmp MaxAmpTmp])
                    
                    
                    view(ThetaView,PhiView);
                    axis('off')
                    hold on
                    if ActMethod==6 & QuiverStatus
                        quiver3(XScalp,YScalp,ZScalp,XMatTmp,YMatTmp,ZMatTmp,1.5)
                    end
                    hold off
                    if isempty(View2d3d) |(View2d3d~=7 & View2d3d~=8)
                        if (PlotEPosStatus==1 & TimeInd==1) | PlotEPosStatus==2
                            if HeadView==1;
                                SensorVisVec=SensorVisVecBack;	  
                            elseif HeadView==2
                                SensorVisVec=SensorVisVecFront;	  
                            elseif HeadView==3
                                SensorVisVec=SensorVisVecTop;	  
                            elseif HeadView==4
                                SensorVisVec=SensorVisVecBottom;	  
                            elseif HeadView==5
                                SensorVisVec=SensorVisVecLeft;	  	
                            elseif HeadView==6
                                SensorVisVec=SensorVisVecRight;	  
                            end
                            PlotECPositions(ScalpCortStatus,3,0,ForeGroundColor,1,EPosSpher(ChanStatusOnVec(SensorVisVec),:),...
                                Radius,SensorCircleStatus,SensorAsteriskStatus,SensorNameStatus,SensorNames(ChanStatusOnVec(SensorVisVec),:))
                        end
                    end
                    if isempty(View2d3d) | (View2d3d~=7 & View2d3d~=8)
                        if (PlotContourStatus==1 & TimeInd==1) | PlotContourStatus==2
                            plot_head_contour(MovieAxesPos(TimeInd,:),ScalpCortStatus,HeadView,ForeGroundColor,1)
                        elseif PlotContourStatus==4
                            PlotSpherBool;
                        end
                    end
                    
                    TimeFrquString=[num2str(round(xTimePotVec(MinPoint+DistPoint.*(TimeInd-1)).*10)./10)];
                    if Domain<3 
                        TimeFrquString=[TimeFrquString,' ms']; 
                    elseif Domain>2 & Domain<5;
                        TimeFrquString=[TimeFrquString,' Hz']; 
                    elseif Domain==5;
                        TimeFrquString=['# ',TimeFrquString]; 
                    end
                    
                    if HeadModel == 1
                        hPointText=text('Units','normal','Position',[.5,1.02],'Color',ForeGroundColor,'String',TimeFrquString,'FontSize',ActFontSize,'HorizontalAlignment','center','FontWeight','bold');
                    else
                        posvec = MovieAxesPos(TimeInd,:);
                        posvec = [posvec(1) posvec(2)+posvec(4)*0.95 posvec(3) posvec(4)/8];
                        hPointText=uicontrol('style','text','Units','normal','Position',posvec,'ForegroundColor',ForeGroundColor,'BackgroundColor',[1 1 1],'String',TimeFrquString,'FontSize',ActFontSize*0.6,'HorizontalAlignment','center','FontWeight','bold');
                    end
                    
                    if PlotLatencyStatus~=1; set(hPointText,'Visible','off'); end
                    if DistPointMeanStatus & DistPoint>1
                        TimeFrquString1=[num2str(round(xTimePotVec(MinPoint+DistPoint.*(TimeInd-1)).*10)./10)];
                        TimeFrquString2=[num2str(round(xTimePotVec(MinPoint-1+DistPoint.*TimeInd).*10)./10)];
                        if Domain<3
                            TimeFrquString=[TimeFrquString1,' ms',' - ',TimeFrquString2,' ms']; 
                        elseif Domain>2 & Domain <5 
                            TimeFrquString=[TimeFrquString1,' Hz',' - ',TimeFrquString2,' Hz']; 
                        elseif Domain==5; 
                            TimeFrquString=['#',TimeFrquString1,' - #',TimeFrquString2]; 
                        end
                        set(hPointText,'String',TimeFrquString,'FontSize',ActFontSize);
                    end
                end
                pause(1)
            end
            
            %=============================================================================
            %============ EnableOnOff
            %=============================================================================	
        elseif strcmp(action,'EnableOnOff')
            
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            hTopMenu=get(hPlot3dList(83),'Userdata');
            
            hFileMenu=get(hTopMenu(1),'children');
            hStyleMenu=get(hTopMenu(2),'children');
            hExportMenu=get(hTopMenu(3),'children');
            hCalcMenu=get(hTopMenu(4),'children');
            hViewMenu=get(hTopMenu(5),'children');
            
            set(hCalcMenu,'Enable','on');
            set(hCalcMenu(1),'Enable','on');	% Calculate Absolut
            set(hCalcMenu(2),'Enable','on'); 	% Calculate Invert
            set(hCalcMenu(3),'Enable','on'); 	% Calculate Difference
            
            set(hExportMenu,'Enable','on');
            set(hExportMenu(1),'Enable','on');	% Calculated distribution
            
        end
        
%=====================================================================================

function [Ms]=Point2Ms(Point,Domain,SampRate,TrigPoint,NPoints)
	
if Domain<3 | Domain==6 | Domain==7	| Domain==8	%Time, Std, Wavelet
	Ms=round((Point-TrigPoint).*1000./SampRate);
elseif Domain>2 & Domain<5	%Frequency
	Ms=(Point-TrigPoint).*(NPoints+1).*(SampRate./2)./NPoints.^2;
elseif Domain==5			%ICA; PCA
	Ms=round(Point)-TrigPoint+1;
end;
return;

%=====================================================================================

function [Point]=Ms2Point(Ms,Domain,SampRate,TrigPoint,NPoints)
	
if Domain<3 | Domain==6 | Domain==7	%Time, Std, Wavelet
	Point=round(Ms.*SampRate./1000+TrigPoint);
elseif Domain>2 & Domain<5	%Frequency		
	Point=round(Ms./((NPoints+1).*(SampRate./2)./NPoints.^2)+TrigPoint);
elseif Domain==5 			%ICA; PCA
	Point=round(Ms)+TrigPoint-1;
end;	
return;
