function []=Plot3d(action);

%   CalcMinNorm.m

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

if nargin<1; action='Initialize'; end;	 
    
    global hPlot3dMenuFig hPlot2dMenuFig hGlobalChildMsgbox ForSensorMat SensorMat
    
    %============================================================================
    %=========== Initialize  ====================================================
    %============================================================================
    if strcmp(action,'Initialize'),
        
        % 	Message=char('Attention !!!');
        % 	Message=char(Message,'');
        % 	Message=char(Message,'In order to standardize the  "Lambda Approx." usage in');
        % 	Message=char(Message,'AvgApprox.m, App2Csd.m and Plot3d.m: ');
        % 	Message=char(Message,'The "Lambda Approx." value (now SLC Lambda) used for the calculation of');
        % 	Message=char(Message,'"Scalp, Lap., Cort" has been divided by 50 in contrast');
        % 	Message=char(Message,'to previous "Plot3d" versions.');
        % 	Message=char(Message,'');
        % 	Message=char(Message,'(Use 50 times bigger values as before in order');
        % 	Message=char(Message,'to keep the old  "Lambda Approx." values.');
        % 	Message=char(Message,'');
        % 	Message=char(Message,'The "Min. Norm." calculation itself is not affected');
        % 	Message=char(Message,'However, since the scalp spherical spline algorithm');
        % 	Message=char(Message,'is used to interpolate the Min. Norm results in order');
        % 	Message=char(Message,'to optimize the display (especially for deeper shells)');
        % 	Message=char(Message,'the SLC Lambda is not neglectable.');
        % 	Message=char(Message,'(In the Min. Norm case you could choose the');
        % 	Message=char(Message,'SLC Lambda value as small as possible (e.g. 0.005))');
        % 	clc;
        % 	disp(Message)
        % 	Message=char('Attention !!!');
        % 	Message=char(Message,'');
        % 	Message=char(Message,'The usage of the lambda value has been changed.');
        % 	Message=char(Message,'Please open MATLAB Command Window for further information.');
        % 	hPlot3dStartMsg=msgbox(Message,'Info','help'); 
        % 	hPlot3dStartMsgChild=get(hPlot3dStartMsg,'Children');
        % 	set(hPlot3dStartMsgChild(length(hPlot3dStartMsgChild)),'Visible','off');
        % 	pause(.1)
        
        TmpAddyPos=-.015;
        if strcmp(computer,'MAC2')	
            MenuFigPosVec=[.8 0 .2 1];
        elseif strcmp(computer,'PCWIN') 
            MenuFigPosVec=[.78 .05 .2 .82];
        elseif strcmp(computer,'SOL2')      	
            MenuFigPosVec=[0.8 0.00 0.2 0.89];			
        end
    
        hPlot3dMenuFig=figure('Units','normal',...
		'Position',MenuFigPosVec, ...
       	'Name','Plot3d Menu:', ...
		'Color',[.99 .99 .99], ...
        'NumberTitle','off');
		
        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','Standard Configuration'); 
		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='Plot3d(''CalcCortMap'');';
        
        hCortMapMethodMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
		'Value',1,...
		'Userdata',1,...
        'Interruptible','on', ...
        'Callback',callbackStr);
        if SpherStatus==0; 
			labelStr='Standard';
			callbackStr='Plot3d(''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];
        labelStr='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';
        callbackStr='Plot3d(''setSpecTask'');';
        
        hSpecTaskMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Value',3, ...
        'Callback',callbackStr);
        
        %====================================
        btnNumber=2;
        %  L2- Minimum Norm text label 
        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';
        callbackStr='Plot3d(''CalcMinimumNorm'');'; 
        hMinNormMethodMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Value',1,...
		'Userdata',1,...
        'Callback',callbackStr);
        
        %====================================
        %====================================
        btnNumber=2;
        
        %  Quiver 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];
		
        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='Plot3d(''SetQuiverStatus'')';
        
        hQuiverMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Orientation', ...
        'Interruptible','on',...
        'Callback',callbackStr,...
        'Value',0,...
        'Enable','on',...
        'Visible','on');
        EEGMEGStatusString=get(hPlot2dList(110),'String');
        if strcmp(EEGMEGStatusString,'MEG')
            set(hQuiverMenu,'Value',0,'Enable','off');
        end
        %====================================
        %====================================
        btnNumber=2;
        
        % AbsMinNormSurf Selection Menu
    	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt./2];
    	callbackStr='Plot3d(''SetAbsMinNormSurfStatus'')';
		
        hAbsMinNormSurfMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Absolute Value', ...
        'Interruptible','on',...
        'Callback',callbackStr,...
        'Value',1,...
        'Enable','on',...
        'Visible','on');
        
        %===================================
        % Save Data Routine text label 
        %===================================
        
        btnNumber=5;
        yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
        labelWidth = btnWid./2;
        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./2 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='Plot3d(''SaveData'');';
        
        hSaveDataMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Enable','off', ...
        'Callback',callbackStr);
        
		
        %====================================
        %===============2d3dView=============
        %====================================
        btnNumber=3;
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        labelWidth = btnWid./2;
        labelBottom=yPos-textHeight./1.5;
        labelLeft = left;
        labelPos = [labelLeft labelBottom labelWidth textHeight];
        h2d3dViewText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',labelPos, ...
        'Horiz','center', ...
        'String','View', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
        
        %====================================
        % The 2d3d View Routine Selection Menu
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left yPos-btnHt btnWid./2 btnHt];
        labelStr='Spec. Surf (3d)|All Surf I (3d)|All Surf II (3d)|Plot (2d)|Spec. Right|Columns & Rows';
        callbackStr='Plot3d(''set2d3dView'');';
        
        h2d3dViewMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Value',4, ...
        'Callback',callbackStr);
        
        %====================================
        %===============HeadView=============
        %===================================
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        labelWidth = btnWid./2;
        labelBottom=yPos-textHeight./1.5;
        labelLeft = left+btnWid./2;
        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./2 yPos-btnHt btnWid./2 btnHt];
        labelStr='Back     [0, 0]|Front    [180, 0]|Top  [0, 90]|Bottom  [180, -90]|Left       [-90, 0]|Right     [90, 0]|Special';
        callbackStr='Plot3d(''setHeadView'');';
        
        hHeadViewMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Value',3, ...
        'Callback',callbackStr);
        
        %====================================
        % ThetaViewHandle
        
        btnNumber=4;     
    	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    	btnPos=[left yPos btnWid./3 btnHt_edit./2];
        
        hThetaViewText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Theta [deg]');
        
        btnPos=[left+btnWid./3 yPos btnWid./6 btnHt_edit./2];
        callbackStr = 'Plot3d(''setThetaView'')';
        
        hThetaViewMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Userdata',0, ...
        'callback',callbackStr);
        
        %===================================
        
        % PhiViewHandle
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left+btnWid./2 yPos btnWid./3 btnHt_edit./2];
        
        hPhiViewText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Phi [deg]');
        
        btnPos=[left+5.*btnWid./6 yPos btnWid./6 btnHt_edit./2];
        callbackStr = 'Plot3d(''setPhiView'')';
        
        hPhiViewMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','90','Userdata',90, ...
        '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='Plot3d(''setPlotEPos'')';
        
        hPlotEPosMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
		'Userdata',2,...
		'Value',2,...
        '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';
        callbackStr='Plot3d(''setPlotContour'');';
        
        hPlotContourMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Value',2, ...
        '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='Plot3d(''setPlotLatency'');';
        
        hPlotLatencyMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Value',1, ...
        'Callback',callbackStr);
        %==============================================================
        % ColorMap (popupmenu)=========================================
        % callback: setColorMap =======================================
        %==============================================================
        
        btnNumber=5;
        yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;
        labelWidth = btnWid./2;
        labelBottom=yPos-textHeight./1.5;
        labelLeft = left+btnWid./2;
        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./2 yPos-btnHt btnWid./2 btnHt];
        labelStr='hsv|hot|cool|jet|pink|flag|copper|gray';
        callbackStr='Plot3d(''setColorMap'');';
        
        hColorMapMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Value',4, ...
        '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='Plot3d(''FlipColormap'')';
        
    	hFlipColormap=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Flip colormap', ...
		'Value',0,...
        '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='Plot3d(''setGrayFit'')';
        
    	hGrayFitMenu=uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
		'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        '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 = 'Plot3d(''setNRowColorMap'')';
        
        hNRowColorMapMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','256','Value',256, ...
        'Userdata',[256 1], ...
        'callback',callbackStr);
        
        %==============================================================
    	% ColorAmpTot (push button)======================================
        % callback: setColorAmpTot ======================================
        %==============================================================
        
        btnNumber=6;
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt./2];
    	callbackStr='Plot3d(''setColorAmpTot'')';
        
    	hColorAmpTot=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','N-Color ', ...
        'Userdata',1,...
        '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 = 'Plot3d(''setMinAmp'')';
        
        hMinAmpMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Userdata',0, ...
        '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 = 'Plot3d(''setMaxAmp'')';
        
        hMaxAmpMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Userdata',0, ...
        '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='Plot3d(''setCenterAmp'')';
        
    	hCenterAmp=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Center', ...
        'Userdata',0,...
        'Value',0,...
        '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='Plot3d(''setSpecAmp'')';
        
        hSpecAmp=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Special', ...
        'Userdata',1,...
        'Value',1,...
        '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='Plot3d(''setAutoAmp'')';
        
    	hAutoAmp=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Auto. Amp.', ...
        'Userdata',1,...
        'Value',1,...
        'Callback',callbackStr);
        
        %===================================
        % MinPointHandle
        %===================================
        
        btnNumber=8.5;     
    	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    	btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
        if Domain<3
            String='Min. time [ms]';
        elseif Domain>2 & Domain<5
            String='Min. frequ. [Hz]';
        elseif Domain==5
      		String='Min. comp. #';
        end	
    
        hMinPointText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String',String,...
        'Enable','on');
        
    	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
        callbackStr = 'Plot3d(''setMinPoint'')';
        
        hMinPointMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',1, ...
        'callback',callbackStr,...
        'Enable','on');
        
    	%===================================
        % MaxPointHandle
        %===================================
        
        btnNumber=8.5;     
    	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    	btnPos=[left yPos-btnHt_edit 2.*btnWid./3 btnHt_edit./2];
    	if Domain<3
            String='Max. time [ms]';
        elseif Domain>2 & Domain<5
      		String='Max. frequ. [Hz]';
        elseif Domain==5
      		String='Max. comp. #';
        end	
        hMaxPointText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String',String,...
		'Enable','on');
        
    	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
        callbackStr = 'Plot3d(''setMaxPoint'')';
        
        hMaxPointMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Value',0, ...
        'callback',callbackStr,...
		'Enable','on');
        
        %====================================
        % CalcDistPoint text edit button=====
        % callback: setDistPoint ============
        %====================================
        % DistPoint text
    	btnNumber=9.5;     
        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 = 'Plot3d(''setDistPoint'')';
    	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, ...
        'callback',callbackStr);
		
        %====================================
        % NDistInt text edit button=====
        % callback: setNDistInt ============
        %====================================
        % NDistInt text
        btnNumber=9.5;     
        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 = 'Plot3d(''setNDistInt'')';
    	
        hNDistIntMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','1','Value',1, ...
        'callback',callbackStr);
		
        %====================================
        % CalcDistPointMean radio button=====
        % callback: setCalcDistPointMean ====
        %====================================
        btnNumber=10.9;  
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left yPos btnWid/2 btnHt./2];
        callbackStr='Plot3d(''setCalcDistPointMean'')';
        
        hCalcDistPointMeanMenu=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Mean interval', ...
		'Userdata',1,...
		'Value',1,...
		'Callback',callbackStr);
		
        %====================================
        % SetTotalInt pushbutton=====
        % callback: setTotalInt ====
        %====================================
        btnNumber=10.9;
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left+btnWid/2 yPos btnWid/2 btnHt./2];
        callbackStr='Plot3d(''setTotalInt'')';
        
        hTotalInt=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Total Interval:', ...
		'Value',0,...
		'Callback',callbackStr,...
		'Enable','on');
        
        %============================================================
        % Use Approximation (radio button)===========================
        % callback: setUseApprox ====================================
        %============================================================
        
        btnNumber=13;
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left yPos-btnHt./2 btnWid btnHt./2];
        callbackStr='Plot3d(''setUseApprox'')';
        
    	hUseApprox=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Use Approximation/Normalization', ...
		'Userdata',1,...
		'Value',1,...
        'Callback',callbackStr);
        
        %==============================================================
    	% Use Approximation (radio button)===========================
        % callback: setUseApproxVec ===================================
        %==============================================================
        
        btnNumber=13;
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left yPos-btnHt btnWid./2 btnHt./2];
        callbackStr='Plot3d(''setUseApproxVec'')';
        
        hUseApproxVec=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Use app. Vector', ...
		'Userdata',0,...
		'Value',0,...
        '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='Plot3d(''setUseApproxMat'')';
        
    	hUseApproxMat=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Use app. Matrix', ...
        'Userdata',0,...
        'Value',0,...
        'Callback',callbackStr);
        
        %==============================================================
    	% Lambda Approx (edit button)=================================
        % callback: setSLCLambdaApprox ===================================
        %==============================================================
        
        btnNumber=11;     
        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 = 'Plot3d(''setSLCLambdaApprox'')';
        
        hSLCLambdaApproxMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0.02','Value',.02, ...
        'callback',callbackStr);
		
		
        btnPos=[left yPos-btnHt_edit btnWid./3 btnHt_edit./2];
        callbackStr = 'Plot3d(''CalcMNLambdaApprox'')';
        
        hCalcMNLambdaApproxMenu = uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'String','Evaluate', ...
		'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 = 'Plot3d(''setMNLambdaApprox'')';
        
        hMNLambdaApproxMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0.02','Value',.02, ...
        'callback',callbackStr);
        
        %==========================================================
        % Min. Beta Approx (edit button)==============================
        % callback: setMinBetaApprox ================================
        %==========================================================
        
        btnNumber=12;     
        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 = 'Plot3d(''setMinBetaApprox'')';
        
        hMinBetaApproxMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0.8','Userdata',.8, ...
        'callback',callbackStr);
        
        
        %============================================================
    	% Beta Wheigt Kind (popupmenu button)==========================
        % callback: setBetaWeightMethod ===============================
        %============================================================
        
        btnNumber=12.5;     
        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='Plot3d(''setBetaWeightMethod'');';
        
        hBetaWeightMethodMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Callback',callbackStr);
        
        %==============================================================
    	% Print to file Kind (popupmenu button)========================
        % callback: setPrint2FileMethod ===============================
        %==============================================================
        
    	btnNumber=14;
    	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='Plot3d(''setPrint2FileMethod'');';
        
        hPrint2FileMethod=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Userdata','JPEG',...
        'Value',3,...
        'Callback',callbackStr);
		
        %==========================================================
    	% Movie Status (radiobutton)===============================
        % callback: setPrint2FileStatus ===========================
        %==========================================================
        
        btnNumber=14;
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    	btnPos=[left yPos-btnHt btnWid./2 btnHt];
    	callbackStr='Plot3d(''setPrint2FileStatus'')';
        
        hPrint2FileStatus=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Print to file', ...
		'Userdata',0,...
		'Value',0,...
        'Callback',callbackStr);
        
        %==========================================================
    	% Movie Pause Status (radiobutton)=========================
        % callback: setMoviePause =================================
        %==========================================================
        btnNumber=16;   
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    	btnPos=[left yPos-btnHt btnWid./2 btnHt];
    	callbackStr='Plot3d(''setMoviePause'')';
        
    	hMoviePause=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Movie Pause', ...
        'Userdata',1,...
        'Value',1,...
        'Callback',callbackStr);
        
        %==========================================================
    	% Plot and Surf Status (radiobutton)=======================
        % callback: setPlotSurfStatus =============================
        %==========================================================
        
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    	callbackStr='Plot3d(''setPlotSurfStatus'')';
        
    	hPlotSurfStatus=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Plot Data', ...
        'Userdata',1,...
        'Value',1,...
        'Callback',callbackStr);
        
        %==============================================================
    	% Print Compression Value (edit button)========================
        % callback: setPrintFileComp ==================================
        %==============================================================
        
        btnNumber=15;
        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 = 'Plot3d(''setPrintFileComp'')';
        
        hPrintFileCompMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','80','Userdata',80, ...
        '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='Plot3d(''Save2Plot'');';
        
        hSave2PlotMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Callback',callbackStr,...
		'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='Plot3d(''ReadPlotData'');';
        
        hReadPlotMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Callback',callbackStr,...
		'Enable','off');
        
        %====================================
        
        btnNumber=17;
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left yPos-btnHt btnWid./2 btnHt];
        callbackStr = 'Plot3d(''PlotSurfData'')';
        hApply=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Apply (m)', ...
		'Userdata','0', ...
		'Enable','off', ...
        'Callback',callbackStr);
        
        %==============================================================
        % Selection of actual file (popupmenu) ========================
        % callback: setActFileNo ======================================
        %==============================================================
        
        btnNumber=17;
    	yPos=menutop-(btnNumber-1)*(btnHt+spacing)+TmpAddyPos;;
    	labelWidth = btnWid./2;
    	labelBottom=yPos-textHeight./1.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)+TmpAddyPos;
    	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    	callbackStr='Plot3d(''setActFileNo'')';
        
    	hActFileNoMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',' ', ...
		'Interruptible','on', ...
		'Value',1, ...
		'Userdata',1, ...
        'Callback',callbackStr,...
		'Enable','on');
		
        
        %=======================================================
        %===========UIMENUES====================================
        %=======================================================
        
        %==============================================================
    	% Menu: File ==================================================
        %==============================================================
        hFileMenu=uimenu('Label','File','ForegroundColor',[0 0 1],'Enable','off');
        
		hSetActFileNoMenu=uimenu(hFileMenu,'Label','Choose Data Set');
		callbackStr = 'Plot3d(''setActFileNo1'')';
		uimenu(hSetActFileNoMenu,'Label','Actual Data Set 1','Callback',callbackStr,'Accelerator','h');
		callbackStr = 'Plot3d(''setActFileNo2'')';
		uimenu(hSetActFileNoMenu,'Label','Actual Data Set 2','Callback',callbackStr,'Accelerator','j');
		callbackStr = 'Plot3d(''setActFileNo3'')';
		uimenu(hSetActFileNoMenu,'Label','Actual Data Set 3','Callback',callbackStr,'Accelerator','k');
		callbackStr = 'Plot3d(''setActFileNo4'')';
		uimenu(hSetActFileNoMenu,'Label','Actual Data Set 4','Callback',callbackStr,'Accelerator','l');
		callbackStr = 'Plot3d(''PlotSurfData'')';
		uimenu(hSetActFileNoMenu,'Label','Apply','Callback',callbackStr,'Accelerator','m','Separator','on');
		
		callbackStr='Plot3d(''OpenFileMatrix'')';
		hFileOpenFileMatrixMenu=uimenu(hFileMenu,'Label','Open file matrix','Callback',callbackStr);
		callbackStr='Plot3d(''SaveFileMatrix'')';
		hFileSaveFileMatrixMenu=uimenu(hFileMenu,'Label','Save file matrix','Callback',callbackStr,'Enable','off');
		callbackStr='Plot3d(''AddFile2FileMatrix'')';
		hFileAddFile2FileMatrixMenu=uimenu(hFileMenu,'Label','Add file to file matrix','Callback',callbackStr,'Enable','off');
		callbackStr='Plot3d(''UseFileMatrix'')';
		hFileUseFileMatrixMenu=uimenu(hFileMenu,'Label','Use file matrix','Callback',callbackStr,'Enable','off','Userdata',0);
        
        %==============================================================
    	% Menu: Style =================================================
        %==============================================================
        hStyleMenu=uimenu('Label','Style','ForegroundColor',[0 0 1],'Enable','on');
        
		%============ Colormap ========================================
		hStyleColormapMenu=uimenu(hStyleMenu,'Label','Colormap','Enable','on');
        callbackStr='Plot3d(''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='Plot3d(''DispSensorName'')';
        hDispSensorNameMenu=uimenu(hDispSensorMenu,'Userdata',0,'Label','Names','Callback',callbackStr);
        callbackStr='Plot3d(''DispSensorCircle'')';
        hDispSensorCircleMenu=uimenu(hDispSensorMenu,'Userdata',1,'Label','Circle','Callback',callbackStr);
        callbackStr='Plot3d(''DispSensorAsterisk'')';
        hDispSensorAsteriskMenu=uimenu(hDispSensorMenu,'Userdata',0,'Label','Asterisk','Callback',callbackStr);
        
        %==============================================================
    	% Menu: Export ================================================
        %==============================================================
        hExportMenu=uimenu('Label','Export','ForegroundColor',[0 0 1],'Enable','on');
		callbackStr='Plot3d(''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='Plot3d(''SaveDataMet1 '')';
        uimenu(hExportSaveDataMenu,'Label','Values at scalp locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet2 '')';
        uimenu(hExportSaveDataMenu,'Label','Values at scalp locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet3 '')';
        uimenu(hExportSaveDataMenu,'Label','Values at sensor locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet4 '')';
        uimenu(hExportSaveDataMenu,'Label','Values at sensor locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet5 '')';
        uimenu(hExportSaveDataMenu,'Label','Values at special scalp locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet6 '')';
        uimenu(hExportSaveDataMenu,'Label','Values at special scalp locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet7 '')';
        uimenu(hExportSaveDataMenu,'Label','Values at special sensor locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet8 '')';
        uimenu(hExportSaveDataMenu,'Label','Values at special sensor locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet9 '')';
        uimenu(hExportSaveDataMenu,'Label','Scalp locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet10'')';
        uimenu(hExportSaveDataMenu,'Label','Scalp locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet11'')';
        uimenu(hExportSaveDataMenu,'Label','Sensor locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet12'')';
        uimenu(hExportSaveDataMenu,'Label','Sensor locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet13'')';
        uimenu(hExportSaveDataMenu,'Label','Special scalp locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet14'')';
        uimenu(hExportSaveDataMenu,'Label','Special scalp locations [float32]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''SaveDataMet15'')';
        uimenu(hExportSaveDataMenu,'Label','Special sensor locations [ascii]','ForegroundColor',[0 0 1],'Callback',callbackStr,'Enable','off');
        callbackStr='Plot3d(''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','off');
        
		%=============================================
		%===============ScalpLapCort2File==========================
		hCalcSLC2FileMenu=uimenu(hCalcMenu,'Label','Scalp, Lap., Cort. => File','Separator','on','Enable','on');
        callbackStr = 'Plot3d(''CalcSLC2FileAll'')';
        hCalcSLC2FileAllMenu=uimenu(hCalcSLC2FileMenu,'Label','Use all original sensors','Callback',callbackStr,'Enable','on');
        callbackStr = 'Plot3d(''CalcSLC2FileGroups'')';
        hCalcSLC2FileGroupsMenu=uimenu(hCalcSLC2FileMenu,'Label','Use predefined sensor groups','Callback',callbackStr,'Enable','on');
        hCalcSLC2FileROIMenu=uimenu(hCalcSLC2FileMenu,'Label','Regions of interest','Enable','off');
        callbackStr = 'Plot3d(''CalcSLC2FileROI'')';
        hCalcSLC2FileUseROIMenu=uimenu(hCalcSLC2FileROIMenu,'Label','Use regions of interest','Callback',callbackStr,'Enable','off');
        callbackStr = 'Plot3d(''ReadROIFile'')';
        hCalcSLCReadROIFileMenu=uimenu(hCalcSLC2FileROIMenu,'Label','Read regions of interest file','Callback',callbackStr,'Enable','off');
		%=============================================
		%===============MinNorm2File==========================
		hCalcMinNorm2FileMenu=uimenu(hCalcMenu,'Label','Minimum Norm  => File','Separator','on','Enable','on');
        if strcmp(EEGMEGStatusString,'MEG')
            callbackStr = 'Plot3d(''CalcNormMagField2File'')';
            hCalcNormMagField2FileMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Save field to sensor configuration','Callback',callbackStr,'Enable','on');
        end
        callbackStr = 'Plot3d(''CalcMinNorm2FileEcfg'')';
        hCalcMinNorm2FileRawMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Save MN to sensor configuration','Callback',callbackStr,'Enable','on','Separator','on');
        callbackStr = 'Plot3d(''CalcMinNorm2FileShell'')';
        hCalcMinNorm2FileShellMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Save MN to actual shell','Callback',callbackStr,'Enable','on');
        callbackStr = 'Plot3d(''CalcMinNorm2FileAll'')';
        hCalcMinNorm2FileAllMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Use all original sensors','Callback',callbackStr,'Enable','on','Separator','on');
        callbackStr = 'Plot3d(''CalcMinNorm2FileGroups'')';
        hCalcMinNorm2FileGroupsMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Use predefined sensor groups','Callback',callbackStr,'Enable','on');
        hCalcMinNorm2FileROIMenu=uimenu(hCalcMinNorm2FileMenu,'Label','Regions of interest','Enable','on','Separator','on');
        callbackStr = 'Plot3d(''CalcMinNorm2FileROI'')';
        hCalcMinNorm2FileUseROIMenu=uimenu(hCalcMinNorm2FileROIMenu,'Label','Use regions of interest','Callback',callbackStr,'Enable','on');
        callbackStr = 'Plot3d(''ReadROIFile'')';
        hCalcMinNormReadROIFileMenu=uimenu(hCalcMinNorm2FileROIMenu,'Label','Read regions of interest file','Callback',callbackStr,'Enable','on');
        
		%=============================================
		%===============ABSOLUTE=======================
		callbackStr = 'Plot3d(''CalcAbs'')';
		hCalcAbsMenu=uimenu(hCalcMenu,'Label','Absolute','Callback',callbackStr,'Separator','on','Enable','off');
        
		%=============================================
		%===============INVERT=======================+
		callbackStr = 'Plot3d(''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 = 'Plot3d(''CalcDifference1'')';
        uimenu(hCalcDifferenceMenu,'Label','Actual - File','Callback',callbackStr,'Separator','on','Enable','on');
        callbackStr = 'Plot3d(''CalcDifference2'')';
        uimenu(hCalcDifferenceMenu,'Label','File - Actual','Callback',callbackStr,'Separator','on','Enable','on');
        
        
        %==============================================================
        % Menu: View ==================================================
        %==============================================================
        hViewMenu=uimenu('Label','View','ForegroundColor',[0 0 1],'Enable','on');
        
		hPlotViewMenu=uimenu(hViewMenu,'Label','2d3d View','ForegroundColor',[0 0 1],'Enable','on');
        callbackStr='Plot3d(''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='Plot3d(''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='Plot3d(''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='Plot3d(''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='Plot3d(''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');
        ActFileNo=get(hPlot2dList(1),'Userdata');
        Plot2dNListHdr=get(hPlot2dList(51),'Userdata');
        ActFilePath=get(hPlot2dList(Plot2dNListHdr+(ActFileNo-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;
        FileNoVec=get(hPlot2dList(56),'Userdata');
        CalcAvgMat=get(hPlot2dList(Plot2dNListHdr+(FileNoVec(ActFileNo)-1).*50+1),'Userdata');
        NTrialAvgVec=get(hPlot2dList(Plot2dNListHdr+(ActFileNo-1).*50+5),'Userdata');
        StdChanTimeMat=get(hPlot2dList(Plot2dNListHdr+(FileNoVec(ActFileNo)-1).*50+6),'Userdata');
        hDataVec=get(hPlot2dList(Plot2dNListHdr+(FileNoVec(ActFileNo)-1).*50+25),'Userdata');
        NChan=get(hPlot2dList(Plot2dNListHdr+(ActFileNo-1).*50+2),'Userdata');
        
        
        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 (',int2str(NChan),'.ecfg)']);
		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 'Plot3dLegCoeff'];
        DipoleRadius=0.04;
        
        hPathLeg=uicontrol('Userdata',PathLeg,'Visible','off');				%59
        PathCoeff=[BasePath 'Plot3dCoeff' 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 'Plot3dInvCoeff'];
        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
        
        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
        
        
        
		
        ExistCalcCoeff(InvIter,0,PIter,MSpherical,LengthLegVec,PathLeg,ParaVec);
        
        %====================================
        NoUse=0;
        
        hPlot3dList=[hCortMapMethodText hCortMapMethodMenu NoUse NoUse hSaveDataText ... 
        hSaveDataMenu NoUse 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 NoUse ...
        hActFileNoText hActFileNoMenu hPrint2FileMethodText hPrint2FileMethod NoUse ...
        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 ...
        hNDistIntText hNDistIntMenu hGrayFitText hCalcMNLambdaApproxMenu];						%125
		
        
        set(hPlot3dMenuFig,'Visible','on','UserData',hPlot3dList);
        Plot3d('setHandleActFileNo')
        Plot3d('setActFileNo')
        Plot3d('setMinMaxAmpString')
        if NPoints3d>10
            set(hNDistIntMenu,'String',10);
        else
            set(hNDistIntMenu,'String',int2str(NPoints3d));
            set(h2d3dViewMenu,'Value',3); %All Surf II (3d)
        end
        Plot3d('setNDistInt')
        pause(1)
        % 	close(hPlot3dStartMsg);
        
        
    elseif  strcmp(action,'set2d3dView')

        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
		View2d3d=get(hPlot3dList(12),'Value');
		if View2d3d==6
        	set(hPlot3dList(30),'Value',1);			%hPlotEPosMenu Just in first view
        	set(hPlot3dList(122),'String','20');	%hNDistIntMenu
       	 	Plot3d('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
                Plot3d('setHeadView');
                Plot3d('CalcCortMap');pause(.1);
                set(hPlot3dList(114),'Userdata',[4 2]);	%hNWinMenu
                set(hPlot3dList(14),'Value',2);			%hHeadViewMenu %Front
                Plot3d('setHeadView');
                Plot3d('PlotSurfData');pause(.1);
            end
            if SpecTaskNo==2 | SpecTaskNo==3
                set(hPlot3dList(114),'Userdata',[4 3]);	%hNWinMenu
                set(hPlot3dList(14),'Value',1);			%hHeadViewMenu %Back
                Plot3d('setHeadView');
                Plot3d('CalcMinimumNorm');pause(.1);
                set(hPlot3dList(114),'Userdata',[4 4]);	%hNWinMenu
                set(hPlot3dList(14),'Value',2);			%hHeadViewMenu %Front
                Plot3d('setHeadView');
                Plot3d('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
                Plot3d('setHeadView');
                Plot3d('CalcCortMap');pause(.1);
                set(hPlot3dList(114),'Userdata',[4 2]);	%hNWinMenu
                set(hPlot3dList(14),'Value',6);			%hHeadViewMenu %Right
                Plot3d('setHeadView');
                Plot3d('PlotSurfData');pause(.1);
            end
            if SpecTaskNo==5 | SpecTaskNo==6
                set(hPlot3dList(114),'Userdata',[4 3]);	%hNWinMenu
                set(hPlot3dList(14),'Value',5);			%hHeadViewMenu %Left
                Plot3d('setHeadView');
                Plot3d('CalcMinimumNorm');pause(.1);
                set(hPlot3dList(114),'Userdata',[4 4]);	%hNWinMenu
                set(hPlot3dList(14),'Value',6);			%hHeadViewMenu %Right
                Plot3d('setHeadView');
                Plot3d('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
                Plot3d('setActFileNo');
                if SpecTaskNo==7
                    Plot3d('CalcCortMap');
                elseif SpecTaskNo==8
                    Plot3d('CalcMinimumNorm');
                end
                pause(.1); 
            end
            set(hPlot3dList(114),'Userdata',[1 1]);		%hNWinMenu
        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,'OpenFileMatrix') 

        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        hTopMenu=get(hPlot3dList(83),'Userdata');
        hFileMenu=get(hTopMenu(1),'children');
        UseFileMatStatus=get(hFileMenu(1),'Userdata');
        BatchFileDefPath=get(hPlot3dList(115),'Userdata');
        if isempty(BatchFileDefPath)
            [BatchFileDefPath]=SetDefPath(1);
        end	
        [NFiles,FileMat,NonUse,BatchFilePath]=ReadFileNames([],BatchFileDefPath,'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; 
            Plot3d('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
            Plot3d('FileMatrixInfo')
        end
    
    elseif  strcmp(action,'SaveFileMatrix') 

        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        FileMat=get(hPlot3dList(100),'Userdata')
        NFiles=get(hPlot3dList(100),'Value');
        Plot3d('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);
        Plot3d('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)];
            Plot3d('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,'');
        hmsgbox=msgbox(Message,'Info','help'); 
        disp(FileMat)
        
    elseif strcmp(action,'ReadROIFile')

        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        ROIDefPath=which('C3-C4-20-ROI.txt')
        IndSepPathVec=findstr(ROIDefPath,filesep);
        if ~isempty(IndSepPathVec)	
            ROIDefPath=ROIDefPath(1:IndSepPathVec(length(IndSepPathVec)));
            ROIDef=[ROIDefPath,'*ROI.txt'];
        else
            ROIDef='*.txt';
        end
        [ROIFile,ROIPath]=uigetfile(ROIDef,'Open ROI file (*ROI.txt):');
        ROIFilePath=[ROIPath,ROIFile];
        if ROIFile==0; return; end
        [ROIMatSpherDeg] = ReadBem(ROIFilePath,1,'Matrix','Ascii');
        ROIMatSpherDeg=ROIMatSpherDeg';
        [NROI,Def4]=size(ROIMatSpherDeg);
        if Def4~=4
            Message=char('Sorry,wrong ROI file format !');
            Message=char(Message,'');
            Message=char(Message,'Please use "C3-C4-20-ROI.txt" file as an example.');
            hmsgbox=msgbox(Message,'Info','help'); 
            return
        end
        Message=char(['Read the following ',int2str(NROI),' regions of interest:']);
        Message=char(Message,'');
        for ROIInd=1:NROI
            Message=char(Message,['Region # ',int2str(ROIInd)]);
            Message=char(Message,['Theta: ', sprintf('%g',ROIMatSpherDeg(ROIInd,1)),'; Phi: ', sprintf('%g',ROIMatSpherDeg(ROIInd,2)),'; Radius: ', sprintf('%g',ROIMatSpherDeg(ROIInd,3)),'; Extension: ', sprintf('%g',ROIMatSpherDeg(ROIInd,4))]);
            Message=char(Message,'');
        end
        hmsgbox=msgbox(Message,'Info','help'); 
        pause(2)
        set(hPlot3dList(107),'Value',NROI,'Userdata',ROIMatSpherDeg);
        
    elseif	strcmp(action,'CalcSLC2FileAll') | ...
        strcmp(action,'CalcSLC2FileGroups') | ...
        strcmp(action,'CalcSLC2FileROI') | ...
		strcmp(action,'CalcNormMagField2File') | ...
        strcmp(action,'CalcMinNorm2FileEcfg') | ...
        strcmp(action,'CalcMinNorm2FileShell') | ...
        strcmp(action,'CalcMinNorm2FileAll') | ...
        strcmp(action,'CalcMinNorm2FileGroups') | ...
        strcmp(action,'CalcMinNorm2FileROI')
        
        hPlot2dList=get(hPlot2dMenuFig,'Userdata'); 
        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        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');
            if isempty(ROIMatSpherDeg)
                Plot3d('ReadROIFile');
                ROIMatSpherDeg=get(hPlot3dList(107),'Userdata');
                NROI=get(hPlot3dList(107),'Value');
            end
        end
        hTopMenu=get(hPlot3dList(83),'Userdata');
        hFileMenu=get(hTopMenu(1),'children');
        UseFileMatStatus=get(hFileMenu(1),'Userdata');
        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');
        
        if strcmp(action,'CalcMinNorm2FileEcfg') | ...
            strcmp(action,'CalcMinNorm2FileShell') | ...
            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
                Plot3d('setMinPointString');
                set(hPlot3dList(49),'Value',NPoints2d); 	  %MaxPoint 
                Plot3d('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')
            
            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,'CalcMinNorm2FileAll') | ...
            strcmp(action,'CalcMinNorm2FileGroups') | ...
            strcmp(action,'CalcMinNorm2FileROI')
            
            Message=char('Please remember: Calculation of L2-Minimum-Norm,');
            Message=char(Message,'depends on the chosen shell and the lambda approximation value ! ');
            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
            Message=char(Message,' ');
            Message=char(Message,'Please choose a file name to export the calculated data.');
        else
            if SLCMethod==1
                SLCString='Scalp';
                Message=char('Please remember: Calculation of the "Scalp Potential"');
            elseif SLCMethod==2
                SLCString='Laplacian';
                Message=char('Please remember: Calculation of the "Laplacian"');
            elseif SLCMethod==3
                SLCString='Cort';
                Message=char('Please remember: Calculation of the "Intracranial Potential Estimation"');
            elseif SLCMethod==4
                SLCString='PerrinScalp';
                Message=char('Please remember: Calculation of the "Perrin Scalp Potential"');
            elseif SLCMethod==5
                SLCString='PerrinLaplacian';
                Message=char('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
            Message=char(Message,' ');
            Message=char(Message,'Please choose a file name to export the calculated data.');
        end
        Message=char(Message,' ');
        hmsgbox=msgbox(Message,'Info','help'); 
        hGlobalChildMsgbox=get(hmsgbox,'Children');
        set(hGlobalChildMsgbox(length(hGlobalChildMsgbox)),'Visible','off');
        if NFiles==0; return; end
        
        if strcmp(action,'CalcMinNorm2FileEcfg') | ...
            strcmp(action,'CalcMinNorm2FileShell') | ...
            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);		
            end
            if ~strcmp(action,'CalcMinNorm2FileEcfg') & ~strcmp(action,'CalcMinNorm2FileShell')
                [SaveFile,SavePath,SaveFilePath]=WriteFilePath('MN.txt','Export calculated data to file:');
            end
        else
            set(hPlot3dList(101),'Value',1);	%CalcSLC2File
            [SaveFile,SavePath,SaveFilePath]=WriteFilePath([SLCString '.txt'],'Export calculated data to file:');
        end
        close(hmsgbox);
        if ~strcmp(action,'CalcMinNorm2FileEcfg')  & ~strcmp(action,'CalcMinNorm2FileShell')
            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		
        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')
            TmpString=[TmpString 'SLC_Lambda; Trigger_Point_[];  Min._Time_[ms];  Max._Time_[ms]; Dist._Time_[ms]; Mean_Status; '];
            fprintf(Fid1,TmpString);
            fprintf(Fid2,TmpString);
        end
        if strcmp(action,'CalcMinNorm2FileAll') | strcmp(action,'CalcSLC2FileAll')
            fprintf(Fid1,'Channel_Number; '); 	
            fprintf(Fid2,'Number_of_channels; ');
        elseif strcmp(action,'CalcMinNorm2FileGroups') | strcmp(action,'CalcSLC2FileGroups')
            fprintf(Fid1,'Group_Number; '); 		
            fprintf(Fid2,'Group_Number; '); 		
        elseif strcmp(action,'CalcMinNorm2FileROI') | strcmp(action,'CalcSLC2FileROI')
            fprintf(Fid5,TmpString);
            fprintf(Fid1,'ROI_Number; '); 		
            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');
            
            ROIMatSpherRad(:,[1 2 4])=pi.*ROIMatSpherDeg(:,[1 2 4])./180;
            ROIMatCart=ROIMatSpherRad;
            ROIMatCart(:,1:3)=change_sphere_cart(ROIMatSpherRad(:,1:2),ScalpRadius, 1);
            
            ScalpLocCart=get(hPlot3dList(58),'Userdata');
            ScalpLocSpher=change_sphere_cart(ScalpLocCart,[], -1);
            ScalpLocIndVec=get(hPlot3dList(106),'Userdata')
            if isempty(ScalpLocIndVec)
                Plot3d('ReadOrCalcScalpLocIndFile');
                ScalpLocIndVec=get(hPlot3dList(106),'Userdata');
            end
            ScalpLocCart=ScalpLocCart(ScalpLocIndVec,:);
            ScalpLocSpher=ScalpLocSpher(ScalpLocIndVec,:);
            DiffScalpLoc=ScalpLocCart;
            MaxNROIScalpLocIndVec=0;
            for ROIInd=1:NROI
                Tau=ROIMatSpherRad(ROIInd,4);
                MaxDist=sqrt((ScalpRadius.*sin(Tau)).^2+(ScalpRadius.*(cos(Tau)-1)).^2);
                CenterROILoc=ROIMatCart(ROIInd,1:3);
                for Ind=1:length(ScalpLocCart);
                    DiffScalpLoc(Ind,:)=ScalpLocCart(Ind,:)-CenterROILoc;
                end
                ROIScalpLocIndVec=find(sqrt(sum(DiffScalpLoc'.^2))<MaxDist);
                NROIScalpLocIndVec=length(ROIScalpLocIndVec);
                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 the given region: %g ;\n\n',NROIScalpLocIndVec);
                fprintf('Cartesian locations:\n\n')
                disp(ScalpLocCart(ROIScalpLocIndVec,:).*1000);
                fprintf('Spherical locations:\n\n')
                disp(180.*ScalpLocSpher(ROIScalpLocIndVec,1:2)./pi);
                fprintf('\n\n\n\n')
                MaxNROIScalpLocIndVec=max([MaxNROIScalpLocIndVec NROIScalpLocIndVec]);
                ROIScalpLocIndMat=zeros(ROIInd,MaxNROIScalpLocIndVec);
                if ROIInd>1
                    ROIScalpLocIndMat(1:ROIInd-1,1:MaxNROIScalpLocIndVecOld)=ROIScalpLocIndMatOld;
                    ROIScalpLocIndMat(ROIInd,1:NROIScalpLocIndVec)=ROIScalpLocIndVec;
                else
                    ROIScalpLocIndMat=ROIScalpLocIndVec;
                end
                ROIScalpLocIndMatOld=ROIScalpLocIndMat;
                MaxNROIScalpLocIndVecOld=MaxNROIScalpLocIndVec;
            end
        end
        if ~strcmp(action,'CalcMinNorm2FileEcfg') & ~strcmp(action,'CalcMinNorm2FileShell')
            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
        for FileIndex=1:NFiles
            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;
                if UseFileMatStatus
                    [File,Path,FilePath]=GetFileNameOfMat(FileMat,FileIndex);	
                    set(hPlot3dList(55),'Userdata',FilePath); %ActFilePath
                    if strcmp(action,'CalcMinNorm2FileEcfg') | strcmp(action,'CalcMinNorm2FileShell')
                        [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(Plot2dAvgFileFormat,'SCADS')
                        [AvgMat,File,Path,FilePath,NTrialAvgVec,StdChanTimeMat,...
                        SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec]=ReadAvgFile(FilePath);
                        [NonUse,ActNPoints]=size(AvgMat);
                    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
                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,'CalcMinNorm2FileAll') | ...
                    strcmp(action,'CalcMinNorm2FileGroups') | ...
                    strcmp(action,'CalcMinNorm2FileROI')
                    
                    Plot3d('CalcMinimumNorm')
                    DataMat=get(hPlot3dList(53),'Userdata');
				elseif strcmp(action,'CalcMagFieldNorm2File')
					 Plot3d('CalcMagFieldNorm')
					 DataMat=get(hPlot3dList(53),'Userdata');
                else
                    Plot3d('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')
                    TmpString=[];
                    for Ind=1:NPointsInt
                        TmpString=[TmpString,'T',int2str(Ind),'; '];
                    end
                    fprintf(Fid1,[TmpString '\n\n']);
                    fprintf(Fid2,[TmpString '\n']);
                end
                if strcmp(action,'CalcMinNorm2FileGroups') | strcmp(action,'CalcSLC2FileGroups')
                    NGroupChan=NGroup; 
                elseif strcmp(action,'CalcMinNorm2FileROI') | strcmp(action,'CalcSLC2FileRoi')
                    NGroupChan=NROI; 	
                end
                Message=char(['Save calculated values of ' int2str(NGroupChan) ' sensors, groups  or ROIs']);
                Message=char(Message,['and ', int2str(NPointsInt) ' points or intervals in file: ']);
                if CalcBaseStatus
                    Message=char(Message,['(Baseline interval: ',int2str(MinBase),' - ',int2str(MaxBase),') ']);
                else
                    Message=char(Message,'(No baseline correction) ');
                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
                    hmsgbox=msgbox(Message,'Info:','help');
                    hGlobalChildMsgbox=get(hmsgbox,'Children');
                    hChild2Msgbox=get(hGlobalChildMsgbox,'Children');
                    set(hGlobalChildMsgbox(length(hGlobalChildMsgbox)),'Visible','off');
                else
                    hChild2Msgbox=get(hGlobalChildMsgbox,'Children');
                    if strcmp(computer,'SOL2')
                        set(hChild2Msgbox,'String',Message);
                    else
                        set(hGlobalChildMsgbox(2),'String',Message);
                    end
                end
                pause(.01);
                if ~strcmp(action,'CalcMinNorm2FileEcfg') & ~strcmp(action,'CalcMinNorm2FileShell')
                    CondNumber=0;
                    if strcmp(Plot2dAvgFileFormat,'SCADS')
                        Nat=findstr(File,'.at');
                        if ~isempty(Nat); 
                            Nat=Nat(length(Nat))+3;
                            if length(File)>=Nat;
                                Tmp=File(Nat)-48
                                if ~isnan(Tmp) 
                                    CondNumber=Tmp;
                                end
                            end
                        end
                        fprintf('temporary CellIndex and SubjectIndex, line 2441 in plot3d')
                        CellIndex=CondNumber
                        SubjectIndex=File(7:8);
                        if strcmp(SubjectIndex(1),'0')
                            SubjectIndex=File(8)-48;
                        else
                            SubjectIndex=(File(7)-48).*10+File(8)-48;
                        end
                    end
                    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')
                    if strcmp(Plot2dAvgFileFormat,'SCADS')
                        SaveAvgFile(SaveFilePath,DataMat,NTrialAvgVec,zeros(size(DataMat)),SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus);
                    end
                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');
                        fprintf(Fid3,'%g\t',DataMat(ChanIndex,:)); 		fprintf(Fid3,'\n');
                    end
                    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
                elseif strcmp(action,'CalcMinNorm2FileGroups') | strcmp(action,'CalcSLC2FileGroups')
                    MaxValGroupVec=zeros(NGroup,1);
                    MinValGroupVec=zeros(NGroup,1);
                    MaxIndGroupVec=zeros(NGroup,1);
                    MinIndGroupVec=zeros(NGroup,1);
                    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');
                        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); 
                        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
                    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
                elseif strcmp(action,'CalcMinNorm2FileROI') | strcmp(action,'CalcSLC2FileROI')
                    DataMat=DataMat(ScalpLocIndVec,:); %932 statt 1024
                    for ROIIndex=1:NROI
                        ROIScalpLocIndVec=ROIScalpLocIndMat(ROIIndex,:);
                        Tmp=find(ROIScalpLocIndVec~=0);
                        if isempty(Tmp); 
                            Message=char(Message,['No location in ' int2str(ROIIndex) ' region of interest.']);
                            hmsgbox=msgbox(Message,'Info','help');
                        else
                            ROIScalpLocIndVec=ROIScalpLocIndVec(Tmp);
                            NROIScalpLocIndVec=length(ROIScalpLocIndVec);
                            DataVec=sum(DataMat(ROIScalpLocIndVec,:),1)./NROIScalpLocIndVec;
                            fprintf(Fid1,[TmpString,int2str(ROIIndex)]);		fprintf(Fid1,'\t');
                            fprintf(Fid1,'%g\t',DataVec);				 	fprintf(Fid1,'\n'); 
                            fprintf(Fid3,'%g\t',DataVec); 
                            Tmp=MsPerPoint.*sum(sqrt(sum((DataMat(ROIScalpLocIndVec,:).^2))./length(ROIScalpLocIndVec)));
                            fprintf(Fid2,'%g\t',Tmp); 						fprintf(Fid2,'\n'); 
                            Tmp=MsPerPoint.*sqrt(sum((DataMat(ROIScalpLocIndVec,:).^2))./length(ROIScalpLocIndVec));
                            fprintf(Fid2,'%g\t',Tmp); 						fprintf(Fid2,'\n');
                            fprintf(Fid4,'%g\t',Tmp);
                            [NoUse,MaxAbsIndVec]=max(abs(DataMat(ROIScalpLocIndVec,:)));
                            fprintf(Fid5,[TmpString,int2str(ROIIndex) '\n\n']);
                            for TimeInd=1:length(DataVec)
                                MaxAbsVal=DataMat(ROIScalpLocIndVec(MaxAbsIndVec(TimeInd)),TimeInd);
                                MeanVal=mean(DataMat(ROIScalpLocIndVec,TimeInd));
                                RMSVal=sqrt(sum(DataMat(ROIScalpLocIndVec,TimeInd).^2,1));
                                MaxAbsScalpLocCart=ScalpLocCart(ROIScalpLocIndVec(MaxAbsIndVec(TimeInd)),:);
                                MaxAbsScalpLocSpher=ScalpLocSpher(ROIScalpLocIndVec(MaxAbsIndVec(TimeInd)),:);
                                fprintf(Fid5,'%g\t',TimeInd); fprintf(Fid5,'\n'); 
                                fprintf(Fid5,'%g\t',MaxAbsScalpLocCart); fprintf(Fid5,'\n'); 
                                fprintf(Fid5,'%g\t',MaxAbsScalpLocSpher); 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',MaxAbsScalpLocCart); 
                                fprintf(Fid6,'%g\t',MaxAbsScalpLocSpher); 
                                fprintf(Fid6,'%g\t',MaxAbsVal); 
                                fprintf(Fid6,'%g\t',MeanVal); 
                                fprintf(Fid6,'%g\t',RMSVal); 
                            end
                        end
                    end
                    fprintf(Fid3,'\n'); 
                    fprintf(Fid4,'\n'); 
                end	
            end
        end
        if ~strcmp(action,'CalcMinNorm2FileEcfg') & ~strcmp(action,'CalcMinNorm2FileShell')
            fclose(Fid1);
            fclose(Fid2);
            fclose(Fid3);
            fclose(Fid4);
            fclose(Fid7);
            if strcmp(action,'CalcMinNorm2FileROI') | strcmp(action,'CalcSLC2FileROI')
                fclose(Fid5);
                fclose(Fid6);
            end
        end
        close(hmsgbox);
        if strcmp(action,'CalcMinNorm2FileEcfg') | strcmp(action,'CalcMinNorm2FileShell') | strcmp(action,'CalcMinNorm2FileAll') | strcmp(action,'CalcMinNorm2FileGroups')  | strcmp(action,'CalcMinNorm2FileROI') 
            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') 
            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');
        hChildMsgbox=get(hmsgbox,'Children');
        set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
        pause(2);
        if ~strcmp(action,'CalcMinNorm2FileEcfg') & ~strcmp(action,'CalcMinNorm2FileShell')
            close(hmsgbox);
        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 strcmp(action,'setActFileNo') | ...
        strcmp(action,'setActFileNo1') | ...
        strcmp(action,'setActFileNo2') | ...
        strcmp(action,'setActFileNo3') | ...
        strcmp(action,'setActFileNo4'),
        
        hPlot2dList=get(hPlot2dMenuFig,'Userdata'); 
        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        ActFileNo2d=get(hPlot2dList(1),'Value');
        if strcmp(action,'setActFileNo')
            ActFileNo3d=get(hPlot3dList(87),'Value');
        else
            ActFileNo3d=str2num(action(length(action)));
        end
        FirstActFileNoStatus=get(hPlot3dList(87),'Userdata');
        Plot2dNListHdr=get(hPlot2dList(51),'Userdata');
        FileNoVec=get(hPlot2dList(56),'Userdata');
        NFileNoVec=length(FileNoVec);	
        LabelString=[];
        for FileIndex=1:NFileNoVec
            FilePath=get(hPlot2dList(Plot2dNListHdr+(FileNoVec(FileIndex)-1).*50+4),'Userdata');
            [File,Path]=SepFilePath(FilePath);
            LabelString=[LabelString,File];
            if NFileNoVec>1 & FileIndex<NFileNoVec
                LabelString=[LabelString '|'];
            end
        end
        if FirstActFileNoStatus==1
            ActFileNo=ActFileNo2d; 
            set(hPlot3dList(87),'Userdata',0);
        else
            if isempty(find(ActFileNo3d==FileNoVec))
                ActFileNo=ActFileNo2d;
            else
                ActFileNo=ActFileNo3d;
            end
        end
        set(hPlot3dList(87),'String',LabelString,'Userdata',0,'Value',ActFileNo);
        ActFilePath=get(hPlot2dList(Plot2dNListHdr+(ActFileNo-1).*50+4),'Userdata');
        set(hPlot3dList(55),'Userdata',ActFilePath);
        Data2Analyse=get(hPlot2dList(Plot2dNListHdr+(FileNoVec(ActFileNo)-1).*50+1),'Userdata');
        set(hPlot3dList(54),'Userdata',Data2Analyse);
        set(hPlot3dList(78),'Userdata',sqrt(sum(Data2Analyse.^2)));
        set(hPlot3dList(33),'Enable','off');				%hApply
        
    elseif strcmp(action,'setDistPoint'),

        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        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);
        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
            set(hPlot3dList(33),'Enable','off');				%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
        Plot3d('setMinPointString')
        set(hPlot3dList(49),'Value',NPoints);	%MaxPoint
        Plot3d('setMaxPointString')
        DistPointVec(1:2)=[1 MsPerPoint];
        set(hPlot3dList(41),'Userdata',DistPointVec,'String',sprintf('%g',MsPerPoint));
        Plot3d('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]);
		%NDistIntTmp=length([MinPoint:DistPoint:MaxPoint])-1
        if NDistIntTmp~=NDistInt
            set(hPlot3dList(122),'Value',NDistIntTmp,'String', sprintf('%g',NDistIntTmp));  
            set(hPlot3dList(41),'Userdata',DistPointVec,'String',sprintf('%g',DistPointMs));
            set(hPlot3dList(33),'Enable','off');					%hApply
        end
    
    elseif strcmp(action,'setCalcDistPointMean'),

        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        set(hPlot3dList(33),'Enable','off');					%hApply
        
    elseif strcmp(action,'setHeadView'),

        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        HeadView=get(hPlot3dList(14),'Value');
        if HeadView~=7
            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	
    
    elseif strcmp(action,'setThetaView'),

        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        ThetaView=get(hPlot3dList(16),'Userdata');
        PhiView=get(hPlot3dList(18),'Userdata');
        ViewVec=get(hPlot3dList(79),'Userdata');			
        
        ThetaViewString=get(hPlot3dList(16),'String');
        ind = find(abs(ThetaViewString)<32);
        ThetaViewString(ind) = 32*ones(size(ind));
        ThetaViewString = ThetaViewString';	
        ThetaViewTmp = eval(['[' ThetaViewString(:)' ']'],'-1')';
        if ThetaView<0 | 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);
                return;
            end
            HeadView=HeadView+1;
        end
        set(hPlot3dList(14),'Value',7);
        
    elseif strcmp(action,'setPhiView'),

        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        ThetaView=get(hPlot3dList(16),'Userdata');
        PhiView=get(hPlot3dList(18),'Userdata');
        ViewVec=get(hPlot3dList(79),'Userdata');			
        
        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);
        HeadView=1;
        while HeadView<7
            if ThetaView==ViewVec(HeadView,1) & PhiViewTmp==ViewVec(HeadView,2);
                set(hPlot3dList(14),'Value',HeadView);
                return;
            end
            HeadView=HeadView+1;
        end
        set(hPlot3dList(14),'Value',7);
        
    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 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
            Plot3d('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);
        set(hPlot3dList(47),'Value',MinPointTmp,'String',sprintf('%g',MsHzMinPoint));
        set(hPlot3dList(33),'Enable','off');				%hApply
        Plot3d('setDistPoint')
        
    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	
            if MinPointTmp>MaxPoint	
                set(hPlot3dList(47),'Value',1); %MinPoint
                Plot3d('setMinPointString')
            end
        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);
        set(hPlot3dList(49),'Value',MaxPointTmp,'String',sprintf('%g',MsHzMaxPoint));
        set(hPlot3dList(33),'Enable','off');				%hApply
        Plot3d('setDistPoint')
        
    elseif strcmp(action,'setMinAmp'),

        hPlot3dList=get(hPlot3dMenuFig,'Userdata');
        v = get(hPlot3dList(22),'Userdata');
        MaxAmp=get(hPlot3dList(24),'Userdata');
        str = get(hPlot3dList(22),'String');
        
        ind = find(abs(str)<22);
        str(ind) = 32*ones(size(ind));
        str = str';	
        vv = eval(['[' str(:)' ']'],'-1')';
        if vv>=MaxAmp | length(vv)~=1
            vv = v;
        end
        vv = round(vv*1000)/1000;
        str = sprintf('%g',vv);
        set(hPlot3dList(22),'Userdata',vv,'String',str);  
        
    elseif strcmp(action,'setMaxAmp'),

        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        v = get(hPlot3dList(24),'Userdata');
        MinAmp=get(hPlot3dList(22),'Userdata');
        str = get(hPlot3dList(24),'String');
        
        ind = find(abs(str)<32);
        str(ind) = 32*ones(size(ind));
        str = str';
        vv = eval(['[' str(:)' ']'],'-1')';
        if vv<=MinAmp | length(vv)~=1
            vv = v;
        end
        vv = round(vv*1000)/1000;
        str = sprintf('%g',vv);
        set(hPlot3dList(24),'Userdata',vv,'String',str);
        
    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 & MinAmp~=-1.*MaxAmp
            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));
        end
    
    elseif strcmp(action,'setAutoAmp'),

        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        AutoAmp=get(hPlot3dList(45),'Value');
        if AutoAmp
            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
        end
    
    elseif strcmp(action,'setUseApprox'),

        hPlot3dList=get(hPlot3dMenuFig,'Userdata');
        set(hPlot3dList(33),'Enable','off');					%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
            set(hPlot3dList(33),'Enable','off');				%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
            set(hPlot3dList(33),'Enable','off');				%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
            set(hPlot3dList(33),'Enable','off');				%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
            set(hPlot3dList(33),'Enable','off');				%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
            set(hPlot3dList(33),'Enable','off');				%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('Plot3dPrintFiles')
            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'); 
        
        Method = get(hPlot3dList(2),'Value');	  %'Scalp|Lap|Cort|Perrin Scalp|Perrin Lap';
        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  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);
                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
        
        Plot3d('setMinMaxAmpString')
        Plot3d('setAutoAmp')	
        Plot3d('chSaveDataLabelString')	
        Plot3d('EnableOnOff')	
        Plot3d('PlotSurfData')
		
    elseif strcmp(action,'CalcMagFieldNorm'), 

 		global InvLFCoeff ForLFCoeff Data2Analyse RadVec NormData ForSensorMat InvSensorMat DipStrength LeadLoc
		hPlot2dList=get(hPlot2dMenuFig,'Userdata');
        hPlot3dList=get(hPlot3dMenuFig,'Userdata');
		MinPoint=get(hPlot3dList(47),'Value');
        MaxPoint=get(hPlot3dList(49),'Value');
		SampRate=get(hPlot2dList(60),'Userdata'); 
		MNLambdaApprox=get(hPlot3dList(109),'Value')
		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');
		PathLFCoeff=get(hPlot3dList(71),'Userdata');
		LeadLocFile=[PathLFCoeff,filesep,'DLoc_197_1_Cart'];
		LeadLoc=ReadData(LeadLocFile,1)';
		NChan=148;
		NLeadLoc=197;
		cnt=1;
% 		for FileIndex=1:NFiles
% 			FileIndex=FileIndex
% 			ECfgFilePathOld=ECfgFilePath;
% 			[File,Path,FilePath]=GetFileNameOfMat(FileMat,FileIndex);	
%           Tmp=findstr(File,'.at');
%           ECfgFile=[File(1:Tmp(length(Tmp))-1),'.pmg'];
% 			ECfgFilePath=[Path,ECfgFile];
% 			if ~strcmp(ECfgFilePathOld,ECfgFilePath)
% 				%===================================================================
% 				%===================================================================
% 				[InvSensorMat,NonUse,NonUse,InvCot]=ReadPmgCotSfpFiles(ECfgFilePath,1,1,0);
% 				%============Rotate pmg,cot,sfp around z axis=======================
% 				InvSensorMatTmp=InvSensorMat;
% 				InvSensorMatTmp(:,1)=-1.*InvSensorMat(:,2);
% 				InvSensorMatTmp(:,2)=InvSensorMat(:,1);
% 				InvSensorMatTmp(:,4)=-1.*InvSensorMat(:,5);
% 				InvSensorMatTmp(:,5)=InvSensorMat(:,4);
% 				InvSensorMat=InvSensorMatTmp;
% 				clear InvSensorMatTmp
% 				InvCotTmp=InvCot
% 				InvCotTmp(1)=-1.*InvCot(2);
% 				InvCotTmp(2)=InvCot(1);
% 				InvCot=InvCotTmp;
% 				clear InvCotTmp 
% 				%=============Subtract center of sphere (cot) from sensor positions=======================
% 				for ChanInd=1:NChan
% 					InvSensorMat(ChanInd,1:3)=InvSensorMat(ChanInd,1:3)-InvCot;
% 				end
% 				InvSensorMat=InvSensorMat';
% 				if cnt==1
% 					SumSensorMat=InvSensorMat;
% 				else
% 					SumSensorMat=SumSensorMat+InvSensorMat;
% 					cnt=cnt+1;
% 				end
% 			end
% 		end
% 		ForSensorMat=SumSensorMat./cnt;
		%===================================================================
		[ForSensorMat,NonUse,NonUse,ForCot]=ReadPmgCotSfpFiles('Paul:Matlab:Plot2d3d:Plot2dUtil:SensorCfg:148.pmg',1,1,0);
		%============Rotate pmg,cot,sfp around z axis=======================
		ForSensorMatTmp=ForSensorMat;
		ForSensorMatTmp(:,1)=-1.*ForSensorMat(:,2);
		ForSensorMatTmp(:,2)=ForSensorMat(:,1);
		ForSensorMatTmp(:,4)=-1.*ForSensorMat(:,5);
		ForSensorMatTmp(:,5)=ForSensorMat(:,4);
		ForSensorMat=ForSensorMatTmp;
		clear ForSensorMatTmp
		ForCotTmp=ForCot;
		ForCotTmp(1)=-1.*ForCot(2);
		ForCotTmp(2)=ForCot(1);
		ForCot=ForCotTmp;
		clear ForCotTmp 
		%=============Subtract center of sphere (cot) from sensor positions=======================
		for ChanInd=1:NChan
			ForSensorMat(ChanInd,1:3)=ForSensorMat(ChanInd,1:3)-ForCot;
		end			
		ForSensorMat=ForSensorMat';
		%===================================================================
		InvLFCoeff=zeros(NChan,NLeadLoc,3);
		ForLFCoeff=zeros(NChan,NLeadLoc,3);
		for i=1:NChan
			fprintf(1,'%g of %g sensors done ...\n',i,NChan)
			for j=1:NLeadLoc
				ForLFCoeff(i,j,:)=sphere_meg(ForSensorMat(1:3,i),ForSensorMat(4:6,i),LeadLoc(1:3,j));
			end
		end
		hPmgCotFig=figure('Units','normal','NumberTitle','off','Position',[0 .4 .4 .6]);
		ECfgFilePathOld=[];
		for FileIndex=1:NFiles
			FileIndex=FileIndex
			ECfgFilePathOld=ECfgFilePath;
			[File,Path,FilePath]=GetFileNameOfMat(FileMat,FileIndex);	
			[AvgMat,File,Path,FilePath,NTrialAvgVec,StdChanTimeMat,...
			SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra]=ReadAvgFile(FilePath);
			Data2Analyse=AvgMat(1:NChan,:);
			if CalcBaseStatus
				[AvgMat]=CalcBaseline(AvgMat,MinBase,MaxBase,1,1);
			end
            Tmp=findstr(File,'.at');
            if ~isempty(Tmp)
                ECfgFile=[File(1:Tmp(length(Tmp))-1),'.pmg'];
			else
                ECfgFile=[File,'.pmg'];
			end
			ECfgFilePath=[Path,ECfgFile];
			if ~strcmp(ECfgFilePathOld,ECfgFilePath)
				%===================================================================
				%===================================================================
				[InvSensorMat,NonUse,NonUse,InvCot]=ReadPmgCotSfpFiles(ECfgFilePath,1,1,0);
				%============Rotate pmg,cot,sfp around z axis=======================
				InvSensorMatTmp=InvSensorMat;
				InvSensorMatTmp(:,1)=-1.*InvSensorMat(:,2);
				InvSensorMatTmp(:,2)=InvSensorMat(:,1);
				InvSensorMatTmp(:,4)=-1.*InvSensorMat(:,5);
				InvSensorMatTmp(:,5)=InvSensorMat(:,4);
				InvSensorMat=InvSensorMatTmp;
				clear InvSensorMatTmp
				InvCotTmp=InvCot
				InvCotTmp(1)=-1.*InvCot(2);
				InvCotTmp(2)=InvCot(1);
				InvCot=InvCotTmp;
				clear InvCotTmp 
				%=============Subtract center of sphere (cot) from sensor positions=======================
				for ChanInd=1:NChan
					InvSensorMat(ChanInd,1:3)=InvSensorMat(ChanInd,1:3)-InvCot;
				end
				InvSensorMat=InvSensorMat';
				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)

				for i=1:NChan
					fprintf(1,'%g of %g sensors done ...\n',i,NChan)
					for j=1:NLeadLoc
						InvLFCoeff(i,j,:)=sphere_meg(InvSensorMat(1:3,i),InvSensorMat(4:6,i),LeadLoc(1:3,j));
					end
				end
				
				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
			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)'))';
			clf;
			plot(Data2Analyse(:,1)); hold on; plot(NormData(:,1),'r');
			hold off
			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)
		end
		
    elseif strcmp(action,'CalcMinimumNorm') %| strcmp(action,'CalcMagFieldNorm'),

        hPlot2dList=get(hPlot2dMenuFig,'Userdata');
        hPlot3dList=get(hPlot3dMenuFig,'Userdata');
        hTopMenu=get(hPlot3dList(83),'Userdata');
        hFileMenu=get(hTopMenu(1),'children');
        UseFileMatStatus=get(hFileMenu(1),'Userdata');
        Tmp = get(hPlot3dList(32),'Value');
        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
		if strcmp(action,'CalcMagFieldNorm'),
			Tmp=6;
		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
        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');
        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);
                Data2AnalyseTmp=zeros(NUsedChan,NPoints2Plot);
                for Ind=1:NPoints2Plot
                    Data2AnalyseTmp(:,Ind)=mean(Data2Analyse(:,(Ind-1).*DistPoint+1:Ind.*DistPoint)')';
                end
                Data2Analyse=Data2AnalyseTmp; clear Data2AnalyseTmp;
            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];
            LeadLocIntMat=[1 350;351 547;548 634;635 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==3 | CalcMinNorm2FileStatus==4 & 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);
                [SensorPosNormMat,ENames,SensorNChan,Cot,SfpMat]=ReadPmgCotSfpFiles(ActECfgFilePath,1);
                SensorMat=SensorPosNormMat;
                SensorMat(1,:) = -SensorPosNormMat(2,:)+Cot(2);
                SensorMat(2,:) = SensorPosNormMat(1,:)-Cot(1);
                SensorMat(3,:) = SensorPosNormMat(3,:)-Cot(3);
                SensorMat(4,:) = -SensorPosNormMat(5,:);
                SensorMat(5,:) = SensorPosNormMat(4,:);
                SensorMat(6,:) = SensorPosNormMat(6,:);
                set(hPlot2dList(111),'Userdata',SensorMat);
                EPosCart=SensorMat(:,1:3); 
                [EPosSpher]=change_sphere_cart(EPosCart,[], -1);
                set(hPlot3dList(57),'Userdata',EPosCart); 
            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);
                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,'SOL2')
                    set(hChild2Msgbox,'String',MessageTmp);
                else
                    set(hChildMsgbox(2),'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,'SOL2')
                            set(hChild2Msgbox,'String',Message);
                        else
                            set(hChildMsgbox(2),'String',Message);
                        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);
                                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
                        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
        %=============================================================
		PILFCoeff=[]
		if strcmp(action,'CalcMagFieldNorm') | 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);
            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');
                    pause(.01);
                    LFCoeff=ReadData(LFCoeffFile,1);
                    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,'SOL2')
                    set(hChild2Msgbox,'String',Message);
                else
                    set(hChildMsgbox(2),'String',Message);
                end
                set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                pause(.01);	
                PILFCoeff=pinv_tikh(LFCoeff,MNLambdaApprox); %MNLambdaApprox=regpar
                SaveData(PILFCoeff,PILFCoeffFile,1);
                set(hPlot3dList(97),'Userdata',PILFCoeff);
                close(hmsgbox);
            else
                Message=char(['Read ',EEGMEGStatusString,' pseudo inverse leadfield coefficients from file:']);
                Message=char(Message,PILFCoeffFile);
                hmsgbox=msgbox(Message,'Info:','help'); 
                hChildMsgbox=get(hmsgbox,'Children');
                set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                pause(.1);
                PILFCoeff=ReadData(PILFCoeffFile,1);
                set(hPlot3dList(97),'Userdata',PILFCoeff);
                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);	
			if strcmp(action,'CalcMagFieldNorm'),
				XYZMat=inv_recon(PILFCoeff((LeadLocInt(1)-1).*LFDim+1:LeadLocInt(2).*LFDim,:),Data2Analyse,1);
            	XMat=XYZMat([1:LFDim:LFDim.*NLeadLoc-LFDim+1],:);	
            	YMat=XYZMat([2:LFDim:LFDim.*NLeadLoc-LFDim+2],:);	
                ZMat=XYZMat([3:3:3.*NLeadLoc],:);	
				NormECfg=int2str(NChan);
                ForLFCoeffFile = [PathLFCoeff,filesep,'LF',EEGMEGStatusString(1),'_',LeadLocCfg,'_',NormECfg];
                %LFE if EEG; LFM if MEG
                ForLFCoeffFid=exist(ForLFCoeffFile);
                if ForLFCoeffFid~=2
					[ForSensorMat,NonUse,NonUse,ForCot]=ReadPmgCotSfpFiles('Paul:Matlab:Plot2d3d:Plot2dUtil:SensorCfg:148.pmg',1,1,0);
					%============Rotate pmg,cot,sfp around z axis=======================
					ForSensorMatTmp=ForSensorMat;
        			ForSensorMatTmp(:,1)=-1.*ForSensorMat(:,2);
					ForSensorMatTmp(:,2)=ForSensorMat(:,1);
					ForSensorMatTmp(:,4)=-1.*ForSensorMat(:,5);
					ForSensorMatTmp(:,5)=ForSensorMat(:,4);
					ForSensorMat=ForSensorMatTmp;
        			clear ForSensorMatTmp
        			ForCotTmp=ForCot;
        			ForCotTmp(1)=-1.*ForCot(2);
					ForCotTmp(2)=ForCot(1);
        			ForCot=ForCotTmp;
        			clear ForCotTmp 
					%=============Subtract center of sphere (cot) from sensor positions=======================
        			for ChanInd=1:NChan
		    			ForSensorMat(ChanInd,1:3)=ForSensorMat(ChanInd,1:3)-ForCot;
        			end
					RotDegVal=0;%15; %degrees backward rotation around x-axis (LPA-RPA)
       				EPosCart=ForSensorMat(:,1:3); 
        			EPosCart=XRotation(EPosCart,RotDegVal);
       				EDirCart=ForSensorMat(:,4:6); 
        			EDirCart=XRotation(EDirCart,RotDegVal);
        			ForSensorMat(:,1:3)=EPosCart;
        			ForSensorMat(:,4:6)=EDirCart;
					Message=['Calculate ' EEGMEGStatusString ' forward leadfield coefficients'];
					Message=char(Message,'and save them to file:');
					Message=char(Message,ForLFCoeffFile);
                    [ForLFCoeff,Orientations,v]=compute_lfdmat(LeadLoc(:,1:3)',ForSensorMat',EEGMEGStatusString,CoorStatusString,[],Message);
                    SaveData(ForLFCoeff,ForLFCoeffFile,1);
                else
                    Message=char(['Read ' EEGMEGStatusString ' forward leadfield coefficients from file:']);
                    Message=char(Message,ForLFCoeffFile);
                    Message=char(Message,' ');
                    hmsgbox=msgbox(Message,'Info:','help'); 
                    hChildMsgbox=get(hmsgbox,'Children');
                    set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                    pause(.01);
                    ForLFCoeff=ReadData(ForLFCoeffFile,1);
                    close(hmsgbox);
               	end
				ForPILFCoeff=pinv_tikh(ForLFCoeff,MNLambdaApprox);
				ForPILFCoeff(1:10,1)-PILFCoeff(1:10,1)
				size(ForLFCoeff)
				LFDim=LFDim
 				max(max(LFCoeff))
				max(max(ForLFCoeff))
				pause
				XForLFCoeff=ForLFCoeff(:,[1:LFDim:LFDim.*NLeadLoc-LFDim+1]);
				YForLFCoeff=ForLFCoeff(:,[2:LFDim:LFDim.*NLeadLoc-LFDim+2],:);	
                ZForLFCoeff=ForLFCoeff(:,[3:3:3.*NLeadLoc],:);	
				size(ZForLFCoeff)
                NormData=((XMat' * XForLFCoeff')+(YMat' * YForLFCoeff')+(ZMat' * ZForLFCoeff'))';
				max(max(Data2Analyse))
				max(max(NormData))
				figure; plot(Data2Analyse(:,1)); hold on; plot(NormData(:,1),'r');
				pause
				%NormData=NormData./10^15;
				hPmgCotFig=figure('Units','normal','NumberTitle','off','Position',[0 0 .8 .92]);
				plot3(SensorMat(:,1),SensorMat(:,2),SensorMat(:,3),'bo')
      			hold on
				quiver3(SensorMat(:,1),SensorMat(:,2),SensorMat(:,3),SensorMat(:,4),SensorMat(:,5),SensorMat(:,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
				return
 				SaveAvgFile('Data:M/EEGData:MEG:FP:FPP:01:1.1:Test.at3',NormData,zeros(NChan,1),zeros(size(NormData)),SampRate,zeros(NChan,1),zeros(NChan,1),2);		
			else	
            	%MNMat=MNMat.*10.^6; %nA/m^2 => nA/mm^2
            	[NMNMat,NoUse]=size(MNMat);
            	%=====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==4 %CalcMinNorm2FileShell
           	         	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,'Plot2dUtil',filesep,'SensorCfg',filesep,int2str(NChan),'.ecfg'];
                            	elseif CalcMinNorm2FileStatus==3
                            	    ECfgTmpFilePath=[BasePath,'Plot2dUtil',filesep,'SensorCfg',filesep,int2str(NLeadLoc),'.ecfg'];
                            	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
			end
            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);
            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
    
        Plot3d('setAutoAmp')	
        Plot3d('chSaveDataLabelString')	
        Plot3d('EnableOnOff')	
        Plot3d('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);
        
    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);
        end
        set(hPlot3dList(106),'Userdata',ScalpLocIndVec);
        %============================================================================	
        %============ 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)
            Plot3d('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,'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); 
        
        Plot3d('setAutoAmp')
        Plot3d('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,[],[],[],[],[],'Choose the data to subtract:');
        [CalcPotChan2]=ReadData(FilePath,1,[],[],[],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); 
            Plot3d('setAutoAmp')
            Plot3d('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,'PlotSurfData'),

        hPlot2dList=get(hPlot2dMenuFig,'Userdata');
        hPlot3dList=get(hPlot3dMenuFig,'Userdata');
        PlotSurfStatus=get(hPlot3dList(84),'Value');
        if PlotSurfStatus==0; return; 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');
        
        set(hPlot3dList(33),'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);
        
        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');
        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');
        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');
        
        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;
    MovieFigPos=[0 .5 .4 .5];
    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	

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
MovieFig=figure('Units','normal',...
'Position',MovieFigPos,...
'Color',BackGroundColor,...
'NumberTitle','off',...
'Name',FigName);
pause(0.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
% 	ColorFacVec=[1:size(ColorMat,1)].^1.25;
% 	ColorFacVec=norm_1(ColorFacVec,1)
% 	for i=1:3
% 		ColorMat(:,i)=ColorFacVec'.*ColorMat(:,i);
% 	end
% 	ColorMat=ColorMat
if FlipColormapStatus; ColorMat=flipud(ColorMat); 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

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

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
        hSurf0=surf(XScalp,YScalp ,ZScalp,CalcPotTmp);
        if ActMethod==6  & ~AbsMinNormSurfStatus	
            set(hSurf0,'Visible','off');
        end
        caxis([MinAmpTmp MaxAmpTmp]);
        view(ThetaView,PhiView);
        shading interp;
        
        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 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
            PlotECPositions(ScalpCortStatus,3,0,ForeGroundColor,1,EPosSpher(ChanStatusOnVec(SensorVisVec),:),...
            Radius,SensorCircleStatus,SensorAsteriskStatus,SensorNameStatus,SensorNames(ChanStatusOnVec(SensorVisVec),:))
        end
        if PlotContourStatus~=3 & HeadView<7
            plot_head_contour(MovieAxesPos(5,:),ScalpCortStatus,HeadView,ForeGroundColor,1)
        end
        hold off
        if MovieIndex==1 | ~SpecAmpStatus
            if MovieIndex>1
                set(hPColorAxes,'XTickLabels',[]);
            end
            hPColorAxes=axes('Units','normal','Position',MovieAxesPos(2,:),'FontSize',FontSizeVec(1));
            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
                pcolor([0 1],XPColor,(ones(2,1)*XPColor)'); 
                set(gca,'XTick',[],'XTickLabel',[],'FontSize',FontSizeVec(1),...
                'XColor',ForeGroundColor,'YColor',ForeGroundColor,'ZColor',ForeGroundColor,'FontWeight','Normal')
                hold off		
            end
            shading interp;
        end
        if Dim2d3dViewVal==5; return; end
        %========================================================================
        if MovieIndex==1;	
            title(PotLapColorString,'Color',ForeGroundColor,'FontSize',FontSizeVec(1));	
            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
            hPointText=text('Units','normal','Position',[.25,.6],'Color',ForeGroundColor,'String',num2str(round(xTimePotVec(MinPoint+DistPoint.*(MovieIndex-1)).*10)/10),'FontSize',FontSizeVec(2),'HorizontalAlignment','left');
            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
            set(hPointText,'String',[num2str(round(xTimePotVec(MinPoint+DistPoint.*(MovieIndex-1)).*10)/10),' - ',num2str(round(xTimePotVec(MinPoint-1+DistPoint.*MovieIndex).*10)/10)]);
        else
            set(hPointText,'String',num2str(round(xTimePotVec(MinPoint+DistPoint.*(MovieIndex-1)).*10)./10));
        end
        %========================================================================
        if MovieIndex==1;
            hAxes1=axes('Units','normal',...
            'Position',MovieAxesPos(3,:),...
            'Color',BackGroundColor,...
            'XColor',ForeGroundColor,...
            'YColor',ForeGroundColor,...
            'FontSize',FontSizeVec(1));
        else
            axes(hAxes1);
            set(hAxes1,'NextPlot','Replace');
        end
    
        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
        
        %========================================================================
        if MovieIndex==1
            hAxes2=axes('Units','normal',...
            'Position',MovieAxesPos(4,:),...
            'Color',BackGroundColor,...
            'XColor',ForeGroundColor,...
            'YColor',ForeGroundColor,...
            'FontSize',FontSizeVec(1));
        else
            axes(hAxes2);
            set(hAxes2,'NextPlot','Replace');
        end
        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
    
        %========================================================================
		
        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
                hSurfTmp=surf(XScalp,YScalp ,ZScalp,CalcPotTmp);
                if ActMethod==6  & ~AbsMinNormSurfStatus	
                    set(hSurfTmp,'Visible','off');
                end		
                caxis([MinAmpTmp MaxAmpTmp])
                view(ViewVec(ViewHeadIndVec(AxesInd),:));	
                shading interp;
                [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 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
                if PlotContourStatus~=3
                    plot_head_contour(MovieAxesPos(MovieAxesPosIndVec(AxesInd),:),ScalpCortStatus,ViewHeadIndVec(AxesInd),ForeGroundColor,1)
                end
                hold off
            end
        end
        hold off
        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(.1); 
            end
        end
    end

    %=========================================================================
    %=========================================================================
    
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
            axes('Units','normal','Position',MovieAxesPos(AxesInd,:));
            hSurf0=surf(XScalp,YScalp ,ZScalp,CalcPotTmp);
            if ActMethod==6 & ~AbsMinNormSurfStatus; set(hSurf0,'Visible','off'); end
            caxis([MinAmpTmp MaxAmpTmp])
            view(ThetaView,PhiView);
            shading interp;
            axis('off')
            hold on
            if ActMethod==6 & QuiverStatus
                quiver3(XScalp,YScalp,ZScalp,XMatTmp,YMatTmp,ZMatTmp,1.5)
            end
            hold off
            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
            if (PlotContourStatus==1 & AxesInd==1) | PlotContourStatus==2
                plot_head_contour(MovieAxesPos(AxesInd,:),ScalpCortStatus,HeadView,ForeGroundColor,1)
            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
            hPointText=text('Units','normal','Position',[.5,1.05],'Color',ForeGroundColor,'String',TimeFrquString,'FontSize',FontSizeVec(2),'HorizontalAlignment','center','FontWeight','bold');
            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
                set(hPointText,'Position',[.5,1.05],'String',TimeFrquString);
            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

elseif Dim2d3dViewVal==6	%Columns & Rows

    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
        axes('Units','normal','Position',MovieAxesPos(TimeInd,:));
        hSurf0=surf(XScalp,YScalp ,ZScalp,CalcPotTmp);
        if ActMethod==6 & ~AbsMinNormSurfStatus; set(hSurf0,'Visible','off'); end
        caxis([MinAmpTmp MaxAmpTmp])
        view(ThetaView,PhiView);
        shading interp;
        axis('off')
        hold on
        if ActMethod==6 & QuiverStatus
            quiver3(XScalp,YScalp,ZScalp,XMatTmp,YMatTmp,ZMatTmp,1.5)
        end
        hold off
        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
        if (PlotContourStatus==1 & TimeInd==1) | PlotContourStatus==2
            plot_head_contour(MovieAxesPos(TimeInd,:),ScalpCortStatus,HeadView,ForeGroundColor,1)
        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
        hPointText=text('Units','normal','Position',[.5,1.02],'Color',ForeGroundColor,'String',TimeFrquString,'FontSize',ActFontSize,'HorizontalAlignment','center','FontWeight','bold');
        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

