function varargout = emegs2d(action,varargin)   
%   emegs2d opens a userinterface to load, display and analyze event
%   related and continuous EEG and MEG data. See '2d-visualization'
%   in the documentation for detailed description.
%
%   Type 'EE' as a shortcut to open emegs2d in EEG-mode, 'EM' to 
%   open it in MEG-mode. 
%   
%   See also EMEGS3D.

%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Markus Junghöfer & Peter Peyk
%   Contributors:   Olaf Hauk, Andreas Keil,                   
%   Thomas Gruber, Andrea de Cesarei, Nathan Weisz.  
%   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.                                                                      




%================= global variables =============================================
%checkin
global hPlot2dMenuFig hPlot3dMenuFig hEOGFig hEKGFig hCorPicFig SensorPosNormMathGetFrequIntervalMenuFig hPlot2dChanFig

% 	Possible actions and button callbacks:
%================================================================================	

if nargin<1; action='InitializeMenue'; end

HistStatus=0;
if HistStatus
	HistFile='emegs2dHist.m';
	HistFilePath=which(HistFile);
	HistFid=fopen(HistFilePath,'a+','b');
	if HistFid==-1
		HistPath=which('emegs2d');
		if ~strcmp(HistPath(length(HistPath)),filesep)
			HistPath=[HistPath,filesep];
		end
		HistFilePath=[HistPath,HistFile];
		HistFid=fopen(HistFilePath,'a+','b');
		if HistFid==-1
			fprintf(1,'Unable to open file for Plot2d action history writing:' )
			fprintf(1,HistFilePath);
			return;
		end
	end
	fprintf(HistFid,['emegs2d(''',action,''');\n']);
	fclose(HistFid);
end
if strcmp(action,'InitializeMenue'),
    MaxNFiles=6;
	NFiles=MaxNFiles;
    hEOGFig=[];
    hEKGFig=[];
	hCorPicFig=[];
	%============ MatlabVersion =================================================	
	Plot2dVersionString='SCADS';						% hList(97); NotSpec, SCADS, Eugene; Neuroscan
	Plot2dVersion=str2num('1.0');						% hList(98)
	MatlabVersionString=version;						% hList(99)
	MainMatlabVersion=str2num(MatlabVersionString(1));	% hList(100)
	%============================================================================
	%============ check working directory =======================================
	%============================================================================
	clc;
	[BasePath,SepPathStr]=StartPath('emegs2d.m');
	if isempty(BasePath) 
		return;	
	end;

	%========== default avg und sensor configuration file format =============
    if strcmp(Plot2dVersionString,'NotSpec')  
      DefAvgFileFormat='Auto'; AvgFileFormatVal=17; DefAvgFileFormatExt='*.*';
      DefECFileFormat='SCADS';  ECFileFormatVal=6; 	% SCADS
    elseif strcmp(Plot2dVersionString,'Eugene')  
		DefAvgFileFormat='AvgEgis'; AvgFileFormatVal=13; DefAvgFileFormatExt='*.avg*';
		DefECFileFormat='SCADS';  ECFileFormatVal=6; % SCADS
	elseif strcmp(Plot2dVersionString,'Neuroscan')  
		DefAvgFileFormat='NeuroscanCnt'; AvgFileFormatVal=15; DefAvgFileFormatExt='*.cnt*';
		DefECFileFormat='SCADS';  ECFileFormatVal=6; % SCADS
	elseif strcmp(Plot2dVersionString,'Egis')  
		DefAvgFileFormat='RawEgis'; AvgFileFormatVal=10; DefAvgFileFormatExt='*.ses*';
		DefECFileFormat='SCADS';  ECFileFormatVal=6; % SCADS
	else 
		DefAvgFileFormat='SCADS'; AvgFileFormatVal=9; DefAvgFileFormatExt='*.at*';
        DefECFileFormat='SCADS';  ECFileFormatVal=6;  % SCADS
	end

	%============================================================================
   	%=========== INITIALIZE MENU ================================================
	%============================================================================
	
	%============== figure with graphs =========================		
   	if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
		ChanFigPosVec=[0 0 0.6 1];	
		MenuFigPosVec=[.6224 0 .2 1];
	elseif strcmp(computer,'PCWIN') 
		ChanFigPosVec=[0 .02 .6 .9];  
		MenuFigPosVec=[.6 .02 0.2 .9];
	elseif strcmp(computer,'SOL2') | strcmp(computer,'LNX86') | strcmp(computer,'GLNX86')
		ChanFigPosVec=[0.01 0.00 .601 0.92];  
		MenuFigPosVec=[0.6224 0.00 0.2 0.89];	
    else
        ChanFigPosVec=[0.01 0.00 .601 0.92];  
		MenuFigPosVec=[0.6224 0.00 0.2 0.89];	
	end;

	%===================================
    % Open figure for data display
	%===================================
   	Plot2dChanFigString='emegs2d Data:';
	CloseRequestFcnStr='emegs2d(''ClosePlot2dChanFig'')';
    set(0,'DefaultFigureCreateFcn','emegs2dopenchan;');
   	hPlot2dChanFig=figure('Units','normal','Position',ChanFigPosVec, ...
	'Name',Plot2dChanFigString,'Color',[1 1 1], ...
	'NumberTitle','off', ...
	'CloseRequestFcn',CloseRequestFcnStr,...
    'MenuBar','none');
	hPlot2dChanAxes=axes('Position',[0 0 1 1],'Visible','off');

	%===================================
    % Open menu figure
	%===================================
    set(0,'DefaultFigureCreateFcn','emegs2dopenmenu;');	
	Plot2dMenuFigString=['emegs2d Menu:'];
	CloseRequestFcnStr='emegs2d(''ClosePlot2dMenuFig'')';
   	hPlot2dMenuFig=figure('Units','normal','Position',MenuFigPosVec, ...
	'Name',Plot2dMenuFigString,'Color',[.99 .99 .99], ...
	'NumberTitle','off', ...
	'CloseRequestFcn',CloseRequestFcnStr,...
    'MenuBar','none','tag','Plot2dMenuFig');
    set(0,'DefaultFigureCreateFcn','');
    
    % 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.0375;
    btnHt_edit=0.050;
    textHeight = 0.05;		
    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 0 0.3];
   	hConsolFrame=uicontrol( ...
	'Style','frame', ...
	'Units','normalized', ...
	'Position',frmPos, ...
	'BackgroundColor',ConsoleRGBColor);
	
 	%==============================================================
    % Selection of actual data set (popupmenu) ====================
	% default file numer: 1 =======================================
	% callback: setActFileNo ======================================
	%==============================================================
	
	btnNumber=1;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelWidth = btnWid./2;
	labelBottom=yPos-textHeight./1.5;
	labelLeft = left;
	labelPos = [labelLeft labelBottom labelWidth textHeight];
   	hActFileNoText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',labelPos, ...
	'Horiz','center', ...
	'String','Actual Data Set', ...
	'Interruptible','off', ...
	'BackgroundColor',ConsoleRGBColor, ...
	'ForegroundColor','white',...
	'Enable','on');
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt btnWid./2 btnHt];
   	labelStr='Data set: 1; not used|Data set: 2; not used|Data set: 3; not used|Data set: 4; not used|Data set: 5; not used|Data set: 6; not used';
	callbackStr='emegs2d(''setActFileNo'')';
	tooltipstring = 'selects the active dataset';
	ActFileNo=1;	% default actual data set number
	
	hActFileNo=uicontrol( ...
	'Style','popupmenu', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',labelStr, ...
	'Interruptible','on', ...
	'Userdata',ActFileNo,...
	'value',ActFileNo,...
	'Callback',callbackStr,...
	'ToolTipString',tooltipstring, ...
	'Enable','off');
	
 	%==============================================================
    % Open Data Set (AVG-Format)==================================
	%==============================================================
	btnNumber=1;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	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','Open Data Set', ...
	'Interruptible','off', ...
	'BackgroundColor',ConsoleRGBColor, ...
	'ForegroundColor','white',...
	'Enable','on');
	
	btnNumber=1;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'emegs2d(''PrepOpenAvgFile'')';
	tooltipstring = 'reads a data file into the active data set';
	hOpenAvgFile=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Open Data Set', ...
	'ToolTipString',tooltipstring, ...
	'Userdata','0', ...
	'Value',0, ...
	'Callback',callbackStr,...
	'Enable','on');

	%====================================
	% AllSpecVisible popupmenu 
	%===================================
    
    btnNumber=3;
  	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelPos = [left yPos-textHeight./1.5 labelWidth textHeight];
   	hAllSpecVisibleText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',labelPos, ...
	'Horiz','center', ...
	'String','Extract sensor (All)', ...
	'Interruptible','off', ...
	'BackgroundColor',ConsoleRGBColor, ...
	'ForegroundColor','white',...
	'Enable','on');
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'emegs2d(''setAllSpecVisible'')';
	tooltipstring = 'extracts/enables a sensor in all datasets';
	hAllSpecVisible=uicontrol( ...
    'Style','popupmenu', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','Enable all', ...
    'Userdata',1,...
    'Value',1,...        
    'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
    'Enable','off');
    
	%==============================================================
	% ActSpecVisible (push button) ================================
	% callback: setActSpecVisible =================================
	%==============================================================
	
	btnNumber=3;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelWidth = btnWid./2;
	labelBottom=yPos-textHeight./1.5;
	labelLeft = left+btnWid./2;
	labelPos = [labelLeft labelBottom labelWidth textHeight];
   	hActSpecVisibleText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',labelPos, ...
	'Horiz','center', ...
	'String','Extract sensor (Act)', ...
	'Interruptible','off', ...
	'BackgroundColor',ConsoleRGBColor, ...
	'ForegroundColor','white',...
	'Enable','on');
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr='emegs2d(''setActSpecVisible'')';
	tooltipstring = 'extract/enables a sensor in the active dataset';
	
	hActSpecVisible=uicontrol( ...
	'Style','popupmenu', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Enable all', ...
	'Horiz','center',...
	'Userdata',1,...
	'Value',1,...
	'Callback',callbackStr,...
	'ToolTipString',tooltipstring, ...
	'Enable','off');

	
   	%==============================================================
	% Color Selection of actual data set data 
	% callback: setColor 
	%==============================================================
	
	btnNumber=2;    
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelBottom=yPos-textHeight./1.5;
	labelPos = [left labelBottom btnWid./3 textHeight];
   	hColorText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',labelPos, ...
	'Horiz','center', ...
	'String','Line Color', ...
	'Interruptible','off', ...
	'BackgroundColor',ConsoleRGBColor, ...
	'ForegroundColor','white',...
	'Enable','on');
	
	ColorFileVec=[4 6 1 5 7 8];
	RGBColorMat=[0 0 0 ; ...	%1
	1 1 1 ; ...	%2
	1 1 0 ; ...	%3
	1 0 0 ; ...	%4
	0 1 0 ; ...	%5
	0 0 1 ; ...	%6
	1 0 1 ; ...	%7
	0 1 1 ];	%8
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt btnWid./3 btnHt];
   	labelStr='black|white|yellow|red|green|blue|magenta|cyan|insert RGB|-------|hsv|hot|cool|jet|pink|flag|copper|gray';
	callbackStr='emegs2d(''setColor'')';
	tooltipstring = 'sets the line color for the active dataset';
	
	hColor=uicontrol( ...
	'Style','popupmenu', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',labelStr, ...
	'Interruptible','on', ...
	'Userdata',RGBColorMat(ColorFileVec(1),:),...	
	'Value',ColorFileVec(1),...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');  
	
  	%==============================================================
	% The LineStyle Selection =====================================
	% default color: solid ========================================
	% callback: setLineStyle ======================================
	%============================================================== 	
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelBottom=yPos-textHeight./1.5;
	labelPos = [left+btnWid./3 labelBottom btnWid./3 textHeight];
   	hLineStyleText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',labelPos, ...
	'Horiz','center', ...
	'String','Line Style', ...
	'Interruptible','off', ...
	'BackgroundColor',ConsoleRGBColor, ...
	'ForegroundColor','white',...
	'Enable','on');
	
	LineStyleFileVec=[1 1 1 1];
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./3 yPos-btnHt btnWid./3 btnHt];
   	labelStr='solid|dashed|dashdot|dotted';
	callbackStr='emegs2d(''setLineStyle'')';
	tooltipstring = 'sets the line style for the active data set';
	
	hLineStyle=uicontrol( ...
	'Style','popupmenu', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',labelStr, ...
	'Interruptible','on', ...
	'Userdata','-',...
	'Value',LineStyleFileVec(1),...
    'ToolTipString',tooltipstring, ...
	'Callback',callbackStr,...
	'Enable','off');
	
  	%==============================================================
	% The LineWidth Selection =====================================
	% default width: 1 ========================================
	% callback: setLineWidth ======================================
	%============================================================== 	
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelBottom=yPos-textHeight./1.5;
	labelPos = [left+2.*btnWid./3 labelBottom btnWid./3 textHeight];
   	hLineWidthText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',labelPos, ...
	'Horiz','center', ...
	'String','Line Width', ...
	'Interruptible','off', ...
	'BackgroundColor',ConsoleRGBColor, ...
	'ForegroundColor','white',...
	'Enable','on');
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+2.*btnWid./3 yPos-btnHt btnWid./3 btnHt];
   	labelStr='0.50 Act|1.00 Act|1.50 Act|2.00 Act|2.50 Act|3.00 Act|0.50 All|1.00 All|1.50 All|2.00 All|2.50 All|3.00 All';
	callbackStr='emegs2d(''setLineWidth'')';
	tooltipstring = 'sets the line width for the active dataset';
	
	hLineWidth=uicontrol( ...
	'Style','popupmenu', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',labelStr, ...
	'Interruptible','on', ...
	'Userdata',ones(MaxNFiles,1),...
    'ToolTipString',tooltipstring, ...
	'Value',8, ... 
	'Callback',callbackStr,...
	'Enable','off');

	%==============================================================
	% ActSpecAllVisible (radio button)=============================
	% callback: setActAllVisible ==================================
	%==============================================================
	btnNumber=4;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 btnWid./2 btnHt./2];
	callbackStr='emegs2d(''setActAllVisible'')';
	tooltipstring = 'hides/unhides the entire active dataset';
	
	hActAllVisible=uicontrol( ...
	'Style','radiobutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Visible Set', ...
	'Userdata',ones(MaxNFiles,1),...
    'ToolTipString',tooltipstring, ...
	'Value',1,...
	'Callback',callbackStr,...
	'Enable','off');

	%==============================================================
	% Clear actual data set (push button)==============================
	% callback: ClearActFile ======================================
	%============================================================== 	
	
	btnNumber=4;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt btnWid./2 btnHt./2];
	
	callbackStr = 'emegs2d(''ClearActFile'')';
	tooltipstring = 'clears the active dataset';
	hClearActFile=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Clear Set', ...
	'Userdata','0', ...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%====================================
	% ZoomSpecChannel push button 
	%===================================
	btnNumber=4;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelPos = [left+btnWid./2 yPos-textHeight./1.5 btnWid./2 textHeight];
	hZoomSpecChanText = uicontrol( ...
    'Style','text', ...
    'Units','normalized', ...
    'Position',labelPos, ...
    'Horiz','left', ...
    'String','Zoom:', ...
    'Interruptible','off', ...
    'BackgroundColor',ConsoleRGBColor, ...
    'ForegroundColor','white',...
	'Enable','on',...
    'Visible','off');

	%===================================
	% MouseZoom toggle button 
	%===================================
	btnNumber=4;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelPos = [left+btnWid./2 yPos-btnHt btnWid./2 btnHt/2];
	tooltipstring = 'turns on/off zoom sensor selection by mouseclick';
	hZoomToggleButton = uicontrol( ...
    'Style','togglebutton', ...
    'Units','normalized', ...
    'Position',labelPos, ...
    'Horiz','center', ...
    'String','Mouse', ...
    'ForegroundColor','black',...
    'ToolTipString',tooltipstring, ...
	'Enable','off',...
    'Callback','emegs2d(''ToggleMouseZoom'');');
    
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'emegs2d(''ZoomSpecChan'')';
	tooltipstring = 'zooms the selected sensor';
	hZoomSpecChan=uicontrol( ...
    'Style','popupmenu', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','Zoom Sensor', ...
    'HorizontalAlignment','center',...
    'Userdata','0', ...
    'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
    'Enable','off');		
	
	%===================================
	% Plot3d push button
	%===================================
	btnNumber=5;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	
	btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'emegs2d(''Plot3d'')';
	tooltipstring = 'opens the emegs3d menu';
	hPlot3d=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Emegs3d', ...
	'Userdata','0', ...
	'Enable','off', ...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	
	%===================================
	% EEG / MEG push button
	%===================================
	btnNumber=5;
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelWidth = btnWid./2;
	labelBottom=yPos-textHeight./1.5;
	labelLeft = left+btnWid./2;
	labelPos = [labelLeft labelBottom labelWidth textHeight];
   	hColorText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',labelPos, ...
	'Horiz','center', ...
	'String','EEG / MEG Status', ...
	'Interruptible','off', ...
	'BackgroundColor',ConsoleRGBColor, ...
	'ForegroundColor','white',...
	'Enable','on');
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'emegs2d(''SetEegMegStatus'')';
	tooltipstring = 'toggles between EEG and MEG mode';
	if strcmp(computer,'SOL2'); 
		EegMegStatus=2; EegMegStatusStr='MEG'; 
	else
		EegMegStatus=1; EegMegStatusStr='EEG'; 
	end
	hSetEegMegStatus=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',EegMegStatusStr, ...
	'Userdata',EegMegStatus, ...
	'Enable','on', ...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','on');
	
	%===================================
	% The View Selection
	%===================================
	btnNumber=6;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt btnWid./2 btnHt];
	labelStr='View: Top|View: Front|View: Back|View: Left|View: Right|View: Norm';
	callbackStr='emegs2d(''setView'')';
	tooltipstring = 'chooses the type of 2d channel arrangement';
	
	hView=uicontrol( ...
	'Style','popupmenu', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',labelStr, ...
	'Interruptible','on', ...
	'Userdata','Norm',...
	'Value',6,...
	'Min',0,...
	'Max',6,...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================
	% The Domain Selection
	%===================================
	btnNumber=6;     
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	labelStr='Domain: Time|Domain: Std|Domain: Power FFT|Domain: Phase FFT|Domain: PCA|Domain: Amp. Wavelet|Domain: Phaselock Wavelet|Domain: Amp. W. II';
	callbackStr='emegs2d(''setDomain'')';
	tooltipstring = 'selects the data domain';
	hDomain=uicontrol( ...
	'Style','popupmenu', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',labelStr, ...
	'Interruptible','on', ...
	'Userdata','Time',...
	'Value',1,...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	Tmp=get(hDomain,'String');
	NDomain=size(Tmp,1);
    
	%===================================
	% 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', ...
	'String','Min. amplitude [µV]',...
	'Enable','off');
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 1.*btnHt_edit./2];
	callbackStr = 'emegs2d(''setMinAmp'')';
	tooltipstring = 'sets the minimum amplitude displayed';
	hMinAmp = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String','0',...
	'Value',0,...
	'Userdata',zeros(NDomain,1), ... %number of domains
	'callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');

	%===================================
	% MaxAmpHandle
	%===================================
	btnNumber=7;     
	btnPos=[left yPos-btnHt_edit 2.*btnWid./3 btnHt_edit./2];
	
	hMaxAmpText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String','Max. amplitude [µV]',...
	'Enable','off');
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
	callbackStr = 'emegs2d(''setMaxAmp'')';
	tooltipstring = 'sets the maximum amplitude displayed';
	
	hMaxAmp = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String','0',...
	'Value',0,...
	'Userdata',zeros(NDomain,1), ... 
    'ToolTipString',tooltipstring, ...
	'callback',callbackStr,...
	'Enable','off');
	%===================================
	%===================================
	
	btnNumber=8;     
	
	%===================================
	% Adjust Amplitude
	%===================================
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 2*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''AdjustAmp'')';
	tooltipstring = 'automatically chooses max. and min. amp. to plot all data';
	hAdjustAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Adjust', ...
	'HorizontalAlignment','center',...
	'Userdata',[], ...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================
	% Center Amplitude
	%===================================
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt 2*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''CenterAmp'')';
	tooltipstring = 'chooses max. and min. amp. with equal absolute value';
	hCenterAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Center', ...
	'HorizontalAlignment','center',...
    'ToolTipString',tooltipstring, ...
	'Callback',callbackStr,...
	'Enable','off');
	
	%===================================
	% Decrease/Increase  Amplitude
	%===================================
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+2.*btnWid./8 yPos-btnHt./2 2.*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''DecIncStatus'')';
	tooltipstring = 'steps through scale modes';
	hDecIncStatusAmp = uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'HorizontalAlignment','Center',...
	'Userdata',[0 1],...
    'ToolTipString',tooltipstring, ...
	'String','+/- 1',...
	'Callback',callbackStr,...
	'Enable','off');
	
	%===================================
	% Invert View
	%===================================
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+2.*btnWid./8 yPos-btnHt 2*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''InvertViewAmp'')';
	tooltipstring = 'toggles polarity direction';
	hInvertViewAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Polarity', ...
	'Userdata',1,...
	'HorizontalAlignment','center',...
    'ToolTipString',tooltipstring, ...
	'Callback',callbackStr,...
	'Enable','off');
	
	%==================================================
	% Slow Decrease  of Amplitude
	%===================================
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+4.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''DecAmp'')';
	tooltipstring = 'decreases abs(min.amp) and abs(max.amp)';
	hDecAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','<', ...
	'HorizontalAlignment','center',...
    'ToolTipString',tooltipstring, ...
	'Callback',callbackStr,...
	'Enable','off');
	
	%===================================
	% Decrease Decrease/Increase Amplitude
	%===================================
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+5.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''DecDecIncAmp'')';
	tooltipstring = 'decreases scaling steps';
	hDecDecIncAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','<<', ...
	'HorizontalAlignment','Center',...
    'ToolTipString',tooltipstring, ...
	'Callback',callbackStr,...
	'Enable','off');
	
	%===================================
	% Increase Decrease/Increase Amplitude
	%===================================
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+6.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''IncDecIncAmp'')';
	tooltipstring = 'increases scaling steps';
	hIncDecIncAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','>>', ...
	'HorizontalAlignment','Center',...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================
	% Slow Increase of Amplitude
	%===================================
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+7.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''IncAmp'')';
	tooltipstring = 'increases abs(min.amp) and abs(max.amp)';
	hIncAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','>', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================
	% MinPointHandle
	%===================================
	
	btnNumber=9;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
	
	hMinPointText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String','Min. time [ms]; # 0',...
	'Enable','off');
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'emegs2d(''setMinPoint'')';
	tooltipstring = 'sets the first time point displayed';
	
	hMinPoint = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String','0',...
	'Value',0,...
	'Userdata',ones(NDomain,1), ...
	'callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================
	%MinPointSlider
	%===================================
	btnPos=[left yPos-btnHt_edit btnWid btnHt_edit./2];
	callbackStr = 'emegs2d(''setMinPointSlider'')';
	tooltipstring = 'sets the first time point displayed';
	hMinPointSlider=uicontrol( ...
	'Style','slider', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Min. Point', ...
	'HorizontalAlignment','center',...
	'Userdata',[], ...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================	
	% MaxPointHandle
	%===================================
	btnNumber=10;    
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
	
	hMaxPointText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String','Max. time [ms]; # 0',...
	'Enable','off');
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'emegs2d(''setMaxPoint'')';
	tooltipstring = 'sets the last time point displayed';
	
	hMaxPoint = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String','0',...
	'Value',0,...
	'Userdata',ones(NDomain,1), ...	 
	'callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================
	%MaxPointSlider
	%===================================
	btnPos=[left yPos-btnHt_edit btnWid btnHt_edit./2];
	callbackStr = 'emegs2d(''setMaxPointSlider'')';
	tooltipstring = 'sets the last time point displayed';
	hMaxPointSlider=uicontrol( ...
	'Style','slider', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Max. Point', ...
	'HorizontalAlignment','center',...
	'Userdata',[], ...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================
	% CursorPointHandle
	%===================================
	btnNumber=11;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
	
	hCursorPointText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String','Curs. time [ms]; # 0',...
	'Enable','off');
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'emegs2d(''setCursorPoint'')';
	tooltipstring = 'sets the time point of a cursor line';
	
	hCursorPoint = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String','0',...
	'Value',1,...
	'Userdata',ones(NDomain,1), ...
	'callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================
	%CursorPointSlider
	%===================================
	btnPos=[left yPos-btnHt_edit btnWid btnHt_edit./2];
	callbackStr = 'emegs2d(''setCursorPointSlider'')';
	tooltipstring = 'sets the time point of a cursor line';
	hCursorPointSlider=uicontrol( ...
	'Style','slider', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Max. Point', ...
	'HorizontalAlignment','center',...
	'Userdata',[], ...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================
	% TrigPointHandle
	%===================================
	btnNumber=12;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt_edit 2.*btnWid./3 btnHt_edit./2];
	
	hTrigPointText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String','Trigger point',...
	'Enable','off');
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
	callbackStr = 'emegs2d(''setTrigPoint'')';
	tooltipstring = 'sets the zero time point (t = 0ms)';
	
	hTrigPoint = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String','1',...
	'Value',1,...
	'Userdata',ones(NDomain,1), ...	
    'ToolTipString',tooltipstring, ...
	'callback',callbackStr,...
	'Enable','off');
	
	%===================================
	% MinBaseHandle
	%===================================
	btnNumber=13;   
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
	
	hMinBaseText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String','Min. baseline [ms]',...
	'Enable','off');
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 1.*btnHt_edit./2];
	callbackStr = 'emegs2d(''setMinBase'')';
	tooltipstring = 'sets the first point in baseline';
	
	hMinBase = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'Value',1,...
	'String','0',...
	'Userdata',ones(NDomain,1), ...	
	'callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================
	% MaxBaseHandle
	%===================================
	
	btnNumber=13;  
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt_edit 2.*btnWid./3 btnHt_edit./2];
	
	hMaxBaseText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String','Max. baseline [ms]',...
	'Enable','off');
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
	callbackStr = 'emegs2d(''setMaxBase'')';
	tooltipstring = 'sets the last point in baseline';
	
	hMaxBase = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'Value',1,...
	'String','0',...
	'Userdata',ones(NDomain,1), ...	
	'callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');		
	%====================================
	hMinMaxText=[hMinAmpText hMaxAmpText hMinPointText hMaxPointText hTrigPointText hCursorPointText hMinBaseText hMaxBaseText];
	%====================================
	
    %====================================
    % The CalcBase radio button
	%===================================
	btnNumber=14;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt btnWid./2 btnHt];
    callbackStr='emegs2d(''setCalcBaseStatus'')';
	tooltipstring = 'activates/deactivates baseline correction';

	hCalcBase=uicontrol( ...
    'Style','radiobutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','Calc. Baseline:', ...
    'Userdata',zeros(NDomain,1),...		
    'Value',0,...
    'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
    'Enable','off');
	
	%====================================
    % The CalcWholeBase push button
	%===================================
	btnNumber=14;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    callbackStr='emegs2d(''setCalcTotalBaseStatus'')';
	tooltipstring = 'activates baseline over all time points';

	hCalcTotalBase=uicontrol( ...
    'Style','pushbutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','Total Interval:', ...
	'Userdata',zeros(NDomain,1),...	
	'Value',0,...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
    %===================================
	%SampRateHandle
	%===================================
	btnNumber=15;  
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hSampRateText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String','Sampling rate [Hz]',...
	'Enable','off');
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'emegs2d(''setSampRate'')';
	tooltipstring = 'sets the sampling rate in Hz';
    
	hSampRate = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String','1','Userdata',1, ...
	'Value',0,...
	'callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');	

	%===================================
	%NPointsHandle
	%===================================
	btnNumber=15;  
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt_edit 2.*btnWid./3 btnHt_edit./2];
    
	hNPointsText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String','Number of points',...
	'Enable','off');
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
	callbackStr = 'emegs2d(''setNPoints'')';
	tooltipstring = 'sets the maximum number of time points displayed';
    
	hNPoints = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String','0','Userdata',0, ...
	'Value',0,...
	'callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');		

	%=================================== 
	% SurfDataMatrix push button 
	%===================================
	btnNumber=16;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt/2 btnWid./2 btnHt/2];
	callbackStr = 'emegs2d(''SurfDataMatrix'')';
	tooltipstring = 'plots the channel-by-time-matrix as a surface plot';
	hSurfDataMatrix=uicontrol( ...
    'Style','pushbutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','Surf Matrix', ...
    'HorizontalAlignment','center',...
    'Userdata','0', ...
    'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
    'Enable','off');

	%====================================
	% InfoFile push button 
	%===================================
	btnNumber=16;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt/2 btnWid./2 btnHt/2];
	callbackStr = 'emegs2d(''InfoAll'')';
	tooltipstring = '';
	hInfoFile=uicontrol( ...
    'Style','pushbutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','Info', ...
    'HorizontalAlignment','center',...
    'Userdata','0', ...
    'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
    'Enable','off');
    
	%==================================== 
	% Plot GlobalPower push button 	
	%===================================
	btnNumber=16;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-3*btnHt/2 btnWid./2 btnHt];
	callbackStr = 'emegs2d(''InitializeGlobPowMenue'')';
	tooltipstring = 'plots the global power / root mean square';
	hPlotGlobPow=uicontrol( ...
    'Style','pushbutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','GP / RMS', ...
	'Userdata','0', ...
    'Callback',callbackStr,...
	'Enable','off');
	
	%====================================  
	% Plot Butterfly push button 
	%===================================
	
	btnNumber=16;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left+btnWid./2 yPos-3*btnHt/2 btnWid./2 btnHt];
	callbackStr = 'emegs2d(''InitializeButterfly'')';
	tooltipstring = 'creates a butterfly-plot';
	hPlotBut=uicontrol( ...
    'Style','pushbutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','Butterfly', ...
    'Userdata','0', ...
    'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
    'Enable','off');
		
	
    %=================================== 
	%  CloseAllButMain button  
	%===================================
	btnNumber=18;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid./2 btnHt/2];
	callbackStr = 'emegs2d(''CloseAllButMain'')';
	tooltipstring = 'closes all windows expect the main 2d and 3d windows';
	hCloseAllButMain=uicontrol( ...
    'Style','pushbutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','CloseAllButMain', ...
    'HorizontalAlignment','center',...
    'Userdata','0', ...
    'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
    'Enable','on');


	%====================================
	% push button 
	%===================================
	btnNumber=18;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos btnWid./2 btnHt/2];
	callbackStr = 'emegs2d(''LastViewDef'')';
	tooltipstring = 'loads last settings used';
	hLastViewDef=uicontrol( ...
    'Style','pushbutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','LastViewDef', ...
    'HorizontalAlignment','center',...
    'Userdata','0', ...
    'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
    'Enable','off');

	%===================================
    % Clear AllFile push button 
	%===================================
    btnNumber=18;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);

    btnPos=[left yPos-btnHt btnWid./4 btnHt];
    callbackStr = 'emegs2d(''ClearAllFiles'')';
	tooltipstring = 'clears all datasets';
    hClearAllFiles=uicontrol( ...
    'Style','pushbutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','Clear All', ...
    'Userdata','0', ...
    'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
    'Enable','off');


	%===================================
    % Close All Figures push button 
	%===================================
    btnNumber=18;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);

    btnPos=[left+btnWid./4 yPos-btnHt/2 btnWid./4 btnHt/2];
    callbackStr = 'emegs2d(''CloseAllFigures'')';
	tooltipstring = 'closes all matlab figures';
    hCloseAllFigures=uicontrol( ...
    'Style','pushbutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','Close All', ...
    'Userdata','0', ...
    'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
    'Enable','on');


	%===================================
    % restart push button 
	%===================================
    btnNumber=18;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);

    btnPos=[left+btnWid./4 yPos-btnHt btnWid./4 btnHt/2];
    callbackStr = 'emegs2d(''restart'')';
	tooltipstring = 'restarts emegs';
    hCloseAllFigures=uicontrol( ...
    'Style','pushbutton', ...
    'Units','normalized', ...
    'Position',btnPos, ...
    'String','Restart', ...
    'Userdata','0', ...
    'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
    'Enable','on');
		
		
	%====================================
	% User defined push button 
	%===================================
	btnNumber=18;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+3.*btnWid./4 yPos-btnHt btnWid./4 btnHt];
	callbackStr = 'emegs2d(''UserDefAction'')';
	tooltipstring = '';
	a=char('User Def')
    a=char(a,'Action')
	hInfoAll=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',a, ...
	'HorizontalAlignment','center',...
	'Userdata','0', ...
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');
	
	%===================================   
	% Plot MedMedVec push button 
	%===================================
	
	btnNumber=18; 
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left+btnWid./2 yPos-btnHt btnWid./4 btnHt];
	%callbackStr = 'emegs2d(''PlotAllChanXCorr'')';
	tooltipstring = '';
	callbackStr = 'emegs2d(''PlotMedMedVec'')';
	hPlotMedMedVec=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','MedVec', ...
	'Userdata','0', ... 
	'Callback',callbackStr,...
    'ToolTipString',tooltipstring, ...
	'Enable','off');

	%====================================================
	% Enable on/off vector
	%===================================
	hMenuEnable=[hActAllVisible hClearActFile hInfoFile hPlotGlobPow hPlotBut ... 
	hSurfDataMatrix hClearAllFiles hPlotMedMedVec hZoomToggleButton]; % menu functions not in the hList
	hMenuTextEnable=[hActSpecVisibleText hColorText hLineStyleText hZoomSpecChanText hAllSpecVisibleText ...
	hSampRateText hNPointsText hLineWidthText]; 
	%====================================================
   	DefFontSizeVec=ReadPlot2dDefFontSizeVec;
	TextMenuFontSize=DefFontSizeVec(1);
   
	if MainMatlabVersion > 4
		set(hMinAmp,'FontSize',TextMenuFontSize);
		set(hMaxAmp,'FontSize',TextMenuFontSize);
		set(hMinPoint,'FontSize',TextMenuFontSize);
		set(hMaxPoint,'FontSize',TextMenuFontSize);
		set(hTrigPoint,'FontSize',TextMenuFontSize);
		set(hCursorPoint,'FontSize',TextMenuFontSize);
		set(hMinBase,'FontSize',TextMenuFontSize);
		set(hMaxBase,'FontSize',TextMenuFontSize);
		set(hSampRate,'FontSize',TextMenuFontSize);
		set(hNPoints,'FontSize',TextMenuFontSize);
	end
	%=======================================================
	%===========UIMENUES====================================
	%=======================================================

	%=======================================================
	%===========TOPMENU FILE================================
	hFileMenu=uimenu('Label','File','ForegroundColor',[0 0 1]);
	
    
    %============ last open files =====================
	hRecentDataMenu=uimenu(hFileMenu,'Label','Recent Files','Separator','on','Enable','on');
	callbackStr = 'emegs2d(''LastOpenFile1'')';
	hLastOpenFile1=uimenu(hRecentDataMenu,'Label','','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''LastOpenFile2'')';
	hLastOpenFile2=uimenu(hRecentDataMenu,'Label','','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''LastOpenFile3'')';
	hLastOpenFile3=uimenu(hRecentDataMenu,'Label','','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''LastOpenFile4'')';
	hLastOpenFile4=uimenu(hRecentDataMenu,'Label','','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''LastOpenFile5'')';
	hLastOpenFile5=uimenu(hRecentDataMenu,'Label','','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''LastOpenFile6'')';
	hLastOpenFile6=uimenu(hRecentDataMenu,'Label','','Callback',callbackStr,'Enable','off');
    
	%----------------------------------------------------------------------
    
	hOpenDataFile=uimenu(hFileMenu,'Label','Open Data Set');
		callbackStr = 'emegs2d(''PrepOpenAvgFile1'')';
		uimenu(hOpenDataFile,'Label','Open Data Set 1','Callback',callbackStr,'Accelerator','1');
		callbackStr = 'emegs2d(''PrepOpenAvgFile2'')';
		uimenu(hOpenDataFile,'Label','Open Data Set 2','Callback',callbackStr,'Accelerator','2');
		callbackStr = 'emegs2d(''PrepOpenAvgFile3'')';
		uimenu(hOpenDataFile,'Label','Open Data Set 3','Callback',callbackStr,'Accelerator','3');
		callbackStr = 'emegs2d(''PrepOpenAvgFile4'')';
		uimenu(hOpenDataFile,'Label','Open Data Set 4','Callback',callbackStr,'Accelerator','4');
        callbackStr = 'emegs2d(''PrepOpenAvgFile5'')';
		uimenu(hOpenDataFile,'Label','Open Data Set 5','Callback',callbackStr,'Accelerator','5');
        callbackStr = 'emegs2d(''PrepOpenAvgFile6'')';
		uimenu(hOpenDataFile,'Label','Open Data Set 6','Callback',callbackStr,'Accelerator','6');
		callbackStr = 'emegs2d(''PrepOpenAvgFile1234'')';
		uimenu(hOpenDataFile,'Label','Open i +/- j Set','Callback',callbackStr,'Accelerator','m','Separator','on');
		callbackStr = 'emegs2d(''PrepOpenAvgFileBat'')';
		uimenu(hOpenDataFile,'Label','Open Batch File','Callback',callbackStr,'Accelerator','b');
	callbackStr = 'emegs2d(''chECfg'')';
	hOpenElectrodeFile=uimenu(hFileMenu,'Label','Open Sensor Set','Callback',callbackStr);	
	
	%===========DataFormat==================================
	hAvgFileFormat=uimenu(hFileMenu,'Label','Data Format','Separator','on');
	
    callbackStr = 'emegs2d(''chAutoDataFormat'')';
    hAutoDataFormatMenu=uimenu(hAvgFileFormat,'Label','Auto','Callback',callbackStr);
	callbackStr = 'emegs2d(''chNeuroscanAvg'')';
	hNeuroscanAvgMenu=uimenu(hAvgFileFormat,'Label','Neuroscan Average','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''chNeuroscanCnt'')';
	hNeuroscanCntMenu=uimenu(hAvgFileFormat,'Label','Neuroscan Continuous','Callback',callbackStr);
	callbackStr = 'emegs2d(''chAmpWave'')';
	hAmpWaveMenu=uimenu(hAvgFileFormat,'Label','Wavelet Amplitude','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''chPhaseWave'')';
	hPhaseWaveMenu=uimenu(hAvgFileFormat,'Label','Wavelet Phaselock','Callback',callbackStr);
	callbackStr = 'emegs2d(''chAvgFileEgis'')';
	hAvgEgisMenu=uimenu(hAvgFileFormat,'Label','Egis Average','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''chGrandAvgFileEgis'')';
	hGrandAvgEgisMenu=uimenu(hAvgFileFormat,'Label','Egis Grand Average','Callback',callbackStr);
	callbackStr = 'emegs2d(''chRawFileEgis'')';
	hRawEgisMenu=uimenu(hAvgFileFormat,'Label','Egis Session','Callback',callbackStr);
% 	if ~strcmp(computer,'MAC2') | strcmp(computer,'MAC')	; 	%no EGIS files available on PC or UNIX
% 		set(hAvgEgisMenu,'Enable','off');
% 		set(hGrandAvgEgisMenu,'Enable','off');
% 		set(hRawEgisMenu,'Enable','off');
% 	end
	callbackStr = 'emegs2d(''chAvgFileSCADS'')';
	hAvgSCADSMenu=uimenu(hAvgFileFormat,'Label','SCADS Average','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''chAppFileSCADS'')';
	hAppSCADSMenu=uimenu(hAvgFileFormat,'Label','SCADS Approx.','Callback',callbackStr);
	callbackStr = 'emegs2d(''chAvgFileAsciiVec'')';
	hAsciiFileMenu=uimenu(hAvgFileFormat,'Label','Ascii','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''chAvgFileAsciiHeaderVec'')';
	hAsciiHeaderFileMenu=uimenu(hAvgFileFormat,'Label','Ascii Header','Callback',callbackStr);
	callbackStr = 'emegs2d(''chAvgFileFloat32Vec'')';
	hFloat32FileMenu=uimenu(hAvgFileFormat,'Label','Float32','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''chAvgFileFloat32HeaderVec'')';
	hFloat32HeaderFileMenu=uimenu(hAvgFileFormat,'Label','Float32 Header','Callback',callbackStr);
	callbackStr = 'emegs2d(''chAvgFileAsciiBesaVec'')';
	hAsciiBesaMenu=uimenu(hAvgFileFormat,'Label','Ascii Besa','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''chAvgFileAsciiMEG'')';
	hAsciiMEGMenu=uimenu(hAvgFileFormat,'Label','MEG BTI Ascii','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''chAvgFileMegBtiMsi'')';
	hAsciiMEGMenu=uimenu(hAvgFileFormat,'Label','MEG BTI MSI','Callback',callbackStr);
	
	%===========Sensor Format=================================
	hECfgFileFormat=uimenu(hFileMenu,'Label','Sensor Format');


	callbackStr = 'emegs2d(''chECfgFileAutoAxes'')';
	hECFileAutoAxesMenu=uimenu(hECfgFileFormat,'Label','Auto Axes','Callback',callbackStr);
	callbackStr = 'emegs2d(''chECfgFileMEGNoSphere'')';
	hECFileMEGNoSphereMenu=uimenu(hECfgFileFormat,'Label','MEG no sphere','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''chECfgFileMEGOnSphere'')';
	hECFileMEGOnSphereMenu=uimenu(hECfgFileFormat,'Label','MEG on sphere','Callback',callbackStr);	
	callbackStr = 'emegs2d(''chECfgFileBesaEEG'')';
	hECFileBesaEEGMenu=uimenu(hECfgFileFormat,'Label','Besa','Callback',callbackStr,'Separator','on');	
	callbackStr = 'emegs2d(''chECfgFileNsSfp'')';
	hECFileNsSfpMenu=uimenu(hECfgFileFormat,'Label','Neuroscan','Callback',callbackStr,'Separator','on','Enable','on');
	callbackStr = 'emegs2d(''chECfgFileSCADS'')';
	hECFileSCADSMenu=uimenu(hECfgFileFormat,'Label','SCADS','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''chECfgFileCartAscii'')';
	hECFileCartAsciiMenu=uimenu(hECfgFileFormat,'Label','Cart. Ascii','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''chECfgFileSpherAscii'')';
	hECFileSpherAsciiMenu=uimenu(hECfgFileFormat,'Label','Spher. Ascii','Callback',callbackStr);
	callbackStr = 'emegs2d(''chECfgFileAxesAscii'')';
	hECFileAxesAsciiMenu=uimenu(hECfgFileFormat,'Label','Axes Ascii','Callback',callbackStr);
	callbackStr = 'emegs2d(''Prep1020ECfgFile'')';
	hECFileSet1020Menu=uimenu(hECfgFileFormat,'Label','10/20 System','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''Prep1010ECfgFile'')';
	hECFileSet1010Menu=uimenu(hECfgFileFormat,'Label','10/10 System','Callback',callbackStr);
	
	%============ save/open view default file =====================
	hDefFileMenu=uimenu(hFileMenu,'Label','Default File','Separator','on');
	callbackStr = 'emegs2d(''AutoViewDefaultFile'')';
	hAutoDefFileMenu=uimenu(hDefFileMenu,'Label','Auto','Callback',callbackStr,'Userdata',0);
	callbackStr = 'emegs2d(''ReadViewDefaultFile'')';
	hOpenDefFileMenu=uimenu(hDefFileMenu,'Label','Open','Callback',callbackStr,'Accelerator','y');
	callbackStr = 'emegs2d(''SaveViewDefaultFile'')';
	hSaveDefFileMenu=uimenu(hDefFileMenu,'Label','Save','Callback',callbackStr,'Accelerator','x','Enable','off');
	hInfoDefFileMenu=uimenu(hDefFileMenu,'Label','Info','Callback',callbackStr,'Separator','on','Enable','on');
	uimenu(hInfoDefFileMenu,'Label','No view def. file opened','Enable','on');
	%-------------------------------------------------------------------------------------------

  
	%---------------------
    
	%==============================================================
   	 % Menu: Style =================================================
	%==============================================================

	hStyleMenu=uimenu('Label','Style','ForegroundColor',[0 0 1]);
	
		%============Axes ===============================
		hStyleSensorAxesMenu=uimenu(hStyleMenu,'Label','Axes','Enable','off');
			hSensorAxesWidthMenu=uimenu(hStyleSensorAxesMenu,'Label','Width','Userdata',13,'Enable','on');
			hSensorAxesHeightMenu=uimenu(hStyleSensorAxesMenu,'Label','Height','Userdata',13,'Enable','on');
			for i=1:20
				if i<=9; IStr=['0',int2str(i)]; else; IStr=int2str(i); end
				callbackStr = ['emegs2d(''setSensorAxesWidth' IStr ''')'];
				uimenu(hSensorAxesWidthMenu,'Label',int2str(i),'Callback',callbackStr,'Enable','on');
				callbackStr = ['emegs2d(''setSensorAxesHeight' IStr ''')'];
				uimenu(hSensorAxesHeightMenu,'Label',int2str(i),'Callback',callbackStr,'Enable','on');
			end
		%============SensorLineColor ===============================
		hStyleSensorLineColorMenu=uimenu(hStyleMenu,'Label','Sensor Line Color','Separator','on','Enable','off');
			callbackStr = 'emegs2d(''setSensorLineColorFlipud'')';
			hSensorLineColorFlipudMenu=uimenu(hStyleSensorLineColorMenu,'Label','Flip Colormap','Callback',callbackStr);
% 			callbackStr = 'emegs2d(''setSensorLineColorNoVec'')';
% 			hSensorLineColorDefMenu=uimenu(hStyleSensorLineColorMenu,'Label','All sensors identical','Callback',callbackStr,'Separator','on');
 			callbackStr = 'emegs2d(''setSensorLineColorDefault'')';
			hSensorLineColorDefMenu=uimenu(hStyleSensorLineColorMenu,'Label','Use default vector','Callback',callbackStr,'Separator','on');
			callbackStr = 'emegs2d(''setSensorLineColorNTrial'')';
			hSensorLineColorNTrialMenu=uimenu(hStyleSensorLineColorMenu,'Label','Use number of trials vector','Callback',callbackStr);
			callbackStr = 'emegs2d(''setSensorLineColorStd'')';
			hSensorLineColorStdMenu=uimenu(hStyleSensorLineColorMenu,'Label','Use Std vector','Callback',callbackStr);
			callbackStr = 'emegs2d(''setSensorLineColorGroups'')';
			hSensorLineColorGroupsMenu=uimenu(hStyleSensorLineColorMenu,'Label','Use channel groups','Callback',callbackStr);
		%============ Text ========================================
		hStyleTextMenu=uimenu(hStyleMenu,'Label','Text','Separator','on','Enable','off');
			callbackStr = 'emegs2d(''DispENames'')';
			hDispElecNameMenu=uimenu(hStyleTextMenu,'Label','Sensor Names','Callback',callbackStr);
			callbackStr = 'emegs2d(''DispFileNames'')';
			hDispFileNameMenu=uimenu(hStyleTextMenu,'Label','File Names','Callback',callbackStr);
			callbackStr = 'emegs2d(''DispCursorAmp'')';
			hDispCursAmpMenu=uimenu(hStyleTextMenu,'Label','Cursor Amplitude','Callback',callbackStr);
			callbackStr = 'emegs2d(''DispNTrials'')';
			hDispTrialsMenu=uimenu(hStyleTextMenu,'Label','Number of Trials','Callback',callbackStr);
			callbackStr = 'emegs2d(''DispMeanStd'')';
			hDispMeanStdMenu=uimenu(hStyleTextMenu,'Label','Mean Std','Callback',callbackStr);
			callbackStr = 'emegs2d(''DispLREarNoseText'')';
			hDispEarMenu=uimenu(hStyleTextMenu,'Label','Left/Right Ear','Callback',callbackStr);
			callbackStr = 'emegs2d(''ChangeDispTextPositions'')';
			uimenu(hStyleTextMenu,'Label','Text Positions','Callback',callbackStr,'Separator','on');
		%==============Zeroline======================================
		hStyleZeroLineMenu=uimenu(hStyleMenu,'Label','Zeroline','Separator','on','Enable','off');
			callbackStr = 'emegs2d(''setZerolineVisible'')';
			hZeroLineOnOffMenu=uimenu(hStyleZeroLineMenu,'Label','Zeroline on ','Callback',callbackStr); %Zeroline on/off
			hStyleZeroLineColorMenu=uimenu(hStyleZeroLineMenu,'Label','Color');
				callbackStr = 'emegs2d(''setZeroLineColorBlack'')';
				hZeroLineBlackMenu=uimenu(hStyleZeroLineColorMenu,'Label','Black','Callback',callbackStr);
				callbackStr = 'emegs2d(''setZeroLineColorWhite'')';
				hZeroLineWhiteMenu=uimenu(hStyleZeroLineColorMenu,'Label','White','Callback',callbackStr);
				callbackStr = 'emegs2d(''setZeroLineColorYellow'')';
				hZeroLineYellowMenu=uimenu(hStyleZeroLineColorMenu,'Label','Yellow','Callback',callbackStr);
				callbackStr = 'emegs2d(''setZeroLineColorRed'')';
				hZeroLineRedMenu=uimenu(hStyleZeroLineColorMenu,'Label','Red','Callback',callbackStr);
				callbackStr = 'emegs2d(''setZeroLineColorBlue'')';
				hZeroLineBlueMenu=uimenu(hStyleZeroLineColorMenu,'Label','Blue','Callback',callbackStr);
				callbackStr = 'emegs2d(''setZeroLineColorGreen'')';
				hZeroLineGreenMenu=uimenu(hStyleZeroLineColorMenu,'Label','Green','Callback',callbackStr);
				callbackStr = 'emegs2d(''setZeroLineColorMagenta'')';
				hZeroLineMagentaMenu=uimenu(hStyleZeroLineColorMenu,'Label','Magenta','Callback',callbackStr);
				callbackStr = 'emegs2d(''setZeroLineColorCyan'')';
				hZeroLineCyanMenu=uimenu(hStyleZeroLineColorMenu,'Label','Cyan','Callback',callbackStr);
	
			hStyleZeroLineStyleMenu=uimenu(hStyleZeroLineMenu,'Label','Line Style');
				callbackStr = 'emegs2d(''setZeroLineStyleSolid'')';
				hZeroLineStyleSolidMenu=uimenu(hStyleZeroLineStyleMenu,'Label','Solid','Callback',callbackStr);
				callbackStr = 'emegs2d(''setZeroLineStyleDash'')';
				hZeroLineStyleDashedMenu=uimenu(hStyleZeroLineStyleMenu,'Label','Dashed','Callback',callbackStr);
				callbackStr = 'emegs2d(''setZeroLineStyleDashDot'')';
				hZeroLineStyleDashDottMenu=uimenu(hStyleZeroLineStyleMenu,'Label','Dash-Dotted','Callback',callbackStr);
				callbackStr = 'emegs2d(''setZeroLineStyleDot'')';
				hZeroLineStyleDottMenu=uimenu(hStyleZeroLineStyleMenu,'Label','Dotted','Callback',callbackStr);	
	
	%============TriggerLine ====================================
	hStyleTrigLineMenu=uimenu(hStyleMenu,'Label','Triggerline','Enable','off');

	callbackStr = 'emegs2d(''setTriggerVisible'')';
	hTriggerLineOnOffMenu=uimenu(hStyleTrigLineMenu,'Label','Trigger off','Callback',callbackStr); %Trigger on/off

	hStyleTrigLineColorMenu=uimenu(hStyleTrigLineMenu,'Label','Color');
	callbackStr = 'emegs2d(''setTriggerLineColorBlack'')';
	hTriggerLineBlackMenu=uimenu(hStyleTrigLineColorMenu,'Label','Black','Callback',callbackStr);
	callbackStr = 'emegs2d(''setTriggerLineColorWhite'')';
	hTriggerLineWhiteMenu=uimenu(hStyleTrigLineColorMenu,'Label','White','Callback',callbackStr);
	callbackStr = 'emegs2d(''setTriggerLineColorYellow'')';
	hTriggerLineYellowMenu=uimenu(hStyleTrigLineColorMenu,'Label','Yellow','Callback',callbackStr);
	callbackStr = 'emegs2d(''setTriggerLineColorRed'')';
	hTriggerLineRedMenu=uimenu(hStyleTrigLineColorMenu,'Label','Red','Callback',callbackStr);
	callbackStr = 'emegs2d(''setTriggerLineColorBlue'')';
	hTriggerLineBlueMenu=uimenu(hStyleTrigLineColorMenu,'Label','Blue','Callback',callbackStr);
	callbackStr = 'emegs2d(''setTriggerLineColorGreen'')';
	hTriggerLineGreenMenu=uimenu(hStyleTrigLineColorMenu,'Label','Green','Callback',callbackStr);
	callbackStr = 'emegs2d(''setTriggerLineColorMagenta'')';
	hTriggerLineMagentaMenu=uimenu(hStyleTrigLineColorMenu,'Label','Magenta','Callback',callbackStr);
	callbackStr = 'emegs2d(''setTriggerLineColorCyan'')';
	hTriggerLineCyanMenu=uimenu(hStyleTrigLineColorMenu,'Label','Cyan','Callback',callbackStr);
	
	hStyleTrigLineStyleMenu=uimenu(hStyleTrigLineMenu,'Label','Line Style');
	callbackStr = 'emegs2d(''setTriggerLineStyleSolid'')';
	hTriggerLineStyleSolidMenu=uimenu(hStyleTrigLineStyleMenu,'Label','Solid','Callback',callbackStr);
	callbackStr = 'emegs2d(''setTriggerLineStyleDash'')';
	hTriggerLineStyleDashedMenu=uimenu(hStyleTrigLineStyleMenu,'Label','Dashed','Callback',callbackStr);
	callbackStr = 'emegs2d(''setTriggerLineStyleDashDot'')';
	hTriggerLineStyleDashDottMenu=uimenu(hStyleTrigLineStyleMenu,'Label','Dash-Dotted','Callback',callbackStr);
	callbackStr = 'emegs2d(''setTriggerLineStyleDot'')';
	hTriggerLineStyleDottMenu=uimenu(hStyleTrigLineStyleMenu,'Label','Dotted','Callback',callbackStr);
	
	%============ CursorLine ====================================
	hStyleCursorLineMenu=uimenu(hStyleMenu,'Label','Cursorline','Enable','off');
	
	callbackStr = 'emegs2d(''setCursorVisible'')';
	hCursorLineOnOffMenu=uimenu(hStyleCursorLineMenu,'Label','Cursor off','Callback',callbackStr); % Cursor on/off

	hStyleCursorLineColorMenu=uimenu(hStyleCursorLineMenu,'Label','Color');
	callbackStr = 'emegs2d(''setCursorLineColorBlack'')';
	hCursorLineBlackMenu=uimenu(hStyleCursorLineColorMenu,'Label','Black','Callback',callbackStr);
	callbackStr = 'emegs2d(''setCursorLineColorWhite'')';
	hCursorLineWhiteMenu=uimenu(hStyleCursorLineColorMenu,'Label','White','Callback',callbackStr);
	callbackStr = 'emegs2d(''setCursorLineColorYellow'')';
	hCursorLineYellowMenu=uimenu(hStyleCursorLineColorMenu,'Label','Yellow','Callback',callbackStr);
	callbackStr = 'emegs2d(''setCursorLineColorRed'')';
	hCursorLineRedMenu=uimenu(hStyleCursorLineColorMenu,'Label','Red','Callback',callbackStr);
	callbackStr = 'emegs2d(''setCursorLineColorBlue'')';
	hCursorLineBlueMenu=uimenu(hStyleCursorLineColorMenu,'Label','Blue','Callback',callbackStr);
	callbackStr = 'emegs2d(''setCursorLineColorGreen'')';
	hCursorLineGreenMenu=uimenu(hStyleCursorLineColorMenu,'Label','Green','Callback',callbackStr);
	callbackStr = 'emegs2d(''setCursorLineColorMagenta'')';
	hCursorLineMagentaMenu=uimenu(hStyleCursorLineColorMenu,'Label','Magenta','Callback',callbackStr);
	callbackStr = 'emegs2d(''setCursorLineColorCyan'')';
	hCursorLineCyanMenu=uimenu(hStyleCursorLineColorMenu,'Label','Cyan','Callback',callbackStr);
	
	hStyleCursorLineStyleMenu=uimenu(hStyleCursorLineMenu,'Label','Line Style');
	callbackStr = 'emegs2d(''setCursorLineStyleSolid'')';
	hCursorLineStyleSolidMenu=uimenu(hStyleCursorLineStyleMenu,'Label','Solid','Callback',callbackStr);
	callbackStr = 'emegs2d(''setCursorLineStyleDash'')';
	hCursorLineStyleDashedMenu=uimenu(hStyleCursorLineStyleMenu,'Label','Dashed','Callback',callbackStr);
	callbackStr = 'emegs2d(''setCursorLineStyleDashDot'')';
	hCursorLineStyleDashDottMenu=uimenu(hStyleCursorLineStyleMenu,'Label','Dash-Dotted','Callback',callbackStr);
	callbackStr = 'emegs2d(''setCursorLineStyleDot'')';
	hCursorLineStyleDottMenu=uimenu(hStyleCursorLineStyleMenu,'Label','Dotted','Callback',callbackStr);	
	
	%============ X-Tick ===============================
	hStyleXTickMenu=uimenu(hStyleMenu,'Label','X-Tick','Separator','on','Enable','off');
	callbackStr = 'emegs2d(''setXTickVal5'')';
	hXTick5Menu=uimenu(hStyleXTickMenu,'Label','5 ms','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''setXTickVal10'')';
	hXTick10Menu=uimenu(hStyleXTickMenu,'Label','10 ms','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''setXTickVal25'')';
	hXTick25Menu=uimenu(hStyleXTickMenu,'Label','25 ms','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''setXTickVal50'')';
	hXTick50Menu=uimenu(hStyleXTickMenu,'Label','50 ms','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''setXTickVal100'')';
	hXTick100Menu=uimenu(hStyleXTickMenu,'Label','100 ms','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''setXTickVal250'')';
	hXTick250Menu=uimenu(hStyleXTickMenu,'Label','250 ms','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''setXTickVal500'')';
	hXTick500Menu=uimenu(hStyleXTickMenu,'Label','500 ms','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''setXTickVal1000'')';
	hXTick1000Menu=uimenu(hStyleXTickMenu,'Label','1000 ms','Callback',callbackStr,'Enable','on');

	%============ BackgroundColor ===============================
	hStyleBackColorMenu=uimenu(hStyleMenu,'Label','Background Color','Separator','on','Enable','off');
	callbackStr = 'emegs2d(''setChanFigBGColorWhite'')';
	hBGColorWhiteMenu=uimenu(hStyleBackColorMenu,'Label','White','Callback',callbackStr);
	callbackStr = 'emegs2d(''setChanFigBGColorBlack'')';
	hBGColorBlackMenu=uimenu(hStyleBackColorMenu,'Label','Black','Callback',callbackStr);
		
	%===========================================
	%===============EXPORT=====================
	hExportMenu=uimenu('Label','Export','ForegroundColor',[0 0 1]);
	
	%===============Data File====================
	hExportAvgFile=uimenu(hExportMenu,'Label','Data File','Enable','off');
        hExportAllAvgFile=uimenu(hExportAvgFile,'Label','All data sets');
            callbackStr = 'emegs2d(''ExportAllAvgFile2SCADS'')';
	        uimenu(hExportAllAvgFile,'Label','SCADS Format','Callback',callbackStr);
            callbackStr = 'emegs2d(''ExportAllAvgFile2KN'')';
	        uimenu(hExportAllAvgFile,'Label','Konstanz Format','Callback',callbackStr);
	        callbackStr = 'emegs2d(''ExportAllAvgFile2Ascii'')';
	        uimenu(hExportAllAvgFile,'Label','Ascii Header Matrix','Callback',callbackStr);
	        callbackStr = 'emegs2d(''ExportAllAvgFile2Besa'')';
	        uimenu(hExportAllAvgFile,'Label','Besa','Callback',callbackStr);
        hExportActAvgFile=uimenu(hExportAvgFile,'Label','Actual data set');
	        callbackStr = 'emegs2d(''ExportActAvgFile2SCADS'')';
	        uimenu(hExportActAvgFile,'Label','SCADS Format','Callback',callbackStr);
	        callbackStr = 'emegs2d(''ExportActAvgFile2KN'')';
	        uimenu(hExportActAvgFile,'Label','Konstanz Format','Callback',callbackStr);
	        callbackStr = 'emegs2d(''ExportActAvgFile2Ascii'')';
	        uimenu(hExportActAvgFile,'Label','Ascii Header Matrix','Callback',callbackStr);
	        callbackStr = 'emegs2d(''ExportActAvgFile2Besa'')';
	        uimenu(hExportActAvgFile,'Label','Besa','Callback',callbackStr);
        hExportFilematrix=uimenu(hExportAvgFile,'Label','Filematrix');
	        callbackStr = 'emegs2d(''ExportFilematrix2SCADS'')';
	        uimenu(hExportFilematrix,'Label','SCADS Format','Callback',callbackStr);
	        callbackStr = 'emegs2d(''ExportFilematrix2KN'')';
	        uimenu(hExportFilematrix,'Label','Konstanz Format','Callback',callbackStr);
	        callbackStr = 'emegs2d(''ExportFilematrix2Ascii'')';
	        uimenu(hExportFilematrix,'Label','Ascii Header Matrix','Callback',callbackStr);
	        callbackStr = 'emegs2d(''ExportFilematrix2Besa'')';
	        uimenu(hExportFilematrix,'Label','Besa','Callback',callbackStr);
	%===============Sensor Configuration===========
	hExportECfgFile=uimenu(hExportMenu,'Label','Sensor File','Enable','off'); 
	callbackStr = 'emegs2d(''ExportECfgFile2MEG'')';
	uimenu(hExportECfgFile,'Label','MEG BTI Format','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''ExportECfgFile2Besa'')';
	uimenu(hExportECfgFile,'Label','Besa Format','Callback',callbackStr,'Enable','on','Separator','on');
	callbackStr = 'emegs2d(''ExportECfgFile2Egis'')';
	uimenu(hExportECfgFile,'Label','Egis Format','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''ExportECfgFile2SCADS'')';
	uimenu(hExportECfgFile,'Label','SCADS Format','Callback',callbackStr);
	callbackStr = 'emegs2d(''ExportECfgFile2CartAscii'')';
	uimenu(hExportECfgFile,'Label','Cart. Ascii Format','Callback',callbackStr);
	callbackStr = 'emegs2d(''ExportECfgFile2SpherAscii'')';
	uimenu(hExportECfgFile,'Label','Spher. Ascii Format','Callback',callbackStr);
	%===============Global Power ===========
	hExportGpRms=uimenu(hExportMenu,'Label','GP / RMS','Enable','off','Separator','on');
	callbackStr = 'emegs2d(''ExportAllGlobalPower'')';
	uimenu(hExportGpRms,'Label','All Points','Callback',callbackStr);
	callbackStr = 'emegs2d(''ExportCursorGlobalPower'')';
	uimenu(hExportGpRms,'Label','Cursor Point','Callback',callbackStr);
	%===============User Data ===========		
	hExportUserData=uimenu(hExportMenu,'Label','User Data','Enable','off');
	callbackStr = 'emegs2d(''ExportUserDataAscii'')';
	uimenu(hExportUserData,'Label','Ascii','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''ExportUserDataBesa'')';
	uimenu(hExportUserData,'Label','Besa','Callback',callbackStr,'Enable','off');
	%callbackStr = 'emegs2d(''ExportUserdataInfo'')';
	hExportUserDataInfo=uimenu(hExportUserData,'Label','Info','Separator','on','Enable','on');
	uimenu(hExportUserDataInfo,'Label','No User Data','Enable','on');

	%============================================
	%==============CALCULATE=====================
	%============================================

	hCalcMenu=uimenu('Label','Calculate','ForeGroundColor',[0 0 1]);
    	%===========================================
	%===============SYNTHETIC==================
	hGlobDissim=uimenu(hCalcMenu,'Label','Global Dissimilarity','ForegroundColor',[0 0 0],'Separator','on');
	%============================================
	callbackStr = 'emegs2d(''GlobDissim1Files'')';
        hhGlobDissim1File=uimenu(hGlobDissim,'Userdata',0,'Label','Actual Dataset','Callback',callbackStr);
	callbackStr = 'emegs2d(''GlobDissim2Files'')';
        hhGlobDissim2Files=uimenu(hGlobDissim,'Userdata',0,'Label','Dataset 1 - 2','Callback',callbackStr);
	%===========================================
	%===============SYNTHETIC==================
	hClusterSizeMenu=uimenu(hCalcMenu,'Label','Min. Cluster Size','ForegroundColor',[0 0 0],'Separator','on');
	%============================================
	callbackStr = 'emegs2d(''OpfigTTestPaiRestrictions'')';
        hSetMinClusterSize=uimenu(hClusterSizeMenu,'Userdata',0,'Label','set size','Callback',callbackStr);
        hApplyMinClusterSize=uimenu(hClusterSizeMenu,'Userdata',0,'Label','apply');
        callbackStr = 'emegs2d(''ApplyMinClusterSizeRestrictionsActual'')';
        hhApplyMinClusterSizeActual=uimenu(hApplyMinClusterSize,'Userdata',0,'Label','actual dataset','Callback',callbackStr);
        callbackStr = 'emegs2d(''ApplyMinClusterSizeRestrictionsAll'')';
        hhApplyMinClusterSizeAll=uimenu(hApplyMinClusterSize,'Userdata',0,'Label','all datasets','Callback',callbackStr);
	
	%===========================================
	%===============SYNTHETIC==================
	hSynthMenu=uimenu(hCalcMenu,'Label','Synthetic','ForegroundColor',[0 0 0],'Separator','on');
		%============================================
		callbackStr = 'emegs2d(''GenSynthData'')';
		hGenSynthMenu=uimenu(hSynthMenu,'Userdata',0,'Label','Generate Synthetic Data','Callback',callbackStr);
    
    %==============RepCon=====================
	hCalcRepConMenu=uimenu(hCalcMenu,'Label','Contrasts','Enable','off','Separator','on');
    
    hCalcRepConListMenu=uimenu(hCalcRepConMenu,'Label','Contrasts from list (RepConDef.txt)');
    hCalcRepConManuMenu=uimenu(hCalcRepConMenu,'Label','Contrasts manually');
    
    callbackStr = 'emegs2d(''CalcRepConListNorm'')';
    hCalcRepConListNormMenu=uimenu(hCalcRepConListMenu,'Label','F, t, pF, pt -values (normal distribution)','Callback',callbackStr);
    callbackStr = 'emegs2d(''CalcRepConListPerm'')';
    hCalcRepConListPermMenu=uimenu(hCalcRepConListMenu,'Label','F, t, pF, pt -values (permutation distribution)','Callback',callbackStr);
    
    callbackStr = 'emegs2d(''CalcRepConManuNorm'')';
    hCalcRepConManuNormMenu=uimenu(hCalcRepConManuMenu,'Label','F,t,pF,pt-values (normal distribution)','Callback',callbackStr);
    callbackStr = 'emegs2d(''CalcRepConManuPerm'')';
    hCalcRepConManuPermMenu=uimenu(hCalcRepConManuMenu,'Label','F,t,pF,pt-values (permutation distribution)','Callback',callbackStr);
    
    %==============CorrCoef=====================
	hCalcCorrCoefMenu=uimenu(hCalcMenu,'Label','Correlation','Enable','off','Separator','on');
    
    callbackStr = 'emegs2d(''CalcCorrCoefList'')';
    hCalcCorrCoefListMenu=uimenu(hCalcCorrCoefMenu,'Label','Weights from list (CorrCoeffDef.txt)','Callback',callbackStr);
    callbackStr = 'emegs2d(''CalcCorrCoefManu'')';
    hCalcCorrCoefManuMenu=uimenu(hCalcCorrCoefMenu,'Label','Weights manually','Callback',callbackStr);
                
	%==============Factor=====================
	hCalcFactorMenu=uimenu(hCalcMenu,'Label','Factor','Enable','off','Separator','on');
	callbackStr = 'emegs2d(''CalcFactorAll'')';
	uimenu(hCalcFactorMenu,'Label','All data sets','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcFactorAct'')';
	uimenu(hCalcFactorMenu,'Label','Actual data set','Callback',callbackStr);
    
	%==============Gradient=====================
	hCalcGradMenu=uimenu(hCalcMenu,'Label','Gradient','Enable','off','Separator','on');
    callbackStr = 'emegs2d(''CalcGradClear'')';
    hCalcGradClearMenu=uimenu(hCalcGradMenu,'Label','No further gradient','Callback',callbackStr,'Tag','CalcGradClear','Userdata',0);
	callbackStr = 'emegs2d(''CalcGradAll'')';
	uimenu(hCalcGradMenu,'Label','All data sets','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''CalcGradAct'')';
	uimenu(hCalcGradMenu,'Label','Actual data set','Callback',callbackStr);
    
    %==============IntegralOFGradient=====================
	hCalcCumSumGradMenu=uimenu(hCalcMenu,'Label','Integral of Gradient','Enable','off','Separator','on');
	callbackStr = 'emegs2d(''CalcCumSumGradAll'')';
	uimenu(hCalcCumSumGradMenu,'Label','All data sets','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcCumSumGradAct'')';
	uimenu(hCalcCumSumGradMenu,'Label','Actual data set','Callback',callbackStr);
	
	%==============Dipole Density=====================
	callbackStr = 'DipDensApp(''InitializeMenu'')';
	hCalcDipDensMenu=uimenu(hCalcMenu,'Label','Dipole Density','Callback',callbackStr,'Enable','on','Separator','on');
	
	%==============t-test=====================
	hCalcTTestMenu=uimenu(hCalcMenu,'Label','t-test','Enable','on','Separator','on');	
        callbackStr = 'emegs2d(''CalcTTestOne'')';
		hCalcTTestOneMenu=uimenu(hCalcTTestMenu,'Label','One sample t-test','Callback',callbackStr,'Enable','on');
        callbackStr = 'emegs2d(''CalcTTestTwo'')';
        hCalcTTestTwoMenu=uimenu(hCalcTTestMenu,'Label','Two sample t-test','Callback',callbackStr,'Enable','on');
        callbackStr = 'emegs2d(''CalcTTestPai'')';
		hCalcTTestPaiMenu=uimenu(hCalcTTestMenu,'Label','Paired t-test','Enable','on','Callback',callbackStr);
    
       hCalcTTestPairesMenu=uimenu(hCalcTTestMenu,'Label','Paired t-test restricted','Enable','on','tag','hCalcTTestPairesMenu');
            callbackStr = 'emegs2d(''CalcTTestPaires'')';
			hCalcTTestPaires2Menu=uimenu(hCalcTTestPairesMenu,'Label','Paired t-test restricted','Enable','on','Callback',callbackStr);
            callbackStr = 'emegs2d(''OpfigTTestPaiRestrictions'')';
			hCalcTTestPairesDefMenu=uimenu(hCalcTTestPairesMenu,'Label','Define','Enable','on','Callback',callbackStr,'Separator','on');
            
	    hCalcTTestSymMenu=uimenu(hCalcTTestMenu,'Label','Symmetry t-test','Enable','on');
			callbackStr = 'emegs2d(''CalcTTestSymLR'')';
			hCalcTTestSymOriLRMenu=uimenu(hCalcTTestSymMenu,'Label','Left - Right','Enable','on','Callback',callbackStr);
			callbackStr = 'emegs2d(''CalcTTestSymFB'')';
			hCalcTTestSymOriFBMenu=uimenu(hCalcTTestSymMenu,'Label','Front - Back','Enable','on','Callback',callbackStr);
              
        callbackStr = 'emegs2d(''CalcTTestT2P'')';
		hCalcTTestT2P=uimenu(hCalcTTestMenu,'Label','(+/-) t => (1/-1) -p','Enable','on','Callback',callbackStr,'Separator','on'); 
        callbackStr = 'emegs2d(''CalcTTestT2Z'')';
        hCalcTTestT2Z=uimenu(hCalcTTestMenu,'Label','t => z','Enable','on','Callback',callbackStr);
            
	%==============MinMax=====================
		hCalcMinMaxMenu=uimenu(hCalcMenu,'Label','Extreme Values','Enable','on','Separator','on');	
			hCalcMinMaxAllMenu=uimenu(hCalcMinMaxMenu,'Label','All data sets','Enable','on');
				hCalcMinMaxAllMaxMenu=uimenu(hCalcMinMaxAllMenu,'Label','Maximum','Enable','on');
					callbackStr = 'emegs2d(''CalcMinMaxAllMaxAbs'')';
					hCalcMinMaxAllMaxAbsMenu=uimenu(hCalcMinMaxAllMaxMenu,'Label','Absolute','Enable','on','Callback',callbackStr);
					callbackStr = 'emegs2d(''CalcMinMaxAllMaxRel'')';
					hCalcMinMaxAllMaxRelMenu=uimenu(hCalcMinMaxAllMaxMenu,'Label','Relative','Enable','on','Callback',callbackStr);
					callbackStr = 'emegs2d(''CalcMinMaxAllMaxARe'')';
					hCalcMinMaxAllMaxAReMenu=uimenu(hCalcMinMaxAllMaxMenu,'Label','Abs. of Rel.','Enable','on','Callback',callbackStr);
					
				hCalcMinMaxAllMinMenu=uimenu(hCalcMinMaxAllMenu,'Label','Minimum','Enable','on');
					callbackStr = 'emegs2d(''CalcMinMaxAllMinAbs'')';
					hCalcMinMaxAllMaxAbsMenu=uimenu(hCalcMinMaxAllMinMenu,'Label','Absolute','Enable','on','Callback',callbackStr);
					callbackStr = 'emegs2d(''CalcMinMaxAllMinRel'')';
					hCalcMinMaxAllMinRelMenu=uimenu(hCalcMinMaxAllMinMenu,'Label','Relative','Enable','on','Callback',callbackStr);
					
				hCalcMinMaxAllMMxMenu=uimenu(hCalcMinMaxAllMenu,'Label','Both','Enable','on','Separator','on');
					callbackStr = 'emegs2d(''CalcMinMaxAllMMxAbs'')';
					hCalcMinMaxAllMMxAbsMenu=uimenu(hCalcMinMaxAllMMxMenu,'Label','Absolute','Enable','on','Callback',callbackStr);
					callbackStr = 'emegs2d(''CalcMinMaxAllMMxRel'')';
					hCalcMinMaxAllMMxRelMenu=uimenu(hCalcMinMaxAllMMxMenu,'Label','Relative','Enable','on','Callback',callbackStr);
					callbackStr = 'emegs2d(''CalcMinMaxAllMMxARe'')';
					hCalcMinMaxAllMMxAReMenu=uimenu(hCalcMinMaxAllMMxMenu,'Label','Abs. of Rel.','Enable','on','Callback',callbackStr);
				
			hCalcMinMaxActMenu=uimenu(hCalcMinMaxMenu,'Label','Actual data set','Enable','on');
				hCalcMinMaxActMaxMenu=uimenu(hCalcMinMaxActMenu,'Label','Maximum','Enable','on');
					callbackStr = 'emegs2d(''CalcMinMaxActMaxAbs'')';
					hCalcMinMaxActMaxAbsMenu=uimenu(hCalcMinMaxActMaxMenu,'Label','Absolute','Enable','on','Callback',callbackStr);
					callbackStr = 'emegs2d(''CalcMinMaxActMaxRel'')';
					hCalcMinMaxActMaxRelMenu=uimenu(hCalcMinMaxActMaxMenu,'Label','Relative','Enable','on','Callback',callbackStr);
					callbackStr = 'emegs2d(''CalcMinMaxActMaxARe'')';
					hCalcMinMaxActMaxAReMenu=uimenu(hCalcMinMaxActMaxMenu,'Label','Abs. of Rel.','Enable','on','Callback',callbackStr);
					
				hCalcMinMaxActMinMenu=uimenu(hCalcMinMaxActMenu,'Label','Minimum','Enable','on');
					callbackStr = 'emegs2d(''CalcMinMaxActMinAbs'')';
					hCalcMinMaxActMinAbsMenu=uimenu(hCalcMinMaxActMinMenu,'Label','Absolute','Enable','on','Callback',callbackStr);
					callbackStr = 'emegs2d(''CalcMinMaxActMinRel'')';
					hCalcMinMaxActMinRelMenu=uimenu(hCalcMinMaxActMinMenu,'Label','Relative','Enable','on','Callback',callbackStr);
					callbackStr = 'emegs2d(''CalcMinMaxActMinARe'')';
					hCalcMinMaxActMinAReMenu=uimenu(hCalcMinMaxActMinMenu,'Label','Abs. of Rel.','Enable','on','Callback',callbackStr);
					
				hCalcMinMaxActMMxMenu=uimenu(hCalcMinMaxActMenu,'Label','Both','Enable','on','Separator','on');
					callbackStr = 'emegs2d(''CalcMinMaxActMMxAbs'')';
					hCalcMinMaxActMMxAbsMenu=uimenu(hCalcMinMaxActMMxMenu,'Label','Absolute','Enable','on','Callback',callbackStr);
					callbackStr = 'emegs2d(''CalcMinMaxActMMxRel'')';
					hCalcMinMaxActMMxRelMenu=uimenu(hCalcMinMaxActMMxMenu,'Label','Relative','Enable','on','Callback',callbackStr);
					callbackStr = 'emegs2d(''CalcMinMaxActMMxARe'')';
					hCalcMinMaxActMMxAReMenu=uimenu(hCalcMinMaxActMMxMenu,'Label','Abs. of Rel.','Enable','on','Callback',callbackStr);
					
	%==============Wavelet=====================
	hCalcWaveMenu=uimenu(hCalcMenu,'Label','Wavelet','Enable','on','Separator','on');

	callbackStr = 'emegs2d(''CalcWave'')';
	hCalcCalcWaveMenu=uimenu(hCalcWaveMenu,'Label','Calculate','Callback',callbackStr);
	
	hCalcPlotWaveMenu=uimenu(hCalcWaveMenu,'Label','Plot and Surf');
	callbackStr = 'emegs2d(''PlotAmpWave'')';
	uimenu(hCalcPlotWaveMenu,'Label','Amplitude','Callback',callbackStr);
	callbackStr = 'emegs2d(''PlotPhaseWave'')';
	uimenu(hCalcPlotWaveMenu,'Label','Phaselock','Callback',callbackStr);
	
	%==============X-Correlation=====================
	hCalcXCorrMenu=uimenu(hCalcMenu,'Label','X-Correlation','Enable','off','Separator','on');

	callbackStr = 'emegs2d(''CalcXCorr123'')';
	uimenu(hCalcXCorrMenu,'Label','(Data set 1 , Data set 2) => Data set 3','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcXCorr124'')';
	uimenu(hCalcXCorrMenu,'Label','(Data set 1 , Data set 2) => Data set 4','Callback',callbackStr);
	
	%============ProMax===========================
	
	hCalcPMAMenu=uimenu(hCalcMenu,'Label','ProMax','Enable','on','Separator','on');		
		hCalcPMAActMenu=uimenu(hCalcPMAMenu,'Label','Actual data set');
			callbackStr = 'emegs2d(''CalcPMAActActDat'')';
			hCalcPMAActActMenu=uimenu(hCalcPMAActMenu,'Label','ProMax of actual data set','Enable','on','Callback',callbackStr);
			callbackStr = 'emegs2d(''CalcPMAActOrgDat'')';
			hCalcPMAActOrgMenu=uimenu(hCalcPMAActMenu,'Label','ProMax of original data set','Enable','on','Callback',callbackStr);
		hCalcPMAAllMenu=uimenu(hCalcPMAMenu,'Label','All data sets');
			callbackStr = 'emegs2d(''CalcPMAAllActDat'')';
			hCalcPMAAllActMenu=uimenu(hCalcPMAAllMenu,'Label','ProMax of actual data set','Enable','on','Callback',callbackStr);
			callbackStr = 'emegs2d(''CalcPMAAllOrgDat'')';
			hCalcPMAActOrgMenu=uimenu(hCalcPMAAllMenu,'Label','ProMax of original data set','Enable','on','Callback',callbackStr);
			
	%============VariMax===========================

	hCalcVMAMenu=uimenu(hCalcMenu,'Label','VariMax','Enable','on','Separator','on');		
		hCalcVMAActMenu=uimenu(hCalcVMAMenu,'Label','Actual data set');
			callbackStr = 'emegs2d(''CalcVMAActActDat'')';
			hCalcVMAActActMenu=uimenu(hCalcVMAActMenu,'Label','VariMax of actual data set','Enable','on','Callback',callbackStr);
			callbackStr = 'emegs2d(''CalcVMAActOrgDat'')';
			hCalcVMAActOrgMenu=uimenu(hCalcVMAActMenu,'Label','VariMax of original data set','Enable','on','Callback',callbackStr);
		hCalcVMAAllMenu=uimenu(hCalcVMAMenu,'Label','All data sets');
			callbackStr = 'emegs2d(''CalcVMAAllActDat'')';
			hCalcVMAAllActMenu=uimenu(hCalcVMAAllMenu,'Label','VariMax of actual data set','Enable','on','Callback',callbackStr);
			callbackStr = 'emegs2d(''CalcVMAAllOrgDat'')';
			hCalcVMAActOrgMenu=uimenu(hCalcVMAAllMenu,'Label','VariMax of original data set','Enable','on','Callback',callbackStr);	
		
	%============ICA===========================

	hCalcICAMenu=uimenu(hCalcMenu,'Label','ICA','Enable','on','Separator','on');
		
		hCalcICAActMenu=uimenu(hCalcICAMenu,'Label','Actual data set');
	
			hCalcICAActActMenu=uimenu(hCalcICAActMenu,'Label','ICA of actual data set');
				callbackStr = 'emegs2d(''CalcICAActActDat'')';
				hCalcActICAActOrgMenu=uimenu(hCalcICAActActMenu,'Label','Data Matrix','Enable','on','Callback',callbackStr);		
		
			hCalcICAActOrgMenu=uimenu(hCalcICAActMenu,'Label','ICA of original data set','Enable','on');
				callbackStr = 'emegs2d(''CalcICAActOrgDat'')';
				hCalcActICAOrgOrgMenu=uimenu(hCalcICAActOrgMenu,'Label','Data Matrix','Enable','on','Callback',callbackStr);
				
	hCalcICAAllMenu=uimenu(hCalcICAMenu,'Label','All data sets');
			
			hCalcICAAllActMenu=uimenu(hCalcICAAllMenu,'Label','ICA of actual data sets');
				callbackStr = 'emegs2d(''CalcICAAllActDat'')';
				hCalcActICAActOrgMenu=uimenu(hCalcICAAllActMenu,'Label','Data Matrix','Enable','on','Callback',callbackStr);
				
			hCalcICAAllOrgMenu=uimenu(hCalcICAAllMenu,'Label','ICA of original data set','Enable','on');
				callbackStr = 'emegs2d(''CalcICAActOrgDat'')';
				hCalcActICAOrgOrgMenu=uimenu(hCalcICAAllOrgMenu,'Label','Data Matrix','Enable','on','Callback',callbackStr);
	
	hCalcICACelMenu=uimenu(hCalcICAMenu,'Label','All Cells');	
		callbackStr = 'emegs2d(''CalcICACelActDat'')';
		hCalcCelICAOrgOrgMenu=uimenu(hCalcICACelMenu,'Label','Data Matrix','Enable','on','Callback',callbackStr);
	
	%============PCA===========================
	hCalcPCAMenu=uimenu(hCalcMenu,'Label','PCA','Enable','on','Separator','on');
		
		hCalcPCAActMenu=uimenu(hCalcPCAMenu,'Label','Actual data set');
	
			hCalcPCAActActMenu=uimenu(hCalcPCAActMenu,'Label','PCA of actual data set');
		
				callbackStr = 'emegs2d(''CalcPCAActActDat'')';
				hCalcActPCAActOrigMenu=uimenu(hCalcPCAActActMenu,'Label','Data Matrix','Enable','on','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPCAActActCov'')';
				hCalcActPCAActDataMenu=uimenu(hCalcPCAActActMenu,'Label','Covariance Matrix','Enable','on','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPCAActActCor'')';
				hCalcActPCAActDataMenu=uimenu(hCalcPCAActActMenu,'Label','Correlation Matrix','Enable','on','Callback',callbackStr);
		
			hCalcPCAActOrgMenu=uimenu(hCalcPCAActMenu,'Label','PCA of original data set','Enable','on');
				callbackStr = 'emegs2d(''CalcPCAActOrgDat'')';
				hCalcActPCAOrgOrgMenu=uimenu(hCalcPCAActOrgMenu,'Label','Data Matrix','Enable','on','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPCAActOrgCov'')';
				hCalcActPCAOrgDataMenu=uimenu(hCalcPCAActOrgMenu,'Label','Covariance Matrix','Enable','on','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPCAActOrgCor'')';
				hCalcActPCAOrgDataMenu=uimenu(hCalcPCAActOrgMenu,'Label','Correlation Matrix','Enable','on','Callback',callbackStr);
		
		hCalcPCAAllMenu=uimenu(hCalcPCAMenu,'Label','All data sets');
			
			hCalcPCAAllActMenu=uimenu(hCalcPCAAllMenu,'Label','PCA of actual data sets');
				
				callbackStr = 'emegs2d(''CalcPCAAllActDat'')';
				hCalcActPCAActOrigMenu=uimenu(hCalcPCAAllActMenu,'Label','Data Matrix','Enable','on','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPCAAllActCov'')';
				hCalcActPCAActDataMenu=uimenu(hCalcPCAAllActMenu,'Label','Covariance Matrix','Enable','on','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPCAAllActCor'')';
				hCalcActPCAActDataMenu=uimenu(hCalcPCAAllActMenu,'Label','Correlation Matrix','Enable','on','Callback',callbackStr);
			
			hCalcPCAAllOrgMenu=uimenu(hCalcPCAAllMenu,'Label','PCA of original data set','Enable','on');
				
				callbackStr = 'emegs2d(''CalcPCAAllOrgDat'')';
				hCalcActPCAOrgOrgMenu=uimenu(hCalcPCAAllOrgMenu,'Label','Data Matrix','Enable','on','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPCAAllOrgCov'')';
				hCalcActPCAOrgDataMenu=uimenu(hCalcPCAAllOrgMenu,'Label','Covariance Matrix','Enable','on','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPCAAllOrgCor'')';
				hCalcActPCAOrgDataMenu=uimenu(hCalcPCAAllOrgMenu,'Label','Correlation Matrix','Enable','on','Callback',callbackStr);

	%============POLYFIT===========================
	hCalcPolyMenu=uimenu(hCalcMenu,'Label','Polyfit','Enable','off','Separator','on');
   		hCalcPolyActMenu=uimenu(hCalcPolyMenu,'Label','Actual data set');
   
   			hCalcPolyActAllMenu=uimenu(hCalcPolyActMenu,'Label','Use all points');
   
				callbackStr = 'emegs2d(''CalcPolyActAllDeg1'')';
				uimenu(hCalcPolyActAllMenu,'Label','Polynomial degree = 1','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyActAllDeg2'')';
				uimenu(hCalcPolyActAllMenu,'Label','Polynomial degree = 2','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyActAllDeg3'')';
				uimenu(hCalcPolyActAllMenu,'Label','Polynomial degree = 3','Callback',callbackStr);
   
   			hCalcPolyActBaseMenu=uimenu(hCalcPolyActMenu,'Label','Use baseline');
   
				callbackStr = 'emegs2d(''CalcPolyActBaseDeg1'')';
				uimenu(hCalcPolyActBaseMenu,'Label','Polynomial degree = 1','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyActBaseDeg2'')';
				uimenu(hCalcPolyActBaseMenu,'Label','Polynomial degree = 2','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyActBaseDeg3'')';
				uimenu(hCalcPolyActBaseMenu,'Label','Polynomial degree = 3','Callback',callbackStr);
   
   			hCalcPolyActFileMenu=uimenu(hCalcPolyActMenu,'Label','Use file');
   
				callbackStr = 'emegs2d(''CalcPolyActFileDeg1'')';
				uimenu(hCalcPolyActFileMenu,'Label','Polynomial degree = 1','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyActFileDeg2'')';
				uimenu(hCalcPolyActFileMenu,'Label','Polynomial degree = 2','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyActFileDeg3'')';
				uimenu(hCalcPolyActFileMenu,'Label','Polynomial degree = 3','Callback',callbackStr);
   
   
   		hCalcPolyAllMenu=uimenu(hCalcPolyMenu,'Label','All data sets');

			hCalcPolyAllAllMenu=uimenu(hCalcPolyAllMenu,'Label','Use all points');
   
				callbackStr = 'emegs2d(''CalcPolyAllAllDeg1'')';
				uimenu(hCalcPolyAllAllMenu,'Label','Polynomial degree = 1','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyAllAllDeg2'')';
				uimenu(hCalcPolyAllAllMenu,'Label','Polynomial degree = 2','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyAllAllDeg3'')';
				uimenu(hCalcPolyAllAllMenu,'Label','Polynomial degree = 3','Callback',callbackStr);
   
   			hCalcPolyAllBaseMenu=uimenu(hCalcPolyAllMenu,'Label','Use baseline');
   
				callbackStr = 'emegs2d(''CalcPolyAllBaseDeg1'')';
				uimenu(hCalcPolyAllBaseMenu,'Label','Polynomial degree = 1','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyAllBaseDeg2'')';
				uimenu(hCalcPolyAllBaseMenu,'Label','Polynomial degree = 2','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyAllBaseDeg3'')';
				uimenu(hCalcPolyAllBaseMenu,'Label','Polynomial degree = 3','Callback',callbackStr);
   
  			 hCalcPolyAllFileMenu=uimenu(hCalcPolyAllMenu,'Label','Use file');
   
				callbackStr = 'emegs2d(''CalcPolyAllFileDeg1'')';
				uimenu(hCalcPolyAllFileMenu,'Label','Polynomial degree = 1','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyAllFileDeg2'')';
				uimenu(hCalcPolyAllFileMenu,'Label','Polynomial degree = 2','Callback',callbackStr);
				callbackStr = 'emegs2d(''CalcPolyAllFileDeg3'')';
				uimenu(hCalcPolyAllFileMenu,'Label','Polynomial degree = 3','Callback',callbackStr);

   %============GROUPS===========================
	hCalcChanGroupsMenu=uimenu(hCalcMenu,'Label','Channel groups','Separator','on','Enable','off');
	callbackStr = 'emegs2d(''CalcChanGroupLeftRightFrontBack'')';
	hCalcChanGroupsLeftRightMenu=uimenu(hCalcChanGroupsMenu,'Label','Left - Right - Front - Back (All)','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''CalcChanGroupLeftRightFrontBackAnd'')';
	hCalcChanGroupsLeftRightMenu=uimenu(hCalcChanGroupsMenu,'Label','Left - Right - Front - Back (And)','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''CalcChanGroupLeftRight'')';
	hCalcChanGroupsLeftRightMenu=uimenu(hCalcChanGroupsMenu,'Label','Left - Right','Callback',callbackStr,'Enable','on','Separator','on');
	callbackStr = 'emegs2d(''CalcChanGroupFrontBack'')';
	hCalcChanGroupFrontBackMenu=uimenu(hCalcChanGroupsMenu,'Label','Front - Back','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''CalcChanGroupLeftRightBack'')';
	hCalcChanGroupsLeftRightMenu=uimenu(hCalcChanGroupsMenu,'Label','Left  - Right (Back)','Callback',callbackStr,'Enable','on','Separator','on');
	callbackStr = 'emegs2d(''CalcChanGroupLeftRightFront'')';
	hCalcChanGroupsLeftRightMenu=uimenu(hCalcChanGroupsMenu,'Label','Left  - Right (Front)','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''CalcChanGroupFrontBackLeft'')';
	hCalcChanGroupFrontBackMenu=uimenu(hCalcChanGroupsMenu,'Label','Front - Back (Left)','Callback',callbackStr,'Enable','on','Separator','on');
	callbackStr = 'emegs2d(''CalcChanGroupFrontBackRight'')';
	hCalcChanGroupFrontBackMenu=uimenu(hCalcChanGroupsMenu,'Label','Front - Back (Right)','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''CalcChanGroupOpen'')';
	hCalcChanGroupsOpenMenu=uimenu(hCalcChanGroupsMenu,'Label','Open group file','Callback',callbackStr,'Enable','on','Separator','on');
	callbackStr = 'emegs2d(''CalcChanGroupMean'')';
	hCalcChanGroupsMeanMenu=uimenu(hCalcChanGroupsMenu,'Label','Mean','Callback',callbackStr,'Separator','on','Enable','off','Tag','CalcChanGroupMean');
	callbackStr = 'emegs2d(''CalcChanGroupGP'')';
	hCalcChanGroupsGPMenu=uimenu(hCalcChanGroupsMenu,'Label','Global Power','Callback',callbackStr,'Enable','off','Tag','CalcChanGroupGP');
	
	%============EDIT EGIS DATA===========================
	hCalcEgisMenu=uimenu(hCalcMenu,'Label','EGIS session file','Separator','on','Enable','on');
	callbackStr = 'emegs2d(''CalcViewEgisData'')';
	hCalcEditEgisMenu=uimenu(hCalcEgisMenu,'Label','View','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''CalcEditEgisData'')';
	hCalcViewEgisMenu=uimenu(hCalcEgisMenu,'Label','Edit','Callback',callbackStr,'Enable','on');
	callbackStr = 'emegs2d(''CalcEyeCorrEgisData'')';
	hCalcEyeCorrEgisMenu=uimenu(hCalcEgisMenu,'Label','Eye Correction','Callback',callbackStr,'Enable','on','Separator','on');
	callbackStr = 'emegs2d(''CalcEyeCorrEgisDataBatch'')';
	hCalcEyeCorrEgisBatchMenu=uimenu(hCalcEgisMenu,'Label','Eye Correction Batch','Callback',callbackStr,'Enable','on');

	%=============USER===========================
	hCalcUserMenu=uimenu(hCalcMenu,'Label','Your own (CalcUserFile.m)','Separator','on','Enable','off');
	callbackStr = 'emegs2d(''CalcUserFileAct'')';
	uimenu(hCalcUserMenu,'Label','Actual data set','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcUserFileAll'')';
	uimenu(hCalcUserMenu,'Label','All data sets','Callback',callbackStr);
			
	%==============AVERAGE=====================
	hCalcAvgMenu=uimenu(hCalcMenu,'Label','Average','Separator','on','Enable','off');

	callbackStr = 'emegs2d(''CalcAvgNoStdWeight123'')';
	uimenu(hCalcAvgMenu,'Label','(Data set 1 , Data set 2) => Data set 3','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcAvgNoStdWeight124'')';
	uimenu(hCalcAvgMenu,'Label','(Data set 1 , Data set 2) => Data set 4','Callback',callbackStr);
	
	hCalcAvgUseStdMenu=uimenu(hCalcAvgMenu,'Label','Use Std Weight Matrix','Separator','on');
	callbackStr = 'emegs2d(''CalcAvgUseStdWeight123'')';
	uimenu(hCalcAvgUseStdMenu,'Label','Avg(Data set 1 , Data set 2) => Data set 3','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcAvgUseStdWeight124'')';
	uimenu(hCalcAvgUseStdMenu,'Label','Avg(Data set 1 , Data set 2) => Data set 4','Callback',callbackStr);
	
	%=============DIFFERENCE=====================
    callbackStr = 'emegs2d(''CalcDiffMenu'')';
	hCalcDiffMenu=uimenu(hCalcMenu,'Label','Difference','Enable','off','Callback',callbackStr,'Accelerator','d');

	%===============FILTER SPATIAL=======================
	hCalcFiltSpatMenu=uimenu(hCalcMenu,'Label','Filter Spatial','Userdata',[],'Separator','on','Enable','off');
    callbackStr = 'emegs2d(''FiltSpatClear'')';
    hCalcFiltSpatAllMenu=uimenu(hCalcFiltSpatMenu,'Label','No further filtering','Callback',callbackStr);
	callbackStr = 'emegs2d(''FiltSpatAll'')';
    hCalcFiltSpatAllMenu=uimenu(hCalcFiltSpatMenu,'Label','All data sets','Callback',callbackStr,'Separator','on');
    callbackStr = 'emegs2d(''FiltSpatAct'')';
	hCalcFiltSpatActMenu=uimenu(hCalcFiltSpatMenu,'Label','Actual data set','Callback',callbackStr);
    
	%===============FILTER TEMPORAL=======================
	hCalcFiltTempMenu=uimenu(hCalcMenu,'Label','Filter Temporal','Enable','off');
	
    callbackStr = 'emegs2d(''FiltCoeffClear'')';
	uimenu(hCalcFiltTempMenu,'Label','No further filtering','Callback',callbackStr);
	hCalcFiltSetCoeffMenu=uimenu(hCalcFiltTempMenu,'Label','Set filter file','Separator','on');
	callbackStr = 'emegs2d(''SetHighFiltCoeff'')';
	uimenu(hCalcFiltSetCoeffMenu,'Label','Highpass','Callback',callbackStr);
	callbackStr = 'emegs2d(''SetLowFiltCoeff'')';
	uimenu(hCalcFiltSetCoeffMenu,'Label','Lowpass','Callback',callbackStr);
	callbackStr = 'emegs2d(''SetHighLowFiltCoeff'')';
	uimenu(hCalcFiltSetCoeffMenu,'Label','High- & lowpass','Callback',callbackStr);

	hCalcFiltSaveFileMenu=uimenu(hCalcFiltTempMenu,'Label','Save filter file','Callback',callbackStr,'Enable','off','Separator','on');
	callbackStr = 'emegs2d(''SaveHighFiltCoeff'')';
	uimenu(hCalcFiltSaveFileMenu,'Label','Highpass','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''SaveLowFiltCoeff'')';
	uimenu(hCalcFiltSaveFileMenu,'Label','Lowpass','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''SaveHighLowFiltCoeff'')';
	uimenu(hCalcFiltSaveFileMenu,'Label','High- & lowpass','Callback',callbackStr,'Enable','off');

	hCalcFiltOpenFileMenu=uimenu(hCalcFiltTempMenu,'Label','Open filter file');
	callbackStr = 'emegs2d(''OpenHighFiltCoeff'')';
	uimenu(hCalcFiltOpenFileMenu,'Label','Highpass','Callback',callbackStr);
	callbackStr = 'emegs2d(''OpenLowFiltCoeff'')';
	uimenu(hCalcFiltOpenFileMenu,'Label','Lowpass','Callback',callbackStr);
	callbackStr = 'emegs2d(''OpenHighLowFiltCoeff'')';
	uimenu(hCalcFiltOpenFileMenu,'Label','High- & lowpass','Callback',callbackStr);

	hCalcFiltFiltMenu=uimenu(hCalcFiltTempMenu,'Label','Filter data','Separator','on','Enable','off');
	hCalcAllFiltFiltMenu=uimenu(hCalcFiltFiltMenu,'Label','All data sets');
	callbackStr = 'emegs2d(''CalcAllFiltHigh'')';
	uimenu(hCalcAllFiltFiltMenu,'Label','Highpass','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''CalcAllFiltLow'')';
	uimenu(hCalcAllFiltFiltMenu,'Label','Lowpass','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''CalcAllFiltHighLow'')';
	uimenu(hCalcAllFiltFiltMenu,'Label','High- & lowpass','Callback',callbackStr,'Enable','off');

	hCalcActFiltFiltMenu=uimenu(hCalcFiltFiltMenu,'Label','Actual data set');
	callbackStr = 'emegs2d(''CalcActFiltHigh'')';
	uimenu(hCalcActFiltFiltMenu,'Label','Highpass','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''CalcActFiltLow'')';
	uimenu(hCalcActFiltFiltMenu,'Label','Lowpass','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''CalcActFiltHighLow'')';
	uimenu(hCalcActFiltFiltMenu,'Label','High- & lowpass','Callback',callbackStr,'Enable','off');
	
    
    %=============================================
	%===============ABSOLUTE=======================
	hCalcAbsMenu=uimenu(hCalcMenu,'Label','Absolute','Separator','on','Enable','off');
	
    callbackStr = 'emegs2d(''CalcAbsClear'')';
    hCalcAbsClearMenu=uimenu(hCalcAbsMenu,'Label','No further abs','Callback',callbackStr,'Tag','CalcAbsClear','Userdata',0);
	callbackStr = 'emegs2d(''CalcAbsAll'')';
	hCalcAbsAllMenu=uimenu(hCalcAbsMenu,'Label','All data sets','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''CalcAbsAct'')';
	hCalcAbsActMenu=uimenu(hCalcAbsMenu,'Label','Actual data set','Callback',callbackStr);
    
	%==============INVERT=====================
	hCalcInvertMenu=uimenu(hCalcMenu,'Label','Invert','Enable','off');
	callbackStr = 'emegs2d(''CalcInvertAll'')';
	uimenu(hCalcInvertMenu,'Label','All data sets','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcInvertAct'')';
	uimenu(hCalcInvertMenu,'Label','Actual data set','Callback',callbackStr);

	%===============NORMALIZE====================
	hCalcNormMenu=uimenu(hCalcMenu,'Label','Normalize & Transform','Enable','off');
	
	hCalcNormAllMenu=uimenu(hCalcNormMenu,'Label','All data sets');
	hCalcNormActMenu=uimenu(hCalcNormMenu,'Label','Actual data set');

	callbackStr = 'emegs2d(''CalcNormAll0x1'')';
	hCalcNormAll0x1=uimenu(hCalcNormAllMenu,'Label','with 0 <=x<=1','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcNormAll1x1'')';
	hCalcNormAll1x1=uimenu(hCalcNormAllMenu,'Label','with -1<=x<=1','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcNormAllMeanStd'')';
	hCalcNormAllMeanStd=uimenu(hCalcNormAllMenu,'Label','with mean=0 & std=1','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcNormAllLogE'')';
	hCalcNormAllLogE=uimenu(hCalcNormAllMenu,'Label','natural log','Callback',callbackStr);
    callbackStr = 'emegs2d(''CalcNormAllLog10'')';
	hCalcNormAllLog10=uimenu(hCalcNormAllMenu,'Label','base 10 log','Callback',callbackStr);
    callbackStr = 'emegs2d(''CalcNormAllSqrt'')';
	hCalcNormAllSqrt=uimenu(hCalcNormAllMenu,'Label','square root','Callback',callbackStr);

	hCalcNormAllToValMenu=uimenu(hCalcNormAllMenu,'Label','to value:','Separator','on');
	callbackStr = 'emegs2d(''CalcNormAllMaxAbs'')';
	hCalcNormMaxMenu=uimenu(hCalcNormAllToValMenu,'Label','Absoluplot2dte Maximum','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcNormAllMedAbs'')';
	hCalcNormMaxMenu=uimenu(hCalcNormAllToValMenu,'Label','Median','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcNormAllMeanAbs'')';
	hCalcNormMaxMenu=uimenu(hCalcNormAllToValMenu,'Label','Mean','Callback',callbackStr);
	
	callbackStr = 'emegs2d(''CalcNormAct0x1'')';
	hCalcNormAll0x1=uimenu(hCalcNormActMenu,'Label','with 0 <=x<=1','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcNormAct1x1'')';
	hCalcNormAct1x1=uimenu(hCalcNormActMenu,'Label','with -1<=x<=1','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcNormActMeanStd'')';
	hCalcNormActMeanStd=uimenu(hCalcNormActMenu,'Label','with mean=0 & std=1','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcNormActLogE'')';
	hCalcNormActLogE=uimenu(hCalcNormActMenu,'Label','natural log','Callback',callbackStr);
    callbackStr = 'emegs2d(''CalcNormActLog10'')';
	hCalcNormActLog10=uimenu(hCalcNormActMenu,'Label','base 10 log','Callback',callbackStr);
    callbackStr = 'emegs2d(''CalcNormActSqrt'')';
	hCalcNormActSqrt=uimenu(hCalcNormActMenu,'Label','square root','Callback',callbackStr);

	hCalcNormAllToValMenu=uimenu(hCalcNormActMenu,'Label','to value:','Separator','on');
	callbackStr = 'emegs2d(''CalcNormActMaxAbs'')';
	hCalcNormMaxMenu=uimenu(hCalcNormAllToValMenu,'Label','Absolute Maximum','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcNormActMedAbs'')';
	hCalcNormMaxMenu=uimenu(hCalcNormAllToValMenu,'Label','Median','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcNormActMeanAbs'')';
	hCalcNormMaxMenu=uimenu(hCalcNormAllToValMenu,'Label','Mean','Callback',callbackStr);
	%=============================================
	
	%=============POTENTIAL======================
	hCalcPotMenu=uimenu(hCalcMenu,'Label','Potential','Separator','on','Enable','off');
	hCalcPotIntMenu=uimenu(hCalcPotMenu,'Label','Integral');
	callbackStr = 'emegs2d(''CalcPotIntegralInteractiv'')';
	uimenu(hCalcPotIntMenu,'Label','Interactiv','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcPotIntegralFile'')';
	uimenu(hCalcPotIntMenu,'Label','File','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcPotIntegralDefault'')';
	uimenu(hCalcPotIntMenu,'Label','Default','Callback',callbackStr);
	
	hCalcPotMeanMenu=uimenu(hCalcPotMenu,'Label','Mean');
	callbackStr = 'emegs2d(''CalcPotMeanInteractiv'')';
	uimenu(hCalcPotMeanMenu,'Label','Interactiv','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcPotMeanFile'')';
	uimenu(hCalcPotMeanMenu,'Label','File','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcPotMeanDefault'')';
	uimenu(hCalcPotMeanMenu,'Label','Default','Callback',callbackStr);


	%===============REREFERENCE====================
	hCalcReRefMenu=uimenu(hCalcMenu,'Label','Rereference','Enable','off');
	hCalcAllReRefMenu=uimenu(hCalcReRefMenu,'Label','All data sets');
	hCalcActReRefMenu=uimenu(hCalcReRefMenu,'Label','Actual data set');

	callbackStr = 'emegs2d(''CalcAllReRefAvgRef'')';
	uimenu(hCalcAllReRefMenu,'Label','Average Reference','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcActReRefAvgRef'')';
	uimenu(hCalcActReRefMenu,'Label','Average Reference','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcAllReRefLinkedEars'')';
	uimenu(hCalcAllReRefMenu,'Label','Linked ears','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcActReRefLinkedEars'')';
	uimenu(hCalcActReRefMenu,'Label','Linked ears','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcAllReRefLeftEar'')';
	uimenu(hCalcAllReRefMenu,'Label','Left ear','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcActReRefLeftEar'')';
	uimenu(hCalcActReRefMenu,'Label','Left ear','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcAllReRefRightEar'')';
	uimenu(hCalcAllReRefMenu,'Label','Right ear','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcActReRefRightEar'')';
	uimenu(hCalcActReRefMenu,'Label','Right ear','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcAllReRefCz'')';
	uimenu(hCalcAllReRefMenu,'Label','Vertex (Cz)','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcActReRefCz'')';
	uimenu(hCalcActReRefMenu,'Label','Vertex (Cz)','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcAllReRefSpecial'')';
	uimenu(hCalcAllReRefMenu,'Label','Special','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcActReRefSpecial'')';
	uimenu(hCalcActReRefMenu,'Label','Special','Callback',callbackStr);
  	callbackStr = 'emegs2d(''CalcAllReRefFromFile'')';
	uimenu(hCalcAllReRefMenu,'Label','From File...','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcActReRefFromFile'')';
	uimenu(hCalcActReRefMenu,'Label','From File...','Callback',callbackStr);       
			
	%==============SAMPLING=====================
	callbackStr = 'emegs2d(''setCalcSampleStatus'')';
	hCalcSampleMenu=uimenu(hCalcMenu,'Label','Sampling  ','Callback',callbackStr,'Enable','off');
	
	%===============GP/RMS====================
	hCalcGPMenu=uimenu(hCalcMenu,'Label','GP/RMS','Enable','off');
	
	hGPDiffMenu=uimenu(hCalcGPMenu,'Label','Difference');
	callbackStr = 'emegs2d(''CalcGPDiff12'')';
	uimenu(hGPDiffMenu,'Label','Data set 1 - Data set 2','Userdata',0,'Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcGPDiff21'')';
	uimenu(hGPDiffMenu,'Label','Data set 2 - Data set 1','Userdata',0,'Callback',callbackStr);
	
	hGPIntegralMenu=uimenu(hCalcGPMenu,'Label','Integral','Separator','on');
	callbackStr = 'emegs2d(''CalcGPIntegralInteractiv'')';
	uimenu(hGPIntegralMenu,'Label','Interactiv','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcGPIntegralFile'')';
	uimenu(hGPIntegralMenu,'Label','File','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcGPIntegralDefault'')';
	uimenu(hGPIntegralMenu,'Label','Default','Callback',callbackStr);
	
	hGPMeanMenu=uimenu(hCalcGPMenu,'Label','Mean');
	callbackStr = 'emegs2d(''CalcGPMeanInteractiv'')';
	uimenu(hGPMeanMenu,'Label','Interactiv','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcGPMeanFile'')';
	uimenu(hGPMeanMenu,'Label','File','Callback',callbackStr);
	callbackStr = 'emegs2d(''CalcGPMeanDefault'')';
	uimenu(hGPMeanMenu,'Label','Default','Callback',callbackStr);
	
	%===============CALCSYMMETRY==================
	hCalcSym=uimenu(hCalcMenu,'Label','Symmetry','Separator','on','Enable','off');
	callbackStr = 'emegs2d(''CalcSymAbs'')';
	uimenu(hCalcSym,'Label','Abs','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''CalcSymSign'')';
	uimenu(hCalcSym,'Label','Sign.','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''CalcSymLat'')';
	uimenu(hCalcSym,'Label','Lat.','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''CalcSymZNormLat'')';
	uimenu(hCalcSym,'Label','Z-Norm. Lat.','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''CalcSymZNormAbsLat'')';
	uimenu(hCalcSym,'Label','Abs. Z-Norm. Lat.','Callback',callbackStr,'Enable','off');
	callbackStr = 'emegs2d(''CalcSymSetPairs'')';
	uimenu(hCalcSym,'Label','Set Pairs','Callback',callbackStr,'Separator','on');
	callbackStr = 'emegs2d(''CalcSymGetPairs'')';
	uimenu(hCalcSym,'Label','Get Pairs','Callback',callbackStr);

	%===============GRAND MEAN====================
	callbackStr = 'emegs2d(''CalcGrandMean'')';
	hGrandMean=uimenu(hCalcMenu,'Label','Grand Mean','Callback',callbackStr,'Separator','on','Enable','off');
	
	%===============ROTATE SENSOR CONFIGURATION===
	callbackStr = 'emegs2d(''RotateSensorPosMenu'')';
	hECFileSet1020Menu=uimenu(hCalcMenu,'Label','Rotate Sensor Config.','Callback',callbackStr,'Separator','on','Enable','on');

	
	%===============RESET====================
	hResetMenu=uimenu(hCalcMenu,'Label','Reset','Separator','on','Enable','off');
	callbackStr = 'emegs2d(''ResetActFile'')';
	uimenu(hResetMenu,'Label','Reset actual data set','Callback',callbackStr);
	callbackStr = 'emegs2d(''ResetAllFiles'')';
	uimenu(hResetMenu,'Label','Reset all data sets','Callback',callbackStr);

	
	%===========================================
	%===============View========================

	hViewMenu=uimenu('Label','View','ForegroundColor',[0 0 1]);
	
		%============================================
		callbackStr = 'emegs2d(''setViewCorPicStatus'')';
		hViewCorPic=uimenu(hViewMenu,'Label','Cor. Picture','Callback',callbackStr,'Userdata',[]);
	
		%============================================
		hViewNegativ=uimenu(hViewMenu,'Label','Negativ','Enable','off','Separator','on');

			callbackStr = 'emegs2d(''setNegativUp'')';
			uimenu(hViewNegativ,'Label','Up','Callback',callbackStr);
			callbackStr = 'emegs2d(''setNegativDown'')';
			uimenu(hViewNegativ,'Label','Down','Callback',callbackStr);
	
	
	%===========================================
	%===============SURFACES====================
	hSurfMenu=uimenu('Label','Emegs3d','ForegroundColor',[0 0 1]);
		callbackStr = 'emegs2d(''Plot3dSLC'')';
		hSurfSLCMenu=uimenu(hSurfMenu,'Label','Scalp Potential','Callback',callbackStr,'Accelerator','b','Enable','off');
		callbackStr = 'emegs2d(''Plot3dMN'')';
		hSurfMNMenu=uimenu(hSurfMenu,'Label','L2 Min. Norm','Callback',callbackStr,'Accelerator','i','Enable','off');
        callbackStr = 'emegs2d(''Plot3dSLCMN'')';
		hSurfSLCMNMenu=uimenu(hSurfMenu,'Label','Scalp Potential and L2 Min. Norm','Callback',callbackStr,'Accelerator','+','Enable','off');
        callbackStr = 'emegs2d(''Plot3dUserDef'')';
		hSurfUserDefMenu=uimenu(hSurfMenu,'Label','Your own (Emegs3dUserDef.m)','Callback',callbackStr,'Accelerator','#','Enable','off');

    %============================================
	%==============Help=========================

	hHelpMenu=uimenu('Label','Help','ForeGroundColor',[0 0 1]);
    callbackStr = 'emegs2d(''HelpBrowser'')';
	hHelpMenuBrowser=uimenu(hHelpMenu,'Label','Help Browser','Callback',callbackStr);
    callbackStr = 'emegs2d(''MFileHelp'')';
    hHelpMenuMFileHelp=uimenu(hHelpMenu,'Label','m-file Help','Callback',callbackStr);
    
    
    
	% hList(65)
	hTopMenu=[hFileMenu hStyleMenu hExportMenu hCalcMenu hViewMenu hSynthMenu hSurfMenu];
	hTop1Menu=get(hTopMenu(1),'children');	% hFileMenu
	hTop2Menu=get(hTopMenu(2),'children');	% hStyleMenu
	hTop4Menu=get(hTopMenu(4),'children');	% hCalcMenu
	
   	%============ pointer ======================================================
	pointer=GetPointer;
	
	%============ actual menu settings ==========================================
	% data file format
	hDataFileFormat=get(hTop1Menu(3),'children');
	for ind=1:length(hDataFileFormat)
		AvgFileFormat=get(hDataFileFormat(ind),'Label');
		PointPosBeg=length(AvgFileFormat)+1;
		PointPosEnd=PointPosBeg+2;
		AvgFileFormat(PointPosBeg:PointPosEnd)=' ';
		if (ind==AvgFileFormatVal) AvgFileFormat(PointPosEnd)=setstr(pointer); end;
		set(hDataFileFormat(ind),'Label',AvgFileFormat,'Userdata',PointPosEnd);
	end;
			
	% sensor configuration file format
	hECFileFormat=get(hTop1Menu(2),'children');
	for ind=1:length(hECFileFormat)
		ECFileFormat=get(hECFileFormat(ind),'Label');
		PointPosBeg=length(ECFileFormat)+1;
		PointPosEnd=PointPosBeg+2;
		ECFileFormat(PointPosBeg:PointPosEnd)=' ';
		if (ind==ECFileFormatVal) ECFileFormat(PointPosEnd)=setstr(pointer); end;
		set(hECFileFormat(ind),'Label',ECFileFormat,'Userdata',PointPosEnd);
	end;	

	% View Default file format
	hViewDefault=get(hTop1Menu(1),'children');
	AutoDefFileMenuStatus=get(hViewDefault(4),'Userdata');
	AutoDefFileMenuLabel=get(hViewDefault(4),'Label');
	PointPosBeg=length(AutoDefFileMenuLabel)+1;
	PointPosEnd=PointPosBeg+2;
	AutoDefFileMenuLabel(PointPosBeg:PointPosEnd)=' ';
	if AutoDefFileMenuStatus
		AutoDefFileMenuLabel(PointPosEnd)=setstr(pointer);
	end
	set(hViewDefault(4),'Label',AutoDefFileMenuLabel);
	
	% text display
	hDisplayText=get(hTop2Menu(6),'children');
	for ind=1:length(hDisplayText)
		DisplayText=get(hDisplayText(ind),'Label');
		PointPosBeg=length(DisplayText)+1;
		PointPosEnd=PointPosBeg+2;
		DisplayText(PointPosBeg:PointPosEnd)=' ';
		if ind==7	% default: sensor names visible
			DisplayText(PointPosEnd)=setstr(pointer);
		end;
		set(hDisplayText(ind),'Label',DisplayText,'Userdata',PointPosEnd);	
	end;	
	
	% zero / trigger / cursor / sensor / line color / style 
	%==============
	hZeroLine=get(hTop2Menu(5),'children');
	hZeroLineColor=get(hZeroLine(2),'children');
	hZeroLineStyle=get(hZeroLine(1),'children');
	hZeroLineOnOffMenu=hZeroLine(3);
	
	hTriggerLine=get(hTop2Menu(4),'children');
	hTriggerLineColor=get(hTriggerLine(2),'children');
	hTriggerLineStyle=get(hTriggerLine(1),'children');
	hTriggerLineOnOffMenu=hTriggerLine(3);
	
	hCursorLine=get(hTop2Menu(3),'children');
	hCursorLineColor=get(hCursorLine(2),'children');
	hCursorLineStyle=get(hCursorLine(1),'children');
	hCursorLineOnOffMenu=hCursorLine(3);
	
	hSensorLineColor=get(hTop2Menu(7),'children');
	
	for ind=1:length(hZeroLineColor)
		ZeroLineColor=get(hZeroLineColor(ind),'Label');	
		TriggerLineColor=get(hTriggerLineColor(ind),'Label');	
		CursorLineColor=get(hCursorLineColor(ind),'Label');		
		PointPosBeg=length(ZeroLineColor)+1;
		PointPosEnd=length(ZeroLineColor)+3;
		ZeroLineColor(PointPosBeg:PointPosEnd)=' ';
		TriggerLineColor(PointPosBeg:PointPosEnd)=' ';
		CursorLineColor(PointPosBeg:PointPosEnd)=' ';
		set(hZeroLineColor(ind),'Label',ZeroLineColor,'Userdata',PointPosEnd);	
		set(hTriggerLineColor(ind),'Label',TriggerLineColor,'Userdata',PointPosEnd);
		set(hCursorLineColor(ind),'Label',CursorLineColor,'Userdata',PointPosEnd);		
	end;	
	for ind=1:length(hZeroLineStyle)
		ZeroLineStyle=get(hZeroLineStyle(ind),'Label');	
		TriggerLineStyle=get(hTriggerLineStyle(ind),'Label');	
		CursorLineStyle=get(hCursorLineStyle(ind),'Label');		
		PointPosBeg=length(ZeroLineStyle)+1;
		PointPosEnd=length(ZeroLineStyle)+3;
		ZeroLineStyle(PointPosBeg:PointPosEnd)=' ';
		TriggerLineStyle(PointPosBeg:PointPosEnd)=' ';
		CursorLineStyle(PointPosBeg:PointPosEnd)=' ';
		set(hZeroLineStyle(ind),'Label',ZeroLineStyle,'Userdata',PointPosEnd);	
		set(hTriggerLineStyle(ind),'Label',TriggerLineStyle,'Userdata',PointPosEnd);
		set(hCursorLineStyle(ind),'Label',CursorLineStyle,'Userdata',PointPosEnd);		
	end;	
	for ind=1:length(hSensorLineColor)
		SensorLineColorMethodLabel=get(hSensorLineColor(ind),'Label');
		PointPosBeg=length(SensorLineColorMethodLabel)+1;
		PointPosEnd=length(SensorLineColorMethodLabel)+3;
		SensorLineColorMethodLabel(PointPosBeg:PointPosEnd)=' ';
		set(hSensorLineColor(ind),'Label',SensorLineColorMethodLabel,'Userdata',PointPosEnd);	
	end
	
	% zero / trigger / cursor line visible on/off 
	%==============
	ZeroLineVisibleLabel=get(hZeroLineOnOffMenu,'Label');
	set(hZeroLineOnOffMenu,'Userdata',length(ZeroLineVisibleLabel));
	TriggerLineVisibleLabel=get(hTriggerLineOnOffMenu,'Label');
	set(hTriggerLineOnOffMenu,'Userdata',length(TriggerLineVisibleLabel));
	CursorLineVisibleLabel=get(hCursorLineOnOffMenu,'Label');
	set(hCursorLineOnOffMenu,'Userdata',length(CursorLineVisibleLabel));
		
	% background color 
	%==============
	hBGColor=get(hTop2Menu(1),'children');
	BGColorVec=get(hPlot2dChanFig,'Color');
	if BGColorVec == [1 1 1] ColorVal=2;	% white
	else ColorVal=1; end;
	for ind=1:2
		BGColorLabel=get(hBGColor(ind),'Label');	
		PointPosBeg=length(BGColorLabel)+1;
		PointPosEnd=length(BGColorLabel)+3;
		BGColorLabel(PointPosBeg:PointPosEnd)=' ';
		if ind==ColorVal BGColorLabel(PointPosEnd)=setstr(pointer); end;
		set(hBGColor(ind),'Label',BGColorLabel,'Userdata',PointPosEnd);
	end;	
	
	% XTick value
	%==============
	hTmp=get(hTop2Menu(2),'children');
	for ind=1:length(hTmp)
		ValLabel=get(hTmp(ind),'Label');
		PointPosBeg=length(ValLabel)+1;
		PointPosEnd=length(ValLabel)+3;
		ValLabel(PointPosBeg:PointPosEnd)=' ';
		set(hTmp(ind),'Label',ValLabel,'Userdata',PointPosEnd);
	end;	

	% AxesWidthHeight value
	%==============
	hhTmp=get(hTop2Menu(8),'children');
	for i=1:2
		hTmp=get(hhTmp(i),'children');
		for ind=1:length(hTmp)
			ValLabel=get(hTmp(ind),'Label');
			PointPosBeg=length(ValLabel)+1;
			PointPosEnd=length(ValLabel)+3;
			ValLabel(PointPosBeg:PointPosEnd)=' ';
			set(hTmp(ind),'Label',ValLabel,'Userdata',PointPosEnd);
		end
	end
	% sampling
	%==============
	SampMenuLabel=get(hTop4Menu(5),'Label');
	PointPosBeg=length(SampMenuLabel);
	PointPosEnd=PointPosBeg+2;
	SampMenuLabel(PointPosBeg:PointPosEnd)=' ';
	set(hTop4Menu(5),'Userdata',PointPosEnd);
	
	%===================================
	%===================================
	%===================================
	%hActFileNo																%1
	hECfgFilePath=uicontrol('Userdata',0,'Visible','off');					%2
	hEPosSpher=uicontrol('Userdata',0,'Value',1,'Visible','off');			%3 Value: 1: If sensor positions are located on sphere; 0: if not
	hENames=uicontrol('Userdata',0,'Visible','off');						%4
	hAxesPosMat=uicontrol('Visible','off');									%5
	
	hhAxesVec=uicontrol('Userdata',0,'Visible','off');						%6
	hhMenuEnable=uicontrol('Userdata',hMenuEnable,'Visible','off');			%7
	hhZeroLine=uicontrol('Userdata',0,'Visible','off');						%8
	hhTrigLine=uicontrol('Userdata',0,'Visible','off');						%9
	hhCursorLine=uicontrol('Userdata',0,'Visible','off');					%10
	
	hhText1=uicontrol('Userdata',[],'Visible','off');						%11
	hhText2=uicontrol('Userdata',[],'Visible','off');						%12
	hhText3=uicontrol('Userdata',[],'Visible','off');						%13
	hhText4=uicontrol('Userdata',[],'Visible','off');						%14
	hhText5=uicontrol('Userdata',[],'Visible','off','Value',0);				%15
	
	hDataSensorNChan=uicontrol('Userdata',[0 0],'Visible','off');			%16
	hFileInfoTextVec=uicontrol('Userdata',zeros(MaxNFiles,1),'Visible','off');		%17
	hBasePath=uicontrol('Userdata',BasePath,'Visible','off');				%18
	%hPlot3d													%19
	%hDomain													%20
	
	hhMinMaxText=uicontrol('Userdata',hMinMaxText,'Visible','off');			%21
	%hTrigPoint												%22
	%hCursorPoint												%23
	hCursorDec=uicontrol('Userdata',2,'Visible','off');					%24
	hhPlot2dChanAxes=uicontrol('Userdata',hPlot2dChanAxes,'Visible','off');	%25
	
	%hView																%26
	hkActAxes=uicontrol('Userdata',0,'Visible','off');					%27
	hActAxes=uicontrol('Userdata',0,'Visible','off');					%28
	hTrigLength=uicontrol('Userdata',0.5,'Visible','off');				%29
	hCursorLength=uicontrol('Userdata',0.5,'Visible','off');			%30

	hkTop=uicontrol('Userdata',0,'Visible','off');						%31
	hAxesTop=uicontrol('Userdata',0,'Visible','off');					%32
	hkFront=uicontrol('Userdata',0,'Visible','off');					%33 
	hAxesFront=uicontrol('Userdata',0,'Visible','off');					%34
	hkBack=uicontrol('Userdata',0,'Visible','off');						%35
	
	hAxesBack=uicontrol('Userdata',0,'Visible','off');					%36
	hkLeft=uicontrol('Userdata',0,'Visible','off');						%37 
	hAxesLeft=uicontrol('Userdata',0,'Visible','off');					%38
	hkRight=uicontrol('Userdata',0,'Visible','off');					%39 
	hAxesRight=uicontrol('Userdata',0,'Visible','off');					%40
	
	hkNorm=uicontrol('Userdata',0,'Visible','off');						%41
	hAxesNorm=uicontrol('Userdata',0,'Visible','off');					%42
	hkAll=uicontrol('Userdata',0,'Visible','off');						%43
	hAxesAll=uicontrol('Userdata',0,'Visible','off');					%44 
	%hActSpecVisible											        %45
	
	%hZoomSpecChan 												        %46
	%hAllSpecVisible 											        %47
	%hInfoAll													        %48
	hhMenuTextEnable=uicontrol('Userdata',hMenuTextEnable,'Visible','off','value',0);%49
	%hNPoints													        %50

	hNListHdr=uicontrol('Userdata',200,'Visible','off');		%51
	%hMinAmp													%52
	%hMaxAmp												%53
	%hMinPoint												%54
	%hMaxPoint												%55

	
	hFileNoVec=uicontrol('Userdata',[],'Visible','off','Value',0);				%56
	%hCalcBase												%57
	%hMinBase												%58
	%hMaxBase												%59
	%SampRate												%60

	%hColor													%61
	%hLineStyle												%62
	hhButVec=uicontrol('Userdata',[],'Visible','off');						%63
	hhSpecChanVec=uicontrol('Userdata',[],'Visible','off');				%64
	hhTopMenu=uicontrol('Userdata',hTopMenu,'Visible','off'); 				%65
	
	hhGPVec=uicontrol('Userdata',[],'Visible','off');						%66
	xxx = uicontrol('Userdata',0,'String','0','Visible','off');				%67
	hGlobPowCursorPoint=0;										%68
	hTakeGlobPowStdWeight=0;									%69
	hGP_RMS=0;												    %70
	
	hGlobPowFig=0;												%71
	hGlobPowAxes=0;											    %72
	hGlobPowTrigLine=0;											%73
	hGlobPowCursorLine=0;										%74
	hGlobPowTimeText=0;										    %75
	
	hSpec1Axes=uicontrol('Userdata',0,'Visible','off');					    %76
	hSpec1ZeroLine=uicontrol('Userdata',0,'Visible','off');				    %77
	hSpec1TrigLine=uicontrol('Userdata',0,'Visible','off');					%78
	hSpec1CursorLine=uicontrol('Userdata',0,'Visible','off');				%79
	hSpec1CursorText=uicontrol('Userdata',0,'Visible','off');				%80
	
	hGPIntMat=uicontrol('Userdata',[],'Visible','off');					%81
	%hOpenAvgFile												%82
	%hhIndexMenuList=uicontrol('Userdata',hIndexMenuList,'Visible','off','value',pointer);		%83
	hIndexMenu=uicontrol('Userdata',pointer,'Visible','off');				%83
	hSymPairs=uicontrol('Userdata',[],'Visible','off');						%84
	hPotIntMat=uicontrol('Userdata',[],'Visible','off');					%85
	
	AsciiFileParaVec=[0 0 129 1 0 0 0 1];
	hAsciiFileParaVec=uicontrol('Userdata',AsciiFileParaVec,'Visible','off');	%86
	hAsciiFileAvgVec=uicontrol('Userdata',[],'Visible','off');				%87
	%hPlotMedMedVec											%88
	%!!!!! Do not use !!!!											%89
	hDefFileNoVec = uicontrol('Userdata',[],'Visible','off');				%90
	
	hDefECfgFilePath=uicontrol('Userdata',[],'Visible','off');				%91
	DefFreqsRipMat=[0 0;0 0;40 50;3 45;5 2;3 45];
	hDefFreqsRipMat=uicontrol('Userdata',DefFreqsRipMat,'Visible','off');		
	hLowFiltCoeff=uicontrol('Userdata',[],'Visible','off');						
	hHighFiltCoeff=uicontrol('Userdata',[],'Visible','off');						
	hFiltVec=[hDefFreqsRipMat,hLowFiltCoeff,hHighFiltCoeff];						
	hhFiltVec=uicontrol('Userdata',hFiltVec,'Visible','off');				%92	
	%hPlot2dChanFig															%93
	hUserData = uicontrol('Userdata',[],'Visible','off');					%94
	hDefZerTriCurColor = uicontrol('Userdata',[],'Visible','off');			%95
	
	hDefZerTriCurLineStyle = uicontrol('Visible','off','value',0);									%96
	hPlot2dVersion=uicontrol('Userdata',Plot2dVersionString,'Value',Plot2dVersion ,'Visible','off');%97
	%hLineWidth													                                    %98
	hMatlabVersionStr=uicontrol('Userdata',MatlabVersionString,'Visible','off');					%99
	hMainMatlabVersion=uicontrol('Userdata',MainMatlabVersion,'Visible','off');						%100
	
	hXTickVal=uicontrol('Userdata',0,'value',0,'Visible','off');			%101
	hhSensorRotVec=uicontrol('Userdata',0,'value',0,'Visible','off');		%102
	hSepPathStr=uicontrol('Userdata',SepPathStr,'Visible','off');			%103
	hSpec2Axes=uicontrol('Userdata',0,'Visible','off');					    %104
	hDefDataPath=uicontrol('Userdata',0,'Visible','off');					%105

	hSpec2AxesVal=uicontrol('Userdata',0,'Visible','off');					%106
	hEditEgisFigHandleVec=uicontrol('Visible','off');						%107
	hOpenAvgFileStatus=uicontrol('Value',0,'Visible','off');				%108
	%hActAllVisible												            %109
	%hSetEegMegStatus											            %110
  	hSensorPosNormMat=uicontrol('Userdata',0,'Visible','off');				%111
   	hFontSizeVec=uicontrol('Userdata',DefFontSizeVec,'Visible','off');		%112
  	hVarVecMat=uicontrol('Visible','off');								    %113
  	hSigValVec=uicontrol('Visible','off');								    %114
   	hBaseMat=uicontrol('Visible','off');								    %115

	%hAdjustAmp												%116
	%hCenterAmp												%117
	%hDecAmp												%118
	%hDecDecIncAmp											%119
	%hIncAmp												%120
	%hIncDecIncAmp											%121
	%hMinPointSlider										%122
	%hMaxPointSlider										%123
 	%hDecIncStatusAmp										%124
	%hInvertViewAmp											%125
	hOpenFileBatch=uicontrol('Value',0,'Visible','off');					%126
	hEyeCorrEgisBatch=uicontrol('Value',0,'Visible','off');					%127
	hRGBColorMat=uicontrol('Userdata',RGBColorMat,'Visible','off');			%128
	%hCalcTotalBase											%129
	hViewCorPicIndVec=uicontrol('Value',0,'Visible','off');	%130
	hViewCorPicPath=uicontrol('Visible','off');				%131
	%hCursorPointSlider										%132
    %ContrastLine                                           %133
    %hCalcFiltTempMenu                          			%134
    %hCalcFiltSpatMenu										%135
    %hMouseZoomMode                                         %136
    %hDataFilePath                                          %137
    %hAxesSizeMode                                          %138
    %hNoUse													%139
    %MaxNFiles;											    %140
    hEcfgInfoText=0;                              			%141
	%hNoUse													%142-200

	%===============================================================
	hCalcAvgMat1=uicontrol('Visible','off');					%201
	hNChan1=uicontrol('Userdata',0,'Visible','off');			%202
	hNPoints1=uicontrol('Userdata',0,'Visible','off');			%203
	hFilePath1=uicontrol('Userdata',0,'Visible','off');			%204
	hNTrialAvgVec1=uicontrol('Userdata',0,'Visible','off');		%205
	
	hStdChanTimeMat1=uicontrol('Userdata',0,'Visible','off');	%206
	hSampRate1=uicontrol('Userdata',0,'Visible','off');			%207
	hAvgRef1=uicontrol('Userdata',0,'Visible','off');			%208
	hMedMedRawVec1=uicontrol('Userdata',0,'Visible','off');		%209
	hMedMedAvgVec1=uicontrol('Userdata',0,'Visible','off');		%210
	
	hMinMinAvgMat1=uicontrol('Userdata',0,'Visible','off');		%211
	hMaxMaxAvgMat1=uicontrol('Userdata',0,'Visible','off');		%212
	hMedMedAvgMat1=uicontrol('Userdata',0,'Visible','off');		%213
	%NoUse=uicontrol('Userdata',0,'Visible','off');				%214
	%NoUse=uicontrol('Userdata',0,'Visible','off');				%215
	hColor1=uicontrol('Value',ColorFileVec(1),'Userdata',RGBColorMat(ColorFileVec(1),:),'Visible','off');	%216
	hLineStyle1=uicontrol('Value',1,'Userdata','-','Visible','off');	%217
	hAllVisible1=uicontrol('Userdata',1,'Visible','off');	    		%218
	hDefColor1=uicontrol('Userdata',0,'Visible','off','value',0);		%219
	hDefLineStyle1=uicontrol('Userdata',0,'Visible','off','value',0);	%220
	
	hECfgFileFormat1=uicontrol('Userdata',DefECFileFormat,'Visible','off','Value',ECFileFormatVal);		    %221
	hAvgFileFormat1=uicontrol('Userdata',DefAvgFileFormat,'Visible','off','Value',AvgFileFormatVal,'String',DefAvgFileFormatExt);		%222
	hOpenAvgFile1=uicontrol('Userdata',0,'Visible','off');			%223
	hOrigAvgMat1=uicontrol('Userdata',0,'Visible','off');			%224
	hhDataVec1=uicontrol('Userdata',0,'Visible','off');				%225

	hGlobPowData1=uicontrol('Userdata',[],'Visible','off');			%226
	hGlobPowAmpText1=uicontrol('Userdata',0,'Visible','off');		%227
	hCalcGlobPowData1=uicontrol('Userdata',[],'Visible','off');		%228
	hSpecChanAmpText1=uicontrol('Userdata',0,'Visible','off');		%229										
	hhSigVec1=uicontrol('Userdata',[],'Visible','off');				%230
	
	hEgisAvgVec1=uicontrol('Userdata',[0 0 0],'Visible','off');		%231
	hEgisRawVec1=uicontrol('Userdata',zeros(12,1),'Visible','off');	%232
	hSensorLineColorVec1=uicontrol('Userdata',[],'Visible','off');	%233
	hAppSCADSVec1=uicontrol('Visible','off');						%234
	hWaveVec1=uicontrol('Visible','off','Userdata',[]);				%235
	hWaveMat1=uicontrol('Visible','off','Userdata',[]);				%236
	
	%===============================================================
	
	hCalcAvgMat2=uicontrol('Userdata',[],'Visible','off');		%251
	hNChan2=uicontrol('Userdata',0,'Visible','off');			%252
	hNPoints2=uicontrol('Userdata',0,'Visible','off');			%253
	hFilePath2=uicontrol('Userdata',0,'Visible','off');			%254
	hNTrialAvgVec2=uicontrol('Userdata',0,'Visible','off');		%255
	
	hStdChanTimeMat2=uicontrol('Userdata',0,'Visible','off');	%256
	hSampRate2=uicontrol('Userdata',0,'Visible','off');			%257
	hAvgRef2=uicontrol('Userdata',0,'Visible','off');			%258
	hMedMedRawVec2=uicontrol('Userdata',0,'Visible','off');		%259
	hMedMedAvgVec2=uicontrol('Userdata',0,'Visible','off');		%260
	
	hMinMinAvgMat2=uicontrol('Userdata',0,'Visible','off');		%261
	hMaxMaxAvgMat2=uicontrol('Userdata',0,'Visible','off');		%262
	hMedMedAvgMat2=uicontrol('Userdata',0,'Visible','off');		%263
	NoUse=uicontrol('Userdata',0,'Visible','off');				%264
	NoUse=uicontrol('Userdata',0,'Visible','off');				%265
	
	hColor2=uicontrol('Value',ColorFileVec(2),'Userdata',RGBColorMat(ColorFileVec(2),:),'Visible','off');	%266
	hLineStyle2=uicontrol('Value',1,'Userdata','-','Visible','off');	%267
	hAllVisible2=uicontrol('Userdata',1,'Visible','off');	    		%268
	hDefColor2=uicontrol('Userdata',0,'Visible','off','value',0);		%269
	hDefLineStyle2=uicontrol('Userdata',0,'Visible','off','value',0);	%270
	
	hECfgFileFormat2=uicontrol('Userdata',DefECFileFormat,'Visible','off','value',ECFileFormatVal);%271
	hAvgFileFormat2=uicontrol('Userdata',DefAvgFileFormat,'Visible','off','value',AvgFileFormatVal,'String',DefAvgFileFormatExt);%272
	hOpenAvgFile2=uicontrol('Userdata',0,'Visible','off');			%273
	hOrigAvgMat2=uicontrol('Userdata',0,'Visible','off');			%274
	hhDataVec2=uicontrol('Userdata',[],'Visible','off');			%275
	
	hGlobPowData2=uicontrol('Userdata',[],'Visible','off');		    %276
	hGlobPowAmpText2=uicontrol('Userdata',0,'Visible','off');		%277
	hCalcGlobPowData2=uicontrol('Userdata',[],'Visible','off');		%278
	hSpecChanAmpText2=uicontrol('Userdata',0,'Visible','off');	    %279														%279
	hhSigVec2=uicontrol('Userdata',[],'Visible','off');			    %280
		
	hEgisAvgVec2=uicontrol('Userdata',[0 0 0],'Visible','off');		%281
	hEgisRawVec2=uicontrol('Userdata',zeros(12,1),'Visible','off');	%282
	hSensorLineColorVec2=uicontrol('Userdata',[],'Visible','off');	%283
	hAppSCADSVec2=uicontrol('Visible','off');					%284
	hWaveVec2=uicontrol('Visible','off','Userdata',[]);			%285
	hWaveMat2=uicontrol('Visible','off','Userdata',[]);			%286
	%===============================================================
	
	hCalcAvgMat3=uicontrol('Userdata',[],'Visible','off');		%301
	hNChan3=uicontrol('Userdata',0,'Visible','off');			%302
	hNPoints3=uicontrol('Userdata',0,'Visible','off');			%303
	hFilePath3=uicontrol('Userdata',0,'Visible','off');			%304
	hNTrialAvgVec3=uicontrol('Userdata',0,'Visible','off');		%305
	
	hStdChanTimeMat3=uicontrol('Userdata',0,'Visible','off');	%306
	hSampRate3=uicontrol('Userdata',0,'Visible','off');			%307
	hAvgRef3=uicontrol('Userdata',0,'Visible','off');			%308
	hMedMedRawVec3=uicontrol('Userdata',0,'Visible','off');		%309
	hMedMedAvgVec3=uicontrol('Userdata',0,'Visible','off');		%310
	
	hMinMinAvgMat3=uicontrol('Userdata',0,'Visible','off');		%311
	hMaxMaxAvgMat3=uicontrol('Userdata',0,'Visible','off');		%312
	hMedMedAvgMat3=uicontrol('Userdata',0,'Visible','off');		%313
	NoUse=uicontrol('Userdata',0,'Visible','off');				%314
	NoUse=uicontrol('Userdata',0,'Visible','off');				%315
	
	hColor3=uicontrol('Value',ColorFileVec(3),'Userdata',RGBColorMat(ColorFileVec(3),:),'Visible','off');	%316
	hLineStyle3=uicontrol('Value',1,'Userdata','-','Visible','off');	%317
	hAllVisible3=uicontrol('Userdata',1,'Visible','off');	    		%318
	hDefColor3=uicontrol('Userdata',0','Visible','off','value',0);		%319
	hDefLineStyle3=uicontrol('Userdata',0,'Visible','off','value',0);	%320

	hECfgFileFormat3=uicontrol('Userdata',DefECFileFormat,'Visible','off','value',ECFileFormatVal);%321
	hAvgFileFormat3=uicontrol('Userdata',DefAvgFileFormat,'Visible','off','value',AvgFileFormatVal,'String',DefAvgFileFormatExt);%322
	hOpenAvgFile3=uicontrol('Userdata',0,'Visible','off');			%323
	hOrigAvgMat3=uicontrol('Userdata',0,'Visible','off');			%324
	hhDataVec3=uicontrol('Userdata',[],'Visible','off');			%325
	
	hGlobPowData3=uicontrol('Userdata',[],'Visible','off');		    %326
	hGlobPowAmpText3=uicontrol('Userdata',0,'Visible','off');		%327
	hCalcGlobPowData3=uicontrol('Userdata',[],'Visible','off');		%328
	hSpecChanAmpText3=uicontrol('Userdata',0,'Visible','off');	    %329														%329
	hhSigVec3=uicontrol('Userdata',[],'Visible','off');			    %330
																	
	hEgisAvgVec3=uicontrol('Userdata',[0 0 0],'Visible','off');		%331
	hEgisRawVec3=uicontrol('Userdata',zeros(12,1),'Visible','off');	%332
	hSensorLineColorVec3=uicontrol('Userdata',[],'Visible','off');	%333
	hAppSCADSVec3=uicontrol('Visible','off');					    %334
	hWaveVec3=uicontrol('Visible','off','Userdata',[]);				%335
	hWaveMat3=uicontrol('Visible','off','Userdata',[]);				%336
    
	%===============================================================
	
	hCalcAvgMat4=uicontrol('Userdata',[],'Visible','off');			%351
	hNChan4=uicontrol('Userdata',0,'Visible','off');				%352
	hNPoints4=uicontrol('Userdata',0,'Visible','off');				%353
	hFilePath4=uicontrol('Userdata',0,'Visible','off');			%354
	hNTrialAvgVec4=uicontrol('Userdata',0,'Visible','off');		%355
	
	hStdChanTimeMat4=uicontrol('Userdata',0,'Visible','off');	%356
	hSampRate4=uicontrol('Userdata',0,'Visible','off');			%357
	hAvgRef4=uicontrol('Userdata',0,'Visible','off');			%358
	hMedMedRawVec4=uicontrol('Userdata',0,'Visible','off');		%359
	hMedMedAvgVec4=uicontrol('Userdata',0,'Visible','off');		%360
	
	hMinMinAvgMat4=uicontrol('Userdata',0,'Visible','off');		%361
	hMaxMaxAvgMat4=uicontrol('Userdata',0,'Visible','off');		%362
	hMedMedAvgMat4=uicontrol('Userdata',0,'Visible','off');		%363
	NoUse=uicontrol('Userdata',0,'Visible','off');				%364
	NoUse=uicontrol('Userdata',0,'Visible','off');				%365
	
	hColor4=uicontrol('Value',ColorFileVec(4),'Userdata',RGBColorMat(ColorFileVec(4),:),'Visible','off');	%366
	hLineStyle4=uicontrol('Value',1,'Userdata','-','Visible','off');	%367
	hAllVisible4=uicontrol('Userdata',1,'Visible','off');	    		%368
	hDefColor4=uicontrol('Userdata',0,'Visible','off','value',0);		%369
	hDefLineStyle4=uicontrol('Userdata',0,'Visible','off','value',0);	%370

	hECfgFileFormat4=uicontrol('Userdata',DefECFileFormat,'Visible','off','value',ECFileFormatVal);%371
	hAvgFileFormat4=uicontrol('Userdata',DefAvgFileFormat,'Visible','off','value',AvgFileFormatVal,'String',DefAvgFileFormatExt);%372
	hOpenAvgFile4=uicontrol('Userdata',0,'Visible','off');			%373
	hOrigAvgMat4=uicontrol('Userdata',0,'Visible','off');			%374
	hhDataVec4=uicontrol('Userdata',[],'Visible','off');			%375
	
	hGlobPowData4=uicontrol('Userdata',[],'Visible','off');		    %376
	hGlobPowAmpText4=uicontrol('Userdata',0,'Visible','off');		%377
	hCalcGlobPowData4=uicontrol('Userdata',[],'Visible','off');		%378
	hSpecChanAmpText4=uicontrol('Userdata',0,'Visible','off');	    %379	
	hhSigVec4=uicontrol('Userdata',[],'Visible','off');			    %380
	
	hEgisAvgVec4=uicontrol('Userdata',[0 0 0],'Visible','off');		%381
	hEgisRawVec4=uicontrol('Userdata',zeros(12,1),'Visible','off');	%382
	hSensorLineColorVec4=uicontrol('Userdata',[],'Visible','off');	%383
	hAppSCADSVec4=uicontrol('Visible','off');					    %384
	hWaveVec4=uicontrol('Visible','off','Userdata',[]);				%385
	hWaveMat4=uicontrol('Visible','off','Userdata',[]);				%386
	
    %===============================================================
	
	hCalcAvgMat5=uicontrol('Userdata',[],'Visible','off');			%401
	hNChan5=uicontrol('Userdata',0,'Visible','off');				%402
	hNPoints5=uicontrol('Userdata',0,'Visible','off');				%403
	hFilePath5=uicontrol('Userdata',0,'Visible','off');			    %404
	hNTrialAvgVec5=uicontrol('Userdata',0,'Visible','off');		    %405
	
	hStdChanTimeMat5=uicontrol('Userdata',0,'Visible','off');	%406
	hSampRate5=uicontrol('Userdata',0,'Visible','off');			%407
	hAvgRef5=uicontrol('Userdata',0,'Visible','off');			%408
	hMedMedRawVec5=uicontrol('Userdata',0,'Visible','off');		%409
	hMedMedAvgVec5=uicontrol('Userdata',0,'Visible','off');		%410
	
	hMinMinAvgMat5=uicontrol('Userdata',0,'Visible','off');		%411
	hMaxMaxAvgMat5=uicontrol('Userdata',0,'Visible','off');		%412
	hMedMedAvgMat5=uicontrol('Userdata',0,'Visible','off');		%413
	NoUse=uicontrol('Userdata',0,'Visible','off');				%414
	NoUse=uicontrol('Userdata',0,'Visible','off');				%415
	
	hColor5=uicontrol('Value',ColorFileVec(5),'Userdata',RGBColorMat(ColorFileVec(5),:),'Visible','off');	%416
	hLineStyle5=uicontrol('Value',1,'Userdata','-','Visible','off');	%417
	hAllVisible5=uicontrol('Userdata',1,'Visible','off');	    		%418
	hDefColor5=uicontrol('Userdata',0,'Visible','off','value',0);		%419
	hDefLineStyle5=uicontrol('Userdata',0,'Visible','off','value',0);	%420

	hECfgFileFormat5=uicontrol('Userdata',DefECFileFormat,'Visible','off','value',ECFileFormatVal);%421
	hAvgFileFormat5=uicontrol('Userdata',DefAvgFileFormat,'Visible','off','value',AvgFileFormatVal,'String',DefAvgFileFormatExt);%422
	hOpenAvgFile5=uicontrol('Userdata',0,'Visible','off');			%423
	hOrigAvgMat5=uicontrol('Userdata',0,'Visible','off');			%424
	hhDataVec5=uicontrol('Userdata',[],'Visible','off');			%425
	
	hGlobPowData5=uicontrol('Userdata',[],'Visible','off');		    %426
	hGlobPowAmpText5=uicontrol('Userdata',0,'Visible','off');		%427
	hCalcGlobPowData5=uicontrol('Userdata',[],'Visible','off');		%428
	hSpecChanAmpText5=uicontrol('Userdata',0,'Visible','off');	    %429	
	hhSigVec5=uicontrol('Userdata',[],'Visible','off');			    %430
	
	hEgisAvgVec5=uicontrol('Userdata',[0 0 0],'Visible','off');		%431
	hEgisRawVec5=uicontrol('Userdata',zeros(12,1),'Visible','off');	%432
	hSensorLineColorVec5=uicontrol('Userdata',[],'Visible','off');	%433
	hAppSCADSVec5=uicontrol('Visible','off');					    %434
	hWaveVec5=uicontrol('Visible','off','Userdata',[]);				%435
	hWaveMat5=uicontrol('Visible','off','Userdata',[]);				%436
    
     %===============================================================
	
	hCalcAvgMat6=uicontrol('Userdata',[],'Visible','off');			%451
	hNChan6=uicontrol('Userdata',0,'Visible','off');				%452
	hNPoints6=uicontrol('Userdata',0,'Visible','off');				%453
	hFilePath6=uicontrol('Userdata',0,'Visible','off');			    %454
	hNTrialAvgVec6=uicontrol('Userdata',0,'Visible','off');		    %455
	
	hStdChanTimeMat6=uicontrol('Userdata',0,'Visible','off');	%456
	hSampRate6=uicontrol('Userdata',0,'Visible','off');			%457
	hAvgRef6=uicontrol('Userdata',0,'Visible','off');			%458
	hMedMedRawVec6=uicontrol('Userdata',0,'Visible','off');		%459
	hMedMedAvgVec6=uicontrol('Userdata',0,'Visible','off');		%460
	
	hMinMinAvgMat6=uicontrol('Userdata',0,'Visible','off');		%461
	hMaxMaxAvgMat6=uicontrol('Userdata',0,'Visible','off');		%462
	hMedMedAvgMat6=uicontrol('Userdata',0,'Visible','off');		%463
	NoUse=uicontrol('Userdata',0,'Visible','off');				%464
	NoUse=uicontrol('Userdata',0,'Visible','off');				%465
	
	hColor6=uicontrol('Value',ColorFileVec(6),'Userdata',RGBColorMat(ColorFileVec(6),:),'Visible','off');	%466
	hLineStyle6=uicontrol('Value',1,'Userdata','-','Visible','off');	%467
	hAllVisible6=uicontrol('Userdata',1,'Visible','off');	    		%468
	hDefColor6=uicontrol('Userdata',0,'Visible','off','value',0);		%469
	hDefLineStyle6=uicontrol('Userdata',0,'Visible','off','value',0);	%470

	hECfgFileFormat6=uicontrol('Userdata',DefECFileFormat,'Visible','off','value',ECFileFormatVal);%471
	hAvgFileFormat6=uicontrol('Userdata',DefAvgFileFormat,'Visible','off','value',AvgFileFormatVal,'String',DefAvgFileFormatExt);%472
	hOpenAvgFile6=uicontrol('Userdata',0,'Visible','off');			%473
	hOrigAvgMat6=uicontrol('Userdata',0,'Visible','off');			%474
	hhDataVec6=uicontrol('Userdata',[],'Visible','off');			%475
	
	hGlobPowData6=uicontrol('Userdata',[],'Visible','off');		    %476
	hGlobPowAmpText6=uicontrol('Userdata',0,'Visible','off');		%477
	hCalcGlobPowData6=uicontrol('Userdata',[],'Visible','off');		%478
	hSpecChanAmpText6=uicontrol('Userdata',0,'Visible','off');	    %479	
	hhSigVec6=uicontrol('Userdata',[],'Visible','off');			    %480
	
	hEgisAvgVec6=uicontrol('Userdata',[0 0 0],'Visible','off');		%481
	hEgisRawVec6=uicontrol('Userdata',zeros(12,1),'Visible','off');	%482
	hSensorLineColorVec6=uicontrol('Userdata',[],'Visible','off');	%483
	hAppSCADSVec6=uicontrol('Visible','off');					    %484
	hWaveVec6=uicontrol('Visible','off','Userdata',[]);				%485
	hWaveMat6=uicontrol('Visible','off','Userdata',[]);				%486
    %===============================================================

	NoUse=0;
	hNoUse=0;
    
    hMouseZoomMode = uicontrol('Visible','off','Userdata',0);	
    hDataFilePath = uicontrol('Visible','off','Userdata',[]);
    hAxesSizeMode = uicontrol('Visible','off','Userdata',0);
	
	hList=[	hActFileNo hECfgFilePath hEPosSpher hENames hAxesPosMat ...                         %1-25
		  	hhAxesVec hhMenuEnable hhZeroLine hhTrigLine hhCursorLine ... 
			hhText1 hhText2 hhText3 hhText4 hhText5 ... 
			hDataSensorNChan hFileInfoTextVec hBasePath hPlot3d hDomain ... 
			hhMinMaxText hTrigPoint hCursorPoint hCursorDec hhPlot2dChanAxes ... 	 			
			hView hkActAxes hActAxes hTrigLength hCursorLength ...                              %26-50
		  	hkTop hAxesTop hkFront hAxesFront hkBack ... 
			hAxesBack hkLeft hAxesLeft hkRight hAxesRight ... 
			hkNorm hAxesNorm hkAll hAxesAll hActSpecVisible ...
			hZoomSpecChan hAllSpecVisible hInfoAll hhMenuTextEnable hNPoints ... 				
			hNListHdr hMinAmp hMaxAmp hMinPoint hMaxPoint ...                                   %51-75
			hFileNoVec hCalcBase hMinBase hMaxBase hSampRate ... 
			hColor hLineStyle hhButVec hhSpecChanVec hhTopMenu ... 
			hhGPVec xxx hGlobPowCursorPoint hTakeGlobPowStdWeight hGP_RMS ... 
			hGlobPowFig hGlobPowAxes hGlobPowTrigLine hGlobPowCursorLine hGlobPowTimeText ...	
			hSpec1Axes hSpec1ZeroLine hSpec1TrigLine hSpec1CursorLine hSpec1CursorText ...      %76-100
			hGPIntMat hOpenAvgFile hIndexMenu hSymPairs hPotIntMat ...                  
			hAsciiFileParaVec hAsciiFileAvgVec hPlotMedMedVec hNoUse hDefFileNoVec ... 
			hDefECfgFilePath hhFiltVec hPlot2dChanFig hUserData hDefZerTriCurColor... 
			hDefZerTriCurLineStyle hPlot2dVersion hLineWidth hMatlabVersionStr hMainMatlabVersion ....	
			hXTickVal hhSensorRotVec hSepPathStr hSpec2Axes hDefDataPath ...                    %101-125
			hSpec2AxesVal hEditEgisFigHandleVec hOpenAvgFileStatus hActAllVisible hSetEegMegStatus ...  
			hSensorPosNormMat hFontSizeVec hVarVecMat hSigValVec hBaseMat ...
			hAdjustAmp hCenterAmp hDecAmp hDecDecIncAmp hIncAmp ...	
			hIncDecIncAmp hMinPointSlider hMaxPointSlider hDecIncStatusAmp hInvertViewAmp ...		
			hOpenFileBatch hEyeCorrEgisBatch hRGBColorMat hCalcTotalBase hViewCorPicIndVec ... %126-150
			hViewCorPicPath hCursorPointSlider hNoUse hCalcFiltTempMenu hCalcFiltSpatMenu  ...
			hMouseZoomMode hDataFilePath hAxesSizeMode hNoUse MaxNFiles ... 
			hEcfgInfoText hLastViewDef hCloseAllButMain hGlobDissim hNoUse ... 
			hLastOpenFile1 hLastOpenFile2 hLastOpenFile3 hLastOpenFile4 hLastOpenFile5 ...											
			hLastOpenFile6 hNoUse hNoUse hNoUse hNoUse ...                                             %151-175
			hNoUse hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ...	
			hNoUse hNoUse hNoUse hNoUse hNoUse ...											 
			hNoUse hNoUse hNoUse hNoUse hNoUse ...                                              %176-200
			hNoUse hNoUse hNoUse hNoUse hNoUse ...
			hNoUse hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ...											
			hCalcAvgMat1 hNChan1 hNPoints1 hFilePath1 hNTrialAvgVec1 ...                        %201-225
			hStdChanTimeMat1 hSampRate1 hAvgRef1 hMedMedRawVec1 hMedMedAvgVec1 ... 
			hMinMinAvgMat1 hMaxMaxAvgMat1 hMedMedAvgMat1 hNoUse hNoUse ... 
			hColor1 hLineStyle1 hAllVisible1 hDefColor1 hDefLineStyle1 ... 
			hECfgFileFormat1 hAvgFileFormat1 hOpenAvgFile1 hOrigAvgMat1 hhDataVec1 ...			
			hGlobPowData1 hGlobPowAmpText1 hCalcGlobPowData1 hSpecChanAmpText1 hhSigVec1 ...   %226-250
			hEgisAvgVec1 hEgisRawVec1 hSensorLineColorVec1 hAppSCADSVec1 hWaveVec1 ... 
			hWaveMat1 hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ...											    
			hCalcAvgMat2 hNChan2 hNPoints2 hFilePath2 hNTrialAvgVec2 ...                        %251-275
			hStdChanTimeMat2 hSampRate2 hAvgRef2 hMedMedRawVec2 hMedMedAvgVec2 ... 
			hMinMinAvgMat2 hMaxMaxAvgMat2 hMedMedAvgMat2 NoUse NoUse ... 
			hColor2 hLineStyle2 hAllVisible2 hDefColor2 hDefLineStyle2 ... 
			hECfgFileFormat2 hAvgFileFormat2 hOpenAvgFile2 hOrigAvgMat2 hhDataVec2 ...			
			hGlobPowData2 hGlobPowAmpText2 hCalcGlobPowData2 hSpecChanAmpText2 hhSigVec2 ...   %276-300
			hEgisAvgVec2 hEgisRawVec2 hSensorLineColorVec2 hAppSCADSVec2 hWaveVec2 ... 
			hWaveMat2 hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ...											    
			hCalcAvgMat3 hNChan3 hNPoints3 hFilePath3 hNTrialAvgVec3 ...                        %301-325
			hStdChanTimeMat3 hSampRate3 hAvgRef3 hMedMedRawVec3 hMedMedAvgVec3 ... 
			hMinMinAvgMat3 hMaxMaxAvgMat3 hMedMedAvgMat3 NoUse NoUse ... 
			hColor3 hLineStyle3 hAllVisible3 hDefColor3 hDefLineStyle3 ... 
			hECfgFileFormat3 hAvgFileFormat3 hOpenAvgFile3 hOrigAvgMat3 hhDataVec3 ...			
			hGlobPowData3 hGlobPowAmpText3 hCalcGlobPowData3 hSpecChanAmpText3 hhSigVec3 ...
			hEgisAvgVec3 hEgisRawVec3 hSensorLineColorVec3 hAppSCADSVec3 hWaveVec3 ... 
			hWaveMat3 hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ...											    
			hCalcAvgMat4 hNChan4 hNPoints4 hFilePath4 hNTrialAvgVec4 ...
			hStdChanTimeMat4 hSampRate4 hAvgRef4 hMedMedRawVec4 hMedMedAvgVec4 ... 
			hMinMinAvgMat4 hMaxMaxAvgMat4 hMedMedAvgMat4 NoUse NoUse ... 
			hColor4 hLineStyle4 hAllVisible4 hDefColor4 hDefLineStyle4 ... 
			hECfgFileFormat4 hAvgFileFormat4 hOpenAvgFile4 hOrigAvgMat4 hhDataVec4 ...			
			hGlobPowData4 hGlobPowAmpText4 hCalcGlobPowData4 hSpecChanAmpText4 hhSigVec4 ...
			hEgisAvgVec4 hEgisRawVec4 hSensorLineColorVec4 hAppSCADSVec4 hWaveVec4 ... 
			hWaveMat4 hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ...                                                   
            hCalcAvgMat5 hNChan5 hNPoints5 hFilePath5 hNTrialAvgVec5 ...                                         
			hStdChanTimeMat5 hSampRate5 hAvgRef5 hMedMedRawVec5 hMedMedAvgVec5 ... 
			hMinMinAvgMat5 hMaxMaxAvgMat5 hMedMedAvgMat5 NoUse NoUse ... 
			hColor5 hLineStyle5 hAllVisible5 hDefColor5 hDefLineStyle5 ... 
			hECfgFileFormat5 hAvgFileFormat5 hOpenAvgFile5 hOrigAvgMat5 hhDataVec5 ...			
			hGlobPowData5 hGlobPowAmpText5 hCalcGlobPowData5 hSpecChanAmpText5 hhSigVec5 ...
			hEgisAvgVec5 hEgisRawVec5 hSensorLineColorVec5 hAppSCADSVec5 hWaveVec5 ... 
			hWaveMat5 hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ...
            hCalcAvgMat6 hNChan6 hNPoints6 hFilePath6 hNTrialAvgVec6 ...                                             
			hStdChanTimeMat6 hSampRate6 hAvgRef6 hMedMedRawVec6 hMedMedAvgVec6 ... 
			hMinMinAvgMat6 hMaxMaxAvgMat6 hMedMedAvgMat6 NoUse NoUse ... 
			hColor6 hLineStyle6 hAllVisible6 hDefColor6 hDefLineStyle6 ... 
			hECfgFileFormat6 hAvgFileFormat6 hOpenAvgFile6 hOrigAvgMat6 hhDataVec6 ...			
			hGlobPowData6 hGlobPowAmpText6 hCalcGlobPowData6 hSpecChanAmpText6 hhSigVec6 ...
			hEgisAvgVec6 hEgisRawVec6 hSensorLineColorVec6 hAppSCADSVec6 hWaveVec6 ... 
			hWaveMat6 hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse ... 
			hNoUse hNoUse hNoUse hNoUse hNoUse]; 											    
			
	set(hPlot2dMenuFig,'Visible','on','UserData',hList);
	if strcmp(DefAvgFileFormat,'AvgEgis') | strcmp(DefAvgFileFormat,'RawEgis')
		emegs2d('chOpenAvgFileButton');
	end
	clear;
 	
	%============================================================================	
	%============ set EEG / MEG Status
	%============================================================================	
elseif strcmp(action,'SetEegMegStatus'),

	hList=get(hPlot2dMenuFig,'Userdata');
	hSetEegMegStatus=hList(110);
	EegMegStatusString=get(hSetEegMegStatus,'String');
	hhMinMaxText=get(hList(21),'Userdata');
	if strcmp(EegMegStatusString,'EEG')
		EegMegStatusString='MEG';
		set(hhMinMaxText(1),'String','Min. amp. [fT]'); %hMinAmpText
		set(hhMinMaxText(2),'String','Max. amp. [fT]'); %hMaxAmpText
	else
		EegMegStatusString='EEG';
		set(hhMinMaxText(1),'String','Min. amp. [µV]'); %hMinAmpText
		set(hhMinMaxText(2),'String','Max. amp. [µV]'); %hMaxAmpText
	end
	set(hSetEegMegStatus,'String',EegMegStatusString);
	
    %============================================================================	
	%============ set number of actual data set 
	%============================================================================	
elseif strcmp(action,'setActFileNo'),
  
	hList=get(hPlot2dMenuFig,'Userdata');
    Domain=get(hList(20),'Value');
    if ~isempty(varargin)
        if iscell(varargin)
            set(hList(1),'Value',varargin{1});
        end
    end
	ActFileNo=get(hList(1),'Value');
	PrevFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	PrevFileFormat=get(hList(NListHdr+(PrevFileNo-1).*50+22),'Userdata');	
	PrevFileFormatVal=get(hList(NListHdr+(PrevFileNo-1).*50+22),'Value');
	PrevFileFormatExt=get(hList(NListHdr+(PrevFileNo-1).*50+22),'String');	
	ActFilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
	%=== color and linestyle of actual Data Set ===
	set(hList(1),'Userdata',ActFileNo);
	ColorVal=get(hList(NListHdr+(ActFileNo-1).*50+16),'Value');
	set(hList(61),'Value',ColorVal);
	LineStyleVal=get(hList(NListHdr+(ActFileNo-1).*50+17),'Value');
	set(hList(62),'Value',LineStyleVal);
	
	%=== Visible Status of Actual Data Set ===
	hActAllVisible=hList(109);
	VisibleStatusVec=get(hActAllVisible,'Userdata');
   	ActVisibleStatus=VisibleStatusVec(ActFileNo);
  	set(hActAllVisible,'Value',ActVisibleStatus);

	%=== file path, file format ===
	if ActFilePath==0
		set(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata',PrevFileFormat,'Value',PrevFileFormatVal,'String',PrevFileFormatExt);
	end
	if (strcmp(PrevFileFormat,'AvgEgis') | strcmp(PrevFileFormat,'GrandAvgEgis') | strcmp(PrevFileFormat,'RawEgis')) & ActFilePath==0
		PrevFilePath=get(hList(NListHdr+(PrevFileNo-1).*50+4),'Userdata');
		ActFilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
		set(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata',PrevFileFormat,'Value',PrevFileFormatVal,'String',PrevFileFormatExt);
		set(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata',PrevFilePath);
	end
	if (strcmp(PrevFileFormat,'AvgEgis') | strcmp(PrevFileFormat,'GrandAvgEgis')) & ActFilePath==0
		PrevEgisAvgVec=get(hList(NListHdr+(PrevFileNo-1).*50+31),'Userdata');
		set(hList(NListHdr+(ActFileNo-1).*50+31),'Userdata',PrevEgisAvgVec);
	elseif strcmp(PrevFileFormat,'RawEgis') & ActFilePath==0
		PrevEgisRawVec=get(hList(NListHdr+(PrevFileNo-1).*50+32),'Userdata');
		set(hList(NListHdr+(ActFileNo-1).*50+31),'Userdata',PrevEgisRawVec);
	end
	%-----------------------------------------------------------------
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	hTextMenu=get(hStyleMenu(6),'children');
	pointer=get(hList(83),'Userdata');
	DisplayTextLabel=get(hTextMenu(3),'Label');
	PointPos=get(hTextMenu(3),'Userdata');
	if strcmp(DisplayTextLabel(PointPos),setstr(pointer))
		emegs2d('DispMeanStdActFileNo')
	end
	DisplayTextLabel=get(hTextMenu(4),'Label');
	PointPos=get(hTextMenu(4),'Userdata');
	if strcmp(DisplayTextLabel(PointPos),setstr(pointer))
		emegs2d('DispNTrialsActFileNo')
	end
	DisplayTextLabel=get(hTextMenu(5),'Label');
	PointPos=get(hTextMenu(5),'Userdata');
	if strcmp(DisplayTextLabel(PointPos),setstr(pointer))
		emegs2d('DispCursorAmpActFileNo')
	end
    if Domain == 8
        if ActFileNo~=PrevFileNo
            emegs2d('PlotData')
        end
    end
	%------------------ change index position in menu ----------------
	%-----------------------------------------------------------------
	clear;

	%============================================================================
    %============ calculate MinAmp, MaxAmp, MinPoint and MaxPoint 
	%============================================================================	
elseif strcmp(action,'SetFirstVal'),
		
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	Domain=get(hList(20),'Value');
	DomainLabelStr=get(hList(20),'String');
	NDomain=size(DomainLabelStr,1);
	TrigPoint=get(hList(22),'Value');
	NListHdr=get(hList(51),'Userdata');
	ActAvgMat=get(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata');
	NPoints=get(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata');
	NPointsString=get(hList(NListHdr+(ActFileNo-1).*50+3),'String');
	SampRate = get(hList(60),'Userdata');
	% set MinPoint 
	MinPoint = (1-TrigPoint).*1000./SampRate;
	MinPointStr=num2str(MinPoint);
	MinPointVec=ones(NDomain,1); 											
	set(hList(54),'Value',1,'Userdata',MinPointVec,'String',MinPointStr);			%hMinPoint
	% set MaxPoint	
	MaxPoint = (NPoints-TrigPoint).*1000./SampRate;
	MaxPointStr=num2str(MaxPoint);
	MaxPointVec=ones(NDomain,1).*NPoints;										
	set(hList(55),'Value',NPoints,'Userdata',MaxPointVec,'String',MaxPointStr);		%hMaxPoint
	%==========
	hMinMaxText=get(hList(21),'Userdata');
	MinPointText=get(hMinMaxText(3),'String');
	Ind=findstr(MinPointText,'#')
	if ~isempty(Ind)
		MinPointText=[MinPointText(1:Ind),' ',int2str(1)];
	else
		MinPointText=[MinPointText,'; #',int2str(1)];
	end
	set(hMinMaxText(3),'String',MinPointText);
	MaxPointText=get(hMinMaxText(4),'String');
	Ind=findstr(MaxPointText,'#');
	if ~isempty(Ind)
		MaxPointText=[MaxPointText(1:Ind),' ',int2str(NPoints)];
	else
		MaxPointText=[MaxPointText,'; # ',int2str(NPoints)];
	end
	set(hMinMaxText(4),'String',MaxPointText);
	%==========
    CursPointText=get(hMinMaxText(6),'String');
    Ind=findstr(CursPointText,'#');
	if ~isempty(Ind)
		CursPointText=[CursPointText(1:Ind),' ',int2str(1)];
	else
		CursPointText=[CursPointText,'; # ',int2str(1)];
	end
	set(hMinMaxText(6),'String',CursPointText);
    %==========
	if NPoints>1
		set(hList(122),'Min',1,'Max',NPoints,'Value',1,'Enable','on'); 				%hMinPointSlider
		set(hList(123),'Min',1,'Max',NPoints,'Value',NPoints,'Enable','on'); 		%hMaxPointSlider
		set(hList(132),'Min',1,'Max',NPoints,'Value',1,'Enable','on'); 				%hCursorPointSlider
		if NPoints>=10
			SliderStep=[1./NPoints 10./NPoints];
		else
			SliderStep=[.1 1];
		end
		set(hList(122),'SliderStep',SliderStep); 	%hMinPointSlider
		set(hList(123),'SliderStep',SliderStep); 	%hMaxPointSlider
		set(hList(132),'SliderStep',SliderStep); 	%hMCursorPointSlider
	else
		set(hList(122),'Enable','off');
		set(hList(123),'Enable','off');
		set(hList(132),'Enable','off');
	end
	
	% minimal, maximal amplitude
	MinAmp=min(min(ActAvgMat));
	MaxAmp=max(max(ActAvgMat));
	if MinAmp==MaxAmp
		Message=char(['The values in this data set are all identical ! (', num2str(MinAmp),')']);
		MinAmp=MinAmp-1;
		MaxAmp=MaxAmp+1;
		Message=char(Message,' ');
		Message=char(Message,['Min. Amp. will be set to ',num2str(MinAmp)]);
		Message=char(Message,['Max. Amp. will be set to ',num2str(MaxAmp)]);
		hmsgbox=msgbox(Message,'Info:','help')
		pause(3)
	end
	% minimal amplitude
	MinAmpVec=get(hList(52),'Userdata');
	MinAmpVec(Domain)=MinAmp;
	set(hList(52),'Value',MinAmp,'Userdata',MinAmpVec,'String',sprintf('%g',(round(MinAmp.*100))./100));	%hMinAmp
	set(hList(NListHdr+(ActFileNo-1).*50+11),'Userdata',MinAmp);
	% maximal amplitude
	MaxAmpVec=get(hList(53),'Userdata');
	MaxAmpVec(Domain)=MaxAmp;
	set(hList(53),'Value',MaxAmp,'Userdata',MaxAmpVec,'String',sprintf('%g',(round(MaxAmp.*100))./100));%hMaxAmp
	set(hList(NListHdr+(ActFileNo-1).*50+12),'Userdata',MaxAmp);

	%============================================================================
    %============ calculate MinAmp, MaxAmp
	%============================================================================	
	
elseif strcmp(action,'CalcFirst'),
		
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	ActAvgMat=get(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata');	
	MinMinAvgMat=min(min(ActAvgMat));
	set(hList(NListHdr+(ActFileNo-1).*50+11),'Userdata',MinMinAvgMat);
	MaxMaxAvgMat=max(max(ActAvgMat));
	set(hList(NListHdr+(ActFileNo-1).*50+12),'Userdata',MaxMaxAvgMat);
	MedMedAvgMat=median(median(ActAvgMat));
	set(hList(NListHdr+(ActFileNo-1).*50+13),'Userdata',MedMedAvgMat);
	
	%============================================================================
    %============ sensor configuration file format
	%============================================================================	
elseif 	strcmp(action,'chECfgFileAutoAxes') | ...
		strcmp(action,'chECfgFileMEGOnSphere') | ...
		strcmp(action,'chECfgFileMEGNoSphere') | ...
		strcmp(action,'chECfgFileBesaEEG') | ...
	   	strcmp(action,'chECfgFileNsSfp') | ...
		strcmp(action,'chECfgFileSCADS') | ...
		strcmp(action,'chECfgFileCartAscii') | ...
	   	strcmp(action,'chECfgFileSpherAscii') | ...
		strcmp(action,'chECfgFileAxesAscii') | ...
		strcmp(action,'Prep1020ECfgFile') | ...
		strcmp(action,'Prep1010ECfgFile'),
		
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	pointer=get(hList(83),'Userdata');
	hTopMenu=get(hList(65),'Userdata');
	hFileMenu=get(hTopMenu(1),'children');
	hECFileFormat=get(hFileMenu(2),'children');
	
	oldECFileFormatVal=get(hList(NListHdr+(ActFileNo-1).*50+21),'value'); %file format value: 11-20
	if  strcmp(action,'chECfgFileAutoAxes') 
		ECfgFileFormat='AutoAxes';
		ECFileFormatVal=11;
		set(hList(26),'Value',1); 		%TopView
	elseif  strcmp(action,'chECfgFileMEGNoSphere') 
		ECfgFileFormat='MEGNoSphere';
		ECFileFormatVal=10;
	elseif  strcmp(action,'chECfgFileMEGOnSphere') 
		ECfgFileFormat='MEGOnSphere';
		ECFileFormatVal=9;
	elseif  strcmp(action,'chECfgFileBesaEEG') 
		ECfgFileFormat='BesaEEG';
		ECFileFormatVal=8;
	elseif  strcmp(action,'chECfgFileNsSfp') 
		ECfgFileFormat='NsSfp';
		ECFileFormatVal=7;
	elseif  strcmp(action,'chECfgFileSCADS') 
		ECfgFileFormat='SCADS';
		ECFileFormatVal=6;
	elseif  strcmp(action,'chECfgFileCartAscii') 
		ECfgFileFormat='CartAscii';
		ECFileFormatVal=5;
	elseif  strcmp(action,'chECfgFileSpherAscii') 
		ECfgFileFormat='SpherAscii';
		ECFileFormatVal=4;
	elseif  strcmp(action,'chECfgFileAxesAscii') 
		ECfgFileFormat='AxesAscii';
		ECFileFormatVal=3;
		set(hList(26),'value',1); 		%TopView
    elseif strcmp(action,'Prep1020ECfgFile')
        ECfgFileFormat='1020ECfgFile';
        ECFileFormatVal=2;
    elseif strcmp(action,'Prep1010ECfgFile')
        ECfgFileFormat='1010ECfgFile';
        ECFileFormatVal=1;
    end
	%-----------------------------------------------------------------
	hSetEegMegStatus=hList(110);
	EegMegStatusString=get(hSetEegMegStatus,'String');
   	if (strcmp(EegMegStatusString,'EEG') & (strcmp(action,'chECfgFileMEGNoSphere') | strcmp(action,'chECfgFileMEGOnSphere'))) | ...
	   (strcmp(EegMegStatusString,'MEG') & ~(strcmp(action,'chECfgFileMEGNoSphere') | strcmp(action,'chECfgFileMEGOnSphere')))
      		emegs2d('SetEegMegStatus')
	end
	
	%------------------ change index position in menu ----------------
	for ind=1:length(hECFileFormat)
		ECfgFileFormatLabel=get(hECFileFormat(ind),'Label');
		PointPos=get(hECFileFormat(ind),'Userdata');
		if (ind==oldECFileFormatVal) ECfgFileFormatLabel(PointPos)=' '; end;
		if (ind==ECFileFormatVal) ECfgFileFormatLabel(PointPos)=setstr(pointer); end;	
		set(hECFileFormat(ind),'Label',ECfgFileFormatLabel);	
	end;	
	%-----------------------------------------------------------------
	set(hList(NListHdr+(ActFileNo-1).*50+21),'Userdata',ECfgFileFormat,'Value',ECFileFormatVal);
	
	if strcmp(action,'Prep1020ECfgFile')
		emegs2d('set1020ECfgFile')
	elseif strcmp(action,'Prep1010ECfgFile')
		emegs2d('set1010ECfgFile')
	end
	
	%============================================================================
    %============ 10-20 electrode configuration file
	%============================================================================	

elseif strcmp(action,'set1020ECfgFile') | strcmp(action,'set1010ECfgFile'),

	hList=get(hPlot2dMenuFig,'Userdata');
	if strcmp(action,'set1020ECfgFile')
		[EPosSpherTmp,ENamesTmp,NChanTmp]=System1020;
	elseif strcmp(action,'set1010ECfgFile')
		[EPosSpherTmp,ENamesTmp,NChanTmp]=System1010;
	end
	[NoUse,NoUse,NoUse,NoUse,CountVec]=ChooseChanInd(NChanTmp,1,[],[],[],[],EPosSpherTmp,ENamesTmp,[],[],3,10,0,1);
	NChan=length(CountVec);
	EPosSpher=EPosSpherTmp(CountVec,:);
	[EPosCart]=change_sphere_cart(EPosSpher,[],1);
	ENames=ENamesTmp(CountVec,:);
	Message=char('Please open the');
	Message=char(Message,'Matlab command window');
	Message=char(Message,'to get details about electrode');
	Message=char(Message,'names and electrode positions');
	msgbox(Message,'Info:','help')
	fprintf('Electrode names:\n\n')
	disp(ENames)
	fprintf('\n\n')
	fprintf('Spherical electrode positions:\n\n')
	disp(EPosSpher(:,1:2))
	fprintf('\n\n')
	fprintf('Cartesian electrode positions:\n\n')
	disp(EPosCart)
	DefFile1=GetDefEcfgFile(NChan);
	DefFile2=strrep(DefFile1,'.ecfg','.SpherAscii');
	DefFile3=strrep(DefFile1,'.ecfg','.CartAscii');
	DefPath=which('129.ecfg');
	OldPath=pwd;
	if ~isempty(DefPath);
		[DefFile,DefPath]=SepFilePath(DefPath);
		if strcmp(DefPath(end),filesep)
			DefPath=DefPath(1:length(DefPath)-1);
		end
		eval(['cd ',DefPath]);
	end	
	FilePath=SaveEConfig(EPosSpher,ENames,DefFile1);
	[File,Path]=SepFilePath(FilePath);
	SaveData(EPosSpher(:,1:2),[Path,DefFile2],1,[],'ascii','ascii');
	SaveData(EPosCart,[Path,DefFile3],1,[],'ascii','ascii');
	emegs2d('chECfgFileSCADS');
	eval(['cd ',OldPath]);
	%============================================================================
    %============ search for sensor configuration file
	%============ name: NChan.NChanecfg
	%============ folder: Plot2d3d:Plot2dUtil:SensorCfg 
	%============ call: ReadECfg, chECfg
	%============================================================================		
	
elseif strcmp(action,'chDefECfg'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
   	ECfgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+21),'Userdata');
	AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
	AvgFileFormatExt=get(hList(NListHdr+(ActFileNo-1).*50+22),'String');
   	Tmp=get(hList(16),'Userdata');
	DataNChan=Tmp(1);
	BasePath=get(hList(18),'Userdata');

	if 	(strcmp(ECfgFileFormat,'MEGOnSphere') | strcmp(ECfgFileFormat,'MEGNoSphere')) & strcmp(AvgFileFormat,'MegBtiMsi')
		emegs2d('ReadECfg');
		return;
	end
	if 	strcmp(ECfgFileFormat,'MEGOnSphere') | ...
		strcmp(ECfgFileFormat,'MEGNoSphere') | ...
		strcmp(ECfgFileFormat,'BesaEEG') | ...
		strcmp(ECfgFileFormat,'NsSfp') | ...
		strcmp(ECfgFileFormat,'SCADS') | ...
		strcmp(ECfgFileFormat,'CartAscii') | ...
		strcmp(ECfgFileFormat,'SpherAscii') | ...
		strcmp(ECfgFileFormat,'AxesAscii')
		
		if 	strcmp(ECfgFileFormat,'MEGOnSphere') | strcmp(ECfgFileFormat,'MEGNoSphere')
			ECfgExt='.pmg';
			DataFilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
			[DataFile,DataPath]=SepFilePath(DataFilePath);
			Tmp=findstr(AvgFileFormatExt,'*');
			while ~isempty(Tmp)
				TmpTmp=find(Tmp(1)~=[1:length(AvgFileFormatExt)]);
				AvgFileFormatExt=AvgFileFormatExt(TmpTmp);
				Tmp=findstr(AvgFileFormatExt,'*');
			end	
			Tmp=findstr(DataFile,AvgFileFormatExt);
			if ~isempty(Tmp)
				ECfgFilePath=[DataPath,DataFile(1:Tmp(length(Tmp))-1),ECfgExt];
			else
				ECfgFilePath=[DataFilePath,ECfgExt];
			end
		elseif 	strcmp(ECfgFileFormat,'BesaEEG')
			ECfgExt='.elp';
		elseif 	strcmp(ECfgFileFormat,'NsSfp')
			ECfgExt='.sfp';
		elseif 	strcmp(ECfgFileFormat,'SCADS')
			ECfgExt='.ecfg';
		elseif 	strcmp(ECfgFileFormat,'CartAscii')
			ECfgExt='.CartAscii';
		elseif 	strcmp(ECfgFileFormat,'SpherAscii')
			ECfgExt='.SpherAscii';
		elseif 	strcmp(ECfgFileFormat,'AxesAscii')
			ECfgExt='.AxesAscii';
		end
		if 	~strcmp(ECfgFileFormat,'MEGOnSphere') & ~strcmp(ECfgFileFormat,'MEGNoSphere')
	   		ECfgFilePath=[BasePath,'emegs2dUtil',filesep,'SensorCfg',filesep,GetDefEcfgFile(DataNChan)];
		end
		ExECfgFilePath=exist(ECfgFilePath);
      	if ExECfgFilePath~=2	% file not found or file ist not an M-file   
         	Message=char('Sorry, but the the sensor configuration default file');
         	Message=char(Message,ECfgFilePath);
			Message=char(Message,'does not exist !');
			Message=char(Message,'');
			Message=char(Message,'Please search for a file with the extension');
			Message=char(Message,[int2str(DataNChan),ECfgExt]);
			Message=char(Message,'or choose a different sensor file format.');
			hmsgbox=msgbox(Message,'Info','help');pause(2);
  			emegs2d('chECfg')
			return;
		end
	else
		emegs2d('chECfg')
		return;
	end
	set(hList(2),'Userdata',ECfgFilePath);
	emegs2d('ReadECfg');
	clear;
	
	%============================================================================
  	%============ interactive input of sensor file path 
	%============ name: *ecfg 
	%============ external function: ReadFilePath 
	%============ call: ReadECfg
	%============================================================================	
elseif strcmp(action,'chECfg'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	ECfgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+21),'Userdata');
	Tmp=get(hList(16),'Userdata');
	DataNChan=Tmp(1);
	SensorNChan=Tmp(2);
	MainMatlabVersion=get(hList(100),'Userdata');
	DataFilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata')

	if 	strcmp(ECfgFileFormat,'AutoAxes')
		emegs2d('ReadECfg')
		return;
	elseif 	strcmp(ECfgFileFormat,'MEGOnSphere') | strcmp(ECfgFileFormat,'MEGNoSphere')
		ECfgExt='.pmg';
   	elseif strcmp(ECfgFileFormat,'BesaEEG')
		ECfgExt='.elp';
	elseif strcmp(ECfgFileFormat,'NsSfp')
		ECfgExt='.sfp';
	elseif strcmp(ECfgFileFormat,'SCADS')
		ECfgExt='.ecfg';
	elseif strcmp(ECfgFileFormat,'CartAscii')
		ECfgExt='.CartAscii';
	elseif strcmp(ECfgFileFormat,'SpherAscii')
		ECfgExt='.SpherAscii';
	elseif strcmp(ECfgFileFormat,'AxesAscii')
		ECfgExt='.AxesAscii'
	else
		ECfgExt='.ecfg';
	end
	DefEcfgFilePath=which('129.ecfg');
	[DefEcfgFile,DefEcfgPath]=SepFilePath(DefEcfgFilePath);
	if ~isempty(DefEcfgPath)
		if DefEcfgPath(end)~=filesep
			DefEcfgPath=[DefEcfgPath,filesep];
		end
	else
		DefEcfgPath=SetDefPath('r');
	end
	if 	~strcmp(ECfgFileFormat,'MEGOnSphere') & ~strcmp(ECfgFileFormat,'MEGNoSphere')
		if DataNChan==0	%No DataMat read in => DataNChan not set
			ECfgMask=['*' ECfgExt];
		else
			ECfgMask=['*',int2str(DataNChan),ECfgExt];
		end
		ECfgFilePathMask=[DefEcfgPath,ECfgMask];
   	else
		if DataFilePath~=0
		    [DataFile,DefEcfgPath]=SepFilePath(DataFilePath);
        end
        ECfgFilePathMask=[DefEcfgPath,'*',ECfgExt];
	end
	[ECfgFile,ECfgPath,ECfgFilePath]=ReadFilePath([],ECfgFilePathMask,'Choose sensor config:');
	if isempty(find(ECfgFile))
		return;
	end
	set(hList(2),'Userdata',ECfgFilePath);
	emegs2d('ReadECfg')
    %SetDefPath('w',ECfgPath);
	
	%============================================================================
  	%============ read sensor configuration file 
	%============ external function: ReadEConfig if bin
	%============ ReadBem if ascii	
	%============ call: Calc2dTimeAxes, chZoomChanButton, chActVisSpecChanButton
	%============ chAllVisSpecChanButton
	%============================================================================	
	
elseif strcmp(action,'ReadECfg'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	ECfgFilePath=get(hList(2),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	
	hTopMenu=get(hList(65),'Userdata');
	hExportMenu=get(hTopMenu(3),'children');
   	hSynthMenu=get(hTopMenu(3),'children');
   	SynthDataStatus=get(hSynthMenu(1),'Userdata');
   	AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');

	DomainLabelStr=get(hList(20),'String');
	NDomain=size(DomainLabelStr,1);
	
	Tmp=get(hList(16),'Userdata');
	DataNChan=Tmp(1);
	SensorNChan=Tmp(2);
	ECfgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+21),'Userdata');
    
	if strcmp(ECfgFileFormat,'AutoAxes')
		if SensorNChan==0
			if DataNChan==0
				[SensorNChan]=IfEmptyInputValInt('Please insert the number of sensors:',[],[],148,1,250,1);
			else
				SensorNChan=DataNChan;
			end
		end
		if SensorNChan==1
			EPos=[0 0];
		elseif SensorNChan==2
			EPos=[0 0;.5 .5];
		else
			NCol=ceil(sqrt(SensorNChan));
			NRow=ceil(SensorNChan./NCol);
			EPos=ones(SensorNChan,2);
			NChanTmp=0; ColInd=0; RowInd=1;
			while NChanTmp<SensorNChan
				NChanTmp=NChanTmp+1;
				if ColInd<NCol
					ColInd=ColInd+1;
				else
					ColInd=1; 
					RowInd=RowInd+1;
				end
				EPos(NChanTmp,1)=ColInd;
				EPos(NChanTmp,2)=-1.*RowInd;
			end
		end
		ENames=[];
		EPosSpher=change_sphere_cart(EPos,[], -1);
		set(hList(3),'Value',0); 		%EPosSpher, value => spherical status
		NDim=2;
	elseif strcmp(ECfgFileFormat,'BesaEEG')
		BesaECfgFid=fopen(ECfgFilePath,'r','b');
        %Test for Old or New Besa elp version
        Tmp=fscanf(BesaECfgFid,'%s',1);
        fseek(BesaECfgFid,0,'bof');
        if strcmp(Tmp,'EEG') | strcmp(Tmp,'MEG') %New Version
            SensorInd=0;
			Message=char('Open new version Besa elp file.');
			hmsgbox=msgbox(Message,'Info','help'); 
            while 1
                tline = fgetl(BesaECfgFid);
                if ~ischar(tline), break, end
                disp(tline)
                SensorInd=SensorInd+1;
            end
            NChan=SensorInd;
			SensorNChan=NChan;
            fseek(BesaECfgFid,0,'bof');
            [a,count]=fscanf(BesaECfgFid,'%s');
            fseek(BesaECfgFid,0,'bof');
            NRow=count./NChan;
            EPosSpherBesa=zeros(NChan,2);
            EegMegRef=[];
            ENames=[];
            for ChanInd=1:NChan
                EegMegRef=char(EegMegRef,fscanf(BesaECfgFid,'%s',1));
                ENames=char(ENames,fscanf(BesaECfgFid,'%s',1));
                EPosSpherBesa(ChanInd,:)=fscanf(BesaECfgFid,'%g',2)';
                if NRow==5; fscanf(BesaECfgFid,'%g',1); end
            end
            EegMegRef=EegMegRef(2:end,:);
            ENames=ENames(2:end,:);
        else
			Message=char('Open old version Besa elp file.');
			hmsgbox=msgbox(Message,'Info','help'); 
		    Tmp='Bloedsinn';
		    while ~strcmp(Tmp,'w')	
			    Tmp=fscanf(BesaECfgFid,'%s',1);
		    end
		    Tmp=fscanf(BesaECfgFid,'%g');
		    NChanProd3=length(Tmp);
		    if mod(NChanProd3,3)~=0; 
			    Message=char('Sorry,');
			    Message=char(Message,'bad Besa sensor file format.');
			    Message=char(Message,'');
			    Message=char(Message,'Please choose a different file .');
			    hmsgbox=msgbox(Message,'Info','help'); 
			    return;
		    else
			    SensorNChan=NChanProd3./3;
		    end;
            fclose(BesaECfgFid);
		    EPosSpherBesa=(reshape(Tmp,3,SensorNChan))';
		    EPosSpherBesa=EPosSpherBesa(:,1:2);
        end
		[EPosSpher]=change_sphere_cart(EPosSpherBesa,[],2)
		NDim=3;
	elseif strcmp(ECfgFileFormat,'MEGOnSphere') | strcmp(ECfgFileFormat,'MEGNoSphere')
 		if strcmp(AvgFileFormat,'MegBtiMsi')
			SensorPosNormMat=get(hList(111),'Userdata');
			SensorNChan=size(SensorPosNormMat,1);
			ENames=get(hList(4),'Userdata');
            Cot=[0 0 0];
			NDim=3;
		else	
			[SensorPosNormMat,ENames,SensorNChan,Cot,FidMat,SfpMat]=ReadPmgCotSfpFiles(ECfgFilePath,0);
		end
        NonRotPmg=SensorPosNormMat;
        NonRotCot=Cot;
        NonRotFid=FidMat;
		if ~isempty(SfpMat)
			NonRotSfp=SfpMat;
		end
        %============Rotate pmg,cot,fisu,sfp around z axis=======================
		SensorPosNormMatTmp=SensorPosNormMat;
        SensorPosNormMatTmp(:,1)=-1.*SensorPosNormMat(:,2);
		SensorPosNormMatTmp(:,2)=SensorPosNormMat(:,1);
		SensorPosNormMatTmp(:,4)=-1.*SensorPosNormMat(:,5);
		SensorPosNormMatTmp(:,5)=SensorPosNormMat(:,4);
		SensorPosNormMat=SensorPosNormMatTmp;
        clear SensorPosNormMatTmp
        CotTmp=Cot;
        CotTmp(1)=-1.*Cot(2);
		CotTmp(2)=Cot(1);
        Cot=CotTmp;
        clear CotTmp 
        FidMatTmp=FidMat;
        FidMatTmp(:,1)=-1.*FidMat(:,2);
		FidMatTmp(:,2)=FidMat(:,1);
        FidMat=FidMatTmp;
        clear FidMatTmp 
		if ~isempty(SfpMat)
			SfpMatTmp=SfpMat;
        	SfpMatTmp(:,1)=-1.*SfpMat(:,2);
			SfpMatTmp(:,2)=SfpMat(:,1);
        	SfpMat=SfpMatTmp;
        	clear SfpMatTmp
		end
		%=============Subtract center of sphere (cot) from sensor positions=======================
        for ChanInd=1:SensorNChan
		    SensorPosNormMat(ChanInd,1:3)=SensorPosNormMat(ChanInd,1:3)-Cot;
        end
        for FidInd=1:size(FidMat,1)
		    FidMat(FidInd,1:3)=FidMat(FidInd,1:3)-Cot;
        end  
		if ~isempty(SfpMat)
			for SfpInd=1:size(SfpMat,1)
		   	 	SfpMat(SfpInd,1:3)=SfpMat(SfpInd,1:3)-Cot;
        	end  
		end
        RotDegVal=0; %degrees backward rotation around x-axis (LPA-RPA)
        EPosCart=SensorPosNormMat(:,1:3); 
        EPosCart=XRotation(EPosCart,RotDegVal);
        EDirCart=SensorPosNormMat(:,4:6); 
        EDirCart=XRotation(EDirCart,RotDegVal);
        SensorPosNormMat(:,1:3)=EPosCart;
        SensorPosNormMat(:,4:6)=EDirCart;
        FidMat=XRotation(FidMat,RotDegVal); 
		if ~isempty(SfpMat)
			SfpMat=XRotation(SfpMat,RotDegVal); 
		end
		PlotSensorPosStatus=1;
		if PlotSensorPosStatus
        	%================Plot sensor positions=================================
       		hPmgCotFig=figure('Units','normal','NumberTitle','off','Position',[0 0 .8 .92],'Name',['Pmg, Cot, Sfp; ',ECfgFilePath]);
        	subplot(2,2,1)
        	plot3(NonRotPmg(:,1),NonRotPmg(:,2),NonRotPmg(:,3),'bo')
        	hold on
        	plot3(NonRotPmg(71,1),NonRotPmg(71,2),NonRotPmg(71,3),'g*')
        	plot3(NonRotCot(1),NonRotCot(2),NonRotCot(3),'r*')
            plot3(NonRotFid(1:3,1),NonRotFid(1:3,2),NonRotFid(1:3,3),'m*')
			if ~isempty(SfpMat)
				plot3(NonRotSfp(:,1),NonRotSfp(:,2),NonRotSfp(:,3),'k.')
			end
        	quiver3(NonRotPmg(:,1),NonRotPmg(:,2),NonRotPmg(:,3),NonRotPmg(:,4),NonRotPmg(:,5),NonRotPmg(:,6),'k');
        	hold off
        	title('Pmg, Cot, Sfp (Bti System)')
        	xlabel('x (y)')
        	ylabel('y (negative x)')
        	zlabel('z (z)') 
            view(180,0)
        	clear NonRotPmg NonRotCot NonRotSfp     
            for i=1:3
        	    subplot(2,2,i+1)
        	    plot3(SensorPosNormMat(:,1),SensorPosNormMat(:,2),SensorPosNormMat(:,3),'bo')
        	    hold on
        	    plot3(SensorPosNormMat(71,1),SensorPosNormMat(71,2),SensorPosNormMat(71,3),'g*')
        	    LSensorPosCart=sqrt(SensorPosNormMat(:,1).^2+SensorPosNormMat(:,2).^2+SensorPosNormMat(:,3).^2)
       	 	    HeadRadius=0.09;
        	    plot3(HeadRadius.*SensorPosNormMat(:,1)./LSensorPosCart,HeadRadius.*SensorPosNormMat(:,2)./LSensorPosCart,HeadRadius.*SensorPosNormMat(:,3)./LSensorPosCart,'bx')
			    plot3(0,0,0,'r*')        
        	    quiver3(SensorPosNormMat(:,1),SensorPosNormMat(:,2),SensorPosNormMat(:,3),SensorPosNormMat(:,4),SensorPosNormMat(:,5),SensorPosNormMat(:,6),'k');
                plot3(FidMat(1:3,1),FidMat(1:3,2),FidMat(1:3,3),'m*')
				if ~isempty(SfpMat)
					plot3(SfpMat(:,1),SfpMat(:,2),SfpMat(:,3),'k.')
				end
        	    xlabel('x- axis')
        	    ylabel('y- axis')
        	    zlabel('z- axis')
               if i==1
                    view(-90,0)
                    title(['Besa (Add. x-rot.(deg.): ',num2str(RotDegVal),'); Left View'])
                elseif i==2
                    view(90,0)
                    title(['Besa (Add. x-rot.(deg.): ',num2str(RotDegVal),'); Right View'])
                elseif i==3
                    view(180,0)
                    title(['Besa (Add. x-rot.(deg.): ',num2str(RotDegVal),'); Front View'])
                end
            end
        	%===========================================================================
		end
		set(hList(111),'Userdata',SensorPosNormMat)	%hSensorPosNormMat
		EPosCart=SensorPosNormMat(:,1:3); 
		[EPosSpher]=change_sphere_cart(EPosCart,[],-1);
		NDim=3;
	elseif strcmp(ECfgFileFormat,'SCADS')
		[SensorNChan,SpherRadius,EPosSpher,ENames,EConfigFile,EConfigPath,ECfgFilePath]=ReadEConfig(ECfgFilePath);
		NDim=2;
	elseif strcmp(ECfgFileFormat,'NsSfp')
		[EPosCart,ENames,FidPosMat,FidNames]=ReadSfpFile(ECfgFilePath,0);
		EPosCart=TransSfpPos(EPosCart,FidPosMat);
		[EPosSpher]=change_sphere_cart(EPosCart,[],-1);
		SensorNChan=size(EPosSpher,1);
		NDim=3;
	elseif strcmp(ECfgFileFormat,'CartAscii') | ...
			strcmp(ECfgFileFormat,'SpherAscii') | ...
			strcmp(ECfgFileFormat,'AxesAscii')
		global EPos
		EPos=ReadData(ECfgFilePath,1,[],'ascii','ascii');
		[SensorNChan,NDim]=size(EPos);
		if 	strcmp(ECfgFileFormat,'CartAscii') 
			if SensorNChan==3 & NDim~=3
				EPosCart=EPos'; SensorNChan=NDim; NDim=3;
			else
				EPosCart=EPos;
			end
			[EPosSpher]=change_sphere_cart(EPosCart,[],-1);
			NDim=3;
		elseif 	strcmp(ECfgFileFormat,'SpherAscii') 
			if (SensorNChan==2 & NDim~=2) | (SensorNChan==3 & NDim~=3)
				EPosSpher=EPos'; Tmp=SensorNChan; SensorNChan=NDim; NDim=Tmp;
			else
				EPosSpher=EPos;
			end
			ENames=[];
			if any(EPosSpher>2.*pi);
				InfoMat=char('Change sensor positions given in grad to rad !');
				hInfoDlg=msgbox(InfoMat,'Info !','help');pause(.001);
				EPosSpher=EPosSpher.*pi./180;
			end
		elseif 	strcmp(ECfgFileFormat,'AxesAscii') 
			if SensorNChan==2 & NDim~=2
				EPos=EPos'; SensorNChan=NDim; NDim=2;	
			end
			EPos(:,2)=-1.*EPos(:,2);
			[EPosSpher]=change_sphere_cart(EPos,[], -1);
			set(hList(3),'Value',0); 		%EPosSpher, value => spherical status
			NDim=2;
			ENames=[];
		end
		[ENames]=SetENames(ENames,SensorNChan);
  	 end
	if NDim==3
		%=========Test Radius of Sensor Positions=========
		RadiusVec=EPosSpher(:,3);
		MeanRadius=mean(RadiusVec);
		TmpRadiusVec=RadiusVec-ones(size(RadiusVec)).*MeanRadius;
		DiffRadiusPer100=abs(TmpRadiusVec)./MeanRadius.*100;
		MaxDiffRadiusPer100=max(DiffRadiusPer100);
		if MaxDiffRadiusPer100>1 | strcmp(ECfgFileFormat,'MEGNoSphere') | strcmp(ECfgFileFormat,'MEGOnSphere')
			if ~strcmp(ECfgFileFormat,'MEGOnSphere') & ~strcmp(ECfgFileFormat,'MEGNoSphere')
				Message=char('The chosen sensor positions');
				Message=char(Message,'do not lay on a sphere.');
				Message=char(Message,'');
				Message=char(Message,'Please open the command');
				Message=char(Message,'window for further details.');
				hmsgbox=msgbox(Message,'Warning','warn');
				fprintf('The chosen sensor positions do not lay on a sphere.\n\n')
				fprintf('Radii of sensor positions:\n\n')
				disp(RadiusVec')
				fprintf('Absolut deviation between radius of sensor\n')
				fprintf('positions and mean of radii in per hundred:\n\n')
				disp(DiffRadiusPer100')
				fprintf('Maximum deviation in per hundred:\n\n')
				disp(MaxDiffRadiusPer100)
				fprintf('\n\n')
				[chTmp,k]=IfEmptyInputSpecVal([],[0:5],1,...
				'Do you want to\n',...
				'project the sensor positions onto a sphere without weighting of sensor positions       [1]',...
				'project the sensor positions onto a sphere with weighting of sensor positions          [2]',...
				'use this sensor positions (Scalp, CSD and intracranial mapping will not be available)  [3]',...
				'or Cancel ?           [4].');
			end
			if 		strcmp(ECfgFileFormat,'MEGOnSphere'); chTmp=1; 
			elseif	strcmp(ECfgFileFormat,'MEGNoSphere'); chTmp=3; 
			end
			if chTmp==1 | chTmp==2
				[EPosCart]=change_sphere_cart(EPosSpher,[],1);
				if chTmp==2
					[WeightVec]=ReadBem([],1,'Matrix','Ascii',[],0,0,'*',['Please choose an (',int2str(SensorNChan),',1) header ascii weight file:'])
				else
					WeightVec=[];
				end
				InfoMat=char('Calculate center of best fitting sphere !');
				InfoMat=char(InfoMat,'');
				InfoMat=char(InfoMat,'Open Matlab Command Window for further details.');
				hInfoDlg=msgbox(InfoMat,'Info !','help');pause(.001);
				[EPosCart,EPosSpher,Center,Radius,CenterIter,RadiusIter,PointVecDiff]=CalcPolSphere(EPosCart,[],ENames,WeightVec);
				EPosSpher=EPosSpher(:,1:2);
				set(hList(3),'Value',1); %EPosSpher, value => spherical status
			elseif chTmp==3
				set(hList(3),'Value',0); %EPosSpher, value => spherical status
			elseif chTmp==4
				return;
			end
		else
			EPosSpher=EPosSpher(:,1:2);
		end
	else
		set(hList(19),'Enable','off'); 	%Surfaces (Plot3d)
	end
	SpherStatus=get(hList(3),'Value');
	if SpherStatus
		EPosSpherTmp=zeros(SensorNChan,3);
		EPosSpherTmp(:,1:2)=EPosSpher(:,1:2);
		EPosSpherTmp(:,3)=ones(SensorNChan,1).*0.092;
		EPosSpher=[]; EPosSpher=EPosSpherTmp; EPosSpherTmp=[];
	end
    
    %%ppcomment
    
   	set(hList(3),'Userdata',EPosSpher);
  	ENames=SetENames(ENames,SensorNChan);
	set(hList(4),'Userdata',ENames);
	set(hList(102),'Userdata',SensorNChan);
	set(hList(16),'Userdata',[DataNChan,SensorNChan]);
    MaxNFiles=hList(140);
	set(hList(115),'Userdata',zeros(SensorNChan,NDomain.*MaxNFiles));  %number of domains  x number of data sets (MaxNFiles) in BaseMat
	set(hExportMenu(3),'Enable','on');	% hExportECfgFile	
	if SensorNChan~=0;
		emegs2d('chZoomChanButton');
		emegs2d('chActVisSpecChanButton');
		emegs2d('chAllVisSpecChanButton');
   	end
	if DataNChan~=0 & ~SynthDataStatus; 
		emegs2d('Calc2dTimeAxes'); 
	end
	%============================================================================
	% =========== rotates sensor positions
	%============ external function: 
	%============ call:	setView
	%============================================================================	

elseif strcmp(action,'RotateSensorPosMenu'),

	hList=get(hPlot2dMenuFig,'Userdata');
	EPosSpher=get(hList(3),'Userdata');
	[EPosCart]=change_sphere_cart(EPosSpher,[],1);
	[NChan,NoUse]=size(EPosSpher);

	%====Rotate Menu===============================
	
	% Information for all buttons (and menus)
   	labelColor=[0.8 0.8 0.8];
	yInitPos=0.90;
 	menutop=.85;
   	btnTop = 0.6;
	top=0.75;
	left=0.05;
	btnWid=1;
	btnHt=0.09;
	textHeight = 0.05;
	textWidth = 0.1;
	% Spacing between the button and the next command's label
	spacing=0.05;
	
   	hSensorRotMenuFig=figure('Units','normal','NumberTitle','off','Position',[.55,.7,.15,.35],...
	'Color',[0 0 0],'Name','Rotate Menu');
   	btnNumber=1;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos 2.*btnWid./3 btnHt];
    
	hSensorXRotText = uicontrol( ...
      		'Style','text', ...
     	  	'Units','normalized', ...
			'Position',btnPos, ...
        	'Horiz','left', ...
        	'Foreground','black', ...
        	'String','X - Rotation [deg]:');

  	btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt];
    
	hSensorXRotMenu = uicontrol( ...
        	'Style','edit', ...
        	'Units','normalized', ...
			'Position',btnPos, ...
        	'Horiz','center', ...
        	'Background','white', ...
        	'Foreground','black', ...
        	'String',int2str(0),'Userdata',0);
			
	btnNumber=2;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos 2.*btnWid./3 btnHt];
    
	hSensorYRotText = uicontrol( ...
      		'Style','text', ...
     	  	'Units','normalized', ...
		'Position',btnPos, ...
        	'Horiz','left', ...
        	'Foreground','black', ...
        	'String','Y - Rotation [deg]:');

  	btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt];
    
	hSensorYRotMenu = uicontrol( ...
        	'Style','edit', ...
        	'Units','normalized', ...
		'Position',btnPos, ...
        	'Horiz','center', ...
        	'Background','white', ...
        	'Foreground','black', ...
        	'String',int2str(0),'Userdata',0);
			
	btnNumber=3;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos 2.*btnWid./3 btnHt];
    
	hSensorZRotText = uicontrol( ...
      		'Style','text', ...
     	  	'Units','normalized', ...
		'Position',btnPos, ...
        	'Horiz','left', ...
        	'Foreground','black', ...
        	'String','Z - Rotation [deg]:');

  	btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt];
    
	hSensorZRotMenu = uicontrol( ...
        	'Style','edit', ...
        	'Units','normalized', ...
		'Position',btnPos, ...
        	'Horiz','center', ...
        	'Background','white', ...
        	'Foreground','black', ...
        	'String',int2str(0),'Userdata',0);
			
	% The View Selection
	btnNumber=4;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos btnWid btnHt];
	labelStr='View: Top|View: Bottom|View: Front|View: Back|View: Left|View: Right';

	hSensorRotViewMenu=uicontrol( ...
		'Style','popupmenu', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String',labelStr, ...
		'Interruptible','on', ...
		'Userdata','Top',...
		'value',1,...
		'Enable','on');
	
	
	btnNumber=5;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos btnWid btnHt];
    
	
  	btnPos=[left yPos btnWid btnHt];
	callbackStr = 'emegs2d(''CalcSensorRotation'')';
    
	hSensorRotApplyMenu = uicontrol( ...
        	'Style','pushbutton', ...
        	'Units','normalized', ...
		'Position',btnPos, ...
        	'Horiz','center', ...
        	'Background','white', ...
        	'Foreground','black', ...
        	'String','Apply','Userdata',0, ...
        	'callback',callbackStr,...
		'Userdata',EPosCart);
			
	btnNumber=6;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos btnWid btnHt];
   	callbackStr = 'emegs2d(''ResetSensorRotation'')';
    
	hSensorRotResetMenu = uicontrol( ...
        	'Style','pushbutton', ...
        	'Units','normalized', ...
		'Position',btnPos, ...
        	'Horiz','center', ...
        	'Background','white', ...
        	'Foreground','black', ...
        	'String','Reset','Userdata',0, ...
        	'callback',callbackStr);
	
	btnNumber=7;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos btnWid btnHt];
   	callbackStr = 'emegs2d(''SaveSensorRotation'')';
    
	hSensorRotSaveMenu = uicontrol( ...
        	'Style','pushbutton', ...
        	'Units','normalized', ...
		'Position',btnPos, ...
        	'Horiz','center', ...
        	'Background','white', ...
        	'Foreground','black', ...
        	'String','Save','Userdata',0, ...
        	'callback',callbackStr);

	hSensorRotPosFig=figure('Units','normal','NumberTitle','off','Position',[0,.5,.5,.5],'Name','Sensor configuration');
	hSensorRotPosAxes=axes('Position',[.05 .05 .9 .9],...
	'XLim',[min(EPosCart(:,1)) max(EPosCart(:,1))],...
	'YLim',[min(EPosCart(:,2)) max(EPosCart(:,2))],...
	'ZLim',[min(EPosCart(:,3)) max(EPosCart(:,3))],...
	'Visible','off');
	
	VisVec=find(EPosCart(:,3)>=0);	%top
	for ChanInd=1:NChan
		hSensorPosTextVec(ChanInd)=text('Position',[EPosCart(ChanInd,1),EPosCart(ChanInd,2),EPosCart(ChanInd,3)],'String',[int2str(ChanInd)],'FontSize',24,'FontWeight','bold');
		if ~isempty(find(VisVec==ChanInd))
			set(hSensorPosTextVec(ChanInd),'Visible','on');
		else
			set(hSensorPosTextVec(ChanInd),'Visible','off');
		end
	end
	hhSensorPosText=uicontrol('Userdata',hSensorPosTextVec,'value',0,'Visible','off');

	NoUse=0;
	hSensorRotVec=[hSensorRotMenuFig hSensorXRotText hSensorXRotMenu hSensorYRotText hSensorYRotMenu ...
				  hSensorZRotText hSensorZRotMenu hSensorRotViewMenu hSensorRotApplyMenu NoUse ...
				  hSensorRotPosFig hSensorRotPosAxes hhSensorPosText hSensorRotResetMenu hSensorRotSaveMenu];
	set(hList(102),'Userdata',hSensorRotVec);

	
elseif strcmp(action,'CalcSensorRotation')| ...
	strcmp(action,'ResetSensorRotation') |...
	strcmp(action,'SaveSensorRotation'),

	hList=get(hPlot2dMenuFig,'Userdata');
	hSensorRotVec=get(hList(102),'Userdata');
	hSensorRotMenuFig=hSensorRotVec(1);
	hSensorView=hSensorRotVec(8);
	EPosCart=get(hSensorRotVec(9),'Userdata');
	[NChan,NoUse]=size(EPosCart);
	hSensorPosFig=hSensorRotVec(11);
	hSensorRotPosAxes=hSensorRotVec(12);
	hSensorPosTextVec=get(hSensorRotVec(13),'Userdata');
	if strcmp(action,'ResetSensorRotation')
		EPosSpher=get(hList(3),'Userdata');
		[EPosCart]=change_sphere_cart(EPosSpher,[],1);
	end
	if strcmp(action,'CalcSensorRotation')
		for XYZIndex=1:3
			v = get(hSensorRotVec(1+XYZIndex.*2),'Userdata');
			str = get(hSensorRotVec(1+XYZIndex.*2),'String');
    		ind = find(abs(str)<32);
    		str(ind) = 32*ones(size(ind));
    		str = str';	
   	 		vv = eval(['[' str(:)' ']'],'-1')';
    		if length(vv)~=1
        		vv = v;
			end
    		vv = round(vv*10)/10;
    		str = sprintf('%g',vv);
			set(hSensorRotVec(1+XYZIndex.*2),'Userdata',vv,'String',str);  
			if XYZIndex==1
				[EPosCart]=XRotation(EPosCart,vv);
			elseif XYZIndex==2
				[EPosCart]=YRotation(EPosCart,vv);
			elseif XYZIndex==3
				[EPosCart]=ZRotation(EPosCart,vv);
			end
		end
	end
	figure(hSensorPosFig);
	SensorViewVal=get(hSensorView,'Value');
	if SensorViewVal==1
		set(hSensorRotPosAxes,'View',[0 90]);	%top
		VisVec=find(EPosCart(:,3)>=0);
	elseif SensorViewVal==2
		set(hSensorRotPosAxes,'View',[180 -90]);%bottom
		VisVec=find(EPosCart(:,3)<=0);
	elseif SensorViewVal==3
		set(hSensorRotPosAxes,'View',[180 0]);	%front
		VisVec=find(EPosCart(:,2)>=0);
	elseif SensorViewVal==4
		set(hSensorRotPosAxes,'View',[0 0]);	%back
		VisVec=find(EPosCart(:,2)<=0);
	elseif SensorViewVal==5
		set(hSensorRotPosAxes,'View',[-90 0]);	%left
		VisVec=find(EPosCart(:,1)<=0);
	elseif SensorViewVal==6
		set(hSensorRotPosAxes,'View',[90 0]);	%right
		VisVec=find(EPosCart(:,1)>=0);
	end
	for ChanInd=1:NChan
		set(hSensorPosTextVec(ChanInd),'Position',[EPosCart(ChanInd,1),EPosCart(ChanInd,2),EPosCart(ChanInd,3)])
		if ~isempty(find(VisVec==ChanInd))
			set(hSensorPosTextVec(ChanInd),'Visible','on');
		else
			set(hSensorPosTextVec(ChanInd),'Visible','off');
		end
	end
	
	set(hSensorRotVec(9),'Userdata',EPosCart);	
	figure(hSensorRotMenuFig);
	if strcmp(action,'SaveSensorRotation')
		[EPosSpher]=change_sphere_cart(EPosCart,[],-1);
		set(hList(3),'Userdata',EPosSpher);
		[ENames]=SetENames([],NChan);
		FileMask=['Rot',int2str(NChan),'.ecfg'];
		SaveEConfig(EPosSpher,ENames,FileMask);
		close(hSensorRotMenuFig);
		close(hSensorPosFig);
	end
	%============================================================================
	% =========== calculate axis position of sensor subplots
	%============ external function: Calc2dTimeAxes
	%============ call:	setView
	%============================================================================	
	
elseif strcmp(action,'Calc2dTimeAxes'),

	hList=get(hPlot2dMenuFig,'Userdata');
	EPosSpher=get(hList(3),'Userdata');
	NChan=size(EPosSpher,1)
	if NChan<4
		kTop=1:NChan;
		kFront=kTop;kFront=kTop;kBack=kTop;kLeft=kTop;kRight=kTop;kNorm=kTop;kAll=kTop;
		if NChan==1
			AxesTop=[.25 .25];
		elseif NChan==2
			AxesTop=[.25 .75;.25 0];
		elseif NChan==3
			AxesTop=[.1 .6;.1 .1;.6 .6];
		end
		AxesFront=AxesTop;AxesBack=AxesTop;AxesLeft=AxesTop;AxesRight=AxesTop;AxesNorm=AxesTop;AxesAll=AxesTop;
	else
		[kTop,AxesTop,kFront,AxesFront,kBack,AxesBack,kLeft,...
		AxesLeft,kRight,AxesRight,kNorm,AxesNorm,kAll,AxesAll,...
		TopStatusVec,FrontStatusVec,BackStatusVec,LeftStatusVec,RightStatusVec,NormStatusVec,AllStatusVec] = ...
		Calc2dTimeAxes(EPosSpher);
	end
	set(hList(31),'Userdata',kTop);
	set(hList(32),'Userdata',AxesTop);
	set(hList(33),'Userdata',kFront);
	set(hList(34),'Userdata',AxesFront);
	set(hList(35),'Userdata',kBack);
	set(hList(36),'Userdata',AxesBack);
	set(hList(37),'Userdata',kLeft);
	set(hList(38),'Userdata',AxesLeft);
	set(hList(39),'Userdata',kRight);
	set(hList(40),'Userdata',AxesRight);
	set(hList(41),'Userdata',kNorm);
	set(hList(42),'Userdata',AxesNorm);
	set(hList(43),'Userdata',kAll);
	set(hList(44),'Userdata',AxesAll);
	emegs2d('setView')
	
    
 	%============================================================================
	% =========== GlobDissim1Files,GlobDissim2Files
	%============================================================================	
elseif strcmp(action,'GlobDissim1Files') |   strcmp(action,'GlobDissim2Files') 
  
    hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	Domain=get(hList(20),'Value');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	ActFileNo=get(hList(1),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	MinBase=get(hList(58),'Value');
	MaxBase=get(hList(59),'Value');
    
	NChan=get(hList(NListHdr+(1-1).*50+2),'Userdata');
    CalcAvgMat = zeros(NChan,NPoints,2);
    GPData = zeros(2,NPoints);
    if strcmp(action,'GlobDissim1Files')
        
        for FileIndex=1:2
			hDataVec=get(hList(NListHdr+(FileNoVec(1)-1).*50+25),'Userdata');
			NActChan=length(hDataVec);
			CalcAvgMat(:,:,FileIndex)=get(hList(NListHdr+(FileNoVec(1)-1).*50+1),'Userdata');
            CalcAvgMatBase = CalcAvgMat(:,:,FileIndex);
            [CalcAvgMatBase,BaseStartPoint,BaseEndPoint,NonUse,BaseVec] = CalcBaseline(CalcAvgMatBase,MinBase,MaxBase,1,1);
            if FileIndex == 2
                CalcAvgMat(:,:,FileIndex) = [CalcAvgMat(:,2:end,FileIndex),CalcAvgMat(:,end,FileIndex)];
            end
			GPData(FileIndex,:)=(sum(CalcAvgMat(:,:,FileIndex).^2))./NChan;
            GPData(FileIndex,:)=sqrt(GPData(FileIndex,:));
            GPMat = ones(NChan,NPoints);
            for ChanInd = 1: NChan
                GPMat(ChanInd,:)=GPMat(ChanInd,:).*GPData(FileIndex,:);
            end
            %Normalisieren am GP
            CalcAvgMat(:,:,FileIndex) = CalcAvgMat(:,:,FileIndex)./GPMat(:,:);  
		end
        
        %Global Dissimilarity
        GlobDissVec = (mean((CalcAvgMat(:,:,1)-CalcAvgMat(:,:,2)).^2,1)).^0.5;
        
    elseif strcmp(action,'GlobDissim2Files')
        
		for FileIndex=1:2
			hDataVec=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+25),'Userdata');
			NActChan=length(hDataVec);
			CalcAvgMat(:,:,FileIndex)=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
            CalcAvgMatBase = CalcAvgMat(:,:,FileIndex);
            [CalcAvgMatBase,BaseStartPoint,BaseEndPoint,NonUse,BaseVec] = CalcBaseline(CalcAvgMatBase,MinBase,MaxBase,1,1);
            CalcAvgMat(:,:,FileIndex) = CalcAvgMatBase;
            figure('name',[num2str(FileIndex),' raw'])
            surf(CalcAvgMat(:,:,FileIndex),'EdgeColor','none')
			GPData(FileIndex,:)=(sum(CalcAvgMat(:,:,FileIndex).^2))./NChan;
            GPData(FileIndex,:)=sqrt(GPData(FileIndex,:));
            GPMat = ones(NChan,NPoints);
            for ChanInd = 1: NChan
                GPMat(ChanInd,:)=GPMat(ChanInd,:).*GPData(FileIndex,:);
            end
            %Normalisieren am GP            
            CalcAvgMat(:,:,FileIndex) = CalcAvgMat(:,:,FileIndex)./GPMat(:,:);              
		end
        %Global Dissimilarity
        GlobDissVec = (mean((CalcAvgMat(:,:,1)-CalcAvgMat(:,:,2)).^2,1)).^0.5;
    end
    
    emegs2d('ZoomSpecChan','GPDissim',GlobDissVec)
    emegs2d('AdjustSpecChanAmp')
    
	%============================================================================
	% =========== set view (top, front, back, left, right or norm)
	%============ call:	InitChanAxes, ChangeLREarNoseTextPosition, PlotData
	%============================================================================	
elseif strcmp(action,'setView'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ViewVal=get(hList(26),'Value');
	OpenAvgFileStatus=get(hList(108),'Value');

    % The Kind of thres fac Selection Menu
	if 	ViewVal==1; 
		ViewStr='Top'; 
		kActAxes=get(hList(31),'Userdata');
		ActAxes=get(hList(32),'Userdata');
	elseif 	ViewVal==2; 
		ViewStr='Front'; 
		kActAxes=get(hList(33),'Userdata');
		ActAxes=get(hList(34),'Userdata');
	elseif 	ViewVal==3; 
		ViewStr='Back'; 
		kActAxes=get(hList(35),'Userdata');
		ActAxes=get(hList(36),'Userdata');
	elseif 	ViewVal==4; 
		ViewStr='Left';
		kActAxes=get(hList(37),'Userdata');
		ActAxes=get(hList(38),'Userdata');
	elseif 	ViewVal==5; 
		ViewStr='Right'; 
		kActAxes=get(hList(39),'Userdata');
		ActAxes=get(hList(40),'Userdata');
	elseif 	ViewVal==6; 
		ViewStr='Norm'; 
		kActAxes=get(hList(41),'Userdata');
		ActAxes=get(hList(42),'Userdata');
	end
	set(hList(26),'Userdata',ViewStr);
	set(hList(27),'Userdata',kActAxes);
	set(hList(28),'Userdata',ActAxes);
	emegs2d('InitChanAxes')
	emegs2d('ChangeLREarNoseTextPosition')
	if ~OpenAvgFileStatus; emegs2d('PlotData'); end
	
	%============================================================================
	%============ InitChanAxes
	%============================================================================		
elseif strcmp(action,'InitChanAxes'),

	hList=get(hPlot2dMenuFig,'Userdata');
	figure(hList(93));		%hPlot2dChanFig
	hPlot2dChanAxes=get(hList(25),'Userdata');
	axes(hPlot2dChanAxes);
	ActFileNo=get(hList(1),'Userdata');
	ENames=get(hList(4),'Userdata');
	NListHdr=get(hList(51),'Userdata');

	TrigPoint=get(hList(22),'Value');
	CursorPoint=get(hList(23),'Value');
		
	kActAxes=get(hList(27),'Userdata');
	ActAxes=get(hList(28),'Userdata');
	TrigLength=get(hList(29),'Userdata');
	CursorLength=get(hList(30),'Userdata');
	
	ActNChan=length(kActAxes);
	
	NChan=get(hList(NListHdr+(ActFileNo-1).*50+2),'Userdata');
	NPoints=get(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata');
	
	MinAmp=get(hList(52),'Value');
	MaxAmp=get(hList(53),'Value');
	MinPoint=get(hList(54),'Value');
	MaxPoint=get(hList(55),'Value');
	SampRate=get(hList(60),'Userdata');
	
	MainMatlabVersion=get(hList(100),'Userdata');
	hSetEegMegStatus=hList(110);
	FontSizeVec=get(hList(112),'Userdata');
	%Width Height of Sensor Axes
	hw=ceil(sqrt(ActNChan));
	MinWidthHeight=1;
	MaxWidthHeight=20;
	if hw<MinWidthHeight; hw=1; elseif hw>MaxWidthHeight; hw=20; end
	if MaxWidthHeight+1-hw<10; StrTmp=['0',int2str(MaxWidthHeight+1-hw)]; else; StrTmp=int2str(MaxWidthHeight+1-hw); end
	emegs2d(['setSensorAxesWidth',StrTmp]);
	emegs2d(['setSensorAxesHeight',StrTmp]);
	ActAxes=ActAxes.*hw./(hw+1);
	AxesPosMat=zeros(ActNChan,4);
	for ChanInd=1:ActNChan	
		AxesPosMat(ChanInd,:)=[ActAxes(ChanInd,1) ActAxes(ChanInd,2) 1/hw  1/hw];
	end
	xVec=[1:NPoints];
	yVec=zeros(size(xVec));
	
	hAxesVec=get(hList(6),'Userdata');
	if hAxesVec~=0
		NChan=length(hAxesVec);
		for ChanInd=1:NChan
			axes(hAxesVec(ChanInd));
			cla;
		end
	end
	ChanFigBGColor=get(hPlot2dMenuFig,'Color');
	if ChanFigBGColor==[0 0 0]; %black
		XColor=[1 1 1]; %white
		XColorVal=2;
	else
		XColor=[0 0 0];
		XColorVal=1;
	end
	YColor=XColor; 
	ChanFigFGColor=XColor;
	
	hView=hList(26);
	ActViewVal=get(hView,'Value');
	MaxNoValHView=get(hView,'Max');
	hhText5=get(hList(15),'Userdata');
	hhText5VisVal=get(hList(15),'Value');	%xxx
	if hhText5VisVal; 						%xxx
		hhText5Visible = 'on';				%xxx
	else 									%xxx
		hhText5Visible = 'off';				%xxx
	end;									%xxx
	
	if length(hhText5)~=1
		set(hhText5,'Visible','off'); 		% clear text
	end;
	LREarFontSize=20;
    LeftEarStart1=.05;
    LeftEarStart2=.405;
    RightEarStart1=.9;
    RightEarStart2=.405;
    if ~isempty(NChan)
        if NChan>255
            LeftEarStart1=.125;
            LeftEarStart2=.45;
            RightEarStart1=.825;
            RightEarStart2=.45;
        end
    end
	LeftLeftEarPosMat=ones(MaxNoValHView,2);
	LeftLeftEarPosMat(:,1)=LeftEarStart1.*LeftLeftEarPosMat(:,1);
	LeftLeftEarPosMat(:,2)=LeftEarStart2.*LeftLeftEarPosMat(:,2);
	
	EarLeftEarPosMat=ones(MaxNoValHView,2);
	EarLeftEarPosMat(:,1)=LeftEarStart1.*EarLeftEarPosMat(:,1);
	EarLeftEarPosMat(:,2)=(LeftEarStart2-.03).*EarLeftEarPosMat(:,2);

	RightRightEarPosMat=ones(MaxNoValHView,2);
	RightRightEarPosMat(:,1)=RightEarStart1.*RightRightEarPosMat(:,1);
	RightRightEarPosMat(:,2)=RightEarStart2.*RightRightEarPosMat(:,2);
	
	EarRightEarPosMat=ones(MaxNoValHView,2);
	EarRightEarPosMat(:,1)=RightEarStart1.*EarRightEarPosMat(:,1);
	EarRightEarPosMat(:,2)=(RightEarStart2-.03).*EarRightEarPosMat(:,2);

	LeftEyePosMat=ones(MaxNoValHView,2);
	LeftEyePosMat(:,1)=.3.*LeftEyePosMat(:,1);
	LeftEyePosMat(:,2)=.915.*LeftEyePosMat(:,2);
	
	RightEyePosMat=ones(MaxNoValHView,2);
	RightEyePosMat(:,1)=.7.*RightEyePosMat(:,1);
	RightEyePosMat(:,2)=.915.*RightEyePosMat(:,2);
	
	NosePosMat=ones(MaxNoValHView,2);
	NosePosMat(:,1)=.5.*NosePosMat(:,1);
	NosePosMat(:,2)=.975.*NosePosMat(:,2);
	NosePosMat(5,:)=[.05 .4];
	
	hText5(1)=text('Position',LeftLeftEarPosMat(ActViewVal,:),'Color',XColor,'FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','left','Visible',hhText5Visible,'String','Left','Userdata',LeftLeftEarPosMat);	%Left (Ear)
	
	hText5(2)=text('Position',EarLeftEarPosMat(ActViewVal,:),'Color',XColor,'FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','left','Visible',hhText5Visible,'String','Ear','Userdata',EarLeftEarPosMat);	% (Left) Ear
	
	hText5(3)=text('Position',RightRightEarPosMat(ActViewVal,:),'Color',XColor,'FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','left','Visible',hhText5Visible,'String','Right','Userdata',RightRightEarPosMat);	%Right (Ear)
	
	hText5(4)=text('Position',EarRightEarPosMat(ActViewVal,:),'Color',XColor,'FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','left','Visible',hhText5Visible,'String','Ear','Userdata',EarRightEarPosMat);	%(Right) Ear
	
	hText5(5)=text('Position',NosePosMat(ActViewVal,:),'Color',XColor,'FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','center','Visible',hhText5Visible,'String','Nose','Userdata',NosePosMat);	% Nose
	
	hText5(6)=text('Position',LeftEyePosMat(ActViewVal,:),'Color',XColor,'FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','center','Visible',hhText5Visible,'String','Left Eye','Userdata',LeftEyePosMat);	% Left Eye

	hText5(7)=text('Position',RightEyePosMat(ActViewVal,:),'Color',XColor,'FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','center','Visible',hhText5Visible,'String','Right Eye','Userdata',RightEyePosMat);	% Right Eye

	hFileInfoTextVec=get(hList(17),'Userdata');
	axes(hPlot2dChanAxes);
	for FileIndex=1:length(hFileInfoTextVec)
		if hFileInfoTextVec(FileIndex)==0
			Tmp=text('HorizontalAlignment','left','FontSize',FontSizeVec(2),'Visible','on');
			hFileInfoTextVec(FileIndex)=Tmp;
		end
	end
	set(hList(17),'Userdata',hFileInfoTextVec);
	hList(141)=text('HorizontalAlignment','left','FontSize',FontSizeVec(2),'Visible','on'); %hEcfgInfoText 

	hAxesVec=[]; hDataVec1=[]; hZeroLine=[]; hTrigLine=[]; hCursorLine=[]; hText1=[];
	NPoints=get(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata');

	if NPoints==1	
		AvgVec=get(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata');
   	end

	for ChanInd=1:ActNChan	
		if NPoints==1	
			hAxesVec(ChanInd)=axes('Units','normal','Position',AxesPosMat(ChanInd,:),'Box','off');
			hTextVec1(ChanInd)=text('String',[num2str(round(AvgVec(ChanInd).*100)./100)],'FontSize',[20],...
			'Color',ChanFigFGColor,'HorizontalAlignment','left','VerticalAlignment','bottom','Visible','on');
		else
			hAxesVec(ChanInd)=axes('Units','normal','Position',AxesPosMat(ChanInd,:),'Box','off','XLim',[MinPoint MaxPoint],...
                'YLim',[MinAmp MaxAmp],'ButtonDownFcn',['emegs2d(''ZoomSpecChan'',get(gcbo,''tag''));'],'tag',num2str(ChanInd));
            %set(gca,'XTickLabelMode','manual','YTickLabelMode','manual','ZTickLabelMode','manual','XColor',[1 1 1],'YColor',[1 1 1],'Color','none');
            axis('off');
            set(gca,'Box','on');
            hZeroLine(ChanInd)=line('XData',[MinPoint MaxPoint],'YData',[0 0],'Color',XColor,'LineStyle','--');
			hTrigLine(ChanInd)=line('XData',[TrigPoint TrigPoint],'YData',[MinAmp.*TrigLength MaxAmp.*TrigLength],'Color',XColor,'LineStyle','--','Visible','off');
			hCursorLine(ChanInd)=line('XData',[CursorPoint CursorPoint],'YData',[MinAmp.*CursorLength MaxAmp.*CursorLength],'Color',XColor,'LineStyle','--','Visible','off');    
        end
		hDataVec1(ChanInd)=line('XData',xVec,'YData',yVec,'Visible','off');
		hDataVec2(ChanInd)=line('XData',xVec,'YData',yVec,'Visible','off');
		hDataVec3(ChanInd)=line('XData',xVec,'YData',yVec,'Visible','off');
		hDataVec4(ChanInd)=line('XData',xVec,'YData',yVec,'Visible','off');
        hDataVec5(ChanInd)=line('XData',xVec,'YData',yVec,'Visible','off');
        hDataVec6(ChanInd)=line('XData',xVec,'YData',yVec,'Visible','off');
        if ~isempty(findstr(ENames(kActAxes(ChanInd),:),num2str(kActAxes(ChanInd))))
            ENameStr=ENames(kActAxes(ChanInd),:);
        else
		    ENameStr=[num2str(kActAxes(ChanInd)),': ',ENames(kActAxes(ChanInd),:)];
        end
		hText1(ChanInd)=text('Units','normal','Position',[.05 .6],'String',ENameStr,'FontSize',FontSizeVec(3),'Color',ChanFigFGColor,'HorizontalAlignment','left','Visible','on');	%EName
		hText2(ChanInd)=text('String',[num2str(kActAxes(ChanInd))],'FontSize',FontSizeVec(3),'HorizontalAlignment','center','Visible','off');%CursorAmp
		hText3(ChanInd)=text('Units','normal','Position',[.05 .75],'FontSize',FontSizeVec(4),'HorizontalAlignment','left','Visible','off');	%NTrials
		hText4(ChanInd)=text('Units','normal','Position',[.05 .9],'FontSize',FontSizeVec(5),'HorizontalAlignment','left','Visible','off');	%MeanStd
        
    	hSigVec1(ChanInd)=text('Units','normal','Position',[.5 .8],'FontSize',18,'HorizontalAlignment','center','Visible','off','FontWeight','bold');%SigVec
    	hSigVec2(ChanInd)=text('Units','normal','Position',[.5 .6],'FontSize',18,'HorizontalAlignment','center','Visible','off','FontWeight','bold');%SigVec
    	hSigVec3(ChanInd)=text('Units','normal','Position',[.5 .4],'FontSize',18,'HorizontalAlignment','center','Visible','off','FontWeight','bold');%SigVec
    	hSigVec4(ChanInd)=text('Units','normal','Position',[.5 .2],'FontSize',18,'HorizontalAlignment','center','Visible','off','FontWeight','bold');%SigVec 	
        hSigVec5(ChanInd)=text('Units','normal','Position',[.5 .0],'FontSize',18,'HorizontalAlignment','center','Visible','off','FontWeight','bold');%SigVec 
        hSigVec6(ChanInd)=text('Units','normal','Position',[.5 .0],'FontSize',18,'HorizontalAlignment','center','Visible','off','FontWeight','bold');%SigVec 
	end
	if NPoints>1	
		AxesWidth=AxesPosMat(1,3);
		AxesHight=AxesPosMat(1,4);
	
		hSpec1Axes=get(hList(76),'Userdata');
		if hSpec1Axes~=0
			set(hSpec1Axes,'Visible','off');
		end
		hSpec1Axes=axes('Units','normal','Position',[0.866 0.05 AxesWidth AxesHight],'Color',ChanFigBGColor,...
		'Box','off','XLim',[MinPoint MaxPoint],'YLim',[MinAmp MaxAmp],...
		'XTick',[MinPoint MaxPoint],'XTickLabel',[(MinPoint-TrigPoint).*1000./SampRate (MaxPoint-TrigPoint).*1000./SampRate],...
		'YTick',[MinAmp MaxAmp],'YTickLabel',[(round(10.*MinAmp))./10 (round(10.*MaxAmp))./10],...
		'XColor',XColor,'YColor',YColor,'Visible','off','FontSize',FontSizeVec(1));

		hSpec1ZeroLine=line('XData',[MinPoint MaxPoint],'YData',[0 0],'Color',XColor,'Linestyle','--','Visible','off');
		hSpec1TrigLine=line('XData',[TrigPoint TrigPoint],'YData',[MinAmp MaxAmp],'Color',XColor,'LineStyle','--','Visible','off');
		hSpec1CursorLine=line('XData',[CursorPoint CursorPoint],'YData',[MinAmp MaxAmp],'Color',XColor,'LineStyle','--','Visible','off');
		hSpec1CursorText=text('Position',[CursorPoint .8.*MinAmp],'FontSize',FontSizeVec(1),'HorizontalAlignment','left','Visible','off');
		
		set(hList(76),'Userdata',hSpec1Axes);
		set(hList(77),'Userdata',hSpec1ZeroLine);
		set(hList(78),'Userdata',hSpec1TrigLine);
		set(hList(79),'Userdata',hSpec1CursorLine);
		set(hList(80),'Userdata',hSpec1CursorText);

	end
	xlabel('Time [ms]','FontSize',FontSizeVec(1));
	EegMegStatusString=get(hSetEegMegStatus,'String');
   	if strcmp(EegMegStatusString,'EEG'); 
      	ylabel('Pot. [µV]','FontSize',FontSizeVec(1)); 
   	else
      	ylabel('Field [fT]','FontSize',FontSizeVec(1)); 
	end
	XLineStyleVal=2; % 2: dashed
	hZeroLineVal=[XColorVal XLineStyleVal];	
	hTriggerLineVal=[XColorVal XLineStyleVal];
	hCursorLineVal=[XColorVal XLineStyleVal];
	
	set(hList(5),'Userdata',AxesPosMat);
	set(hList(6),'Userdata',hAxesVec);
	set(hList(8),'Userdata',hZeroLine,'Value',hZeroLineVal);
	set(hList(9),'Userdata',hTrigLine,'Value',hTriggerLineVal);
	set(hList(10),'Userdata',hCursorLine,'Value',hCursorLineVal);
	set(hList(11),'Userdata',hText1);
	set(hList(12),'Userdata',hText2);
	set(hList(13),'Userdata',hText3);
	set(hList(14),'Userdata',hText4);
   	set(hList(15),'Userdata',hText5);
	set(hList(15),'Value',hhText5VisVal);
  	ActFileNo=1;	
   	set(hList(NListHdr+(ActFileNo-1).*50+25),'Userdata',hDataVec1);
   	set(hList(NListHdr+(ActFileNo-1).*50+30),'Userdata',hSigVec1);
   	ActFileNo=2;	
   	set(hList(NListHdr+(ActFileNo-1).*50+25),'Userdata',hDataVec2);
   	set(hList(NListHdr+(ActFileNo-1).*50+30),'Userdata',hSigVec2);
  	ActFileNo=3;	
   	set(hList(NListHdr+(ActFileNo-1).*50+25),'Userdata',hDataVec3);
   	set(hList(NListHdr+(ActFileNo-1).*50+30),'Userdata',hSigVec3);
  	ActFileNo=4;	
   	set(hList(NListHdr+(ActFileNo-1).*50+25),'Userdata',hDataVec4);
   	set(hList(NListHdr+(ActFileNo-1).*50+30),'Userdata',hSigVec4);
    ActFileNo=5;	
   	set(hList(NListHdr+(ActFileNo-1).*50+25),'Userdata',hDataVec5);
   	set(hList(NListHdr+(ActFileNo-1).*50+30),'Userdata',hSigVec5);
    ActFileNo=6;	
   	set(hList(NListHdr+(ActFileNo-1).*50+25),'Userdata',hDataVec6);
   	set(hList(NListHdr+(ActFileNo-1).*50+30),'Userdata',hSigVec6);
	set(hPlot2dMenuFig,'Userdata',hList);	
	%============================================================================
	%============ ChangeDispTextPositions
	%============================================================================	
	
elseif  strcmp(action,'ChangeDispTextPositions')

	Message=char('Please open the');
	Message=char(Message,'Matlab command window');
	Message=char(Message,'to change the text positions:');
	msgbox(Message,'Info:','help')
	
	hList=get(hPlot2dMenuFig,'Userdata');
	MainMatlabVersion=get(hList(100),'Userdata');
	
	hText1=get(hList(11),'Userdata');
	hText3=get(hList(13),'Userdata');
	hText4=get(hList(14),'Userdata');

	Text1Pos=get(hText1(1),'Position');
	[xPos1]=IfEmptyInputValInt('Please insert the x-Position','of sensor names:',[],Text1Pos(1),0,1,1);
	[yPos1]=IfEmptyInputValInt('Please insert the y-Position','of sensor names:',[],Text1Pos(2),0,1,0);
	
	[xPos3]=IfEmptyInputValInt('Please insert the x-Position','of number of trials:',[],xPos1,0,1,1);
	[yPos3]=IfEmptyInputValInt('Please insert the y-Position','of number of trials:',[],yPos1+.15,0,1,0);

	[xPos4]=IfEmptyInputValInt('Please insert the x-Position','of mean std:',[],xPos1,0,1,1);
	[yPos4]=IfEmptyInputValInt('Please insert the y-Position','of mean std:',[],yPos1+.3,0,1,0);

	if MainMatlabVersion>4
		set(hText1,'Position',[xPos1 yPos1]);
		set(hText3,'Position',[xPos3 yPos3]);
		set(hText4,'Position',[xPos4 yPos4]);
	else
		Tmp=get(hList(16),'Userdata');
		DataNChan=Tmp(1);
		SensorNChan=Tmp(2);
		for ChanInd=1:SensorNChan
			set(hText1(ChanInd),'Position',[xPos1 yPos1]);
			set(hText3(ChanInd),'Position',[xPos3 yPos3]);
			set(hText4(ChanInd),'Position',[xPos4 yPos4]);
		end
	end
    
elseif   strcmp(action,'chAutoDataFormat')
    
    hList=get(hPlot2dMenuFig,'Userdata');
    
    F=char('.at;chAvgFileSCADS;');
    F=char(F,'.app;chAppFileSCADS;');
    F=char(F,'.ave;chAvgFileEgis;');
    F=char(F,'.gave;chGrandAvgFileEgis;');
    F=char(F,'.seg;chRawFileEgis;');
    F=char(F,'.E;chRawFileEgis;');
    F=char(F,'.ses;chRawFileEgis;');
    F=char(F,'.seg;chRawFileEgis;');
    F=char(F,'.avr;chAvgFileAsciiBesaVec;');
    F=char(F,'.avg;chAvgNeuroscan;');
    F=char(F,'.cnt;chCntNeuroscan;');
    F=char(F,'.msi;chAvgFileMegBtiMsi;');
    F=char(F,'.raw;chAvgFileAsciiMEG;');
    F=char(F,'.awa;chAmpWave;');
    F=char(F,'.pwa;chPhaseWave;');
    
	OldPath=pwd;
    DefPath=SetDefPath('r')
	if ~isempty(DefPath);
		[DefFile,DefPath]=SepFilePath(DefPath);
		if strcmp(DefPath(end),filesep)
			DefPath=DefPath(1:length(DefPath)-1);
		end
		eval(['cd ',DefPath]);
	end	
    
    [File,Path] = uigetfile( ...
        {'*.at*;', 'SCADS Average (*.at*)'; ...
            '*.app*', 'SCADS Approx (*.app*)'; ...
            '*.ave*;', 'Egis Average (*.ave*)'; ...
            '*.gave*', 'Egis Grand Average (*.gave*)'; ...
            '*.E*; *.ses; *.seg', 'Egis Session (*.E*, *.ses, *.seg)'; ...
            '*.avr*', 'Besa Ascii (*.avr*)'; ...
            '*.avg*', 'Neuroscan Average (*.avg*)'; ...
            '*.cnt*', 'Neuroscan Continuous (*.cnt*)'; ...
            '*.msi*', 'BTI Binary (*.msi*)'; ...
            '*.raw*', 'BTI Ascii(*.raw*)'; ...
            '*.awa*', 'Wavelet Amplitude (*.awa*)'; ...
            '*.msi*', 'Wavelet Phase (*.pwa*)'; ...
        }, ...
        'Pick a file');
    
    if File==0; return; end
    for i=1:size(F,1)
        Tmp=findstr(F(i,:),';');
        Ext=F(i,1:Tmp(1)-1);
        FV(i)=length(findstr(File,Ext));
    end
    NF=find(FV);
    if length(NF)==0
        Message=char(' ');
	    Message=char(Message,'Unknown file format');
	    Message=char(Message,'');
	    hmsgbox=msgbox(Message,'Info','help');
        return
    elseif length(NF)==1
        SetDefPath('w',Path);
        Tmp=findstr(F(NF,:),';');
        action=F(NF,Tmp(1)+1:Tmp(2)-1);
        eval(['emegs2d(''',action,''')'])
    elseif length(NF>1)
        Message=char(' ');
	    Message=char(Message,'Unknown file format');
	    Message=char(Message,'');
	    hmsgbox=msgbox(Message,'Info','help');
        return
    end
    
    %============================================================================
	%============ chAvgFile ...: change data format of actual data set
	%============ call: chOpenAvgFileButton
	%============================================================================
    
elseif  strcmp(action,'chNeuroscanAvg') | ...
		strcmp(action,'chNeuroscanCnt') | ...
		strcmp(action,'chAmpWave') | ...
		strcmp(action,'chPhaseWave') | ...
		strcmp(action,'chAvgFileSCADS') | ...
		strcmp(action,'chAppFileSCADS') | ...
		strcmp(action,'chAvgFileEgis') | ...
		strcmp(action,'chGrandAvgFileEgis') | ...
		strcmp(action,'chRawFileEgis') | ...
		strcmp(action,'chAvgFileAsciiBesaVec') |...
		strcmp(action,'chAvgFileAsciiMEG') |...
		strcmp(action,'chAvgFileMegBtiMsi') |...
		strcmp(action,'chAvgFileAsciiVec') |...
		strcmp(action,'chAvgFileAsciiHeaderVec') | ...
		strcmp(action,'chAvgFileFloat32Vec') |...
		strcmp(action,'chAvgFileFloat32HeaderVec') | ...
		strcmp(action,'chSyntheticData'),
		
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	oldDataFormatInd=get(hList(NListHdr+(ActFileNo-1).*50+22),'Value');
	pointer=get(hList(83),'Userdata');
	hTopMenu=get(hList(65),'Userdata');
	hFileMenu=get(hTopMenu(1),'children');
	hDataFormat=get(hFileMenu(3),'children');
	
	if  strcmp(action,'chAvgFileAsciiMEG') 
		AvgFileFormat='AsciiMEG';
		AvgFileFormatVal=1;DataFormatInd=2;
		AvgFileFormatExt='*.raw*';
		emegs2d('chECfgFileMEGOnSphere');
	elseif  strcmp(action,'chAvgFileAsciiBesaVec') 
		AvgFileFormat='AsciiBesaVec';
		AvgFileFormatExt='*.avr*';
		AvgFileFormatVal=2;DataFormatInd=3;
	elseif  strcmp(action,'chAvgFileFloat32HeaderVec') 
		AvgFileFormat='Float32HeaderVec';
		AvgFileFormatExt='*';
		AvgFileFormatVal=3;DataFormatInd=4;
	elseif  strcmp(action,'chAvgFileFloat32Vec') 
		AvgFileFormat='Float32Vec';
		AvgFileFormatExt='*';
		AvgFileFormatVal=4;DataFormatInd=5;
	elseif  strcmp(action,'chAvgFileAsciiHeaderVec') 
		AvgFileFormat='AsciiHeaderVec';
		AvgFileFormatExt='*';
		AvgFileFormatVal=5;DataFormatInd=6;
	elseif  strcmp(action,'chAvgFileAsciiVec') 
		AvgFileFormat='AsciiVec';
		AvgFileFormatExt='*';
		AvgFileFormatVal=6;DataFormatInd=7;
	elseif  strcmp(action,'chAppFileSCADS') 
		AvgFileFormat='AppSCADS';
		AvgFileFormatExt='*.app*';
		AvgFileFormatVal=7;DataFormatInd=8;
	elseif  strcmp(action,'chAvgFileSCADS') 
		AvgFileFormat='SCADS';
		AvgFileFormatExt='*.at*';
		AvgFileFormatVal=8;DataFormatInd=9;
	elseif  strcmp(action,'chRawFileEgis') 
		AvgFileFormat='RawEgis';
		Plot2dVersionString=get(hList(97),'Userdata');
		if strcmp(Plot2dVersionString,'SCADS')
			AvgFileFormatExt='*.E*';
		else
			AvgFileFormatExt='*.ses*';
		end
		AvgFileFormatVal=9;DataFormatInd=10;
	elseif  strcmp(action,'chGrandAvgFileEgis') 
		AvgFileFormat='GrandAvgEgis';
		AvgFileFormatExt='*.gave*';
		AvgFileFormatVal=10;DataFormatInd=11;
	elseif  strcmp(action,'chAvgFileEgis') 
		AvgFileFormat='AvgEgis';
		AvgFileFormatExt='*.ave*';
		AvgFileFormatVal=11;DataFormatInd=12;
	elseif  strcmp(action,'chSyntheticData') 
		AvgFileFormat='SyntheticData';
		AvgFileFormatExt='*';
		AvgFileFormatVal=12;DataFormatInd=15;
	elseif  strcmp(action,'chAmpWave') 
		AvgFileFormat='AmpWave';
		AvgFileFormatExt='*.awa*';
		AvgFileFormatVal=13;DataFormatInd=14;
	elseif  strcmp(action,'chPhaseWave') 
		AvgFileFormat='PhaseWave';
		AvgFileFormatExt='*.pwa*';
		AvgFileFormatVal=14;DataFormatInd=13;
	elseif  strcmp(action,'chAvgFileMegBtiMsi') 
		AvgFileFormat='MegBtiMsi';
		AvgFileFormatVal=15;DataFormatInd=1;
		AvgFileFormatExt='*.msi';
		emegs2d('chECfgFileMEGOnSphere');
	elseif  strcmp(action,'chNeuroscanAvg') 
		AvgFileFormat='NeuroscanAvg';
		AvgFileFormatExt='*.avg*';
		AvgFileFormatVal=16;DataFormatInd=16;
	elseif  strcmp(action,'chNeuroscanCnt') 
		AvgFileFormat='NeuroscanCnt';
		AvgFileFormatExt='*.cnt*';
		AvgFileFormatVal=17;DataFormatInd=15;
	end
	if strcmp(action,'chAvgFileSCADS') 
		set(hList(126),'Enable','on');	%hOpenFileBatch
	else
		set(hList(126),'Enable','off');
	end
	if  strcmp(action,'chRawFileEgis') 
		set(hList(49),'Value',10); %EnableValue
	else
		set(hList(49),'Value',11); %EnableValue
	end
	if  strcmp(action,'chAvgFileAsciiMEG')  | strcmp(action,'chAvgFileMegBtiMsi') 
		set(hList(110),'String','MEG');	%SetEegMegStatus
	end
	%------------------ change index position in menu ----------------
	for ind=1:length(hDataFormat)
		AvgFileFormatLabel=get(hDataFormat(ind),'Label');
		PointPos=get(hDataFormat(ind),'Userdata');
		if (ind==oldDataFormatInd) AvgFileFormatLabel(PointPos)=' '; end;
		if (ind==DataFormatInd) AvgFileFormatLabel(PointPos)=setstr(pointer); end;
		set(hDataFormat(ind),'Label',AvgFileFormatLabel);
	end;	
	%-----------------------------------------------------------------
	
	set(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata',AvgFileFormat,'Value',DataFormatInd,'String',AvgFileFormatExt);
	emegs2d('EnableOnOff');	
	emegs2d('chOpenAvgFileButton');

	%============================================================================
	%============ chOpenAvgFileButton
	%============================================================================
	
elseif strcmp(action,'chOpenAvgFileButton'),

	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	ActFilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
	AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
	hOpenAvgFile=hList(82);

	if strcmp(AvgFileFormat,'AvgEgis') | strcmp(AvgFileFormat,'GrandAvgEgis')

		EgisAvgVec=get(hList(NListHdr+(ActFileNo-1).*50+31),'Userdata');
		ActCellNo=EgisAvgVec(1);
		NCells=EgisAvgVec(3);
		NSubjectsVec=EgisAvgVec(7+NCells:6+2.*NCells);
		labelStr=' File                 ';
		if NCells~=0; 
			for CellInd=1:NCells
				for SubjectInd=1:NSubjectsVec(CellInd)
					if strcmp(AvgFileFormat,'AvgEgis')
						labelStr=[labelStr,'| Cell: ',int2str(CellInd),'; Subject:',int2str(SubjectInd)];
					else
						labelStr=[labelStr,'| Cell: ',int2str(CellInd)];
					end
				end
			end
		end
		set(hOpenAvgFile,...
			'Style','popupmenu', ...
        	'String',labelStr, ...
			'Userdata',0,...
			'value',ActCellNo+1);
			
	elseif  strcmp(AvgFileFormat,'RawEgis')

		EgisRawVec=get(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata');
		ActCellNo=EgisRawVec(1);
		NCells=EgisRawVec(3);
		NTrialsVec=EgisRawVec(7+NCells:6+2.*NCells);
		labelStr=' File                 ';
		if NCells~=0; 
			for CellInd=1:NCells
				for TrialInd=1:NTrialsVec(CellInd)
					labelStr=[labelStr,'| Cell:',int2str(CellInd),'; Trial:',int2str(TrialInd)];
				end
			end
		end
		set(hOpenAvgFile,...
			'Style','popupmenu', ...
        	'String',labelStr, ...
			'Userdata',0,...
			'Value',ActCellNo+1);
			
	elseif  strcmp(AvgFileFormat,'AppSCADS') | ...
			strcmp(AvgFileFormat,'MegBtiMsi') | ...
			strcmp(AvgFileFormat,'NeuroscanCnt') | ...
			strcmp(AvgFileFormat,'NeuroscanAvg')

		Tmp=get(hList(NListHdr+(ActFileNo-1).*50+34),'Userdata');
		if isempty(Tmp); 
			NTrials=0; 
		else
			if strcmp(AvgFileFormat,'AppSCADS') 
				NTrials=Tmp(6);
			elseif strcmp(AvgFileFormat,'MegBtiMsi') 
				NTrials=Tmp(4); %MsiRawVec(4);
			elseif strcmp(AvgFileFormat,'NeuroscanCnt')
				NsEvents=Tmp.events;
				NTrials=size(NsEvents,2);
			elseif strcmp(AvgFileFormat,'NeuroscanAvg')
				NTrials=size(Tmp.data,1);
			end
		end
		labelStr=' File                 ';
		for TrialInd=1:NTrials
			labelStr=[labelStr '| Trial:',int2str(TrialInd)];
		end
		set(hOpenAvgFile,...
			'Style','popupmenu', ...
        	'String',labelStr, ...
			'Userdata',0,...
			'Value',1);	
        if strcmp(AvgFileFormat,'AppSCADS') 
           position = get(hOpenAvgFile,'position');
           btnWid=0.8;
           uicontrol('units','normalized','position',[position(1),position(2)+position(4)/8,btnWid/4,position(4)/3.5],'String','<--','Callback','emegs2d(''AppLastTrial'')');
           uicontrol('units','normalized','position',[position(1)+btnWid/4,position(2)+position(4)/8,btnWid/4,position(4)/3.5],'String','-->','Callback','emegs2d(''AppNextTrial'')');
       end
	else
		set(hOpenAvgFile,...
       		'Style','pushbutton', ...
       	 	'String','Open Data Set', ...
		    'Userdata','0');
	end	
		
 	%=============================================================================
	%============ chZoomChanButton, chActVisSpecChanButton, chAllVisSpecChanButton
	%=============================================================================	
elseif 	strcmp(action,'chZoomChanButton') | ...
		strcmp(action,'chActVisSpecChanButton') | ...
		strcmp(action,'chAllVisSpecChanButton'),

	hList=get(hPlot2dMenuFig,'Userdata');
	Tmp=get(hList(16),'Userdata');
	SensorNames=get(hList(4),'Userdata');
	DataNChan=Tmp(1);
	SensorNChan=Tmp(2);
    if strcmp(action,'chZoomChanButton')
        labelStr='Zoom Sensor';
    else
        labelStr='Enable all';
    end
	for ChanInd=1:SensorNChan; 
		labelStr=[labelStr '| ',int2str(ChanInd),': ',SensorNames(ChanInd,:)];
	end;
	if strcmp(action,'chZoomChanButton')
		hSpec=hList(46);
	elseif strcmp(action,'chActVisSpecChanButton')
		hSpec=hList(45);
	elseif strcmp(action,'chAllVisSpecChanButton')
		hSpec=hList(47);
	end	
	set(hSpec,'String',labelStr,'Userdata',0,'value',1);


 	%=============================================================================
	%============ PrepOpenAvgFile
	%============ call:	OpenAvgFile
	%=============================================================================	
elseif strcmp(action,'PrepOpenAvgFile') | ...
	strcmp(action,'PrepOpenAvgFile1') | ...
	strcmp(action,'PrepOpenAvgFile2') | ...
	strcmp(action,'PrepOpenAvgFile3') | ...
	strcmp(action,'PrepOpenAvgFile4') | ...
    strcmp(action,'PrepOpenAvgFile5') | ...
    strcmp(action,'PrepOpenAvgFile6') | ...
	strcmp(action,'PrepOpenAvgFile1234')|...
	strcmp(action,'PrepOpenAvgFileBat'),
	 
	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
    MaxNFiles=hList(140);
    
    if ~isempty(varargin)
        ActFileNo = varargin{1};
    else
	    ActFileNo=get(hList(1),'Userdata');
    end
    
	AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
	AvgFileFormatExt=get(hList(NListHdr+(ActFileNo-1).*50+22),'String');
	AsciiFileParaVec=[0 0 129 1 0 0 0 1];
	set(hList(86),'Userdata',AsciiFileParaVec);
	if strcmp(action,'PrepOpenAvgFile')
        if ~isempty(varargin)
            emegs2d('OpenAvgFile',varargin);
        else
		    emegs2d('OpenAvgFile');
        end
		return;
	end
	if ~strcmp(action,'PrepOpenAvgFile1234') & ~strcmp(action,'PrepOpenAvgFileBat')
		set(hList(1),'Value',str2num(action(length(action))));
		emegs2d('setActFileNo');
		emegs2d('OpenAvgFile');
	elseif strcmp(action,'PrepOpenAvgFile1234')
		DataSetIndex=ActFileNo;
		ActFileNoOld=ActFileNo;
		FileMatPrev=[];
		if ActFileNo>1
			for i=1:ActFileNo-1
				FilePath=get(hList(NListHdr+(i-1).*50+4),'Userdata');
				if i==1
					FileMatPrev=char(FilePath);
				else
					FileMatPrev=char(FileMatPrev,FilePath);
				end
			end
		end
		OpenFileBatchVal=1;
		[DefFilePath]=SetDefPath(1,AvgFileFormatExt);
		[File1,Path,FilePath]=ReadFilePath([],DefFilePath,'Choose starting file:')
		if File1==0; return; end
		SetDefPath('w',Path);
		FileMat=char(FilePath);
		i=findstr(File1,'.at');
		i=i+3; %'.at'
		j=0;
        RestFileName1=[];
		while 1
			k=str2num(File1(i+j));
			if (i+j)==length(File1); break; end
            if isempty(k); j=j-1; break; end
			j=j+1;
		end
        if length(File1)>i+j
            RestFileName1=File1(i+j+1:end);
        end
		AtNumber1=str2num(File1(i:i+j));
		AtNumberVec=AtNumber1;
		D=dir(Path);
		i=0;
		NFiles=1;
		while i<size(D,1)
			i=i+1;
			File2=D(i).name;
			j=findstr(File2,'.at');
			if ~isempty(j)
				if length(File1)<j | length(File1)~=length(File2)
					k=0;
				else
					k=strcmp(File1(1:j),File2(1:j));
				end
				if k & ~strcmp(File1,File2)
					j=j+3; %'.at'
					k=0;
					while 1
						l=str2num(File2(j+k));
						if (j+k)==length(File2); break; end
                        if isempty(l); k=k-1; break; end
						k=k+1;
					end
                    if length(File2)>j+k
                        RestFileName2=File2(j+k+1:end);
                    else
                        RestFileName2=[];
                    end
                    if isempty(RestFileName1) | strcmp(RestFileName1,RestFileName2)
                        AtNumber2=str2num(File2(j:j+k));
                        if ~isempty(AtNumber2)
                            FileMat=char(FileMat,[Path,File2]);
                            NFiles=NFiles+1;
                            AtNumberVec(NFiles)=AtNumber2;
                        end
                    end
				end
			end
		end
		a=find(AtNumberVec>AtNumber1);
		b=find(AtNumberVec<AtNumber1);
		if ~isempty(a)
			AtNumberVec=AtNumberVec([1,a]);
			FileMat=FileMat([1,a],:);
			[a,b]=sort(AtNumberVec);
		elseif isempty(a) & ~isempty(b)
			AtNumberVec=AtNumberVec([1,b]);
			FileMat=FileMat([1,b],:);
			[a,b]=sort(-AtNumberVec);
		else
			b=1;
		end
		FileMat=FileMat(b,:);
		NFiles=min([MaxNFiles,NFiles]);
		FileMat=FileMat(1:NFiles,:);
		if ~isempty(FileMatPrev)
			FileMat=char(FileMatPrev,FileMat);
		end
		set(hList(126),'Value',OpenFileBatchVal,'Userdata',FileMat); %hOpenFileBatchVal
		%emegs2d('FileMatrixInfo');
		while DataSetIndex-ActFileNo+1<=NFiles
			set(hList(1),'Value',DataSetIndex);	  %ActFileNumber
			emegs2d('setActFileNo');
			emegs2d('OpenAvgFileNoPlot');
			DataSetIndex=DataSetIndex+1;
		end
		set(hList(126),'Value',0,'Userdata',[]); 	%hOpenFileBatch
		set(hList(1),'Value',ActFileNoOld);			%ActFileNumber
		emegs2d('setActFileNo');
		emegs2d('PlotData');
	elseif strcmp(action,'PrepOpenAvgFileBat')
		DataSetIndex=1;
		OpenFileBatchVal=1;
		[DefFilePath] = SetDefPath(1,AvgFileFormatExt);
		[NFiles,FileMat,NonUse,BatchFilePath]=ReadFileNames([],DefFilePath,'Choose Batch File:');
		if NFiles<1; return; end
		[BatchFile,BatchPath]=SepFilePath(BatchFilePath);
		SetDefPath(2,BatchPath);
        NFiles=min([NFiles,MaxNFiles]);
        FileMat=FileMat(1:NFiles,:);
		set(hList(126),'Value',OpenFileBatchVal,'Userdata',FileMat); %hOpenFileBatchVal
		emegs2d('FileMatrixInfo');
		if  strcmp(AvgFileFormat,'SCADS')
			while  DataSetIndex<NFiles+1
				set(hList(1),'Value',DataSetIndex);	   %ActFileNumber
				emegs2d('setActFileNo');
				emegs2d('OpenAvgFileNoPlot');
				DataSetIndex=DataSetIndex+1;
				OpenFileBatchVal=get(hList(126),'Value');
			end
			set(hList(126),'Value',0,'Userdata',[]); %hOpenFileBatch
			set(hList(1),'Value',1);	%ActFileNumber
			emegs2d('PlotData');
		elseif strcmp(AvgFileFormat,'RawEgis')	
			return;
		end
	end
    
    	%=============================================================================
	%============ App Last Trial===============================
	%=============================================================================
elseif  strcmp(action,'AppLastTrial') 
    
    
    hList=get(hPlot2dMenuFig,'Userdata');
    FileNoVec=get(hList(56),'Userdata');
   	NListHdr=get(hList(51),'Userdata');
    ActFileNo=get(hList(1),'Userdata');
    if ~isempty(varargin)
        AvgFileFormat = varargin{2};
    else
		AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
        if strcmp(AvgFileFormat,'Auto')
            emegs2d('chAutoDataFormat')
            AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
        end
    end
	AvgFileFormatExt=get(hList(NListHdr+(ActFileNo-1).*50+22),'String');
	FileNoVec=get(hList(56),'Userdata');
	hOpenAvgFile=hList(82);
    CurrentTrial = get(hOpenAvgFile,'Value');
    if CurrentTrial>2
        set(hOpenAvgFile,'Value',CurrentTrial-1);
        emegs2d('OpenAvgFile');
    end
        
    %=============================================================================
	%============ App Next Trial===============================
	%=============================================================================
elseif  strcmp(action,'AppNextTrial') 
    
     
    hList=get(hPlot2dMenuFig,'Userdata');
    FileNoVec=get(hList(56),'Userdata');
   	NListHdr=get(hList(51),'Userdata');
    ActFileNo=get(hList(1),'Userdata');
    if ~isempty(varargin)
        AvgFileFormat = varargin{2};
    else
		AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
        if strcmp(AvgFileFormat,'Auto')
            emegs2d('chAutoDataFormat')
            AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
        end
    end
	AvgFileFormatExt=get(hList(NListHdr+(ActFileNo-1).*50+22),'String');
	FileNoVec=get(hList(56),'Userdata');
	hOpenAvgFile=hList(82);
    CurrentTrial = get(hOpenAvgFile,'Value');
    String = get(hOpenAvgFile,'String');
    if CurrentTrial<size(String,1)
        set(hOpenAvgFile,'Value',CurrentTrial+1);
        emegs2d('OpenAvgFile');
    end
	%=============================================================================
	%============ Info about actual files in file matrix===============================
	%=============================================================================
elseif  strcmp(action,'FileMatrixInfo') 

	hList=get(hPlot2dMenuFig,'Userdata'); 
	FileMat=get(hList(126),'Userdata'); %hOpenFileBatchVal
	[NFiles,NonUse]=size(FileMat);
	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'); 
	pause(0.001);
	disp(FileMat)	
	%=============================================================================
	%============ OpenAvgFile: open and read data file
	%============ external functions: ReadAvgFile, ReadEGISAvgFile
	%============	ReadEGISHeader
	%============ call:	... CalcBase, setColor, setLineStyle, PlotData
	%=============================================================================	
	
elseif strcmp(action,'OpenAvgFile') | strcmp(action,'OpenAvgFileNoPlot'),

	hList=get(hPlot2dMenuFig,'Userdata');
    FileNoVec=get(hList(56),'Userdata');
    
    if isempty(FileNoVec)
        FirstLoadStatus = 1;
    else
        FirstLoadStatus = 0;
    end
    %uiwait(errordlg(num2str(FileNoVec)));
    if ~isempty(varargin)
        ActFileNo = varargin{1};
        if ActFileNo==-1
            ActFileNo=length(FileNoVec)+1;
            %uiwait(errordlg(num2str(ActFileNo)));
            set(hList(1),'Value',ActFileNo,'userdata',ActFileNo);
            emegs2d('setActFileNo');
        end 
    else
	    ActFileNo=get(hList(1),'Userdata');
    end
    
	NListHdr=get(hList(51),'Userdata');
    if ~isempty(varargin)
        AvgFileFormat = varargin{2};
        if isempty(varargin{2})
            AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
            if strcmp(AvgFileFormat,'Auto')
                emegs2d('chAutoDataFormat')
                AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
            end
        end
    else
		AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
        if strcmp(AvgFileFormat,'Auto')
            emegs2d('chAutoDataFormat')
            AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
        end
    end
	AvgFileFormatExt=get(hList(NListHdr+(ActFileNo-1).*50+22),'String');
	FileNoVec=get(hList(56),'Userdata');
	hOpenAvgFile=hList(82);
	hPlot2dChanFig=hList(93);
	set(hList(108),'Value',1);				%hOpenAvgFileStatus
	Tmp=get(hList(16),'Userdata');
	DataNChan=Tmp(1);
	SensorNChan=Tmp(2);
	Domain=get(hList(20),'Value');
	SepPathStr=get(hList(103),'Userdata');
	DefDataPath=get(hList(105),'Userdata');
	
	EegMegStatusString=get(hList(110),'String');
	OpenFileBatchVal=get(hList(126),'Value'); 

	if DefDataPath==0;
		DefDataFilePath=SetDefPath(1,AvgFileFormatExt,'Visual.at1.ar');
	else
		DefDataFilePath=[DefDataPath,AvgFileFormatExt];
	end
    [DefDataFilePath]=SwitchGrandBatch(DefDataFilePath,'Batch2Grand',1);
    %==============================================================
	if isempty(FileNoVec)
		FileNoVec=ActFileNo;
	end
	if ~any(FileNoVec==ActFileNo)
		FileNoVec(length(FileNoVec)+1)=ActFileNo;
		FileNoVec=sort(FileNoVec);
	end
	set(hList(56),'Userdata',FileNoVec);
	%======================================
	if strcmp(AvgFileFormat,'AmpWave') | strcmp(AvgFileFormat,'PhaseWave')
		
        if ~isempty(varargin)
			[WaveMat,FilePath,SizeDataMat,NDim,Version,SampRate,AvgRef,StartF0,EndF0,DeltaF0,NTap,SigmaM,EegMegStatus,NChanExtra,AmpPhaseStatus]=...
			ReadWaveletData(varargin{3},[],DefDataFilePath,['Read ',AvgFileFormat,' data (',AvgFileFormatExt,'):']);
        else
            [WaveMat,FilePath,SizeDataMat,NDim,Version,SampRate,AvgRef,StartF0,EndF0,DeltaF0,NTap,SigmaM,EegMegStatus,NChanExtra,AmpPhaseStatus]=...
			ReadWaveletData([],[],DefDataFilePath,['Read ',AvgFileFormat,' data (',AvgFileFormatExt,'):']);
            filepathcell = get(hList(117),'userdata');
            filepathcell{3}{ActFileNo}=FilePath;
            filepathcell{2}{ActFileNo}='AmpWave';
            filepathcell{1}{ActFileNo}=ActFileNo;
            set(hList(117),'Userdata',filepathcell);
        end
		if isempty(WaveMat); 
			set(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata',[]); %WaveVec
			return; 
		end
		[File,Path]=SepFilePath(FilePath);
		SetDefPath(2,Path);
		NChanTot=SizeDataMat(1);
		NChan=NChanTot-NChanExtra;
		NPoints=SizeDataMat(2);
		NFrequ=SizeDataMat(3);
		WaveVec(1)=Version;
		WaveVec(2)=NChan;
		WaveVec(3)=NPoints;
		WaveVec(4)=NFrequ;
		WaveVec(5)=SampRate;
		WaveVec(6)=AvgRef;
		WaveVec(7)=StartF0;
		WaveVec(8)=EndF0;
		WaveVec(9)=DeltaF0;
		WaveVec(10)=NTap;
		WaveVec(11)=SigmaM;
		WaveVec(12)=1; 			%StartF0IndPlot
		WaveVec(13)=NFrequ;   	%EndF0IndPlot
		if (EegMegStatus==2 & strcmp(EegMegStatusString,'EEG')) | (EegMegStatus==1 & strcmp(EegMegStatusString,'MEG'))
			emegs2d('SetEegMegStatus')
			EegMegStatusString=get(hList(110),'String');
		end
		if strcmp(EegMegStatusString,'MEG')
			WaveMat=WaveMat(1:NChan,:,:).*10.^15;
		end
		set(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata',WaveVec);
		set(hList(NListHdr+(ActFileNo-1).*50+36),'Userdata',WaveMat);
        GetFrequInterval('InitializeMenue',[StartF0:DeltaF0:EndF0],'Wavelet Frequency Interval');
		AvgMat=squeeze(mean(WaveMat,3));
		
	%======================================
	elseif strcmp(AvgFileFormat,'SCADS')
		if OpenFileBatchVal
			FileMat=get(hList(126),'Userdata');	
			[File,Path,FilePath]=GetFileNameOfMat(FileMat,ActFileNo);
		else
			FilePath=[];
		end	
        if ~isempty(varargin)
			[AvgMat,File,Path,FilePath,NTrialAvgVec,StdChanTimeMat,...
			SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra]=ReadAvgFile(varargin{3},[],DefDataFilePath);
        else
            [AvgMat,File,Path,FilePath,NTrialAvgVec,StdChanTimeMat,...
			SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra]=ReadAvgFile(FilePath,[],DefDataFilePath);
            filepathcell = get(hList(117),'userdata');
            filepathcell{3}{ActFileNo}=FilePath;
            filepathcell{2}{ActFileNo}='SCADS';
            filepathcell{1}{ActFileNo}=ActFileNo;
            set(hList(117),'Userdata',filepathcell);	
        end
        if isempty(AvgMat); return; end
		SetDefPath(2,Path);
		[NChanTot,NPoints]=size(AvgMat);
		NChan=NChanTot-NChanExtra;
		if (EegMegStatus==2 & strcmp(EegMegStatusString,'EEG')) | (EegMegStatus==1 & strcmp(EegMegStatusString,'MEG'))
			emegs2d('SetEegMegStatus')
			EegMegStatusString=get(hList(110),'String');
		end
		if strcmp(EegMegStatusString,'MEG')
			AvgMat(1:NChan,:)=AvgMat(1:NChan,:).*10.^15;
			StdChanTimeMat(1:NChan,:)=StdChanTimeMat(1:NChan,:).*10.^15;
		end
		if NChanExtra>0; 
			if isempty(hEOGFig)
				hEOGFig=figure('Units','normal','NumberTitle','off','Position',[.85 .5 .15 .2],'Name','Averaged EOG');
				if NChanExtra>2
					hEKGFig=figure('Units','normal','NumberTitle','off','Position',[.85 .75 .15 .2],'Name','Averaged EKG');
				end
			end
			EOGMat=AvgMat(NChan+1:NChan+2,:).*10.^6;	%µV	
			HEOG=EOGMat(1,:);
			HEOG=HEOG-mean(HEOG);
			MinHEOG=min(HEOG);
			MaxHEOG=max(HEOG);
			VEOG=EOGMat(2,:);		
			VEOG=VEOG-mean(VEOG);
			MinVEOG=min(VEOG);
			MaxVEOG=max(VEOG);
			if NChanExtra>2
				EKG=AvgMat(NChan+3,:).*10.^3;			%mV
				EKG=EKG-mean(EKG);
				MinEKG=min(EKG);
				MaxEKG=max(EKG);
			end
			AvgMat=AvgMat(1:NChan,:);
			TimeVec=1000./SampRate.*[0:NPoints-1];
			global hEOGFig hEKGFig
			figure(hEOGFig)
			plot(TimeVec,VEOG-mean(VEOG),'r');
			hold on
			plot(TimeVec,HEOG-mean(VEOG),'b--');
			hold off
			axis([min(TimeVec) max(TimeVec) min([MinHEOG MinVEOG]) max([MaxHEOG MaxVEOG])]);
			xlabel('Time [ms]')
			ylabel('Amplitude [µV]')
			if NChanExtra>2
				figure(hEKGFig)
				plot(TimeVec,EKG);
				axis([min(TimeVec) max(TimeVec) MinEKG MaxEKG]);
				xlabel('Time [ms]')
				ylabel('Amplitude [µV]')
			end
		end
		%======================================
	elseif strcmp(AvgFileFormat,'AppSCADS') 
		AppSCADSVec=get(hList(NListHdr+(ActFileNo-1).*50+34),'Userdata');
		CellSubjectVal=get(hOpenAvgFile,'Value'); % file + CellNo
		if CellSubjectVal==1; % File
			FilePath=[]; 
			SpecTrial=1;
			ReadHdrStatus=1;
		else
			FilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
			[File,Path]=SepFilePath(FilePath);
			SpecTrial=CellSubjectVal-1;
			ReadHdrStatus=0;
		end
		[AvgMat,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,chAvgRef,File,Path,FilePath,EegMegStatus,NChanExtra]=...
		ReadAppData(FilePath,SpecTrial,[],[],0,DefDataFilePath);
		if File==0;	set(hList(108),'Value',0);	return; end	%hOpenAvgFileStatus
		if SpecTrial==1; 
			if NChanExtra>0; 
				global hEOGFig hEKGFig
				if isempty(hEOGFig)
					hEOGFig=figure('Units','normal','NumberTitle','off','Position',[.85 .5 .15 .2],'Name',['EOG of Trial ',sprintf('%g',SpecTrial)]);
				end
				if isempty(hEKGFig)
					hEKGFig=figure('Units','normal','NumberTitle','off','Position',[.85 .75 .15 .2],'Name',['EKG of Trial ',sprintf('%g',SpecTrial)]);
				end
			end
			SetDefPath(2,Path); 
		end
		if (EegMegStatus==2 & strcmp(EegMegStatusString,'EEG')) | (EegMegStatus==1 & strcmp(EegMegStatusString,'MEG'))
			emegs2d('SetEegMegStatus')
			EegMegStatusString=get(hList(110),'String');
		end
		if strcmp(EegMegStatusString,'MEG')
			AvgMat(1:NChan,:)=AvgMat(1:NChan,:).*10.^15;		%fT
		end
		if NChanExtra>0; 
			EKGMat=AvgMat(NChan+3,:).*10.^3;					%mV
			EOGMat=AvgMat(NChan+1:NChan+2,:).*10.^6;			%µV				
			AvgMat=AvgMat(1:NChan,:);
			TimeVec=1000./SampRate.*[0:NPoints-1];
			global hEOGFig hEKGFig
			figure(hEOGFig)
			set(hEOGFig,'Name',['EOG of trial ',sprintf('%g',SpecTrial)]);
			plot(TimeVec,EOGMat');
			axis([0 333 -30 30])
			%axis([min(TimeVec) max(TimeVec) min(min(EOGMat)) max(max(EOGMat))]);
			xlabel('Time [ms]')
			ylabel('Amplitude [µV]')

			figure(hEKGFig)
			set(hEKGFig,'Name',['EKG of trial ',sprintf('%g',SpecTrial)]);
			plot(TimeVec,EKGMat');
			axis([0 333 -1 1])
			%axis([min(TimeVec) max(TimeVec) min(min(EKGMat)) max(max(EKGMat))]);
			xlabel('Time [ms]')
			ylabel('Amplitude [mV]')
			pause(.01)
		end
		AppSCADSVec(1)=Version;
		AppSCADSVec(2)=LHeader;
		AppSCADSVec(3)=ScaleBins;
		AppSCADSVec(4)=NChan;
		AppSCADSVec(5)=NPoints;
		AppSCADSVec(6)=NTrials;
		AppSCADSVec(7)=SampRate;
		AppSCADSVec(8)=chAvgRef;
		AppSCADSVec(9)=EegMegStatus;
		AppSCADSVec(10)=NChanExtra;
		
		set(hList(NListHdr+(ActFileNo-1).*50+34),'Userdata',AppSCADSVec);
		if CellSubjectVal==1; % File
			emegs2d('chOpenAvgFileButton');
		end
		NTrialAvgVec=ones(NChan,1);
		ViewCorPicStatus=get(hList(130),'Value')
		if ViewCorPicStatus
			emegs2d('setViewCorPic')
		end
	%======================================
	elseif strcmp(AvgFileFormat,'AvgEgis') | strcmp(AvgFileFormat,'GrandAvgEgis')
		EgisAvgVec=get(hList(NListHdr+(ActFileNo-1).*50+31),'Userdata');
		CellSubjectVal=get(hOpenAvgFile,'Value'); % file + CellNo
		if CellSubjectVal==1; % File
			FilePath=[]; ReadHdrStatus=1; SpecCell=1; SpecSubject=1; 
			SampRateVec=[]; NCells=[]; NSubjectsVec=[]; 
			NPointsVec=[]; NChan=[]; NTrialsVec=[]; LHdr=[]; ScaleBins=[];
		else
			FilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
			[File,Path]=SepFilePath(FilePath);
			ReadHdrStatus=0;
			SpecSubject=EgisAvgVec(2);
			NCells=EgisAvgVec(3);
			NChan=EgisAvgVec(4);
			LHdr=EgisAvgVec(5);
			ScaleBins=EgisAvgVec(6);
			SampRateVec=EgisAvgVec(7:6+NCells);
			NSubjectsVec=EgisAvgVec(7+NCells:6+2.*NCells);
			NPointsVec=EgisAvgVec(7+2.*NCells:6+3.*NCells);
			NTrialsVec=EgisAvgVec(7+3.*NCells:6+3.*NCells+sum(NSubjectsVec));
			CellSubjectVal=CellSubjectVal-1;
			SpecCell=0;
			Tmp=CellSubjectVal-1;
			while SpecCell<=NCells & CellSubjectVal>Tmp
				SpecCell=SpecCell+1;
				Tmp=sum(NSubjectsVec(1:SpecCell));
			end
			SpecSubject=CellSubjectVal-sum(NSubjectsVec(1:(SpecCell-1)));
		end
		[AvgMat,File,Path,FilePath,SampRateVec,NCells,...
		NSubjectsVec,NPointsVec,NChan,NTrialsVec,LHdr,ScaleBins,StdChanTimeMat,NTrialAvgVec]= ...
		ReadEGISAvgFile(FilePath,ReadHdrStatus,SpecCell,SpecSubject,...
		SampRateVec,NCells,NSubjectsVec,NPointsVec,NChan,NTrialsVec,LHdr,ScaleBins,DefDataFilePath);
		if File==0; 
			set(hList(108),'Value',0);						%hOpenAvgFileStatus
			return; 
		end
		if ReadHdrStatus
			if File~=0
				set(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata',FilePath);
			else
				set(hList(108),'Value',0);					%hOpenAvgFileStatus
				return;
			end
			EgisAvgVec(1)=SpecCell;
			EgisAvgVec(2)=SpecSubject;
			EgisAvgVec(3)=NCells;
			EgisAvgVec(4)=NChan;
			EgisAvgVec(5)=LHdr;
			EgisAvgVec(6)=ScaleBins;
			EgisAvgVec(7:6+NCells)=SampRateVec;
			EgisAvgVec(7+   NCells:6+2.*NCells)=NSubjectsVec;
			EgisAvgVec(7+2.*NCells:6+3.*NCells)=NPointsVec;
			EgisAvgVec(7+3.*NCells:6+3.*NCells+sum(NSubjectsVec))=NTrialsVec;
			set(hList(NListHdr+(ActFileNo-1).*50+31),'Userdata',EgisAvgVec);
			emegs2d('chOpenAvgFileButton');
		else
			EgisAvgVec(1)=SpecCell;
			EgisAvgVec(2)=SpecSubject;
			set(hList(NListHdr+(ActFileNo-1).*50+31),'Userdata',EgisAvgVec);
		end
		SampRate=SampRateVec(SpecCell);
		NPoints=NPointsVec(SpecCell);
		
	%======================================
	elseif strcmp(AvgFileFormat,'RawEgis')
        
		EgisRawVec=get(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata');
		CellTrialVal=get(hOpenAvgFile,'Value'); % file + CellNo
		if CellTrialVal==1; % File
			EgisEyeCorrBatchFileNo=get(hList(127),'Value');
			if EgisEyeCorrBatchFileNo>0
				FileMat=get(hList(127),'Userdata');
				FilePath=FileMat(EgisEyeCorrBatchFileNo,:);
				set(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata',FilePath);
			else
				FilePath=[];
			end
			ReadHdrStatus=1; SpecCell=1; SpecTrial=1;
		else
			if OpenFileBatchVal
				ActFileNoTmp=1;
				EgisRawVec=get(hList(NListHdr+(ActFileNoTmp-1).*50+32),'Userdata');
				set(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata',EgisRawVec);
			else
				ActFileNoTmp=ActFileNo;
			end
			FilePath=get(hList(NListHdr+(ActFileNoTmp-1).*50+4),'Userdata');
			[File,Path]=SepFilePath(FilePath);
			ReadHdrStatus=0;
			SpecTrial=EgisRawVec(2);
			NCells=EgisRawVec(3);
			NChan=EgisRawVec(4);
			LHdr=EgisRawVec(5);
			SampRateVec=EgisRawVec(7:6+NCells);
			NTrialsVec=EgisRawVec(7+NCells:6+2.*NCells);
			NPointsVec=EgisRawVec(7+2.*NCells:6+3.*NCells);
			ChanGainVec=EgisRawVec(10+3.*NCells+2.*NChan:9+3.*NCells+3.*NChan);	
			if ~OpenFileBatchVal
				CellTrialVal=CellTrialVal-1;
			else
				CellTrialVal=ActFileNo;
			end
			SpecCell=0;
			Tmp=CellTrialVal-1;
			while SpecCell<=NCells & CellTrialVal>Tmp
				SpecCell=SpecCell+1;
				Tmp=sum(NTrialsVec(1:SpecCell));
			end
			SpecTrial=CellTrialVal-sum(NTrialsVec(1:(SpecCell-1)));
		end
 		set(hPlot2dChanFig,'Name',['Raw EGIS data of cell ',int2str(SpecCell),' and trial '  int2str(SpecTrial),'.']);
		if ReadHdrStatus	
			RawEgisBitsRangeStatus=0		
			[RawEgisHeader,File,Path,FilePath,SampRateVec,NCells,NTrialsVec,...
			NPointsVec,NChan,LHdr,LCellHdr,BrdGain,ChanZeroVec,ChanGainVec,HdrVer,Bits,Range,LData,LSpecCellMat]=ReadEGISHeader(FilePath,[],DefDataFilePath,[],[],RawEgisBitsRangeStatus);
			if File~=0; 
				set(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata',FilePath); 
			else;
				set(hList(108),'Value',0);						%hOpenAvgFileStatus
				return; 
			end
			EgisRawVec(1)=SpecCell;
			EgisRawVec(2)=SpecTrial;
			EgisRawVec(3)=NCells;
			EgisRawVec(4)=NChan;
			EgisRawVec(5)=LHdr;
			EgisRawVec(6)=0;	%NoUse
            NCells=NCells
            SampRateVec=SampRateVec
			EgisRawVec(7:6+NCells)=SampRateVec
			EgisRawVec(7+   NCells:6+2.*NCells)=NTrialsVec;
			EgisRawVec(7+2.*NCells:6+3.*NCells)=NPointsVec;
			EgisRawVec(7+3.*NCells)=Bits;
			EgisRawVec(8+3.*NCells)=Range;
			EgisRawVec(9+3.*NCells)=BrdGain;
			EgisRawVec(10+3.*NCells:9+3.*NCells+NChan)=ChanZeroVec;
			EgisRawVec(10+3.*NCells+NChan:9+3.*NCells+2.*NChan)=ChanGainVec;
			[ChanGainVec]=CalcGainVec(ChanGainVec,Bits,Range)
			EgisRawVec(10+3.*NCells+2.*NChan:9+3.*NCells+3.*NChan)=ChanGainVec;
			set(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata',EgisRawVec);
			NTrialAvgVec=ones(NChan,1);
			emegs2d('chOpenAvgFileButton');
		else
			EgisRawVec(1)=SpecCell;
			EgisRawVec(2)=SpecTrial;
			set(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata',EgisRawVec);
		end
		fid=fopen(FilePath,'r','b');
		if SpecCell==1
			NSeek=LHdr+(SpecTrial-1).*NChan.*NPointsVec(1).*2;
		else
			NSeek=LHdr+(sum(NPointsVec(1:SpecCell-1).*NTrialsVec(1:SpecCell-1))+(SpecTrial-1).*NPointsVec(SpecCell)).*NChan.*2;
		end
		FseekStatus=fseek(fid,NSeek,-1);
		if FseekStatus==-1; error('FseekStatus error'); end
		[AvgMat,Count]=fread(fid,[NChan,NPointsVec(SpecCell)],'int16');
		if Count~=NChan.*NPointsVec(SpecCell); error('Count~=NChan.*NPointsVec(SpecCell)'); end
		for TimeInd=1:NPointsVec(SpecCell)
			%DataMat(:,TimeInd)=(DataMat(:,TimeInd)-ChanZero).*ChanGainVec; %No consideration of ChanZero
			AvgMat(:,TimeInd)=AvgMat(:,TimeInd).*ChanGainVec;
		end
		fclose(fid);
		SampRate=SampRateVec(SpecCell);
		NPoints=NPointsVec(SpecCell);
		NTrialAvgVec=ones(NChan,1);
		%========if CalcEditEgisDataFigure is open=============
		hEditEgisFig=hList(107);
		if hEditEgisFig~=0
			hTopMenu=get(hList(65),'Userdata');
			hCalcMenu=get(hTopMenu(4),'children');	
			hCalcEditEgisData=hCalcMenu(16);
			LSpecCellMat=get(hCalcEditEgisData,'Userdata');
			if ~isempty(LSpecCellMat)
				eval(['global LSpecCell',int2str(SpecCell)]);
				eval(['LSpecCell',int2str(SpecCell),'=LSpecCellMat;']);
%				WriteEGISHeader(FilePath,1,0);
			end
		end
		EtStatus=0
		if EtStatus
			global hImageFig
			if isempty(hImageFig)
				hImageFig=figure('Units','normal','NumberTitle','off','Position',[.7 .425 .275 .425]);
				axes('Position',[0 0 1 1],'Visible','off');
			else
				figure(hImageFig)
			end
			if strcmp(File(5),'R')
				ImPath='Data:IAPS:AllPics:'
				PicNoVec=ReadAscii('Paul:Data:EEG:ET:R2:ET00R2.IAPS.txt');
				ActPicNo=PicNoVec(SpecTrial);
				PicIndStr=AddZeros2CountStr(ActPicNo,3)
				ImFilePath=[ImPath,PicIndStr,'.jpg'];
				ImMat=imread(ImFilePath,'jpg');
				set(hImageFig,'Name',['Trial # ',int2str(SpecTrial),'; IAPS # ',int2str(ActPicNo)])
				
			elseif strcmp(File(5),'C')
				ImPath='Rudi:Data:EEG:ET:C1:ET00C1.txt'
				XYMat=ReadAscii(ImPath)';
				x=XYMat(SpecTrial,1);
				y=XYMat(SpecTrial,2);
				xi=x;
				yi=y;
				ImMat=zeros(640,480,3);
				ImMat(xi-4:xi+4,yi-3:yi+3,1)=ones(9,7,1);
				set(hImageFig,'Name',['Trial # ',int2str(SpecTrial),'; x=',int2str(x),'; y=',int2str(y)])
			else
				error('Unknown RCStatus')
			end
			image(ImMat); 
			axis('off');
			hold off
		end
	%======================================
	elseif strcmp(AvgFileFormat,'AsciiHeaderVec') | strcmp(AvgFileFormat,'Float32HeaderVec')
		if strcmp(AvgFileFormat,'AsciiHeaderVec')
			[File,Path]=uigetfile(DefDataFilePath,'Choose ascii header file:');
			FilePath=[Path,File];
			if isempty(find(FilePath)); 
				set(hList(108),'Value',0);						%hOpenAvgFileStatus
				return; 
			end;	
			fid=fopen(FilePath,'r','b');
			NChan=fscanf(fid,'%g',1);
			NPoints=fscanf(fid,'%g',1);
			[AvgMat,Count]=fscanf(fid,'%g',[NChan,NPoints]);
		elseif strcmp(AvgFileFormat,'Float32HeaderVec')
			[File,Path]=uigetfile(DefDataFilePath,'Choose a float32 header file:');
			FilePath=[Path,File];
			if isempty(find(FilePath)); 
				set(hList(108),'Value',0);					%hOpenAvgFileStatus
				return; 
			end;
			fid=fopen(FilePath,'r','b');
 			NChan=fread(fid,1,'float32')
 			NPoints=fread(fid,1,'float32')
			[AvgMat,Count]=fread(fid,[NChan,NPoints],'float32');
		end	
		fclose(fid);
		if Count~=NChan.*NPoints
			Message=char('Sorry,');
			Message=char(Message,'');
			Message=char(Message,'bad number of points in header ascii file.');
			hmsgbox=msgbox(Message,'Info','help'); 
			set(hList(108),'Value',0);						%hOpenAvgFileStatus
			return;
		end
	%======================================
	elseif strcmp(AvgFileFormat,'AsciiBesaVec')
		[AvgMat,TSB,DI,SB,SC,NPoints,NChan,SampRate,TrigPoint,File,Path,FilePath]=ReadAsciiBesa([],DefDataFilePath);
%  		AvgMat=AvgMat.*10^6;
		if isempty(AvgMat)
			Message=char('Sorry,');
			Message=char(Message,'');
			Message=char(Message,'bad number of points in header ascii file.');
			hmsgbox=msgbox(Message,'Info','help'); 
			set(hList(108),'Value',0);						%hOpenAvgFileStatus
			return;
		end
		TrigPointVec=get(hList(22),'Userdata');
		TrigPointVec(Domain)=TrigPoint;
		set(hList(22),'Value',TrigPoint,'Userdata',TrigPointVec,'String',sprintf('%g',TrigPoint));	
	%======================================
	elseif strcmp(AvgFileFormat,'NeuroscanAvg')
		CellTrialVal=get(hOpenAvgFile,'Value') % file + TrialNo
		global NsStruct
		if CellTrialVal==1; % File
			[File,Path]=uigetfile(DefDataFilePath,'Choose a Neuroscan .avg file:');
			if File==0; return; end
			SetDefPath('w',Path);
			FilePath=[Path,File];
			NsStruct=ReadNeuroscanStruct(FilePath);
			set(hList(NListHdr+(ActFileNo-1).*50+34),'Userdata',NsStruct);
			emegs2d('chOpenAvgFileButton');
		else
			NsStruct=get(hList(NListHdr+(ActFileNo-1).*50+34),'Userdata');
			FilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
			[File,Path]=SepFilePath(FilePath);
		end
		NsHeader=NsStruct.header;
		NsScale=NsHeader.scale;
		NChan=NsHeader.nchannels;
		NPoints=NsHeader.pnts;
		SampRate=NsHeader.rate;
		NsData=NsStruct.data;
		NsVariance=NsStruct.variance
		AvgMat=zeros(NChan,NPoints);
		StdChanTimeMat=zeros(NChan,NPoints);
		for i=1:NChan
			AvgMat(i,:)=NsData(i).samples';
			StdChanTimeMat(i,:)=NsVariance(i).samples';
		end
		MedMedRawVec=[];
		MedMedAvgVec=[];
		NTrialAvgVec=ones(NChan,1);
		AvgRef=0;
		%======================================
	elseif strcmp(AvgFileFormat,'NeuroscanCnt') 
		NPoints=get(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata');
		TrigPointVec=get(hList(22),'Userdata');
		TrigPoint=TrigPointVec(Domain);
		if isempty(NPoints); NPoints=0; end
		if NPoints==0; NPoints=100; end
		PreTrig=TrigPoint-1;
		PostTrig=NPoints-PreTrig-1;
		CellTrialVal=get(hOpenAvgFile,'Value') % file + TrialNo
		if CellTrialVal==1; % File
			ReadHdrStatus=1;
			[File,Path]=uigetfile(DefDataFilePath,'Choose a Neuroscan .cnt file:');
			if File==0; return; end
			SetDefPath('w',Path);
			FilePath=[Path,File];
			NsStruct=ReadNeuroscanStruct(FilePath);
			set(hList(NListHdr+(ActFileNo-1).*50+34),'Userdata',NsStruct);
			ActTrial=1;
			emegs2d('chOpenAvgFileButton');
		else
			ReadHdrStatus=0;
			NsStruct=get(hList(NListHdr+(ActFileNo-1).*50+34),'Userdata');
			FilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
			[File,Path]=SepFilePath(FilePath);
			ActTrial=CellTrialVal-1;
		end
		NsHeader=NsStruct.header;
		SampRate=NsHeader.rate;
		AvgMat=ReadNeuroscanTrial(FilePath,ActTrial,NsStruct,PreTrig,PostTrig);
		[NChan,NPoints]=size(AvgMat);
		MedMedRawVec=[];
		MedMedAvgVec=[];
		NTrialAvgVec=ones(NChan,1);
		StdChanTimeMat=zeros(NChan,NPoints);
		AvgRef=0;
	%======================================
	elseif strcmp(AvgFileFormat,'AsciiMEG')
		[File,Path]=uigetfile(DefDataFilePath,'Choose an ascii MEG file:');
		FilePath=[Path,File];
		if isempty(find(FilePath));
			set(hList(108),'Value',0);						%hOpenAvgFileStatus
			return; 
		end;	
		fid=fopen(FilePath,'r','b');
		[AvgVec,Count]=fscanf(fid,'%g');
		fclose(fid);
		if SensorNChan==0 | ActFileNo==1	%Reads new sensor configuration 
			set(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata',FilePath);
			emegs2d('chDefECfg');
			Tmp=get(hList(16),'Userdata');
			DataNChan=Tmp(1);
			SensorNChan=Tmp(2);
		end
		NPoints=Count./SensorNChan;
		if (round(NPoints))-NPoints~=0
			Message=char('Sorry,');
			Message=char(Message,'');
			Message=char(Message,'bad number of points in header ascii file.');
			hmsgbox=msgbox(Message,'Info','help'); 
			set(hList(108),'Value',0);						%hOpenAvgFileStatus
			return;
		end
		AvgMat=reshape(AvgVec,NPoints,SensorNChan)';
	%======================================
	elseif strcmp(AvgFileFormat,'MegBtiMsi')

		AvgRef=0;
		MsiRawVec=get(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata')  %compare with EgisRawVec
		TrialVal=get(hOpenAvgFile,'Value');
		if TrialVal==1; % File
			EyeCorrBatchFileNo=get(hList(127),'Value');
			if EyeCorrBatchFileNo>0
				FileMat=get(hList(127),'Userdata');
				FilePath=FileMat(EyeCorrBatchFileNo,:);
				set(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata',FilePath);
			else
				FilePath=[];
			end
			ReadSetStatus=1; 
            SpecTrial=1;
		else
			if OpenFileBatchVal
				ActFileNoTmp=1;
				MsiRawVec=get(hList(NListHdr+(ActFileNoTmp-1).*50+32),'Userdata');
				set(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata',MsiRawVec);
			else
				ActFileNoTmp=ActFileNo;
			end
			FilePath=get(hList(NListHdr+(ActFileNoTmp-1).*50+4),'Userdata');
			[File,Path]=SepFilePath(FilePath);
			ReadSetStatus=0;
			SpecTrial=TrialVal-1
			NTotChan=MsiRawVec(2)
			NPoints=MsiRawVec(3)
			NTrials=MsiRawVec(4)
			NMegChan=MsiRawVec(5)
			NChan=NMegChan
			NEegChan=MsiRawVec(6)
			SampRate=MsiRawVec(7)
			SampPeriod=MsiRawVec(8)
			BaseMs=MsiRawVec(9)
			Duration=MsiRawVec(10)
			NBit=MsiRawVec(11)
            NExternChan=MsiRawVec(12)
% 			if OpenFileBatchVal==0
% 				TrialVal=TrialVal-1;
% 			else
% 				TrialVal=ActFileNo;
% 			end
% 			SpecCell=0;
% 			Tmp=CellTrialVal-1;
% 			while SpecCell<=NCells & CellTrialVal>Tmp
% 				SpecCell=SpecCell+1;
% 				Tmp=sum(NTrialsVec(1:SpecCell));
% 			end
% 			SpecTrial=CellTrialVal-sum(NTrialsVec(1:(SpecCell-1)));
		end
		if ReadSetStatus
			[DefFilePath]=SetDefPath(1,AvgFileFormatExt);
			[File,Path]=uigetfile(DefFilePath,'Please choose a *msi* file:');
			if File==0; return; end
			if ~strcmp(Path(length(Path)),filesep); Path=[Path,filesep]; end
			FilePath=[Path,File];
			SetDefPath(2,FilePath);
			SetFilePath=[FilePath,'.set'];
			[SetFilePath,MsiParaVec,MEGSensorPosMat,EEGSensorPosMat,MEGSensorNameVec,EEGSensorNameVec,MEGSensorIndexVec,EEGSensorIndexVec,MsiFormat]=ReadMsiSet(SetFilePath);
			if File~=0; 
				set(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata',SetFilePath); 
			else;
				set(hList(108),'Value',0);						%hOpenAvgFileStatus
				return; 
			end
 			NTotChan=MsiParaVec(1);
			NPoints=MsiParaVec(2);
			NTrials=MsiParaVec(3);
			NMegChan=MsiParaVec(4); NChan=NMegChan;
			NEegChan=MsiParaVec(5);
			SampRate=MsiParaVec(6);
			SampPeriod=MsiParaVec(7);
			BaseMs=MsiParaVec(8);
			Duration=MsiParaVec(9);
			NBit=MsiParaVec(10);
			NExternChan=MsiParaVec(11);
            
            MsiRawVec=zeros(20+NTotChan,1);
			MsiRawVec(1)=SpecTrial;			
			MsiRawVec(2:12)=MsiParaVec;
            
            MEegSensorIndexVec=zeros(NTotChan,1);
			MEegSensorIndexVec(1:NMegChan)=MEGSensorIndexVec;
			MEegSensorIndexVec(NMegChan+1:NMegChan+NEegChan)=EEGSensorIndexVec;
			MsiRawVec(21:20+NTotChan)=MEegSensorIndexVec;

			set(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata',MsiRawVec);
            MEGSensorPosMat
			set(hList(111),'Userdata',MEGSensorPosMat);	%hSensorPosNormMat
			set(hList(4),'Userdata',MEGSensorNameVec);
			[SetFile,SetPath]=SepFilePath(SetFilePath);
			set(hList(2),'Userdata',[SetPath,sprintf('%g',NChan),'.pmg']);
			TrigPoint=1+round(-1.*BaseMs./(1000./SampRate));
			TrigPointVec=get(hList(22),'Userdata');
			TrigPointVec(Domain)=TrigPoint;
			set(hList(22),'Value',TrigPoint,'Userdata',TrigPointVec,'String',sprintf('%g',TrigPoint));	
			emegs2d('chOpenAvgFileButton');
		else
			MsiRawVec(1)=SpecTrial;
			set(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata',MsiRawVec);
		end
		if NBit==2
			MsiFormat='int16';
		elseif NBit==4
			MsiFormat='float32';
		else
			error('Unknown MsiFormat'); 
		end
		%=========Read SpecTrial from Msi file============================
		fid=fopen(FilePath,'r','b');
		NSeek=(SpecTrial-1).*NTotChan.*NPoints.*NBit;
		FseekStatus=fseek(fid,NSeek,-1)
		if FseekStatus==-1; error('FseekStatus error'); end
		MEegSensorIndexVec=MsiRawVec(21:20+NTotChan);
		[AvgMat,Count]=fread(fid,[NTotChan,NPoints],MsiFormat);
		if Count~=NTotChan.*NPoints; error('Count~=NChan.*NPointsVec(SpecCell)'); end
		fclose(fid);		
        AvgMat=AvgMat(MEegSensorIndexVec,:);
		%============================================================
		if NEegChan>0; 
			global hEOGFig hEKGFig
			%hEOGFig=[]; hEKGFig=[];
			if isempty(hEOGFig)
				hEOGFig=figure('Units','normal','NumberTitle','off','Position',[.7 .00 .275 .425],'Name',['EOG of trial: ',int2str(SpecTrial)]);
				if NEegChan>2 
					hEKGFig=figure('Units','normal','NumberTitle','off','Position',[.7 .50 .275 .425],'Name',['EKG of trial: ',int2str(SpecTrial)]);
				end
            else
                set(hEOGFig,'Name',['EOG of trial: ',int2str(SpecTrial)])
                if NEegChan>2 
                    set(hEKGFig,'Name',['EKG of trial: ',int2str(SpecTrial)])
			    end
            end
			EOGMat=AvgMat(NMegChan+1:NMegChan+2,:).*10.^6;	%µV	
			HEOG=EOGMat(1,:);
			HEOG=HEOG-mean(HEOG);
			MinHEOG=min(HEOG);
			MaxHEOG=max(HEOG);
			VEOG=EOGMat(2,:);		
			VEOG=VEOG-mean(VEOG);
			MinVEOG=min(VEOG);
			MaxVEOG=max(VEOG);
			if NEegChan>2; 
				EKG=AvgMat(NMegChan+3,:).*10.^3;			%mV
				EKG=EKG-mean(EKG);
				MinEKG=min(EKG);
				MaxEKG=max(EKG);
			end
			AvgMat=AvgMat(1:NMegChan,:);
			TimeVec=1000./SampRate.*[0:NPoints-1];
			global hEOGFig hEKGFig
			figure(hEOGFig)
			plot(TimeVec,VEOG-mean(VEOG),'r');
			hold on
			plot(TimeVec,HEOG-mean(VEOG),'b--');
			hold off
			axis([min(TimeVec) max(TimeVec) min([MinHEOG MinVEOG]) max([MaxHEOG MaxVEOG])]);
			xlabel('Time [ms]')
			ylabel('Amplitude [µV]')
			if NEegChan>2; 
				figure(hEKGFig)
				plot(TimeVec,EKG);
				axis([min(TimeVec) max(TimeVec) MinEKG MaxEKG]);
				xlabel('Time [ms]')
				ylabel('Amplitude [µV]')
			end
		end
		AvgMat=AvgMat(1:NMegChan,:).*10.^15;	%fT
	%======================================
	elseif strcmp(AvgFileFormat,'AsciiVec') | strcmp(AvgFileFormat,'Float32Vec')
		AsciiFileParaVec=get(hList(86),'Userdata');
		hAsciiFileImportFig=AsciiFileParaVec(6);
		if hAsciiFileImportFig==0
			if strcmp(AvgFileFormat,'AsciiVec') 
				[File,Path]=uigetfile(DefDataFilePath,'Choose an ascii file:');
			elseif strcmp(AvgFileFormat,'Float32Vec')
				[File,Path]=uigetfile(DefDataFilePath,'Choose a float32 file:');
			end
			FilePath=[Path,File];
			if isempty(find(FilePath)); 
				set(hList(108),'Value',0);						%hOpenAvgFileStatus
				return; 
			end;	
			fid=fopen(FilePath,'r','b');
			if strcmp(AvgFileFormat,'AsciiVec') 
				AvgVec=fscanf(fid,'%g');
			elseif strcmp(AvgFileFormat,'Float32Vec')
				AvgVec=fread(fid,inf,'float32');
			end
			fclose(fid);
			set(hList(87),'Userdata',AvgVec);
			set(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata',FilePath);
			[NAsciiFilePoints,NoUse]=size(AvgVec);
			AsciiFileParaVec(1)=NAsciiFilePoints;
			if SensorNChan==0; DefSensorNChan=129; else; DefSensorNChan=SensorNChan; end
			AsciiFileParaVec(3)=DefSensorNChan;
			set(hList(86),'Userdata',AsciiFileParaVec);
			emegs2d('InitAsciiFileImportFig');
			AsciiFileParaVec=get(hList(86),'Userdata');		
		else
			AvgVec=get(hList(87),'Userdata');
			FilePath=get(hAsciiFileImportFig,'Userdata');
			[File,Path]=SepFilePath(FilePath);
		end
		NAsciiFilePoints=AsciiFileParaVec(1);
		NAsciiFileCalcPoints=AsciiFileParaVec(2);
		NAsciiFileChan=AsciiFileParaVec(3);
		NAsciiFileCond=AsciiFileParaVec(4);
		AsciiFileActCond=AsciiFileParaVec(5);
		
		hNAsciiFileCalcPoints=AsciiFileParaVec(7);
		AsciiFileCCTFormat=AsciiFileParaVec(8);

		if NAsciiFileChan.*NAsciiFileCond~=0
			NAsciiFileCalcPoints=NAsciiFilePoints./(NAsciiFileChan.*NAsciiFileCond);
			if round(NAsciiFileCalcPoints)==NAsciiFileCalcPoints
				NAsciiFileCalcPointsString=['Number of points in condition: ',int2str(NAsciiFileCalcPoints)];
				set(hNAsciiFileCalcPoints,'String',NAsciiFileCalcPointsString);
			else
				NAsciiFileCalcPointsString=[ int2str(NAsciiFileCalcPoints),' Bad NChan or NCond !'];
				set(hNAsciiFileCalcPoints,'String',NAsciiFileCalcPointsString);
			end
		end
		if NAsciiFileChan.*NAsciiFileCond.*NAsciiFileCalcPoints~=NAsciiFilePoints | AsciiFileActCond<=0 | AsciiFileActCond>NAsciiFileCond
			set(hList(108),'Value',0);						%hOpenAvgFileStatus
			return;
		end
		if AsciiFileCCTFormat==1;     %Cond-Chan-Time 
			AvgMat=reshape(AvgVec,NAsciiFileCalcPoints,NAsciiFileCond.*NAsciiFileChan)';
			AvgMat=AvgMat((AsciiFileActCond-1).*NAsciiFileChan+1:AsciiFileActCond.*NAsciiFileChan,:);
		elseif AsciiFileCCTFormat==2; %Cond-Time-Chan
			AvgMat=reshape(AvgVec,NAsciiFileChan,NAsciiFileCond.*NAsciiFileCalcPoints);
			AvgMat=AvgMat(:,(AsciiFileActCond-1).*NAsciiFileCalcPoints+1:AsciiFileActCond.*NAsciiFileCalcPoints);
		elseif AsciiFileCCTFormat==3; %Chan-Cond-Time
			AvgMat=reshape(AvgVec,NAsciiFileCalcPoints,NAsciiFileCond.*NAsciiFileChan)';
			AvgMat=AvgMat(AsciiFileActCond:NAsciiFileCond:NAsciiFileCond.*NAsciiFileChan,:);
		elseif AsciiFileCCTFormat==4; %Chan-Time-Cond
			AvgMat=reshape(AvgVec,NAsciiFileCond,NAsciiFileCalcPoints.*NAsciiFileChan);
			AvgMat=(reshape(AvgMat(AsciiFileActCond,:),NAsciiFileCalcPoints,NAsciiFileChan))';
		elseif AsciiFileCCTFormat==5; %Time-Cond-Chan
			AvgMat=reshape(AvgVec,NAsciiFileChan,NAsciiFileCalcPoints.*NAsciiFileCond);
			AvgMat=AvgMat(:,AsciiFileActCond:NAsciiFileCond:NAsciiFileCalcPoints.*NAsciiFileCond);
		elseif AsciiFileCCTFormat==6; %Time-Chan-Cond
			AvgMat=reshape(AvgVec,NAsciiFileCond,NAsciiFileCalcPoints.*NAsciiFileChan);
			AvgMat=(reshape(AvgMat(AsciiFileActCond,:),NAsciiFileChan,NAsciiFileCalcPoints));
		end		
	end
	if isempty(AvgMat);	
		set(hList(108),'Value',0);						%hOpenAvgFileStatus
		return; 
	end
	[NChan,NPoints]=size(AvgMat);	
	DataNChan=NChan;
	if SensorNChan~=0 & DataNChan~=SensorNChan
		Message=char('Sorry, ');
		Message=char(Message,'');
		Message=char(Message,'Bad number of channels');
		Message=char(Message,'in data set or sensor configuration.');
		Message=char(Message,'');
		Message=char(Message,['Number of channels in data set :                   ',int2str(DataNChan)]);
		Message=char(Message,['Number of channels in sensor configuration: ',int2str(SensorNChan)]);
		hmsgbox=msgbox(Message,'Info !','help'); 
		set(hList(108),'Value',0);						%hOpenAvgFileStatus
		return;
	end
	SetDefPath(2,Path);
	if  strcmp(AvgFileFormat,'AsciiHeaderVec') | ...
		strcmp(AvgFileFormat,'AsciiVec') | ...
		strcmp(AvgFileFormat,'Float32HeaderVec') | ...
		strcmp(AvgFileFormat,'Float32Vec') | ...
		strcmp(AvgFileFormat,'AsciiMEG')
		
		NTrialAvgVec=ones(NChan,1);
		StdChanTimeMat=zeros(NChan,NPoints);
		if strcmp(AvgFileFormat,'AsciiMEG')
			SampRate=500;
		else
			SampRate=get(hList(60),'Userdata');
		end
		if SampRate==0
			Message=char('Since the sampling rate is not given:');
			Message=char(Message,'');
			Message=char(Message,'Sampling rate will be set to 100 ')
			hmsgbox=msgbox(Message,'Info','help'); 
			SampRate=100;
			pause(2)
		end
		AvgRef=1;
		MedMedRawVec=[];
		MedMedAvgVec=[];
	elseif strcmp(AvgFileFormat,'AsciiBesaVec')
		NTrialAvgVec=ones(NChan,1);
		StdChanTimeMat=zeros(NChan,NPoints);
		AvgRef=1;
		MedMedRawVec=[];
		MedMedAvgVec=[];
	elseif strcmp(AvgFileFormat,'AvgEgis')  | ...
		strcmp(AvgFileFormat,'GrandAvgEgis') | ...
		strcmp(AvgFileFormat,'RawEgis') | ...
		strcmp(AvgFileFormat,'AppSCADS'),
		
		if ~strcmp(AvgFileFormat,'AvgEgis') 
			StdChanTimeMat=zeros(NChan,NPoints);
		end
		AvgRef=1;
		MedMedRawVec=[];
		MedMedAvgVec=[];
	elseif strcmp(AvgFileFormat,'AmpWave') | ...
		strcmp(AvgFileFormat,'PhaseWave') | ...
		strcmp(AvgFileFormat,'MegBtiMsi'),
		
		NTrialAvgVec=ones(NChan,1);
		StdChanTimeMat=zeros(NChan,NPoints);
		MedMedRawVec=[];
		MedMedAvgVec=[];
	end
    if mean(mean(AvgMat))>10^14;
        AvgMat=AvgMat.*10^-14;
    end
	set(hList(16),'Userdata',[DataNChan,SensorNChan]);
	set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',AvgMat);
	set(hList(NListHdr+(ActFileNo-1).*50+24),'Userdata',AvgMat);
	set(hList(NListHdr+(ActFileNo-1).*50+2),'Userdata',DataNChan);
	set(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata',NPoints);
	set(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata',FilePath);
	set(hList(NListHdr+(ActFileNo-1).*50+5),'Userdata',NTrialAvgVec);
	set(hList(NListHdr+(ActFileNo-1).*50+6),'Userdata',StdChanTimeMat);
	set(hList(NListHdr+(ActFileNo-1).*50+7),'Userdata',SampRate);
	SampRateString = sprintf('%g',SampRate);
	set(hList(60),'Userdata',SampRate,'String',SampRateString);
	NPointsString = sprintf('%g',NPoints);
	set(hList(50),'Userdata',NPoints,'String',NPointsString);
	set(hList(NListHdr+(ActFileNo-1).*50+8),'Userdata',AvgRef);
	set(hList(NListHdr+(ActFileNo-1).*50+9),'Userdata',MedMedRawVec);
	set(hList(NListHdr+(ActFileNo-1).*50+10),'Userdata',MedMedAvgVec);
	set(hList(105),'Userdata',Path);	%DefDataPath
	if (length(FileNoVec)==1 & ~strcmp(AvgFileFormat,'AvgEgis')  & ~strcmp(AvgFileFormat,'GrandAvgEgis') & ~strcmp(AvgFileFormat,'RawEgis') & ~strcmp(AvgFileFormat,'AppSCADS') & ~strcmp(AvgFileFormat,'NeuroscanCnt')); 
		Tmp1=1; 
	else
		Tmp1=0; 
	end
	if ((strcmp(AvgFileFormat,'AvgEgis') | strcmp(AvgFileFormat,'GrandAvgEgis') | (strcmp(AvgFileFormat,'RawEgis')  | (strcmp(AvgFileFormat,'AppSCADS')) | (strcmp(AvgFileFormat,'NeuroscanCnt')))) & ReadHdrStatus)
		Tmp2=1; 
	else
		Tmp2=0; 
	end
	if Tmp1 | Tmp2
		emegs2d('SetFirstVal'); 
		emegs2d('CalcFirst');
		if SensorNChan==0
			DefFileNoVec=get(hList(90),'Userdata');
			% ------ default sensor configuration file ----------
			if ~isempty(DefFileNoVec) 
				DefECfgFilePath = get(hList(91),'Userdata');
				SepPathStr=get(hList(103),'Userdata');
				index_p = findstr(DefECfgFilePath,'.');
				index_dp = findstr(DefECfgFilePath,SepPathStr);
				DefNChan=(DefECfgFilePath(index_dp(length(index_dp))+1:(index_p(1)-1)));
				if (findstr(DefNChan,num2str(NChan)) & ~isempty(DefFileNoVec))
					set(hList(2),'Userdata',DefECfgFilePath);
					emegs2d('ReadECfg');	
				else
					Message=char('Sorry,');
					Message=char(Message,'');
					Message=char(Message,'incorrect default sensor configuration file. ')
					Message=char(Message,'Searching another!');
					hmsgbox=msgbox(Message,'Info','help'); 
					emegs2d('chDefECfg');
				end
			%-------------------------------------------------------	
			else	
				emegs2d('chDefECfg');
			end
			%-------------------------------------------------------
		end	
		EPosSpher=get(hList(3),'Userdata');
		if isempty(EPosSpher); EPosSpher=0; end
		if EPosSpher==0
			emegs2d('chECfgFileAutoAxes');
			emegs2d('ReadECfg');	
		end
        if Domain == 8
             AxesSizeStatus = get(hList(118),'userdata');
             if AxesSizeStatus == 0
                 emegs2d('Calc2dTimeAxes');
             end
        else
     	    emegs2d('Calc2dTimeAxes');
        end
            
                
		hTopMenu=get(hList(65),'Userdata');
		hFileMenu=get(hTopMenu(1),'children');
		hDefFileMenu=get(hFileMenu(1),'children');
		hInfoFileMenu=get(hDefFileMenu(1),'children');
		hAutoDefFileMenu=hDefFileMenu(4);
		AutoViewDefaultFileStatus=get(hAutoDefFileMenu,'Userdata');
		if AutoViewDefaultFileStatus
			emegs2d('ReadViewDefaultFile')
		end
	end
	if Domain~=8
        emegs2d('CalcBase');
    end
	emegs2d('setColor');
	emegs2d('setLineStyle');
	%--------- set menu index -----------
	emegs2d('SetZeroLineColorIndex');
	emegs2d('SetTriggerLineColorIndex');
	emegs2d('SetCursorLineColorIndex');
	emegs2d('SetZeroLineStyleIndex');
	emegs2d('SetTriggerLineStyleIndex');
	emegs2d('SetCursorLineStyleIndex');
	emegs2d('SetDefXTickVal');
	%------------------------------------
	hFileInfoTextVec=get(hList(17),'Userdata');
	hFileInfoText=hFileInfoTextVec(ActFileNo);
	VisibleStatus=get(hFileInfoText,'Visible');
	if strcmp(VisibleStatus,'on'); emegs2d('DispFileNamesVisible'); end
	if strcmp(AvgFileFormat,'AsciiBesaVec') | ...
		strcmp(AvgFileFormat,'MegBtiMsi'); 
		emegs2d('setTrigPoint'); 
	end
	%--------- set enable value ----------
	if length(FileNoVec)==1
		set(hList(49),'value',1);	
	elseif length(FileNoVec)==2
		set(hList(49),'value',4);
	elseif length(FileNoVec)==4
		set(hList(49),'value',5);
	else
		set(hList(49),'value',7);	
	end;		
	emegs2d('EnableOnOff');	
	%--------------------------------------
 	if Domain == 1
		if ~strcmp(action,'OpenAvgFileNoPlot')
 			emegs2d('PlotData');
		end
    elseif Domain == 8
 		emegs2d('PlotData');
    else
 		emegs2d('setDomain');
 	end;
	%--------------------------------------
	if Domain ~= 1 & Domain ~=8
		emegs2d('setDomain');
	end;
   	set(hList(108),'Value',0);						%hOpenAvgFileStatus
   	emegs2d('setActAllVisible')
   	emegs2d('SetActFileNoLabelString')
   if FirstLoadStatus	
       set(hList(142),'Enable','on');
   end
   
   
  	%======================================================================
  	%=======LastViewDef
	%=============================================================================

elseif strcmp(action,'LastViewDef'),
    plot2dpathutilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2ddefviewdef.udef');
    emegs2d('ReadViewDefaultFile',plot2dpathutilpath);


  	%=============================================================================
	%============ InitAsciiFileImportFig
	%============ external functions: ReadAvgFile, ReadEGISAvgFile
	%============					ReadEGISHeader
	%============ call:	... CalcBase, setColor, setLineStyle, PlotData
	%======================================================================
elseif strcmp(action,'SetActFileNoLabelString'),

	hList=get(hPlot2dMenuFig,'Userdata'); 
	ActFileNo=get(hList(1),'Value');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NFileNoVec=length(FileNoVec);
	LabelString=[];
	MaxNFiles=hList(140);
	for FileIndex=1:MaxNFiles
		LabelString=[LabelString,'Data set: ',int2str(FileIndex),'; '];
		if ~isempty(FileNoVec)
			if any(FileNoVec==FileIndex)
				FilePath=get(hList(NListHdr+(FileIndex-1).*50+4),'Userdata');
				[File,Path]=SepFilePath(FilePath);
				LabelString=[LabelString,File];
			else
				LabelString=[LabelString,'not used'];
			end
		else
			LabelString=[LabelString,'not used'];
		end
		if FileIndex<MaxNFiles
			LabelString=[LabelString '|'];
		end
	end
	set(hList(1),'String',LabelString);
	
elseif strcmp(action,'InitAsciiFileImportFig'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	FilePath=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+4),'Userdata');
	[File]=SepFilePath(FilePath);
 	if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
  		FigPosVec=[0,.75,.25,.5];
   	elseif strcmp(computer,'PCWIN') | strcmp(computer,'SOL2') | strcmp(computer,'LNX86') | strcmp(computer,'GLNX86')
   		FigPosVec=[0.01 0.55 0.3 0.4];   
   	end;
   
	% Information for all buttons (and menus)
   	labelColor=[0.8 0.8 0.8];
	yInitPos=0.90;
 	menutop=0.6;
   	btnTop = 0.6;
    	top=0.75;
    	left=0.05;
    	btnWid=0.5;
    	btnHt=0.15;
    	textHeight = 0.05;
    	textWidth = 0.1;
    	% Spacing between the button and the next command's label
    	spacing=0;
	
	AsciiFileParaVec=get(hList(86),'Userdata');
	NAsciiFilePoints=AsciiFileParaVec(1);
	NAsciiFileCalcPoints=AsciiFileParaVec(2);
	NAsciiFileChan=AsciiFileParaVec(3);
	NAsciiFileCond=AsciiFileParaVec(4);
	AsciiFileActCond=AsciiFileParaVec(5);
	
	AsciiFileParaVec(1)=NAsciiFilePoints;
	AvgVec=zeros(NAsciiFilePoints,1);
	
	hAsciiFileImportFig=figure('Units','normal','NumberTitle','off','Position',FigPosVec,...
	'Color',[0 0 0],'Name','Import Ascii File Information','Userdata',FilePath);
	AsciiFileParaVec(6)=hAsciiFileImportFig;

	hAsciiFileImportAxes=axes('Position',[0 0 1 1],'Visible','off');

	FileString=['File: ' File];
	text('FontSize',[12],'Position',[0.05 0.9],'Color',[1 1 1],'String',FileString);
	NAsciiFilePointsString=['Number of points in file: ',int2str(NAsciiFilePoints)];
	text('FontSize',[12],'Position',[0.05 0.8],'Color',[1 1 1],'String',NAsciiFilePointsString);
	NAsciiFileCalcPointsString=['Number of points in condition: ',int2str(NAsciiFileCalcPoints)];
	hNAsciiFileCalcPoints=text('FontSize',[12],'Position',[0.05 0.7],'Color',[1 1 1],'String',NAsciiFileCalcPointsString);
	AsciiFileParaVec(7)=hNAsciiFileCalcPoints;
	
	%===================================
   	% Condition-Channel-Time Format
	AsciiFileCCTFormat=AsciiFileParaVec(8);

   	btnNumber=1;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt btnWid btnHt];
	
	labelStr='Cond-Chan-Time|Cond-Time-Chan|Chan-Cond-Time|Chan-Time-Cond|Time-Cond-Chan|Time-Chan-Cond';
	callbackStr = 'emegs2d(''setAsciiImportFileCCTFormat'')';
    
	hAsciiFileCCTFormat=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
	'Userdata',1,...
	'value',1,...
        'Callback',callbackStr);

	%===================================
   	% Number of channels
   	btnNumber=2;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos 2.*btnWid./3 btnHt./2];
    
	h = uicontrol( ...
      		'Style','text', ...
     	  	'Units','normalized', ...
		'Position',btnPos, ...
        	'Horiz','left', ...
        	'Foreground','black', ...
        	'String','Number of sensors:');

  	btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt./2];
	callbackStr = 'emegs2d(''setAsciiImportFileNChan'')';
    
	hAsciiNChan = uicontrol( ...
        	'Style','edit', ...
        	'Units','normalized', ...
		'Position',btnPos, ...
        	'Horiz','center', ...
        	'Background','white', ...
        	'Foreground','black', ...
        	'String',int2str(NAsciiFileChan),'Userdata',NAsciiFileChan, ...
        	'callback',callbackStr);

	%===================================
   	% Number of conditions
    
	btnNumber=3;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
  	btnPos=[left yPos 2.*btnWid./3 btnHt./2];
    
	h = uicontrol( ...
       		'Style','text', ...
      	  	'Units','normalized', ...
			'Position',btnPos, ...
        	'Horiz','left', ...
        	'Foreground','black', ...
        	'String','Number of conditions:');

   	btnPos=[left+2.*btnWid./3 yPos btnWid./3 1.*btnHt./2];
	callbackStr = 'emegs2d(''setAsciiImportFileNCond'')';
    
	hAsciiNCond = uicontrol( ...
        	'Style','edit', ...
        	'Units','normalized', ...
			'Position',btnPos, ...
        	'Horiz','center', ...
        	'Background','white', ...
        	'Foreground','black', ...
        	'String',int2str(NAsciiFileCond),'Userdata',NAsciiFileCond, ...
        	'callback',callbackStr);
		
	%===================================
    	% Number of actual condition
    
	btnNumber=4;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos 2.*btnWid./3 btnHt./2];
    
	h = uicontrol( ...
       		'Style','text', ...
      	  	'Units','normalized', ...
		'Position',btnPos, ...
        	'Horiz','left', ...
        	'Foreground','black', ...
        	'String','Actual condition:');

   	btnPos=[left+2.*btnWid./3 yPos btnWid./3 1.*btnHt./2];
	callbackStr = 'emegs2d(''setAsciiImportFileActCond'')';
    
	hAsciiActCond = uicontrol( ...
        	'Style','edit', ...
        	'Units','normalized', ...
		'Position',btnPos, ...
        	'Horiz','center', ...
        	'Background','white', ...
        	'Foreground','black', ...
        	'String',int2str(AsciiFileActCond),'Userdata',AsciiFileActCond, ...
        	'callback',callbackStr);
	
	
	set(hList(86),'Userdata',AsciiFileParaVec);
	
	%=============================================================================
	%=============================================================================	
	
elseif strcmp(action,'setAsciiImportFileCCTFormat'),

	v = get(gco,'value');
	hList=get(hPlot2dMenuFig,'Userdata');
	AsciiFileParaVec=get(hList(86),'Userdata')
	AsciiFileParaVec(8)=v;
	set(hList(86),'Userdata',AsciiFileParaVec);
	
	%=============================================================================
	%=============================================================================	
elseif strcmp(action,'setAsciiImportFileNChan'),
	 
	v = get(gco,'Userdata');
	hList=get(hPlot2dMenuFig,'Userdata');
	AsciiFileParaVec=get(hList(86),'Userdata')
	NAsciiFilePoints=AsciiFileParaVec(1)
	str = get(gco,'String');
	ind = find(abs(str)<32);
	str(ind) = 32*ones(size(ind));
   	str = str';	
	vv = eval(['[' str(:)' ']'],'-1')'
	vv=round(vv)
	if vv>NAsciiFilePoints | length(vv)~=1
		vv = v;
	end
   	str = sprintf('%g',vv);
	set(gco,'Userdata',vv,'String',str);
	AsciiFileParaVec(3)=vv
	set(hList(86),'Userdata',AsciiFileParaVec);
	emegs2d('chAvgFileAsciiVec');	
	emegs2d('OpenAvgFile');	

	%=============================================================================
	%=============================================================================	
elseif strcmp(action,'setAsciiImportFileNCond'),

	v = get(gco,'Userdata');
	hList=get(hPlot2dMenuFig,'Userdata');
	AsciiFileParaVec=get(hList(86),'Userdata');
	NAsciiFilePoints=AsciiFileParaVec(1);
	str = get(gco,'String');
	ind = find(abs(str)<32);
	str(ind) = 32*ones(size(ind));
	str = str';	
	vv = eval(['[' str(:)' ']'],'-1')';
	vv=round(vv);
	if vv>=NAsciiFilePoints | length(vv)~=1
		vv = v;
	end
	str = sprintf('%g',vv);
	set(gco,'Userdata',vv,'String',str);
	AsciiFileParaVec(4)=vv;
	set(hList(86),'Userdata',AsciiFileParaVec);
	emegs2d('chAvgFileAsciiVec');	
	emegs2d('OpenAvgFile');	
	
	%=============================================================================
	%=============================================================================	
elseif strcmp(action,'setAsciiImportFileActCond'),
	 
	v = get(gco,'Userdata');
	hList=get(hPlot2dMenuFig,'Userdata');
	AsciiFileParaVec=get(hList(86),'Userdata');
	NAsciiFileCond=AsciiFileParaVec(4);
	str = get(gco,'String');
	ind = find(abs(str)<32);
	str(ind) = 32*ones(size(ind));
	str = str';	
	vv = eval(['[' str(:)' ']'],'-1')';
	vv=round(vv);
	if vv>NAsciiFileCond | length(vv)~=1
		vv = v;
	end
	str = sprintf('%g',vv);
	set(gco,'Userdata',vv,'String',str);
	AsciiFileParaVec(5)=vv;
	set(hList(86),'Userdata',AsciiFileParaVec);
	emegs2d('chAvgFileAsciiVec');	
	emegs2d('OpenAvgFile');
	%=============================================================================
	%=============================================================================	
elseif 	strcmp(action,'CalcSymAbs') | ...
		strcmp(action,'CalcSymSign') | ...	
		strcmp(action,'CalcSymLat') | ...
		strcmp(action,'CalcSymZNormLat') | ...
		strcmp(action,'CalcSymZNormAbsLat') | ...
		strcmp(action,'CalcSymSetPairs') | ...
		strcmp(action,'CalcSymGetPairs')

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	hTopMenu=get(hList(65),'Userdata');
	hCalcMenu=get(hTopMenu(4),'children');
	hCalcSymMenu=get(hCalcMenu(3),'children');
	
	NUsedFiles=length(FileNoVec);		
	
	if 	strcmp(action,'CalcSymSetPairs')
		EPosSpher=get(hList(3),'Userdata');
		ENames=get(hList(4),'Userdata');
		NChan=get(hList(102),'Userdata');
		[NoUse,NoUse,NoUse,NoUse,CountVec]=ChooseChanInd(NChan,1,[],[],[],[],EPosSpher,ENames,[],[],3,10,0,2);
		SymPairs=reshape(CountVec,2,length(CountVec)./2)';
		set(hList(84),'Userdata',SymPairs);
		Save2Bem(SymPairs,[],[],1,'Matrix','Ascii',[],0,1,1,'DefaultPairs');
		set(hCalcSymMenu(3:7),'Enable','on');
		return;
	elseif 	strcmp(action,'CalcSymGetPairs')
		[SymPairs] = ReadBem([],1,'Matrix')
		set(hList(84),'Userdata',SymPairs);
		set(hCalcSymMenu(3:7),'Enable','on');
		return;
	else
		SymPairs=get(hList(84),'Userdata');
		if isempty(SymPairs); return; end
	end
	if	strcmp(action,'CalcSymAbs') 
		SymNormFlag='abs';			SymNormFlagString='(Abs.)';
		UserDataInfoLabel='Symmetry abs.';
	elseif	strcmp(action,'CalcSymSign') 
		SymNormFlag='sign';			SymNormFlagString='(Sign.)';
		UserDataInfoLabel='Symmetry sign.';
	elseif	strcmp(action,'CalcSymLat') 
		SymNormFlag='lat';  		SymNormFlagString='(Lat.)';
		UserDataInfoLabel='Symmetry lat.';
	elseif	strcmp(action,'CalcSymZNormLat') 
		SymNormFlag='znormlat'; 	SymNormFlagString='(Z-Norm. Lat.)';
		UserDataInfoLabel='Symmetry Z-norm lat.';
	elseif	strcmp(action,'CalcSymZNormAbsLat') 
		SymNormFlag='znormabslat'; 	SymNormFlagString='(Abs. Z-Norm. Lat.)';
		UserDataInfoLabel='Symmetry abs. Z-norm lat.';
	end

	kActAxes=get(hList(27),'Userdata');
	NActChan=length(kActAxes);
	MinAmp=get(hList(52),'Value');
	MaxAmp=get(hList(53),'Value');
	MinPoint=get(hList(54),'Value');
	MSMinPointString=get(hList(54),'String');	%
	MaxPoint=get(hList(55),'Value');
	MSMaxPointString=get(hList(55),'String');	%
	NChan=get(hList(NListHdr+2),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	SampRate=get(hList(60),'Userdata');	
	TrigPoint=get(hList(22),'Value');
	CursorPoint=get(hList(23),'Value');	
	BGColor=get(hList(93),'Color');
	
	hTopMenu=get(hList(65),'Userdata');
	hExportMenu=get(hTopMenu(3),'children');	
	hExportUserData=get(hExportMenu(1),'children'); 
	hUserDataInfo=get(hExportUserData(1),'children');
	
	MainMatlabVersion=get(hList(100),'Userdata');

	hSymFig=figure('Units','normal','NumberTitle','off','Position',[0,.75,.5,.25],'Name',['Symmetry: ' SymNormFlagString]);
	hSymAxes=axes('Units','normal','Position',[.1 .15 .85 .7],'Color',BGColor,'Box','on','XLim',[MinPoint MaxPoint]);
	
	if TrigPoint>MinPoint & TrigPoint<MaxPoint	% trigger time between minimum and maximum time
		if MainMatlabVersion<5
			set(hSymAxes,'xtick',[TrigPoint MaxPoint],'XTickLabel',[0 0 round((MaxPoint-TrigPoint).*1000./SampRate)]);	
		else
			set(hSymAxes,'xtick',[TrigPoint MaxPoint],'XTickLabel',[0 round((MaxPoint-TrigPoint).*1000./SampRate)]);	
		end
	else		% trigger time smaller than minimum time
		if MainMatlabVersion<5
			set(hSymAxes,'xtick',[MinPoint MaxPoint],'XTickLabel',[0 round((MinPoint-TrigPoint).*1000./SampRate) round((MaxPoint-TrigPoint).*1000./SampRate)]);	
		else
			set(hSymAxes,'xtick',[MinPoint MaxPoint],'XTickLabel',[round((MinPoint-TrigPoint).*1000./SampRate) round((MaxPoint-TrigPoint).*1000./SampRate)]);	
		end
	end
	xlabel('Time [ms]');ylabel('Symmetry Index [ ]');
	
	% zero line
	hZeroLine=get(hList(8),'Userdata');
	ZeroLineColor=get(hZeroLine(1),'Color')
	ZeroLineStyle=get(hZeroLine(1),'LineStyle')
	% trigger line
	hTriggerLine=get(hList(9),'Userdata');
	TriggerLineColor=get(hTriggerLine(1),'Color');
	TriggerLineStyle=get(hTriggerLine(1),'LineStyle');
	hSymTrigLine=line('XData',[TrigPoint TrigPoint],'YData',[-100 100],'Color',TriggerLineColor,'LineStyle',TriggerLineStyle);
	%hList(#)=hSymTrigLine;
	% cursor line
	hCursorLine=get(hList(10),'Userdata');
	CursorLineColor=get(hCursorLine(1),'Color');
	CursorLineStyle=get(hCursorLine(1),'LineStyle');
	hSymCursorLine=line('XData',[CursorPoint CursorPoint],'YData',[-100 100],'Color',CursorLineColor,'LineStyle',CursorLineStyle);
	%hList(#)=hSymCursorLine;
	MinSymVec=10.^6;
	MaxSymVec=-10.^6;
	
	hSymPairsFig=figure('Units','normal','NumberTitle','off','Position',[0 0 NUsedFiles*.15 .75],'Name',['Symmetry Pairs: ' SymNormFlagString]);
	hSymPairsAxes=axes('Units','Normal','Position',[.01 0.01 .98 .98],'Box','off');
	SymMat=zeros(NUsedFiles,NPoints);
	for FileIndex=1:NUsedFiles
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		hDataVec=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+25),'Userdata');
		VisibleVec=ones(NActChan,1);
		for ChanInd=1:NActChan
			VisibleStatus=get(hDataVec(ChanInd),'Visible');
			if strcmp(VisibleStatus,'off')
				VisibleVec(ChanInd)=0;
			end
		end
		VisibleOnVec=find(VisibleVec==1);
		[NoUse,NSymPairs]=size(SymPairs);
		GoodSymPairsIndex=0;
		GoodSymPairsVec=[];
		for SymPairIndex=1:NSymPairs
			Tmp1=find(kActAxes(VisibleOnVec)==SymPairs(1,SymPairIndex));
			Tmp2=find(kActAxes(VisibleOnVec)==SymPairs(2,SymPairIndex));
			if ~isempty(Tmp1) & ~isempty(Tmp2)
				GoodSymPairsIndex=GoodSymPairsIndex+1;
				GoodSymPairsVec(GoodSymPairsIndex)=SymPairIndex;
			end
		end
		SymPairsTmp=SymPairs(:,GoodSymPairsVec);
		[NoUse,NSymPairsTmp]=size(SymPairsTmp);
		[SymVec] = CalcSymmetry(CalcAvgMat,SymPairsTmp,SymNormFlag);
		MinSymVec=min([MinSymVec min(SymVec)]);
		MaxSymVec=max([MaxSymVec max(SymVec)]);
		ActColor=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+16),'Userdata');
		ActLineStyle=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+17),'Userdata');
		axes(hSymAxes);
		line('XData',[1:NPoints],'YData',SymVec,'Color',ActColor,'LineStyle',ActLineStyle)
		if	~strcmp(action,'CalcSymNormAbsLat') 
			line('XData',[1 NPoints],'YData',[0 0],'Color',ZeroLineColor,'LineStyle',ZeroLineStyle)
		end
		if FileIndex==NUsedFiles; set(hSymAxes,'YLim',[1.1.*MinSymVec 1.1.*MaxSymVec]); end
		for SymPairInd=1:NSymPairsTmp
			XTmp=0.1+(1./NUsedFiles).*(FileIndex-1);
			YTmp=1-SymPairInd./NSymPairs;
			axes(hSymPairsAxes);
			text('Units','Normal','Position',[XTmp YTmp],'String',int2str(SymPairsTmp(1,SymPairInd)))
			text('Units','Normal','Position',[XTmp+.1 YTmp],'String','<--->','Color',ActColor)
			text('Units','Normal','Position',[XTmp+.25 YTmp],'String',int2str(SymPairsTmp(2,SymPairInd)))
		end
		axis('off')
		SymMat(FileIndex,:)=SymVec';
	end
	set(hUserDataInfo,'Label',UserDataInfoLabel);
	set(hList(94),'Userdata',SymMat);	%User data	
	set(hExportUserData,'Enable','on');	%Export User data enable on
	%=============================================================================
	%=============================================================================	
elseif 	strcmp(action,'CalcGrandMean')
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
	
	if strcmp(AvgFileFormat,'AsciiBesaVec') 
		filterSpec='*.avr';
	elseif strcmp(AvgFileFormat,'AsciiHeaderVec') 
		filterSpec='*';
	elseif strcmp(AvgFileFormat,'SCADS') 
		filterSpec='*.at*';
	else
		Message=char('Sorry,');
		Message=char(Message,'');
		Message=char(Message,'this application is right now just available');
		Message=char(Message,'using "AsciiBesaVec", "AsciiHeaderVec" or');
		Message=char(Message,'"SCADS" data file format.');
		hmsgbox=msgbox(Message,'Info','help'); 
		return;
	end
	
	[GrandMeanData,GrandMeanFileMat]=CalcGrandMean([],AvgFileFormat,filterSpec);
	set(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+1),'Userdata',GrandMeanData);
	ActFilePath=[pwd, 'GrandMean'];
	set(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata',ActFilePath);

	emegs2d('CalcFirst');
	emegs2d('CalcBase');
	emegs2d('setColor');
	emegs2d('setLineStyle');
	emegs2d('PlotData');
   	emegs2d('SetActFileNoLabelString')
	hFileInfoTextVec=get(hList(17),'Userdata');
	hFileInfoText=hFileInfoTextVec(ActFileNo);
	VisibleStatus=get(hFileInfoText,'Visible');
	if strcmp(VisibleStatus,'on'); emegs2d('DispFileNamesVisible'); end

	%=============================================================================
	%=============================================================================	
elseif	strcmp(action,'ResetActFile') | ...
		strcmp(action,'ResetAllFiles');
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NFiles=length(FileNoVec);
	NListHdr=get(hList(51),'Userdata');
	
	if strcmp(action,'ResetActFile')
		FileNoVec=FileNoVec(ActFileNo);
	end
	for FileIndex=1:length(FileNoVec)
		OrigAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+24),'Userdata');
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',OrigAvgMat);
	end
    set(hList(57),'Value',0); %CalcBaseStatus
	emegs2d('PlotData');	
    emegs2d('AdjustAmp');

    %=============================================================================
	%=============================================================================	
elseif 	strcmp(action,'CalcEditEgisData') | ...
		strcmp(action,'CalcViewEgisData') | ...
		strcmp(action,'CalcEyeCorrEgisData') | ...
		strcmp(action,'CalcEyeCorrEgisDataBatch'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	hTopMenu=get(hList(65),'Userdata');
	hCalcMenu=get(hTopMenu(4),'children');	
	hCalcEditEgisData=hCalcMenu(16);
	FileNoVec=get(hList(56),'Userdata');
	NFiles=length(FileNoVec);
	NListHdr=get(hList(51),'Userdata');
	
	EditEgisFigHandleVec=zeros(60,1);

	FilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
	AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');

	if strcmp(action,'CalcEyeCorrEgisDataBatch'),
		FileMat=get(hList(127),'Userdata'); 
		if isempty(FileMat)
			if ~strcmp(AvgFileFormat,'RawEgis')
				emegs2d('chRawFileEgis'); 
				AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
			end
			emegs2d('PrepOpenAvgFileBat'); 
			FileMat=get(hList(126),'Userdata'); 
			set(hList(127),'Userdata',FileMat,'Value',1); 
		end
		[NFiles,NonUse]=size(FileMat);
		FilePath=FileMat(1,:);
		emegs2d('OpenAvgFile'); 
	else
		set(hList(127),'Value',0); %EgisEyeCorrBatchStatus
	end
	if ~strcmp(AvgFileFormat,'RawEgis') | isempty(FilePath)
		emegs2d('chRawFileEgis'); 
		emegs2d('OpenAvgFile'); 
		FilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
		AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
	end
	[File,Path]=SepFilePath(FilePath);
	[RawEgisHeader,File,Path,FilePath,SampRateVec,NCells,NTrialsVec,...
	NPointsVec,NChan,LHdr,LCellHdr,BrdGain,ChanZeroVec,ChanGainVec,HdrVer,Bits,Range,LData,LSpecCellMat]=ReadEGISHeader(FilePath,[],[],1);
	set(hCalcEditEgisData,'Userdata',LSpecCellMat);
	%====================================
    % The figure
	if strcmp(action,'CalcEyeCorrEgisData') | ...
		strcmp(action,'CalcEyeCorrEgisDataBatch')
		if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
      			EditEgisFigPosVec=[.6 0 .4 .5];
   		elseif strcmp(computer,'PCWIN') 
      			EditEgisFigPosVec=[.61 .01 .4 .5];
      		elseif strcmp(computer,'SOL2') | strcmp(computer,'LNX86') | strcmp(computer,'GLNX86')
      			EditEgisFigPosVec=[.6224 .01 .4 .5];		
		end;
		NYButton=6;
	else
		if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
			EditEgisFigPosVec=[.6 0 .4 .33];
		elseif strcmp(computer,'PCWIN') 
			EditEgisFigPosVec=[.61 .01 .4 .33];
		elseif strcmp(computer,'SOL2') | strcmp(computer,'LNX86') | strcmp(computer,'GLNX86')
			EditEgisFigPosVec=[.6224 .01 .4 .33];		
		end;
		NYButton=3;
	end
	
	EditEgisFigString=['EGIS File: ',File,'; Cell: 1; Trial: 1'];
   	hEditEgisFig=figure('Units','normal','Position',EditEgisFigPosVec, ...
	'Name',EditEgisFigString,'Color',[.99 .99 .99], ...
	'NumberTitle','off');
	EditEgisFigHandleVec(1)=hEditEgisFig;
	%====================================
	% The Console frame
	FrameColor=[0 0.1 0.99];
   	hConsolFrame=uicontrol( ...
	'Style','frame', ...
	'Units','normalized', ...
	'Position',[0.02 0.02 .96 .96], ...
	'BackgroundColor',FrameColor);
	
	EditEgisFigHandleVec(2)=hConsolFrame;
	%====================================
	% The Axes
	hEditEgisAxes=axes('Position',[0 0 1 1],'Visible','off');
	EditEgisFigHandleVec(3)=hEditEgisAxes;
	%==============================================================
	%================= Good, bad, ??? trial==========================
	%==============================================================
	
    DistLeft=0.05;
	DistRight=DistLeft;
	DistTop=0.05;
	DistBottom=0.05;
	DistXButton=DistLeft;
	DistYButton=DistLeft;
	NXButton=3; 
	btnWid=(1-(DistLeft+(DistXButton+NXButton).*DistXButton))./NXButton;
	btnHt=(1-DistBottom-(DistTop+(DistYButton+NYButton).*DistYButton))./NYButton;
	
	%==============================================================
		
	if strcmp(action,'CalcEyeCorrEgisData') | ...
		strcmp(action,'CalcEyeCorrEgisDataBatch')
		
		XButton=1; YButton=6;
		NButton31=2;
		Button31=1;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		hSetBlinkLimText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String','Lim [µV]',...
		'Enable','on');
		EditEgisFigHandleVec(41)=hSetBlinkLimText;
		
		
		btnPos=[btnWid./2+DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		callbackStr = 'emegs2d(''SetBlinkLim'')';
		hSetBlinkLim = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String','100',...
		'Value',100,...
		'callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(42)=hSetBlinkLim;
				
		XButton=2; YButton=6;
		NButton31=2;
		Button31=1;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		hSetBlinkCorrThresFacText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String','Thres [%]',...
		'Enable','on');
		EditEgisFigHandleVec(49)=hSetBlinkCorrThresFacText;
		
		btnPos=[btnWid./2+DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		callbackStr = 'emegs2d(''SetBlinkCorrThresFac'')';
		hSetBlinkCorrThresFac = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String','33',...
		'Value',33,...
		'callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(50)=hSetBlinkCorrThresFac;

		XButton=2; YButton=6;
		NButton31=2;
		Button31=2;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		hSetPlotPolyFitChanStepText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String','Step',...
		'Enable','on');
		EditEgisFigHandleVec(51)=hSetPlotPolyFitChanStepText;

		PlotPccChanStep=max([1,floor(NChan./10)]);
		btnPos=[btnWid./2+DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		callbackStr = 'emegs2d(''SetPlotPolyFitChanStep'')';
		hPlotPolyFitChanStep = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String',int2str(PlotPccChanStep),...
		'Value',PlotPccChanStep,...
		'callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(52)=hPlotPolyFitChanStep;
		
		XButton=3; YButton=6;
		NButton31=2;
		Button31=2;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		hSetPreBlinkIntText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String','Pre  [ms]',...
		'Enable','on');
		EditEgisFigHandleVec(43)=hSetPreBlinkIntText;

		btnPos=[btnWid./2+DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		callbackStr = 'emegs2d(''SetPreBlinkInt'')';
		hSetPreBlinkInt = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String','200',...
		'Value',0,...			%set later in line emegs2d('SetPreBlinkInt')
		'callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(44)=hSetPreBlinkInt;

		Button31=1;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		hSetPostBlinkIntText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String','Post [ms]',...
		'Enable','on');
		EditEgisFigHandleVec(45)=hSetPostBlinkIntText;

		btnPos=[btnWid./2+DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		callbackStr = 'emegs2d(''SetPostBlinkInt'')';
		hSetPostBlinkInt = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String','300',...
		'Value',0,...		%set later in line emegs2d('SetPostBlinkInt')
		'callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(46)=hSetPostBlinkInt;
		
		XButton=1; YButton=5;
		NButton31=2;
		Button31=2;
		
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
		callbackStr = 'emegs2d(''SetLeftRightVCorStatus'')';
		hSetLeftRightVCorStatus=uicontrol( ...
		'Style','popupmenu', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','Vert. EOG Left|Vert. EOG Right|Vert. EOG Both', ...
		'Value',1, ...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(39)=hSetLeftRightVCorStatus;
		
		XButton=1; YButton=5;
		NButton31=2;
		Button31=1;
		
 		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
		callbackStr = 'emegs2d(''SetPlotPauseStatus'')';
 		hPlotPauseStatus=uicontrol( ...
 		'Style','radiobutton',...
 		'Units','normalized',...
 		'Position',btnPos,...
		'Value',0,...
		'Userdata',zeros(1,NFiles),...
		'Callback',callbackStr,...
		'FontSize', [10],...
		'BackgroundColor',FrameColor,...
		'FontWeight','bold',...
		'String','Plot Pause',...
 		'Horiz','center',...
 		'Enable','on');	
		EditEgisFigHandleVec(40)=hPlotPauseStatus;
		
		XButton=1; YButton=4;
		NButton31=3;

		Button31=3;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
 		callbackStr = 'emegs2d(''SetSaveCorrStatus'')';
		hSetSaveCorrStatus=uicontrol( ...
		'Style','radiobutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'HorizontalAlignment','center',...
		'String','Save Corr.', ...
		'FontSize', [10], ...
		'BackgroundColor',FrameColor,...
		'FontWeight','bold',...
		'Value',1,...
		'Userdata',ones(1,NFiles),...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(4)=hSetSaveCorrStatus;

		Button31=2;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
 		callbackStr = 'emegs2d(''SetSaveEyeStatus'')';
		hSetSaveEyeStatus=uicontrol( ...
		'Style','radiobutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'HorizontalAlignment','center',...
		'String','Save Eye', ...
		'FontSize', [10], ...
		'BackgroundColor',FrameColor,...
		'FontWeight','bold',...
		'Value',1,...
		'Userdata',ones(1,NFiles),...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(5)=hSetSaveEyeStatus;
		
		Button31=1;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
 		callbackStr = 'emegs2d(''SetSavePccStatus'')';
		hSetSavePccStatus=uicontrol( ...
		'Style','radiobutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'HorizontalAlignment','center',...
		'String','Save Pcc', ...
		'FontSize', [10], ...
		'BackgroundColor',FrameColor,...
		'FontWeight','bold',...
		'Value',1,...
		'Userdata',ones(1,NFiles),...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(6)=hSetSavePccStatus;	
		%==============================================================
		
		XButton=2; YButton=4;
		NButton31=3;
		
		Button31=3;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
 		callbackStr = 'emegs2d(''SetPlotBlinkStatus'')';
		hSetPlotBlinkStatus=uicontrol( ...
		'Style','radiobutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'HorizontalAlignment','center',...
		'String','Plot Blink', ...
		'FontSize', [10], ...
		'BackgroundColor',FrameColor,...
		'FontWeight','bold',...
		'Value',0,...
		'Userdata',zeros(1,NFiles),...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(7)=hSetPlotBlinkStatus;
		
		Button31=2;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
 		callbackStr = 'emegs2d(''SetPlotPolyFitStatus'')';
		hSetPlotPolyFitStatus=uicontrol( ...
		'Style','radiobutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'HorizontalAlignment','center',...
		'String','Plot Polyfit', ...
		'FontSize', [10], ...
		'BackgroundColor',FrameColor,...
		'FontWeight','bold',...
		'Value',0,...
		'Userdata',zeros(1,NFiles),...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(8)=hSetPlotPolyFitStatus;
		
		Button31=1;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
 		callbackStr = 'emegs2d(''SetPlotAvgEOGStatus'')';
		hSetPlotAvgEOGStatus=uicontrol( ...
		'Style','radiobutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'HorizontalAlignment','center',...
		'String','Plot Avg. EOG', ...
		'FontSize', [10], ...
		'BackgroundColor',FrameColor,...
		'FontWeight','bold',...
		'Value',0,...
		'Userdata',zeros(1,NFiles),...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(9)=hSetPlotAvgEOGStatus;
		%==============================================================
		
		XButton=3; YButton=4;
		NButton31=3;
		
		Button31=3;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
 		callbackStr = 'emegs2d(''SetPlotCorr2Status'')';
		hSetPlotCorr2Status=uicontrol( ...
		'Style','radiobutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'HorizontalAlignment','center',...
		'String','Plot Corr. 2', ...
		'FontSize', [10], ...
		'BackgroundColor',FrameColor,...
		'FontWeight','bold',...
		'Value',0,...
		'Userdata',zeros(1,NFiles),...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(10)=hSetPlotCorr2Status;
		
		Button31=2;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
 		callbackStr = 'emegs2d(''SetPlotAvgCorrStatus'')';
		hSetPlotAvgCorrStatus=uicontrol( ...
		'Style','radiobutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'HorizontalAlignment','center',...
		'String','Plot Avg. Corr.', ...
		'FontSize', [10], ...
		'BackgroundColor',FrameColor,...
		'FontWeight','bold',...
		'Value',0,...
		'Userdata',zeros(1,NFiles),...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(11)=hSetPlotAvgCorrStatus;
		
		Button31=1;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
 		callbackStr = 'emegs2d(''SetCorAvgCellStatus'')';
		hSetCorAvgCellStatus=uicontrol( ...
		'Style','radiobutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'HorizontalAlignment','center',...
		'String','Plot Avg. Cell', ...
		'FontSize', [10], ...
		'BackgroundColor',FrameColor,...
		'FontWeight','bold',...
		'Value',0,...
		'Userdata',zeros(1,NFiles),...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(12)=hSetCorAvgCellStatus;
		
		%==============================================================
		labelStr=[];
		for ChanInd=1:NChan
			labelStr=[labelStr,int2str(ChanInd),'|'];
		end
		%==============================================================
		XButton=2; YButton=5;
		NButton31=2;
		
		Button31=3;
		labelPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
		
		String=char('  Horizontal EOG');
		String=char(String,'Left         Right');
   		hSetHorLeftRightEOGChanText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',labelPos, ...
		'Horiz','center', ...
		'String',String, ...
		'Interruptible','off', ...
		'BackgroundColor',FrameColor,...
		'ForegroundColor',[0 0 0],...
		'FontWeight','Bold',...
		'Enable','on');
		EditEgisFigHandleVec(13)=hSetHorLeftRightEOGChanText;
		
		Button31=1;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];
		if NChan==128 | NChan==129
			Value=128;
        elseif NChan==256 | NChan==257
			Value=251; 
		else
			Value=1;
		end
		callbackStr = 'emegs2d(''SetHorLeftEOGChan'')';
		hSetHorLeftEOGChan=uicontrol( ...
		'Style','popupmenu', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String',labelStr, ...
		'Value',Value, ...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(14)=hSetHorLeftEOGChan;
		
		btnPos=[btnWid./2+DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		if NChan==128 | NChan==129
			Value=125;
        elseif NChan==256 | NChan==257
			Value=227; 
		else
			Value=1;
		end
		callbackStr = 'emegs2d(''SetHorRightEOGChan'')';
		hSetHorRightEOGChan=uicontrol( ...
		'Style','popupmenu', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String',labelStr, ...
		'Value',Value, ...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(15)=hSetHorRightEOGChan;
		
		%==============================================================
		XButton=3; YButton=5;
		NButton31=2;
		
		Button31=3;
		labelPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
		
		String=char('  Vertical EOG');
		String=char(String,'Left        Right');
		
   		hSetVertLeftRightEOGChanText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',labelPos, ...
		'Horiz','center', ...
		'String',String, ...
		'Interruptible','off', ...
		'BackGroundColor',FrameColor,...
		'ForeGroundColor',[0 0 0],...
		'FontWeight','Bold',...
		'Enable','on');
		EditEgisFigHandleVec(16)=hSetVertLeftRightEOGChanText;
		
		Button31=1;
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];
		if NChan==128 | NChan==129
			Value=127;
        elseif NChan==256 | NChan==257
            Value=242; 
		else
			Value=1;
		end
		callbackStr = 'emegs2d(''SetVertLeftBotEOGChan'')';
		hSetVertLeftBotEOGChan=uicontrol( ...
		'Style','popupmenu', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String',labelStr, ...
		'Value',Value, ...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(17)=hSetVertLeftBotEOGChan;
		
		btnPos=[btnWid./2+DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		if NChan==128 | NChan==129
			Value=126;
        elseif NChan==256 | NChan==257
            Value=241; 
		else
			Value=1;
		end
		callbackStr = 'emegs2d(''SetVertRightBotEOGChan'')';
		hSetVertRightBotEOGChan=uicontrol( ...
		'Style','popupmenu', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String',labelStr, ...
		'Value',Value, ...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(18)=hSetVertRightBotEOGChan;
		
		%==============================================================		
		Button31=2;
		
		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		if NChan==128 | NChan==129
			Value=26;
        elseif NChan==256 | NChan==257
            Value=36; 
		else
			Value=1;
		end
		callbackStr = 'emegs2d(''SetVertLeftTopEOGChan'')';
		hSetVertLeftTopEOGChan=uicontrol( ...
		'Style','popupmenu', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String',labelStr, ...
		'Value',Value, ...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(19)=hSetVertLeftTopEOGChan;
		
		btnPos=[btnWid./2+DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid./2 btnHt./NButton31];	
		if NChan==128 | NChan==129
			Value=8;
        elseif NChan==256 | NChan==257
            Value=18; 
		else
			Value=1;
		end
		callbackStr = 'emegs2d(''SetVertRightTopEOGChan'')';
		hSetVertRightTopEOGChan=uicontrol( ...
		'Style','popupmenu', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String',labelStr, ...
		'Value',Value, ...
		'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(20)=hSetVertRightTopEOGChan;	
	end
	
	%===========================================
    
    XButton=3; YButton=1;
    btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt) btnWid./2 btnHt];	
    callbackStr = 'emegs2d(''CalcEditEgisDataNextFile'')';
    hCalcEditEgisDataNextFile=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','>>>', ...
        'FontSize', 24, ...
        'BackgroundColor',[1 1 1],...
        'FontWeight','bold',...
        'Userdata','0', ...
        'Callback',callbackStr,...
        'Enable','on');
    EditEgisFigHandleVec(21)=hCalcEditEgisDataNextFile;
    
    %===========================================
    btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid)+btnWid./2 DistBottom+(YButton-1)*(DistYButton+btnHt) btnWid./2 btnHt];	
    callbackStr = 'emegs2d(''CalcEditEgisDataLastFile'')';
    hCalcEditEgisDataLastFile=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','<<<', ...
        'FontSize', 24, ...
        'BackgroundColor',[1 1 1],...
        'FontWeight','bold',...
        'Userdata','0', ...
        'Callback',callbackStr,...
        'Enable','on');
	EditEgisFigHandleVec(22)=hCalcEditEgisDataLastFile;

	%===========================================
	XButton=2; YButton=1;
   	btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt) btnWid./2 btnHt];	
	callbackStr = 'emegs2d(''CalcEditEgisDataNextCell'')';
	hCalcEditEgisDataNextCell=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','>>', ...
	'FontSize', 24, ...
	'BackgroundColor',[1 1 1],...
	'FontWeight','bold',...
	'Userdata','0', ...
        'Callback',callbackStr,...
	'Enable','on');
	EditEgisFigHandleVec(23)=hCalcEditEgisDataNextCell;

	%===========================================
   	btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid)+btnWid./2 DistBottom+(YButton-1)*(DistYButton+btnHt) btnWid./2 btnHt];	
	callbackStr = 'emegs2d(''CalcEditEgisDataLastCell'')';
	hCalcEditEgisDataLastCell=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','<<', ...
	'FontSize', 24, ...
	'BackgroundColor',[1 1 1],...
	'FontWeight','bold',...
	'Userdata','0', ...
        'Callback',callbackStr,...
	'Enable','on');
	EditEgisFigHandleVec(24)=hCalcEditEgisDataLastCell;

	%===========================================
	XButton=1; YButton=2;
   	btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt) btnWid btnHt];	
	if strcmp(action,'CalcEditEgisData') | strcmp(action,'CalcViewEgisData')
		callbackStr = 'emegs2d(''CalcEditEgisDataGivenStatus'')';
		String='Given';
		Userdata='0';
		FontSize=16;
		Enable='off';
		BackgroundColor=[1 1 1];
		ForegroundColor=[0 0 0];
	elseif strcmp(action,'CalcEyeCorrEgisData') |  strcmp(action,'CalcEyeCorrEgisDataBatch')
		callbackStr = 'emegs2d(''SearchBlinkCorrEgisData'')';
		String='Search Blink';
		Userdata=[];
		FontSize=12;
		Enable='on';
		BackgroundColor=[0 0 1];
		ForegroundColor=[1 1 1];
	end
	hCalcEditEgisDataGivenStatus=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',String, ...
	'FontSize',FontSize, ...
	'BackgroundColor',BackgroundColor,...
	'ForegroundColor',ForegroundColor,...
	'FontWeight','bold',...
	'Userdata',Userdata, ...
        'Callback',callbackStr,...
	'Enable',Enable);
	EditEgisFigHandleVec(25)=hCalcEditEgisDataGivenStatus;

	%===========================================
	XButton=2; YButton=2;
   	btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt) btnWid btnHt];	
	if strcmp(action,'CalcEditEgisData') | strcmp(action,'CalcViewEgisData')
		callbackStr = 'emegs2d(''CalcEditEgisDataDefaultStatus'')';
		String='Default';
		Userdata='0';
		FontSize=16;
		Enable='off';
	elseif strcmp(action,'CalcEyeCorrEgisData') | strcmp(action,'CalcEyeCorrEgisDataBatch')
		callbackStr = 'emegs2d(''SetBlinkIntCorrEgisData'')';
		String='Set Blink Int.';
		Userdata=[];
		FontSize=12;
		Enable='on';
	end
	
	hCalcEditEgisDataDefaultStatus=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',String, ...
	'FontSize',FontSize, ...
	'BackgroundColor',[1 1 1],...
	'FontWeight','bold',...
	'Userdata','0', ...
        'Callback',callbackStr,...
	'Enable',Enable);
	EditEgisFigHandleVec(26)=hCalcEditEgisDataDefaultStatus;

	%===========================================
	%===========================================
	XButton=1; YButton=3;
   	btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt) btnWid btnHt];	
	if strcmp(action,'CalcEditEgisData') | strcmp(action,'CalcViewEgisData')
		callbackStr = 'emegs2d(''CalcEditEgisDataGoodTrial'')';
		String='Good Trial';
		Userdata='0';
		FontSize=16;
	elseif strcmp(action,'CalcEyeCorrEgisData') | strcmp(action,'CalcEyeCorrEgisDataBatch')
		callbackStr = 'emegs2d(''SetBlinkCorrEgisData'')';
		String='Set Blink';
		Userdata=[];
		FontSize=12;
	end
	hCalcEditEgisDataGoodTrial=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',String, ...
	'FontSize',FontSize, ...
	'FontWeight','bold',...
	'BackgroundColor',[0 .5 0],...
	'Userdata',Userdata, ...
        'Callback',callbackStr,...
	'Enable','on');
	if strcmp(action,'CalcViewEgisData'); 
		set(hCalcEditEgisDataGoodTrial,'Visible','off'); 
	end
	EditEgisFigHandleVec(27)=hCalcEditEgisDataGoodTrial;

	if strcmp(action,'CalcEditEgisData')
		callbackStr = 'emegs2d(''CalcEditEgisDataBadTrial'')';
		String='Bad Trial';
		Userdata='0';
		FontSize=16;
	elseif strcmp(action,'CalcEyeCorrEgisData') | strcmp(action,'CalcEyeCorrEgisDataBatch')
		callbackStr = 'emegs2d(''RunCalcEyeCorrEgisData'')';
		String='Run Eye Corr.';
		Userdata=[];
		FontSize=12;
	end	
	XButton=2; YButton=3;
   	btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt) btnWid btnHt];	
	hCalcEditEgisDataBadTrial=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',String, ...
	'FontSize',FontSize, ...
	'FontWeight','bold',...
	'BackgroundColor',[1 0 0],...
	'Userdata',Userdata, ...
        'Callback',callbackStr,...
	'Enable','on');
	if strcmp(action,'CalcViewEgisData')
		set(hCalcEditEgisDataBadTrial,'Visible','off'); 
	end
	EditEgisFigHandleVec(28)=hCalcEditEgisDataBadTrial;

	if strcmp(action,'CalcEditEgisData')
		XButton=3; YButton=3;
   		btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt) btnWid btnHt];	
		callbackStr = 'emegs2d(''CalcEditEgisDataQuestTrial'')';
		hCalcEditEgisDataQuestTrial=uicontrol( ...
      	  	'Style','pushbutton', ...
      	 	'Units','normalized', ...
      	 	'Position',btnPos, ...
     	  	'String','??? Trial', ...
		'FontSize',16, ...
		'BackgroundColor',[0 0 1],...
		'FontWeight','bold',...
		'Userdata','0',...
        	'Callback',callbackStr,...
		'Enable','on');
		EditEgisFigHandleVec(29)=hCalcEditEgisDataQuestTrial;
		
	elseif strcmp(action,'CalcEyeCorrEgisData') | strcmp(action,'CalcEyeCorrEgisDataBatch')
	
        hCalcEditEgisDataQuestTrial=0;
        XButton=3; YButton=3;
        NButton31=3;
        
        Button31=3;
        btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
        callbackStr = 'emegs2d(''SetBlinkCorrEgisDataStatus'')';
        hBlinkCorrEgisDataStatus=uicontrol( ...
            'Style','radiobutton', ...
            'Units','normalized', ...
            'Position',btnPos, ...
            'HorizontalAlignment','center',...
            'String','Blink Corr.', ...
            'FontSize', [10], ...
            'BackgroundColor',FrameColor,...
            'FontWeight','bold',...
            'Value',1,...
            'Userdata',ones(1,NFiles),...
            'Callback',callbackStr,...
            'Enable','on');
        EditEgisFigHandleVec(30)=hBlinkCorrEgisDataStatus;
        
        Button31=2;
        btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
        callbackStr = 'emegs2d(''SetVertCorrEgisDataStatus'')';
        hVertCorrEgisDataStatus=uicontrol( ...
            'Style','radiobutton', ...
            'Units','normalized', ...
            'Position',btnPos, ...
            'HorizontalAlignment','center',...
            'String','Vertical Corr.', ...
            'FontSize', [10], ...
            'BackgroundColor',FrameColor,...
            'FontWeight','bold',...
            'Value',1,...
            'Userdata',ones(1,NFiles),...
            'Callback',callbackStr,...
            'Enable','on');
        EditEgisFigHandleVec(31)=hVertCorrEgisDataStatus;
        
        Button31=1;
        btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
        callbackStr = 'emegs2d(''SetHorCorrEgisDataStatus'')';
        hHorCorrEgisDataStatus=uicontrol( ...
            'Style','radiobutton', ...
            'Units','normalized', ...
            'Position',btnPos, ...
            'HorizontalAlignment','center',...
            'String','Horizontal Corr.', ...
            'FontSize', [10], ...
            'BackgroundColor',FrameColor,...
            'FontWeight','bold',...
            'Value',1,...
            'Userdata',ones(1,NFiles),...
            'Callback',callbackStr,...
            'Enable','on');
        EditEgisFigHandleVec(32)=hHorCorrEgisDataStatus;
    end
    XButton=1; YButton=1;
    btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt) btnWid./2 btnHt];	
    callbackStr = 'emegs2d(''CalcEditEgisDataNextTrial'')';
    hCalcEditEgisDataNextTrial=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','>', ...
        'FontSize', 24, ...
        'BackgroundColor',[1 1 1],...
        'FontWeight','bold',...
        'Userdata','0', ...
        'Callback',callbackStr,...
        'Enable','on');
    EditEgisFigHandleVec(33)=hCalcEditEgisDataNextTrial;
    
    XButton=1; YButton=1;
    btnPos=[DistLeft+btnWid./2 DistBottom+(YButton-1)*(DistYButton+btnHt) btnWid./2 btnHt];	
    callbackStr = 'emegs2d(''CalcEditEgisDataLastTrial'')';
    hCalcEditEgisDataLastTrial=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','<', ...
        'FontSize', 24, ...
        'BackgroundColor',[1 1 1],...
        'FontWeight','bold',...
        'Userdata','0', ...
        'Callback',callbackStr,...
        'Enable','on');
    EditEgisFigHandleVec(34)=hCalcEditEgisDataLastTrial;
    
    NButton31=4;
    
    XButton=3; YButton=2;
    Button31=4;
    btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
    callbackStr = 'emegs2d(''CalcEditEgisDataAutoTrial'')';
    hCalcEditEgisDataAutoTrial=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'HorizontalAlignment','center',...
        'String','Next Auto', ...
        'FontSize', [12], ...
        'BackgroundColor',FrameColor,...
        'FontWeight','bold',...
        'Userdata','1', ...
        'Value',1,...
        'Callback',callbackStr,...
        'Enable','on');
    EditEgisFigHandleVec(35)=hCalcEditEgisDataAutoTrial;
    
    Button31=3;
    btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
    callbackStr = 'emegs2d(''CalcEditEgisDataAutoGoodTrial'')';
    hCalcEditEgisDataAutoGoodTrial=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'HorizontalAlignment','center',...
        'String','Next Good', ...
        'FontSize', [12], ...
        'BackgroundColor',FrameColor,...
        'FontWeight','bold',...
        'Userdata','0', ...
        'Value',0,...
        'Callback',callbackStr,...
        'Enable','on');
    EditEgisFigHandleVec(36)=hCalcEditEgisDataAutoGoodTrial;
    
    Button31=2;
    btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
    callbackStr = 'emegs2d(''CalcEditEgisDataAutoBadTrial'')';
    hCalcEditEgisDataAutoBadTrial=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'HorizontalAlignment','center',...
        'String','Next Bad', ...
        'FontSize', [12], ...
        'BackgroundColor',FrameColor,...
        'FontWeight','bold',...
        'Userdata','0', ...
        'Value',0,...
        'Callback',callbackStr,...
        'Enable','on');
    EditEgisFigHandleVec(37)=hCalcEditEgisDataAutoBadTrial;
    
    Button31=1;
    btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) DistBottom+(YButton-1)*(DistYButton+btnHt)+(Button31-1)*btnHt./NButton31 btnWid btnHt./NButton31];	
    callbackStr = 'emegs2d(''CalcEditEgisDataAutoQuestTrial'')';
    hCalcEditEgisDataAutoQuestTrial=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'HorizontalAlignment','center',...
        'String','Next ???', ...
        'FontSize', [12], ...
        'BackgroundColor',FrameColor,...
        'FontWeight','bold',...
        'Userdata','0', ...
        'Value',0,...
        'Callback',callbackStr,...
        'Enable','on');
    EditEgisFigHandleVec(38)=hCalcEditEgisDataAutoQuestTrial;
    
    %=====================================================
    if NChan==128 | NChan==129
        BlinkSensorVec=[127 17 126  26 22 14 8];
    elseif NChan==256 | NChan==257
        BlinkSensorVec=[45, 30, 31, 25, 18, 10, 46, 37, 32, 19, 11, 2, 38, 33, 26, 20, 12, 3, 34, 27, 21, 13, 4, 22, 14, 5, 28, 226];
    else
        BlinkSensorVec=[];
    end
    EditEgisFigHandleVec(47)=uicontrol('Userdata',BlinkSensorVec,'Visible','off');	%47
    EditEgisFigHandleVec(48)=uicontrol('Value',0,'Visible','off');					%48	hBlinkFig
    EditEgisFigHandleVec(53)=uicontrol('Value',0,'Visible','off');					%53	hPolyFitFig
    EditEgisFigHandleVec(54)=uicontrol('Value',0,'Visible','off');					%54	hAvgEOGFig
    
    set(hList(107),'Userdata',EditEgisFigHandleVec);
    emegs2d('CalcEditEgisDataFirstTrial')
    if strcmp(action,'CalcEyeCorrEgisData') |  strcmp(action,'CalcEyeCorrEgisDataBatch')
        emegs2d('SetPreBlinkInt')
        emegs2d('SetPostBlinkInt')
    end
% 	hEditEgisFig
% 	hConsolFrame
%	hEditEgisAxes
% 	hSetSaveCorrStatus
%	hSetSaveEyeStatus
%	hSetSaveEyeStatus
% 	hSetPlotBlinkStatus
% 	hSetPlotPolyFitStatus
% 	hSetPlotAvgEOGStatus
% 	hSetPlotCorr2Status
% 	hSetPlotAvgCorrStatus
% 	hSetCorAvgCellStatus
% 	hSetHorLeftRightEOGChanText
% 	hSetHorLeftEOGChan
% 	hSetHorRightEOGChan
% 	hSetVertLeftRightEOGChanText
% 	hSetVertLeftBotEOGChan
% 	hSetVertRightBotEOGChan
% 	hSetVertLeftTopEOGChan
% 	hSetVertRightTopEOGChan
% 	hCalcEditEgisDataNextFile
% 	hCalcEditEgisDataLastFile
% 	hCalcEditEgisDataNextCell
% 	hCalcEditEgisDataLastCell
% 	hCalcEditEgisDataGivenStatus		SearchBlink
% 	hCalcEditEgisDataDefaultStatus	SetBlinkInt
% 	hCalcEditEgisDataGoodTrial		SetBlink
% 	hCalcEditEgisDataBadTrial
% 	hCalcEditEgisDataQuestTrial
% 	hBlinkCorrEgisDataStatus
% 	hVertCorrEgisDataStatus
% 	hHorCorrEgisDataStatus
% 	hCalcEditEgisDataNextTrial
% 	hCalcEditEgisDataLastTrial
% 	hCalcEditEgisDataAutoTrial
% 	hCalcEditEgisDataAutoGoodTrial
% 	hCalcEditEgisDataAutoBadTrial
% 	hCalcEditEgisDataAutoQuestTrial
% 	hSetLeftRightVCorStatus
% 	hPlotPauseStatus
% 	hSetBlinkLimText
% 	hSetBlinkLim
% 	hSetPreBlinkIntText
% 	hSetPreBlinkInt
% 	hSetPostBlinkIntText
%	hSetPostBlinkInt

elseif strcmp(action,'SetPlotBlinkStatus') | ...
	 strcmp(action,'SetPlotPolyFitStatus') | ...
	 strcmp(action,'SetPlotAvgEOGStatus'),
	 
	hList=get(hPlot2dMenuFig,'Userdata');
	EditEgisFigHandleVec=get(hList(107),'Userdata');
	if strcmp(action,'SetPlotBlinkStatus')
		TmpInd1=7; TmpInd2=48; FigName='Blink Figure';
	elseif strcmp(action,'SetPlotPolyFitStatus')
		TmpInd1=8; TmpInd2=53; FigName='Polyfit Figure';
	elseif strcmp(action,'SetPlotAvgEOGStatus')
		TmpInd1=9; TmpInd2=54; FigName='Avg. EOG Figure';
	end
	PlotStatus=get(EditEgisFigHandleVec(TmpInd1),'Value');
	hFig=get(EditEgisFigHandleVec(TmpInd2),'Value');
	if PlotStatus
		if hFig==0
			hFig=figure('Units','normal','Position',[0 0 .5 .4],'Name',FigName,'NumberTitle','off');
			set(EditEgisFigHandleVec(TmpInd2),'Value',hFig);
		else
			figure(hFig);
		end
	else
		if hFig~=0
			close(hFig);
		end
		set(EditEgisFigHandleVec(TmpInd2),'Value',0);
	end
	figure(EditEgisFigHandleVec(1));
	
elseif strcmp(action,'SetBlinkLim') |  ...
	strcmp(action,'SetBlinkCorrThresFac') | ...
	strcmp(action,'SetPlotPolyFitChanStep'),

	hList=get(hPlot2dMenuFig,'Userdata');
	DecInc=get(hList(124),'Userdata'); 
	DecIncAmp=DecInc(2);
	Tmp=max([1./DecIncAmp 1000]);
	EditEgisFigHandleVec=get(hList(107),'Userdata');
	
	if strcmp(action,'SetBlinkLim'); 
		TmpInd=42; MinVal=0;
	elseif strcmp(action,'SetBlinkCorrThresFac'); 
		TmpInd=50; MinVal=0;
	elseif strcmp(action,'SetPlotPolyFitChanStep'); 
		TmpInd=52; MinVal=0;
	end
	Val=get(EditEgisFigHandleVec(TmpInd),'Value');
	ValStr = get(EditEgisFigHandleVec(TmpInd),'String');
	[Val]=String2Value(ValStr,Val,MinVal);
	set(EditEgisFigHandleVec(TmpInd),'Value',Val,'String',sprintf('%g',round(Val*Tmp)/Tmp));

elseif  strcmp(action,'SetPreBlinkInt') | strcmp(action,'SetPostBlinkInt')

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NPoints=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+3),'Userdata');
	Domain=get(hList(20),'Value');
	SampRate=get(hList(60),'Userdata');
	EditEgisFigHandleVec=get(hList(107),'Userdata');
	PreVal=get(EditEgisFigHandleVec(44),'Value');
	PreStr=get(EditEgisFigHandleVec(44),'String');
	PostVal=get(EditEgisFigHandleVec(46),'Value');
	PostStr=get(EditEgisFigHandleVec(46),'String');
	if strcmp(action,'SetPreBlinkInt')
		[MsPreValTmp]=String2Value(PreStr);
		[PreValTmp]=Ms2Point(MsPreValTmp,Domain,SampRate,0,NPoints);
		if PreValTmp>NPoints-PostVal;
			PreValTmp=NPoints-PostVal;
		end
		if PreValTmp<0;
			PreValTmp=0;
		end
		[MsPreVal]=Point2Ms(PreValTmp,Domain,SampRate,0,NPoints);
		PreStr = sprintf('%g',round(MsPreVal.*1000)./1000);
		set(EditEgisFigHandleVec(44),'Value',PreValTmp,'String',PreStr);
	elseif strcmp(action,'SetPostBlinkInt')
		[MsPostValTmp]=String2Value(PostStr);
		[PostValTmp]=Ms2Point(MsPostValTmp,Domain,SampRate,0,NPoints);
		if PostValTmp>NPoints-PreVal;
			PostValTmp=NPoints-PreVal;
		end
		if PostValTmp<0;
			PostValTmp=0;
		end
		[MsPostVal]=Point2Ms(PostValTmp,Domain,SampRate,0,NPoints);
		PostStr = sprintf('%g',round(MsPostValTmp.*1000)./1000);
		set(EditEgisFigHandleVec(46),'Value',PostValTmp,'String',PostStr);
	end
	
elseif strcmp(action,'CalcEditEgisDataNextFile') | strcmp(action,'CalcEditEgisDataLastFile')

	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	EditEgisFigHandleVec=get(hList(107),'Userdata');
	EgisEyeCorrBatchStatus=get(hList(127),'Value');
	if EgisEyeCorrBatchStatus==0; 
		EgisEyeCorrBatchFileNo=1; 
	else
		EgisEyeCorrBatchFileNo=EgisEyeCorrBatchStatus;	
	end
	if EgisEyeCorrBatchStatus	%Batch
		FileMat=get(hList(127),'Userdata');
		[NFiles,NonUse]=size(FileMat);
		if strcmp(action,'CalcEditEgisDataNextFile')
			if EgisEyeCorrBatchFileNo==NFiles
				EgisEyeCorrBatchFileNo=1;
			else
				EgisEyeCorrBatchFileNo=EgisEyeCorrBatchFileNo+1;
			end
		elseif strcmp(action,'CalcEditEgisDataLastFile')
			if EgisEyeCorrBatchFileNo==1
				EgisEyeCorrBatchFileNo=NFiles;
			else
				EgisEyeCorrBatchFileNo=EgisEyeCorrBatchFileNo-1;
			end
		end
		set(hList(127),'Value',EgisEyeCorrBatchFileNo);
		
		TmpVec=get(EditEgisFigHandleVec(32),'Userdata');
		set(EditEgisFigHandleVec(32),'Value',TmpVec(EgisEyeCorrBatchFileNo));		%Hor Corr
		TmpVec=get(EditEgisFigHandleVec(31),'Userdata');
		set(EditEgisFigHandleVec(31),'Value',TmpVec(EgisEyeCorrBatchFileNo));		%Vertical Corr
		TmpVec=get(EditEgisFigHandleVec(30),'Userdata');	
		set(EditEgisFigHandleVec(30),'Value',TmpVec(EgisEyeCorrBatchFileNo));		%Blink Corr
		
		if TmpVec(EgisEyeCorrBatchFileNo)==1; 
			Enable='on'; 
		else; 
			Enable='off'; 
		end
		set(EditEgisFigHandleVec(25),'Enable',Enable);	%SearchBlink
		set(EditEgisFigHandleVec(26),'Enable',Enable);	%SetBlinkInt
		set(EditEgisFigHandleVec(27),'Enable',Enable);	%SetBlink
		
		FilePath=FileMat(EgisEyeCorrBatchFileNo,:);
		set(hList(82),'Value',1); % hOpenAvgFile=hList(82); CellSubjectVal==file + CellNo
		emegs2d('OpenAvgFile'); 
		[ActFile,ActPath]=SepFilePath(FilePath);
		EditEgisFigString=['EGIS File: ',ActFile,'; Cell: 1 ; Trial: 1'];
		hEditEgisFig=EditEgisFigHandleVec(1);
		set(hEditEgisFig,'Name',EditEgisFigString);
		figure(hEditEgisFig);
	end
	
elseif 	strcmp(action,'SetBlinkCorrEgisDataStatus') | ...
		strcmp(action,'SetVertCorrEgisDataStatus')  | ...
		strcmp(action,'SetHorCorrEgisDataStatus')
	
	hList=get(hPlot2dMenuFig,'Userdata');
	EditEgisFigHandleVec=get(hList(107),'Userdata');
	EgisEyeCorrBatchStatus=get(hList(127),'Value');
	if EgisEyeCorrBatchStatus==0; 
		EgisEyeCorrBatchFileNo=1; 
	else
		EgisEyeCorrBatchStatus=1;
		EgisEyeCorrBatchFileNo=EgisEyeCorrBatchStatus;
	end
	if strcmp(action,'SetBlinkCorrEgisDataStatus') 		
		TmpInd=30;	%hBlinkCorrEgisDataStatus
	elseif strcmp(action,'SetVertCorrEgisDataStatus') 
		TmpInd=31;	%hVertCorrEgisDataStatus
	elseif strcmp(action,'SetHorCorrEgisDataStatus') 
		TmpInd=32;	%hHorCorrEgisDataStatus
	end
	TmpVec=get(EditEgisFigHandleVec(TmpInd),'Userdata');
	TmpVal=get(EditEgisFigHandleVec(TmpInd),'Value');
	TmpVec(EgisEyeCorrBatchFileNo)=TmpVal;
	set(EditEgisFigHandleVec(TmpInd),'Userdata',TmpVec);
	if strcmp(action,'SetBlinkCorrEgisDataStatus')
		if TmpVal==1; 
			Enable='on'; 
		else; 
			Enable='off'; 
		end
		set(EditEgisFigHandleVec(25),'Enable',Enable);	%SearchBlink
		set(EditEgisFigHandleVec(26),'Enable',Enable);	%SetBlinkInt
		set(EditEgisFigHandleVec(27),'Enable',Enable);	%SetBlink
	end
	
elseif 	strcmp(action,'CalcEditEgisDataAutoTrial') | ...
	strcmp(action,'CalcEditEgisDataAutoGoodTrial') | ...
	strcmp(action,'CalcEditEgisDataAutoBadTrial') | ...
	strcmp(action,'CalcEditEgisDataAutoQuestTrial') 

	hList=get(hPlot2dMenuFig,'Userdata');
	EditEgisFigHandleVec=get(hList(107),'Userdata');
	EgisEyeCorrBatchStatus=get(hList(127),'Value');
	
	if strcmp(action,'CalcEditEgisDataAutoQuestTrial')
		Status=get(EditEgisFigHandleVec(38),'Value');				%hCalcEditEgisDataAutoQuestTrial	hCalcEditEgisDataAutoGoodTrial
		if Status==1; set(EditEgisFigHandleVec([37 36]),'Value',0); end	%hCalcEditEgisDataAutoBadTrial
	elseif strcmp(action,'CalcEditEgisDataAutoBadTrial')
		Status=get(EditEgisFigHandleVec(37),'Value');
		if Status==1; set(EditEgisFigHandleVec([38 36]),'Value',0); end
	elseif strcmp(action,'CalcEditEgisDataAutoGoodTrial')
		Status=get(EditEgisFigHandleVec(36),'Value');
		if Status==1; set(EditEgisFigHandleVec([38 37]),'Value',0); end
	end
	set(EditEgisFigHandleVec(33),'Enable','on'); %Enable hCalcEditEgisDataNextTrial
	set(EditEgisFigHandleVec(34),'Enable','on'); %Enable hCalcEditEgisDataLastTrial
	emegs2d('TestNextLastCalcEditEgisDataTrialStatus')
	
	%=============================================================================
	%=============================================================================	
elseif 	strcmp(action,'CalcEditEgisDataFirstTrial') | ...
	strcmp(action,'CalcEditEgisDataGoodTrial') | ...
	strcmp(action,'CalcEditEgisDataBadTrial') | ...
	strcmp(action,'CalcEditEgisDataQuestTrial') | ...
	strcmp(action,'CalcEditEgisDataNextTrial') | ...
	strcmp(action,'CalcEditEgisDataLastTrial') | ...
	strcmp(action,'TestNextLastCalcEditEgisDataTrialStatus')  | ...
	strcmp(action,'SetBlinkCorrEgisData') | ...
	strcmp(action,'SearchBlinkCorrEgisData') | ...
	strcmp(action,'SetBlinkIntCorrEgisData') | ...
	strcmp(action,'RunCalcEyeCorrEgisData'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	Domain=get(hList(20),'Value');
	DecInc=get(hList(124),'Userdata'); DecIncAmp=DecInc(2);
	DecIncAmpTmp=max([1./DecIncAmp 1000]);
	NListHdr=get(hList(51),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	EditEgisFigHandleVec=get(hList(107),'Userdata');
	EgisEyeCorrBatchStatus=get(hList(127),'Value');
	FileNoVec=get(hList(56),'Userdata');
	NFiles=length(FileNoVec);
	ActFilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
	[ActFile,ActPath]=SepFilePath(ActFilePath);
	hOpenAvgFile=hList(82);
	
	hTopMenu=get(hList(65),'Userdata');
	hCalcMenu=get(hTopMenu(4),'children');	
	hCalcEditEgisData=hCalcMenu(16);
	LSpecCellMat=get(hCalcEditEgisData,'Userdata');
	
	LSpecCellVec=LSpecCellMat(:,1);
	EgisRawVec=get(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata');

	SpecCell=EgisRawVec(1);
	SpecTrial=EgisRawVec(2);
	NCells=EgisRawVec(3);
	NTrialsVec=EgisRawVec(7+NCells:6+2.*NCells);
	
	if 	strcmp(action,'SetBlinkCorrEgisData') | ...
		strcmp(action,'SearchBlinkCorrEgisData') | ...
		strcmp(action,'SetBlinkIntCorrEgisData') | ...
		strcmp(action,'RunCalcEyeCorrEgisData')
		
		hPlot2dChanFig=hList(93);
		
		global GlobalXCorrVec BlinkBatMatVec
		global BlinkMaxPoint BlinkMinPoint NBlinkPoints CellTrialTimeBlinkMat
		global MaxGlobalXCorrVec MaxXCorrVecPoint MaxGlobalXCorrVecPoint MinGlobalXCorrVec GlobalXCorrMat
		if any(strcmp(who('global'),'NoSubAvgEEGIndVec'))
			global NoSubAvgEEGIndVec
			Message=char('Do not subtract the average of ');
			Message=char(Message,'the following time interval from ');
			Message=char(Message,'single trials prior to correction:');
			Message=char(Message,'');
			Message=char(Message,[int2str(min(NoSubAvgEEGIndVec)),' : ',int2str(max(NoSubAvgEEGIndVec)),' (in points and independent of trigger)']);
			hmsgbox=msgbox(Message,'Info:','help'); 	
		else
			NoSubAvgEEGIndVec=[];
		end
		%==============
		SaveCorStatus=get(EditEgisFigHandleVec(4),'Value');
		SaveEyeStatus=get(EditEgisFigHandleVec(5),'Value');
		SavePccStatus=get(EditEgisFigHandleVec(6),'Value');
		%==============
		PlotBlinkStatus=get(EditEgisFigHandleVec(7),'Value');
		hBlinkFig=get(EditEgisFigHandleVec(48),'Value');
		PlotPolyFitStatus=get(EditEgisFigHandleVec(8),'Value');
		hPolyFitFig=get(EditEgisFigHandleVec(53),'Value');
		PlotPolyFitChanStep=get(EditEgisFigHandleVec(52),'Value');
		PlotAvgEOGStatus=get(EditEgisFigHandleVec(9),'Value')	;	%hSetPlotAvgEOGStatus
		hAvgEOGFig=get(EditEgisFigHandleVec(54),'Value');			%hAvgEOGFig
		PlotCorStatus=get(EditEgisFigHandleVec(10),'Value');		%hSetPlotCorr2Status
		PlotCorAvgStatus=get(EditEgisFigHandleVec(11),'Value');		%hSetPlotAvgCorrStatus
		PlotCorCellAvgStatus=get(EditEgisFigHandleVec(12),'Value');	%hSetCorAvgCellStatus
		%==============
		PlotPauseStatus=get(EditEgisFigHandleVec(40),'Value');		%hPlotPauseStatus
		%==============
		HEOGPair(1)=get(EditEgisFigHandleVec(14),'Value');			%hSetHorLeftEOGChan
		HEOGPair(2)=get(EditEgisFigHandleVec(15),'Value')	;		%hSetHorRightEOGChan
		VLEOGPair(2)=get(EditEgisFigHandleVec(19),'Value');			%hSetVertLeftTopEOGChan
		VLEOGPair(1)=get(EditEgisFigHandleVec(17),'Value');			%hSetVertLeftBotEOGChan
		VREOGPair(2)=get(EditEgisFigHandleVec(20),'Value');			%hSetVertRightTopEOGChan
		VREOGPair(1)=get(EditEgisFigHandleVec(18),'Value');			%hSetVertRightBotEOGChan
		LeftRightVCorStatus=get(EditEgisFigHandleVec(39),'Value');	%hLeftRightVCorStatus
		%==============
		BlinkLim=get(EditEgisFigHandleVec(42),'Value');				%hSetBlinkLim
		PreBlinkInt=get(EditEgisFigHandleVec(44),'Value');			%hSetPreBlinkInt
		PostBlinkInt=get(EditEgisFigHandleVec(46),'Value');			%hSetPostBlinkInt
		%==============
		BlinkSensorVec=get(EditEgisFigHandleVec(47),'Userdata');
		NBlinkSensors=length(BlinkSensorVec);
		BlinkCorrThresFac=get(EditEgisFigHandleVec(50),'Value');
		BlinkCorrThresFac=BlinkCorrThresFac./100;
		%==============
		EgisRawVec=get(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata');
		NCells=EgisRawVec(3);
		NChan=EgisRawVec(4);
		LHdr=EgisRawVec(5);
		SampRateVec=EgisRawVec(7:6+NCells);
		NTrialsVec=EgisRawVec(7+NCells:6+2.*NCells);
		NPointsVec=EgisRawVec(7+2.*NCells:6+3.*NCells);
		NBytesInTrial=NPointsVec.*NChan.*2;
		NBytesInCell=NBytesInTrial.*NTrialsVec;
		NPointsInCell=NPointsVec(SpecCell);
		ChanGainVec=EgisRawVec(10+3.*NCells+2.*NChan:9+3.*NCells+3.*NChan);
		%==============	
		ActFileNo=get(hList(1),'Userdata');
		NListHdr=get(hList(51),'Userdata');
		FileNoVec=get(hList(56),'Userdata');
   		NUsedFiles=length(FileNoVec);
		CalcAvgMat=get(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata');
		hChildProgressMsgbox=[];
		[NChan,NPoints]=size(CalcAvgMat);
		if strcmp(action,'SearchBlinkCorrEgisData')
			MinPointSlider=get(hList(122),'Value'); 
			MaxPointSlider=get(hList(123),'Value'); 
			if MinPointSlider~=1; 
				set(hList(122),'Value',1); 
				emegs2d('setMinPointSlider');
			end
			if MaxPointSlider~=NPointsInCell; 
				set(hList(123),'Value',NPointsInCell);
				emegs2d('setMaxPointSlider');
			end
			Tmp=[];
			EgisSesFid=fopen(ActFilePath,'r','b');	
			fseek(EgisSesFid,LHdr+(SpecCell-1).*NBytesInCell+(SpecTrial-1).*NBytesInTrial,'bof');
			SpecTrial=SpecTrial+1;
			while 1
				Plot2dChanFigName=['Search for Eye Blink; Cell: ',int2str(SpecCell),'; Trial: ', int2str(SpecTrial-1),'.'];
				set(hPlot2dChanFig,'Name',Plot2dChanFigName);	
				[CalcAvgMat,Count]=fread(EgisSesFid,[NChan,NPointsInCell],'int16');
				for TimeInd=1:NPointsInCell
					CalcAvgMat(:,TimeInd)=CalcAvgMat(:,TimeInd).*ChanGainVec;
				end
				if LeftRightVCorStatus==1 | LeftRightVCorStatus==3
					VLEOGVec1=CalcAvgMat(VLEOGPair(1),:).*ChanGainVec(VLEOGPair(1));
					VLEOGVec1=VLEOGVec1-mean(VLEOGVec1);
					VLEOGVec2=CalcAvgMat(VLEOGPair(2),:).*ChanGainVec(VLEOGPair(2));
					VLEOGVec2=VLEOGVec2-mean(VLEOGVec2);
					VLEOGVec=abs(VLEOGVec1-VLEOGVec2);
				elseif LeftRightVCorStatus==2 | LeftRightVCorStatus==3
					VREOGVec1=CalcAvgMat(VREOGPair(1),:).*ChanGainVec(VREOGPair(1));
					VREOGVec1=VREOGVec1-mean(VREOGVec1);
					VREOGVec2=CalcAvgMat(VREOGPair(2),:).*ChanGainVec(VREOGPair(2));
					VREOGVec2=VREOGVec2-mean(VREOGVec2);
					VREOGVec=abs(VREOGVec1-VREOGVec2);
				end
				if LeftRightVCorStatus==1
					Tmp=find(VLEOGVec>BlinkLim);
				elseif LeftRightVCorStatus==2
					Tmp=find(VREOGVec>BlinkLim);
				elseif LeftRightVCorStatus==3
					Tmp=find(VLEOGVec>BlinkLim & VREOGVec>BlinkLim);
				end
                MaxInd=[];
				if ~isempty(Tmp)
					[MaxTmp,MaxInd]=max(VLEOGVec(Tmp));
					MaxInd=Tmp(MaxInd);
					if MaxInd<PreBlinkInt | MaxInd>NPointsInCell-PostBlinkInt
						Tmp=[];
					end
				end
				if ~isempty(Tmp)
					break;
				else
					SpecTrial=SpecTrial+1;
					if SpecTrial>NTrialsVec(SpecCell)
						SpecCell=SpecCell+1;
						SpecTrial=1;
						if SpecCell>NCells
							SpecCell=1;
							Tmp=1;
							break;
						end
					end
				end
			end %while
			fclose(EgisSesFid);
			ActFileNo=1;
			set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',CalcAvgMat); 
            if ~isempty(MaxInd)
	 		    set(hList(132),'Value',MaxInd);	%CursorPointSlider	
			    emegs2d('setCursorPointSlider');
            end
			emegs2d('PlotData');
			emegs2d('AdjustAmp');
			pause(.001)
			EgisRawVec(1)=SpecCell;
			EgisRawVec(2)=SpecTrial;
			set(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata',EgisRawVec);
			CellTrialVal=1+sum(NTrialsVec(1:SpecCell-1))+SpecTrial;
			set(hOpenAvgFile,'Value',CellTrialVal); %CellTrialVal
			EditEgisFigString=['EGIS File: ',ActFile,'; Cell: '  int2str(SpecCell),'; Trial: ',int2str(SpecTrial-1)];
			set(EditEgisFigHandleVec(1),'Name',EditEgisFigString);
			figure(EditEgisFigHandleVec(1))
			return;
		end
		if strcmp(action,'SetBlinkIntCorrEgisData'),
			CursorPoint=get(hList(23),'Value');		
			if CursorPoint<=PreBlinkInt	%Auto
				[NonUse,CursorPointTmp]=max(mean(abs(CalcAvgMat(BlinkSensorVec,:)),1));
			else
				CursorPointTmp=CursorPoint;
			end
			set(hList(122),'Value',CursorPointTmp-PreBlinkInt); 	%MinPointSlider
			set(hList(123),'Value',CursorPointTmp+PostBlinkInt); 	%MaxPointSlider
			emegs2d('setMinPointSlider');
			emegs2d('setMaxPointSlider');
			Plot2dChanFigName=['Eye Blink Interval'];
			set(hPlot2dChanFig,'Name',Plot2dChanFigName);	
			return;
		end
		if strcmp(action,'SetBlinkCorrEgisData')
			set(hPlot2dChanFig,'Name','Set Eye Blink');
			BlinkMinPoint=get(hList(122),'Value'); %MinPointSlider
			BlinkMaxPoint=get(hList(123),'Value'); %MaxPointSlider
			NBlinkPoints=BlinkMaxPoint-BlinkMinPoint+1;
			[GradBlinkX,GradBlinkY]=gradient(CalcAvgMat);
			BlinkMat=GradBlinkX(:,BlinkMinPoint:BlinkMaxPoint);
			XCorrVec=xcorr(BlinkMat(1,:),CalcAvgMat(1,:));
			[NoUse,NCorrPoints]=size(XCorrVec);
			GlobalXCorrVec=0.*XCorrVec;
			for ChanInd=1:NBlinkSensors
				GlobalXCorrVec=GlobalXCorrVec+xcorr(BlinkMat(BlinkSensorVec(ChanInd),:),GradBlinkX(BlinkSensorVec(ChanInd),:));
			end	
			[MaxGlobalXCorrVec,MaxGlobalXCorrVecPoint]=max(GlobalXCorrVec);
			MinGlobalXCorrVec=min(GlobalXCorrVec);
			if PlotBlinkStatus
				figure(hBlinkFig); 
				set(hBlinkFig,'Name',['Cell: ',int2str(SpecCell),' ;  Trial: '  int2str(SpecTrial)]);
				plot(GlobalXCorrVec,'r'); 
				hold on
				plot([ceil(NCorrPoints./2) NCorrPoints],BlinkCorrThresFac.*[MaxGlobalXCorrVec MaxGlobalXCorrVec],'--g')
				axis([ceil(NCorrPoints./2) NCorrPoints 1.1.*MinGlobalXCorrVec 1.1.*MaxGlobalXCorrVec])
				pause(.01)
			end
			set(hList(122),'Value',1); 			%MinPointSlider
			set(hList(123),'Value',NPoints); 	%MaxPointSlider
			emegs2d('setMinPointSlider');
			emegs2d('setMaxPointSlider');
			EgisEyeCorrBatchFileNo=get(hList(127),'Value');
			
			if EgisEyeCorrBatchFileNo>0	%Batch
				FileMat=get(hList(127),'Userdata');
				[NFiles,NonUse]=size(FileMat);
				[n,m]=size(BlinkMat);
				BlinkBatMat=get(EditEgisFigHandleVec(27),'Userdata');
				if isempty(BlinkBatMat)	
					BlinkBatMat=zeros(NFiles,n,m);
					[p,q]=size(GlobalXCorrVec);
					GlobalXCorrMat=zeros(NFiles,q);
				else
					BlinkBatMat=get(EditEgisFigHandleVec(27),'Userdata');
					if m>max(BlinkBatMatVec)
						Tmp=zeros(NFiles,n,m);
						Tmp(NFiles,n,1:max(BlinkBatMatVec))=BlinkBatMat;
						BlinkBatMat=Tmp; Tmp=[];
					end				
				end
				BlinkBatMatVec(EgisEyeCorrBatchFileNo)=m;
				BlinkBatMat(EgisEyeCorrBatchFileNo,1:n,1:m)=BlinkMat;
				set(EditEgisFigHandleVec(27),'Userdata',BlinkBatMat);
				GlobalXCorrMat(EgisEyeCorrBatchFileNo,:)=GlobalXCorrVec;
				emegs2d('CalcEditEgisDataNextFile')
			else
				set(EditEgisFigHandleVec(27),'Userdata',BlinkMat);
			end
			return
		end
		
		if strcmp(action,'RunCalcEyeCorrEgisData')	
			
			Plot2dChanFigName=['Run Eye Blink and Movement Correction of File: ',ActFile];
			set(hPlot2dChanFig,'Name',Plot2dChanFigName);	
			
			EgisEyeCorrBatchFileNo=get(hList(127),'Value'); 
			if EgisEyeCorrBatchFileNo==0	%No Batch
				ActBatchFileNo=1;
				NFiles=1;
				BlinkCorStatus=get(EditEgisFigHandleVec(30),'Value');
				VertEyeCorStatus=get(EditEgisFigHandleVec(31),'Value');
				HorEyeCorStatus=get(EditEgisFigHandleVec(32),'Value');
			else
				ActBatchFileNo=EgisEyeCorrBatchFileNo;
				Tmp=get(EditEgisFigHandleVec(30),'Userdata'); 	BlinkCorStatus=Tmp(EgisEyeCorrBatchFileNo);
				Tmp=get(EditEgisFigHandleVec(31),'Userdata');	VertEyeCorStatus=Tmp(EgisEyeCorrBatchFileNo);
				Tmp=get(EditEgisFigHandleVec(32),'Userdata');	HorEyeCorStatus=Tmp(EgisEyeCorrBatchFileNo);
				set(EditEgisFigHandleVec(30),'Value',BlinkCorStatus);
				set(EditEgisFigHandleVec(31),'Value',VertEyeCorStatus);
				set(EditEgisFigHandleVec(32),'Value',HorEyeCorStatus);
			end
            BlinkMat=get(EditEgisFigHandleVec(27),'Userdata');
			if BlinkCorStatus 	
				if EgisEyeCorrBatchFileNo>0	%Batch
					[NFiles,n,m]=size(BlinkMat);
					Tmp=zeros(n,m);
					Tmp(:,:)=BlinkMat(EgisEyeCorrBatchFileNo,:,:);
					BlinkMat=Tmp;
					if all(BlinkMat==0)
						BlinkMat=[];
					end
					GlobalXCorrVec=GlobalXCorrMat(EgisEyeCorrBatchFileNo,:);
				end
				if isempty(BlinkMat)
					if EgisEyeCorrBatchFileNo==0	%No Batch
						Message=char('Sorry,');
						Message=char(Message,'');
						Message=char(Message,'using blink correction you have to define a typical blink first.');
						Message=char(Message,'');
						Message=char(Message,'Search for a blink event using the ">" push button of the eye correction menu');
						Message=char(Message,'and define the blink interval using "Min. Time" and " Max. Time".');
						Message=char(Message,'');
						Message=char(Message,'Push "Set Blink" in the eye correction window.');
						Message=char(Message,'');
						Message=char(Message,'(Try to find a blink, which starts and ends within a trial.)');
						Message=char(Message,'');
						hmsgbox=msgbox(Message,'Info:','help'); 
						return;
					else
						Message=char('Warning !');
						Message=char(Message,'');
						Message=char(Message,'No blink defined for file');
						Message=char(Message,ActFile);
						Message=char(Message,'=> No blink correction');
						Message=char(Message,'');
						hmsgbox=msgbox(Message,'Info:','help'); 
						BlinkCorStatus=0;
						Tmp=get(EditEgisFigHandleVec(30),'Userdata'); 	Tmp(EgisEyeCorrBatchFileNo)=BlinkCorStatus;
						set(EditEgisFigHandleVec(30),'Userdata',Tmp,'Value',BlinkCorStatusj); 
					end
				end
				[MaxGlobalXCorrVec,MaxGlobalXCorrVecPoint]=max(GlobalXCorrVec);
			end
			if isempty(BlinkMat)
				NBlinkPoints=0,
			else
				[NoUse NBlinkPoints]=size(BlinkMat);
			end
			[NoUse,NCorrPoints]=size(GlobalXCorrVec);
			XCorrMat=zeros(NChan,NCorrPoints);
			CellTrialTimeBlinkMat=[];
			NCellTrialTimeBlinkMat=0;
			AvgHEOG=zeros(NCells,NPoints);
			AvgVLEOG=zeros(NCells,NPoints);
			AvgVREOG=zeros(NCells,NPoints);
% 			AvgBEOG=zeros(NCells,NPoints);
% 			SumBEOG=zeros(NCells,NPoints);
			OnesBEOG=ones(1,NPoints);
			AvgEEG=zeros(NChan,NPoints);
% 			AvgBEOGMat=zeros(NChan,NPoints);	
			if PlotAvgEOGStatus; figure(hAvgEOGFig); end
			%=================
			%=================	
					
			if BlinkCorStatus;
				StartEyeCorLoopIndex=1;
			else
				if VertEyeCorStatus
					StartEyeCorLoopIndex=4;
				else
					if HorEyeCorStatus
						StartEyeCorLoopIndex=7;
					else
						return;
					end
				end
			end
			if HorEyeCorStatus;
				EndEyeCorLoopIndex=9;
			else
				if VertEyeCorStatus
					EndEyeCorLoopIndex=6;
				else
					if BlinkCorStatus
						EndEyeCorLoopIndex=3;
					else
						return;
					end
				end
			end

			LoopIndex=0;
			NLoops=EndEyeCorLoopIndex-StartEyeCorLoopIndex+1;
			PolyfitDeg=1;	%PolyFit
			PolyCoeffMat=zeros(3,NChan,PolyfitDeg+1); %Blink, Vertical, Horizontal
			EgisSesFid=fopen(ActFilePath,'r','b');
			EgisHeader=fread(EgisSesFid,LHdr,'int8');
			hChildReadSaveMsgbox=[];
			hChildProgressMsgbox=[];
			BVHLet=[];
			TotSubFilePath=[ActFilePath '.tmp'];			%Write trials-avg into temporary file (.tmp)
			for  EyeCorLoopIndex=StartEyeCorLoopIndex:EndEyeCorLoopIndex
				LoopIndex=LoopIndex+1;
				%================================================
				%======First calculate average EEG and EOG loop======
				%================================================
				if any([1 4 7]==EyeCorLoopIndex)
					if EyeCorLoopIndex==1; 
						BVHLet=[BVHLet 'b']; 
						BVHLine='Blink Correction';
					elseif EyeCorLoopIndex==4; 
						BVHLet=[BVHLet 'v'];
						BVHLine='Vertical movement';
						if LeftRightVCorStatus==1; %1=Left; 2=Right; 3=Both
							EOGPair=VLEOGPair;
						elseif LeftRightVCorStatus==2; 
							EOGPair=VREOGPair;
						elseif LeftRightVCorStatus==3; 
							EOGPair=zeros(4,1);
							EOGPair(1:2)=VLEOGPair;
							EOGPair(3:4)=VREOGPair;
						end
					elseif EyeCorLoopIndex==7; 
						BVHLet=[BVHLet 'h'];
						BVHLine='Horizontal movement';
						EOGPair=HEOGPair;
					end
					FileLine=['File ',int2str(ActBatchFileNo),' of ',int2str(NFiles),' ("',ActFile,'")'];
					CorFilePath=[ActFilePath '.' BVHLet '.cor'];
					if LoopIndex==1
						ReadAvgFid=EgisSesFid;						%Read trials from original EGIS session file in first correction loop (.E*)
					else
						ReadAvgFid=fopen(CorFilePathOld,'r','b');	%Read corrected trials from old corrected EGIS session file (.cor) in following correction loop
						fseek(ReadAvgFid,LHdr,-1);
					end
					TotSubFid=fopen(TotSubFilePath,'w','b');
					%==============
					
					Message=char('Calculate averaged EEG and EOG of file:');
					Message=char(Message,'');
					Message=char(Message,ActFilePath);
					Message=char(Message,'');
					if SaveCorStatus
						Message=char(Message,'Save eye corrected data to file:');
						Message=char(Message,'');
						Message=char(Message,CorFilePath);
						Message=char(Message,'');
					end
					if SaveEyeStatus
						EyeFilePath=[ActFilePath '.' BVHLet '.eye'];	%Write correction eye artifact trials into eye EGIS session file (.eye)
						Message=char(Message,'Save eye correction data to file:');
						Message=char(Message,'');
						Message=char(Message,EyeFilePath);
						Message=char(Message,'');
					end
					if SavePccStatus
						PolyCoeffFilePath=[ActFilePath '.pcc'];		%Write polynom correction coefficients in file (.pcc)
						Message=char(Message,'Save correction coefficients to file:');
						Message=char(Message,'');
						Message=char(Message,PolyCoeffFilePath);
						Message=char(Message,'');
					end
					Message=char(Message,'Save temporary data to file:');
					Message=char(Message,'');
					Message=char(Message,TotSubFilePath);
					Message=char(Message,'');
					Message=char(Message,'');
					if isempty(hChildReadSaveMsgbox)
						hReadSaveMsgbox=msgbox(Message,'Read and Save Info:','help');
                        hChildReadSaveMsgbox=get(hReadSaveMsgbox,'Children');
                    else
                        if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
                            set(hChildReadSaveMsgbox(2),'String',Message);
                        else
                            hChild2ReadSaveMsgbox=get(hChildReadSaveMsgbox(2),'Children');
                            set(hChild2ReadSaveMsgbox,'String',Message);
                        end
                        pause(.001)
                    end
                    if isempty(hChildProgressMsgbox)
						Message=char(zeros(12,1));
						hProgressMsgbox=msgbox(Message,'Progress Info:','help'); 
						hChildProgressMsgbox=get(hProgressMsgbox,'Children');
					end
					%==============
					for SpecCell=1:NCells	
						NTrialsInCell=NTrialsVec(SpecCell);
						%NTrialsInCell=10;
						NPointsInCell=NPointsVec(SpecCell);
						DefCount=NChan.*NPointsInCell;
						for SpecTrial=1:NTrialsInCell;
							Message=char(BVHLine);
							Message=char(Message,'(Average)');
							Message=char(Message,'');
							if EyeCorLoopIndex>3;
								Message=char(Message,['EOG ',int2str(EOGPair(1)),'  -  ',int2str(EOGPair(2))]);
								if length(EOGPair)>2
									Message=char(Message,['EOG ',int2str(EOGPair(3)),'  -  ',int2str(EOGPair(4))]);
								end
							else
								Message=char(Message,'');
							end
							Message=char(Message,FileLine);
							Message=char(Message,['Loop ',int2str(LoopIndex),' of ',int2str(NLoops)]);
							Message=char(Message,['Cell ',int2str(SpecCell),' of ',int2str(NCells)]);
							Message=char(Message,['Trial ',int2str(SpecTrial),' of ',int2str(NTrialsInCell)]);
							Message=char(Message,'');
                            if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
                                set(hChildProgressMsgbox(2),'String',Message);
                            else
                                hChild2ProgressMsgbox=get(hChildProgressMsgbox(2),'Children');
                                set(hChild2ProgressMsgbox,'String',Message);
                            end
							pause(.001);
							[CalcAvgMat,Count]=fread(ReadAvgFid,[NChan,NPointsInCell],'int16'); %Original EGIS in first loop; Old corrected in following loops
							if Count~=DefCount; error; end	
							for TimeInd=1:NPointsInCell
								CalcAvgMat(:,TimeInd)=CalcAvgMat(:,TimeInd).*ChanGainVec;
							end
%	 						RawEEGMat(sum(NTrialsVec(1:SpecCell-1))+SpecTrial,:,:)=CalcAvgMat;
							if PlotAvgEOGStatus
								ActFileNo=1;
								set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',CalcAvgMat);
								Plot2dChanFigName=['Calculate averaged EOG and EEG; Cell: ',int2str(SpecCell),'; Trial: '];
								set(hPlot2dChanFig,'Name',[Plot2dChanFigName, int2str(SpecTrial),'.']);	
								AvgEEG=((SpecTrial-1).*AvgEEG+CalcAvgMat)./SpecTrial;
								ActFileNo=2;
								set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',AvgEEG);
								emegs2d('PlotData');
								pause(.001)
								figure(hAvgEOGFig)
							else
								AvgEEG=AvgEEG+CalcAvgMat;
							end
						
							if HorEyeCorStatus
								HEOG=CalcAvgMat(HEOGPair(1),:)-CalcAvgMat(HEOGPair(2),:);
								if PlotAvgEOGStatus
									AvgHEOG(SpecCell,:)=((SpecTrial-1).*AvgHEOG(SpecCell,:)+HEOG)./SpecTrial;
									plot(HEOG,'r'); 
									hold on
									plot(AvgHEOG,'r--');
									set(hAvgEOGFig,'Name',['HEOG (red -); AvgHEOG (red --); VLEOG (blue -); AvgVLEOG (blue --); Cell: ',int2str(SpecCell),' ;  Trial: '  int2str(SpecTrial)]);
								else
									AvgHEOG(SpecCell,:)=AvgHEOG(SpecCell,:)+HEOG;
								end
							end
							if VertEyeCorStatus | BlinkCorStatus
								VLEOG=CalcAvgMat(VLEOGPair(1),:)-CalcAvgMat(VLEOGPair(2),:);
								VREOG=CalcAvgMat(VREOGPair(1),:)-CalcAvgMat(VREOGPair(2),:);
								if PlotAvgEOGStatus
									AvgVLEOG(SpecCell,:)=((SpecTrial-1).*AvgVLEOG(SpecCell,:)+VLEOG)./SpecTrial;
									AvgVREOG(SpecCell,:)=((SpecTrial-1).*AvgVREOG(SpecCell,:)+VREOG)./SpecTrial;
									plot(VLEOG,'b'); 
									hold on
									plot(AvgVLEOG,'b--'); 
									set(hAvgEOGFig,'Name',['HEOG (red -); AvgHEOG (red --); VLEOG (blue -); AvgVLEOG (blue --); Cell: ',int2str(SpecCell),' ;  Trial: '  int2str(SpecTrial)]);
									WaitBat(PlotPauseStatus);
								else
									AvgVLEOG(SpecCell,:)=AvgVLEOG(SpecCell,:)+VLEOG;
									AvgVREOG(SpecCell,:)=AvgVREOG(SpecCell,:)+VREOG;
								end
							end
							hold off
							%=============================
							if BlinkCorStatus;	
								XCorrVec=0.*GlobalXCorrVec;	
								[GradBlinkX,GradBlinkY]=gradient(CalcAvgMat);
								for ChanInd=1:NBlinkSensors
									XCorrVec=XCorrVec+xcorr(BlinkMat(BlinkSensorVec(ChanInd),:),GradBlinkX(BlinkSensorVec(ChanInd),:));
								end
								if PlotBlinkStatus; 
									figure(hBlinkFig); 
								end
								TopThresXCorrVec=find(XCorrVec>=BlinkCorrThresFac.*MaxGlobalXCorrVec);
								MoreTop=1;
								while (~isempty(TopThresXCorrVec) & MoreTop)
									%=====================
									if PlotBlinkStatus
										set(hBlinkFig,'Name',['GlobalXCorrVec (red); XCorrVec (blue); Threshold (green); Cell: ',int2str(SpecCell),' ;  Trial: '  int2str(SpecTrial)]);
										plot(GlobalXCorrVec,'r'); 
										hold on
                                        plot(XCorrVec,'b');
										plot([1 NCorrPoints],BlinkCorrThresFac.*[MaxGlobalXCorrVec MaxGlobalXCorrVec],'--g')				
									end
									%=====================		
									Tmp=find(TopThresXCorrVec-TopThresXCorrVec(1)>NBlinkPoints./2);
									if isempty(Tmp)
										Tmp=length(TopThresXCorrVec)+1;
										MoreTop=0;
									end
									[MaxXCorrVec,MaxXCorrVecPoint]=max(XCorrVec(TopThresXCorrVec(1:Tmp(1)-1)));
									MaxXCorrVecPoint=MaxXCorrVecPoint+TopThresXCorrVec(1)-1;
									if MoreTop
										TopThresXCorrVec=TopThresXCorrVec(Tmp(1):length(TopThresXCorrVec));
									end
                                    MaxGlobalXCorrVecPoint=MaxGlobalXCorrVecPoint
                                    MaxXCorrVecPoint=MaxXCorrVecPoint
                                    BlinkMinPoint=BlinkMinPoint
                                    BlinkMaxPoint=BlinkMaxPoint
									%SpecBlinkPoint=MaxXCorrVecPoint-NPoints+1
                                    SpecBlinkPoint=MaxGlobalXCorrVecPoint-MaxXCorrVecPoint
                                    SpecBlinkMinPoint=SpecBlinkPoint+BlinkMinPoint
                                    SpecBlinkMaxPoint=SpecBlinkPoint+BlinkMaxPoint
                                    PreBlinkInt=PreBlinkInt
                                    SpecBlinkCursPoint=SpecBlinkMinPoint+PreBlinkInt
									if PlotBlinkStatus
										plot([MaxXCorrVecPoint MaxXCorrVecPoint],[1.1.*MinGlobalXCorrVec 1.1.*MaxGlobalXCorrVec],'--g')
									end
									EyeCorrStart=max(1,SpecBlinkMinPoint)
									EyeCorrEnd=min(NPointsInCell,SpecBlinkMaxPoint)
                                    SpecBlinkCursPoint=max(1,SpecBlinkCursPoint)
                                    SpecBlinkCursPoint=min(NPointsInCell,SpecBlinkCursPoint)
									NCellTrialTimeBlinkMat=NCellTrialTimeBlinkMat+1;
									CellTrialTimeBlinkMat=[CellTrialTimeBlinkMat;[SpecCell SpecTrial EyeCorrStart EyeCorrEnd]];
									if PlotBlinkStatus
                                        figure(hBlinkFig); 
										%axis([ceil(NCorrPoints./2) NCorrPoints 1.1.*MinGlobalXCorrVec 1.1.*MaxGlobalXCorrVec])
                                        axis([1 NCorrPoints 1.1.*MinGlobalXCorrVec 1.1.*MaxGlobalXCorrVec])
										hold off	
										if MoreTop
											pause(1)		
										else
                                            pause(.001)
                                        end
                                        EgisRawVec(1)=SpecCell;
                                        EgisRawVec(2)=SpecTrial;
                                        set(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata',EgisRawVec);
                                        CellTrialVal=1+sum(NTrialsVec(1:SpecCell-1))+SpecTrial;
                                        set(hOpenAvgFile,'Value',CellTrialVal); %CellTrialVal
                                        EditEgisFigString=['EGIS File: ',ActFile,'; Cell: '  int2str(SpecCell),'; Trial: ',int2str(SpecTrial)];
                                        set(EditEgisFigHandleVec(1),'Name',EditEgisFigString);
                                        ActFileNo=1;
                                        set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',CalcAvgMat);
                                        emegs2d('PlotData');
								        pause(.001)
                                        Plot2dChanFigName=['Blink in Cell ',int2str(SpecCell),' and Trial ',int2str(SpecTrial),'.'];
                                        set(hPlot2dChanFig,'Name',Plot2dChanFigName);	
                                        set(hList(122),'Value',EyeCorrStart); 	        %MinPointSlider
                                        emegs2d('setMinPointSlider');
			                            set(hList(123),'Value',EyeCorrEnd); 	        %MaxPointSlider
			                            emegs2d('setMaxPointSlider');
                                        set(hList(132),'Value',SpecBlinkCursPoint); 	%SetCursorPoint
			                            emegs2d('setCursorPointSlider');
                                        WaitBat(PlotPauseStatus);
                                    end
                                end	%while (~isempty(TopThresXCorrVec) & MoreTop)	
							end %BlinkCorStatus
						end
						if ~PlotAvgEOGStatus
							AvgEEG=AvgEEG./NTrialsInCell;
							AvgHEOG(SpecCell,:)=AvgHEOG(SpecCell,:)./NTrialsInCell;
							AvgVLEOG(SpecCell,:)=AvgVLEOG(SpecCell,:)./NTrialsInCell;
							AvgVREOG(SpecCell,:)=AvgVREOG(SpecCell,:)./NTrialsInCell;
						end
					end %NCells
					%=================
					%First loop
					%=================
				elseif any([2 3 5 6 8 9]==EyeCorLoopIndex)
					%=================
					%Second and third loop
					%=================
					FSeekStatus=fseek(ReadAvgFid,LHdr,-1);				%Original EGIS in first loop; Old corrected in following loops
					if FSeekStatus==-1; error; end
					if any([2 5 8]==EyeCorLoopIndex)					%Subtraction and Polyfit loop		
						CorFid=fopen(CorFilePath,'w','b');				
						fwrite(CorFid,EgisHeader,'int8');				%Write corrected trials (.cor) into new corrected EGIS session file
						if SaveEyeStatus
							EyeFid=fopen(EyeFilePath,'w','b');
							fwrite(EyeFid,EgisHeader,'int8');
						end
					end
					for SpecCell=1:NCells
						NTrialsInCell=NTrialsVec(SpecCell);
						%NTrialsInCell=10;
						NPointsInCell=NPointsVec(SpecCell);
						if any([3,6,9]==EyeCorLoopIndex)
							ActZeroMat=zeros(NChan,NPointsInCell);	
							AvgRawEEG=ActZeroMat;
							AvgRawEEGTmp=ActZeroMat;
							AvgEyeEEG=ActZeroMat;
							AvgEyeEEGTmp=ActZeroMat;
							AvgCorEEG=ActZeroMat;
							AvgCorEEGTmp=ActZeroMat;
						end
						NPointsOnes=ones(1,NPointsInCell);
						EgisRawVec(1)=SpecCell;
						if EyeCorLoopIndex==2
							CellTrialTimeBlinkMat=CellTrialTimeBlinkMat
							SpecCell=SpecCell
							Tmp=[];
							if ~isempty(CellTrialTimeBlinkMat)
								Tmp=find(CellTrialTimeBlinkMat(:,1)==SpecCell);
							end
							if NCellTrialTimeBlinkMat==1
								TrialTimeBlinkMat=CellTrialTimeBlinkMat(2:4);
							else
								TrialTimeBlinkMat=CellTrialTimeBlinkMat(Tmp,2:4);
							end
                            TrialTimeBlinkMat=TrialTimeBlinkMat
							NTotBlinkPoints=length(Tmp)+sum(TrialTimeBlinkMat(:,3))-sum(TrialTimeBlinkMat(:,2));
							TotSubBEOGStart=1;
							TotSubEOG=zeros(1,NTotBlinkPoints);
							TotEOG=TotSubEOG;
							TotSubEEG=zeros(NChan,NTotBlinkPoints);
                            NTotBlinkPoints=NTotBlinkPoints
						elseif EyeCorLoopIndex==3
							TotSubBEOGStart=1;
						elseif EyeCorLoopIndex==5 | EyeCorLoopIndex==8
							TotSubEOG=zeros(1,NTrialsInCell.*NPointsInCell);
							TotEOG=TotSubEOG;
						end
						for SpecTrial=1:NTrialsInCell
							Message=char(BVHLine);
							if any([2 5 8]==EyeCorLoopIndex)
								Message=char(Message,'(Subtraction)');
							else
								Message=char(Message,'(Correction)');
							end
							Message=char(Message,'');
							Message=char(Message,['Loop ',int2str(LoopIndex),' of ',int2str(NLoops)]);
							Message=char(Message,['Cell ',int2str(SpecCell),' of ',int2str(NCells)]);
							Message=char(Message,['Trial ',int2str(SpecTrial),' of ',int2str(NTrialsInCell)]);
							if strcmp(computer,'MAC2')
                                set(hChildProgressMsgbox(2),'String',Message);
                            else
                                hChild2ProgressMsgbox=get(hChildProgressMsgbox(2),'Children');
                                set(hChild2ProgressMsgbox,'String',Message);
                            end
							pause(.001);
							[CalcAvgMat,Count]=fread(ReadAvgFid,[NChan,NPointsInCell],'int16'); %Original EGIS in first loop; Old corrected in following loops
							if Count~=DefCount; error; end
							for TimeInd=1:NPointsInCell
								CalcAvgMat(:,TimeInd)=CalcAvgMat(:,TimeInd).*ChanGainVec;
							end
							ActFileNo=1;
							set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',CalcAvgMat);
							%=============================================================
							%=======Subtract averaged EEG and EOG from raw EEG and EOG=======
							%=======Egis in first loop; old corrected in following loops=========
							%=============================================================
							if EyeCorLoopIndex==2	%Blink Correction
								if NCellTrialTimeBlinkMat==1
									if TrialTimeBlinkMat(1)==SpecTrial
										SpecBlinkIndVec=TrialTimeBlinkMat(1);
										EyeCorrStartVec=TrialTimeBlinkMat(2);
										EyeCorrEndVec=TrialTimeBlinkMat(3);
									else
										SpecBlinkIndVec=[];
									end
								else
									SpecBlinkIndVec=find(TrialTimeBlinkMat(:,1)==SpecTrial);
									EyeCorrStartVec=TrialTimeBlinkMat(SpecBlinkIndVec,2);
									EyeCorrEndVec=TrialTimeBlinkMat(SpecBlinkIndVec,3);
								end
								for SpecBlinkIndInd=1:length(SpecBlinkIndVec)
									EyeCorrStart=EyeCorrStartVec(SpecBlinkIndInd);
									EyeCorrEnd=EyeCorrEndVec(SpecBlinkIndInd);
									if  LeftRightVCorStatus==1  | LeftRightVCorStatus==3 %Left | Both
										LEOG=CalcAvgMat(VLEOGPair(1),EyeCorrStart:EyeCorrEnd)-CalcAvgMat(VLEOGPair(2),EyeCorrStart:EyeCorrEnd); %VLEOG
									end
									if LeftRightVCorStatus==2 | LeftRightVCorStatus==3 %Right | Both
										REOG=CalcAvgMat(VREOGPair(1),EyeCorrStart:EyeCorrEnd)-CalcAvgMat(VREOGPair(2),EyeCorrStart:EyeCorrEnd); %VREOG
									end
									if LeftRightVCorStatus==1
 										SubBEOG=LEOG-AvgVREOG(SpecCell,EyeCorrStart:EyeCorrEnd);
										BEOG=LEOG;
									elseif  LeftRightVCorStatus==2
										SubBEOG=REOG-AvgVLEOG(SpecCell,EyeCorrStart:EyeCorrEnd);
										BEOG=REOG;
									elseif  LeftRightVCorStatus==3
										SubBEOG=((LEOG-AvgVLEOG(SpecCell,EyeCorrStart:EyeCorrEnd))+(REOG-AvgVREOG(SpecCell,EyeCorrStart:EyeCorrEnd)))./2;
										BEOG=(LEOG+REOG)./2;
									end
									TotSubBEOGEnd=TotSubBEOGStart+EyeCorrEnd-EyeCorrStart;
									TotSubEOG(TotSubBEOGStart:TotSubBEOGEnd)=SubBEOG;
									TotEOG(TotSubBEOGStart:TotSubBEOGEnd)=BEOG;
 									SubEEG=CalcAvgMat(:,EyeCorrStart:EyeCorrEnd)-AvgEEG(:,EyeCorrStart:EyeCorrEnd);
									%==========Do not subtract averaged EEG from special points (intervals) given with NoSubAvgEEGIndVec e.g. [101:151]==========
									if ~isempty(NoSubAvgEEGIndVec)
										SubEEG(:,NoSubAvgEEGIndVec)=CalcAvgMat(:,NoSubAvgEEGIndVec);
									end
									%=============================================================================================================================
%Temporary
% 									SubEEG=CalcAvgMat(:,EyeCorrStart:EyeCorrEnd);
% 									%Subtract baseline
% 									for ChanInd=1:NChan
% 										SubEEG(ChanInd,:)=SubEEG(ChanInd,:)-mean(SubEEG(ChanInd,:));
% 									end
% size(SubEEG)
% size(TotSubEEG(:,TotSubBEOGStart:TotSubBEOGEnd))
									TotSubEEG(:,TotSubBEOGStart:TotSubBEOGEnd)=SubEEG;
									TotSubBEOGStart=TotSubBEOGEnd+1;
								end
							elseif EyeCorLoopIndex==5 | EyeCorLoopIndex==8	%no blink correction
								if EyeCorLoopIndex==5		%Vertical Correction
									if  LeftRightVCorStatus==1  | LeftRightVCorStatus==3 %Left | Both
										LEOG=CalcAvgMat(VLEOGPair(1),:)-CalcAvgMat(VLEOGPair(2),:); %VLEOG
									end
									if LeftRightVCorStatus==2 | LeftRightVCorStatus==3 %Right | Both
										REOG=CalcAvgMat(VREOGPair(1),:)-CalcAvgMat(VREOGPair(2),:); %RLEOG
									end
									if LeftRightVCorStatus==1
										EOG=LEOG;
										AvgVEOG=AvgVLEOG;
									elseif  LeftRightVCorStatus==2
										EOG=REOG;
										AvgVEOG=AvgVREOG;
									elseif  LeftRightVCorStatus==3
										EOG=(LEOG+REOG)./2;
										AvgVEOG=(AvgVLEOG+AvgVREOG)./2;
									end
									TotSubEOG((SpecTrial-1).*NPointsInCell+1:SpecTrial.*NPointsInCell)=EOG-AvgVEOG(SpecCell,:);
									TotEOG((SpecTrial-1).*NPointsInCell+1:SpecTrial.*NPointsInCell)=EOG;
									ColorString='b';
								elseif EyeCorLoopIndex==8	 %Horizontal Correction
									EOG=CalcAvgMat(HEOGPair(1),:)-CalcAvgMat(HEOGPair(2),:); %HEOG
									TotSubEOG((SpecTrial-1).*NPointsInCell+1:SpecTrial.*NPointsInCell)=EOG-AvgHEOG(SpecCell,:);
									TotEOG((SpecTrial-1).*NPointsInCell+1:SpecTrial.*NPointsInCell)=EOG;
									ColorString='r';
								end
								if PlotAvgEOGStatus
									figure(hAvgEOGFig)
									plot(TotEOG,ColorString); 
									hold on
									plot(TotSubEOG,[ColorString '--']); 
									pause(.1)
								end
								SubEEG=CalcAvgMat-AvgEEG;
								%==========Do not subtract averaged EEG from special points (intervals) given with NoSubAvgEEGIndVec e.g. [101:151]==========
								if ~isempty(NoSubAvgEEGIndVec)
									SubEEG(:,NoSubAvgEEGIndVec)=CalcAvgMat(:,NoSubAvgEEGIndVec);
								end
								%=============================================================================================================================
% 								%Subtract baseline
% 								for ChanInd=1:NChan
% 									SubEEG(ChanInd,:)=SubEEG(ChanInd,:)-mean(SubEEG(ChanInd,:));
% 								end
								for TimeInd=1:NPointsInCell
									SubEEG(:,TimeInd)=SubEEG(:,TimeInd)./ChanGainVec;
								end
								fwrite(TotSubFid,SubEEG','int16');	%Write TotSubEEG in NPoints x NChan format !!!!	
% 								TotSubEEG(:,(SpecTrial-1).*NPoints+1:SpecTrial.*NPoints)=SubEEG;
							end %if EyeCorLoopIndex==2 elseif EyeCorLoopIndex==5 | EyeCorLoopIndex==8
							%==============================================
							%===End of subtraction loop; jump to coeff loop====
							%==============================================
							%==============================================
							%============Correction Loops===================
							%==============================================
							if any([3,6,9]==EyeCorLoopIndex)
								if EyeCorLoopIndex==6 | EyeCorLoopIndex==9
									EyeCorrStartVec=1; EyeCorrEndVec=NPointsInCell; SpecBlinkIndVec=1;
								elseif EyeCorLoopIndex==3
									if NCellTrialTimeBlinkMat==1
										if TrialTimeBlinkMat(1)==SpecTrial
											SpecBlinkIndVec=TrialTimeBlinkMat(1);
											EyeCorrStartVec=TrialTimeBlinkMat(2);
											EyeCorrEndVec=TrialTimeBlinkMat(3);
										else
											SpecBlinkIndVec=[];
										end
									else
										SpecBlinkIndVec=find(TrialTimeBlinkMat(:,1)==SpecTrial);
										EyeCorrStartVec=TrialTimeBlinkMat(SpecBlinkIndVec,2);
										EyeCorrEndVec=TrialTimeBlinkMat(SpecBlinkIndVec,3);
									end
								end
								if ~isempty(SpecBlinkIndVec)
									EOGCorMat=zeros(NChan,NPointsInCell);
									for SpecBlinkIndInd=1:length(SpecBlinkIndVec)
										EyeCorrStart=EyeCorrStartVec(SpecBlinkIndInd);
										EyeCorrEnd=EyeCorrEndVec(SpecBlinkIndInd);
								 		if EyeCorLoopIndex==6 | EyeCorLoopIndex==9
% 											EOGTmp=TotSubEOG((SpecTrial-1).*NPointsInCell+1:SpecTrial.*NPointsInCell);
											EOGTmp=TotEOG((SpecTrial-1).*NPointsInCell+1:SpecTrial.*NPointsInCell);
										elseif EyeCorLoopIndex==3
											TotSubBEOGEnd=TotSubBEOGStart+EyeCorrEnd-EyeCorrStart;
% 											EOGTmp=TotSubEOG(TotSubBEOGStart:TotSubBEOGEnd);
											EOGTmp=TotEOG(TotSubBEOGStart:TotSubBEOGEnd);
											TotSubBEOGStart=TotSubBEOGEnd+1;
										end
										OnesTmp=ones(1,EyeCorrEnd-EyeCorrStart+1);
										for ChanInd=1:NChan	
											EOGCorMat(ChanInd,EyeCorrStart:EyeCorrEnd)=polyval(PolyCoeffMat(EyeCorLoopIndex./3,ChanInd,:),EOGTmp);
% 											MeanVec=mean(CalcAvgMat(ChanInd,EyeCorrStart:EyeCorrEnd));
% 											EOGCorMat(ChanInd,EyeCorrStart:EyeCorrEnd)=EOGCorMat(ChanInd,EyeCorrStart:EyeCorrEnd)+OnesTmp.*MeanVec;
										end
									end
									if SaveEyeStatus
										SaveEyeMat=EOGCorMat;
										for TimeInd=1:NPointsInCell
											SaveEyeMat(:,TimeInd)=EOGCorMat(:,TimeInd)./ChanGainVec;
										end
										fwrite(EyeFid,SaveEyeMat,'int16');
									end
% 									CorEEGMat(sum(NTrialsVec(1:SpecCell-1))+SpecTrial,:,:)=EOGCorMat;
									if PlotCorStatus
										ActFileNo=2;
										set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',EOGCorMat);
										ActFileNo=3;
										set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',CalcAvgMat-EOGCorMat);
										if EyeCorLoopIndex==3
											Plot2dChanFigName=['Trial Data; 1: Raw; 2: Blink; 3: Corrected; Cell: ',int2str(SpecCell),'; Trial: '  int2str(SpecTrial),'.'];
										elseif EyeCorLoopIndex==6
											Plot2dChanFigName=['Trial Data; 1: Raw; 2: Vert.; 3: Corrected; Cell: ',int2str(SpecCell),'; Trial: '  int2str(SpecTrial),'.'];
										elseif EyeCorLoopIndex==9
											Plot2dChanFigName=['Trial Data; 1: Raw; 2: Horiz.; 3: Corrected; Cell: ',int2str(SpecCell),'; Trial: '  int2str(SpecTrial),'.'];
										end
										emegs2d('PlotData');
										set(hPlot2dChanFig,'Name',Plot2dChanFigName);
										WaitBat(PlotPauseStatus);
									end
									AvgRawEEG=AvgRawEEG+CalcAvgMat;
									if PlotCorAvgStatus
										AvgRawEEGTmp=((SpecTrial-1).*AvgRawEEGTmp+CalcAvgMat)./SpecTrial;
									end
									CalcAvgMat=CalcAvgMat-EOGCorMat;
									AvgCorEEG=AvgCorEEG+CalcAvgMat;
									AvgEyeEEG=AvgEyeEEG+EOGCorMat;
									if PlotCorAvgStatus
										MinAmp=get(hList(52),'Value');
										MinAmpVec=get(hList(52),'Userdata');
										MinAmpVecAvg=MinAmpVec;
										MinAmpAvg=MinAmp./sqrt(SpecTrial);
										MinAmpVecAvg(Domain)=MinAmpAvg;
										MaxAmp=get(hList(53),'Value');
										MaxAmpVec=get(hList(52),'Userdata');
										MaxAmpVecAvg=MaxAmpVec;
										MaxAmpAvg=MaxAmp./sqrt(SpecTrial);
										MaxAmpVecAvg(Domain)=MaxAmpAvg;
										set(hList(52),'Value',MinAmpAvg,'Userdata',MinAmpVecAvg,'String',sprintf('%g',round(MinAmpAvg*DecIncAmpTmp)/DecIncAmpTmp));  
										set(hList(53),'Value',MaxAmpAvg,'Userdata',MaxAmpVecAvg,'String',sprintf('%g',round(MaxAmpAvg*DecIncAmpTmp)/DecIncAmpTmp));  
										if EyeCorLoopIndex==3
											Plot2dChanFigName=['Tmp. Averaged Data; 1: Raw; 2: Blink; 3: Corrected; Cell ',int2str(SpecCell),'; Trial '  int2str(SpecTrial),'.'];
										elseif EyeCorLoopIndex==6
											Plot2dChanFigName=['Tmp. Averaged Data; 1: Raw; 2: Vert.; 3: Corrected; Cell ',int2str(SpecCell),'; Trial '  int2str(SpecTrial),'.'];
										elseif EyeCorLoopIndex==9
											Plot2dChanFigName=['Tmp. Averaged Data; 1: Raw; 2: Horiz.; 3: Corrected; Cell ',int2str(SpecCell),'; Trial '  int2str(SpecTrial),'.'];
										end
										AvgCorEEGTmp=((SpecTrial-1).*AvgCorEEGTmp+CalcAvgMat)./SpecTrial;
										AvgEyeEEGTmp=((SpecTrial-1).*AvgEyeEEGTmp+EOGCorMat)./SpecTrial;
										ActFileNo=1;
										set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',AvgRawEEGTmp);
										ActFileNo=2;
 										set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',AvgEyeEEGTmp);
										ActFileNo=3;
										set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',AvgCorEEGTmp);
										emegs2d('PlotData');
										set(hPlot2dChanFig,'Name',Plot2dChanFigName);
										WaitBat(PlotPauseStatus);
										set(hList(52),'Value',MinAmp,'Userdata',MinAmpVec,'String',sprintf('%g',round(MinAmp*DecIncAmpTmp)/DecIncAmpTmp));  
										set(hList(53),'Value',MaxAmp,'Userdata',MaxAmpVec,'String',sprintf('%g',round(MaxAmp*DecIncAmpTmp)/DecIncAmpTmp));  
									end
								else		%if ~isempty(SpecBlinkIndVec)
									if SaveEyeStatus
										fwrite(EyeFid,ActZeroMat,'int16');	%Write zeros in trials whithout blink artifact
									end
								end 		%if ~isempty(SpecBlinkIndVec)
							
								%=======Plot averaged raw, eye and corrected data==================
								if SpecTrial==NTrialsInCell & PlotCorCellAvgStatus
									AvgRawEEG=AvgRawEEG./NTrialsInCell;
									AvgEyeEEG=AvgEyeEEG./NTrialsInCell;
									AvgCorEEG=AvgCorEEG./NTrialsInCell;
									
									if EyeCorLoopIndex==3
										Plot2dChanFigName=['Averaged Data; 1: Raw; 2: Blink; 3: Corrected; Cell ',int2str(SpecCell),';'];
									elseif EyeCorLoopIndex==6
										Plot2dChanFigName=['Averaged Data; 1: Raw; 2: Vert.; 3: Corrected; Cell ',int2str(SpecCell),';'];
									elseif EyeCorLoopIndex==9
										Plot2dChanFigName=['Averaged Data; 1: Raw; 2: Horiz.; 3: Corrected; Cell ',int2str(SpecCell),'; '];
									end
									ActFileNo=1;
									set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',AvgRawEEG);
									ActFileNo=2;
									set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',AvgEyeEEG);
									ActFileNo=3;
									set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',AvgCorEEG);
									emegs2d('PlotData');
									set(hPlot2dChanFig,'Name',Plot2dChanFigName);
									if EyeCorLoopIndex~=9; WaitBat(PlotPauseStatus); end
								end
								%==============================================
								SaveCorMat=CalcAvgMat;
								for TimeInd=1:NPointsInCell
									SaveCorMat(:,TimeInd)=SaveCorMat(:,TimeInd)./ChanGainVec;
								end
								fwrite(CorFid,SaveCorMat,'int16');	%Corrected Data
							end %if any([3,6,9]==EyeCorLoopIndex); Correction Loop
							pause(.001)
							%==============================================
						end %Trials
						%==============================================
						%============Correction Coeff Loops=============
						%==============================================
						if any([2,5,8]==EyeCorLoopIndex)
						
							[SortTotSubEOGVal,SortTotSubEOGInd]=sort(TotSubEOG);
							[SortSortTotSubEOGIndVal,SortSortTotSubEOGIndInd]=sort(SortTotSubEOGInd);
							
							if EyeCorLoopIndex~=2
								fclose(TotSubFid);					%Close from writing
								TotSubFid=fopen(TotSubFilePath,'r','b');	%Open to read
								TotSubEEGChanVec=zeros(1,NTrialsInCell.*NPointsInCell);
								SortTotSubEEGChanVec=TotSubEEGChanVec;
								NSeekPoints=NPointsInCell.*2;
								NSeekTrials=NSeekPoints.*(NChan-1);
							end
							for ChanInd=1:NChan
								Message=char(BVHLine);
								Message=char(Message,'(Correlation)');
								Message=char(Message,'');
								Message=char(Message,['Loop ',int2str(LoopIndex),' of ',int2str(NLoops)]);
								Message=char(Message,['Cell ',int2str(SpecCell),' of ',int2str(NCells)]);
								Message=char(Message,['Channel ',int2str(ChanInd),' of ',int2str(NChan)]);
								if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
                                    set(hChildProgressMsgbox(2),'String',Message);
                                else
                                    hChild2ProgressMsgbox=get(hChildProgressMsgbox(2),'Children');
                                    set(hChild2ProgressMsgbox,'String',Message);
                                end
								pause(.001);
								if EyeCorLoopIndex==2
									TotSubEEGChanVec=TotSubEEG(ChanInd,:);
								else
									fseek(TotSubFid,(ChanInd-1).*NSeekPoints,-1);
									for TrialInd=1:NTrialsInCell;
										TotSubEEGChanVec((TrialInd-1).*NPointsInCell+1:TrialInd.*NPointsInCell)=fread(TotSubFid,NPointsInCell,'int16');
										if  TrialInd<NTrialsInCell;
											FSeekStatus=fseek(TotSubFid,NSeekTrials,0);
											if FSeekStatus==-1; error('fseek error'); end
										end
									end
									TotSubEEGChanVec=TotSubEEGChanVec.*ChanGainVec(ChanInd);
								end
								SortTotSubEEGChanVec=TotSubEEGChanVec(SortTotSubEOGInd);
 								p=polyfit(SortTotSubEOGVal,SortTotSubEEGChanVec,PolyfitDeg);
								PolyCoeffMat((EyeCorLoopIndex+1)./3,ChanInd,:)=p;
								if PlotPolyFitStatus & round(ChanInd./PlotPolyFitChanStep)==ChanInd./PlotPolyFitChanStep
									figure(hPolyFitFig);
									p=polyfit(SortTotSubEEGChanVec,SortTotSubEOGVal,PolyfitDeg);
									EEGTmp=polyval(p,SortTotSubEEGChanVec);
									set(hPolyFitFig,'Name',['Polyfit of degree: ',int2str(PolyfitDeg),'; Channel: ',int2str(ChanInd),';']);
									plot(EEGTmp,'g'); 
									hold on
									plot(SortTotSubEOGVal,'b'); 
									plot(SortTotSubEEGChanVec,'r'); 
									title([' p: ' num2str(p(1)) ]);
									pause(.01)
									hold off
								end
							end	
						end	%if any([2,5,8]==EyeCorLoopIndex); Correction Loop 
						%==============================================
						%==============================================
					end %NCell
				end	%if any([1 4 7]==EyeCorLoopIndex)  elseif any([2 3 5 6 8 9]==EyeCorLoopIndex)
				if any([3 6 9]==EyeCorLoopIndex)
					fclose(ReadAvgFid);
					fclose(CorFid);
					if SaveEyeStatus; fclose(EyeFid); end
					fclose(TotSubFid);	%Close from reading
					if ~SaveCorStatus & LoopIndex./3==2
						fprintf('Delete '); fprintf(CorFilePathOld);
						delete([CorFilePathOld]); %Delete second last correction file
					end
					CorFilePathOld=CorFilePath;
				end
				%=================
				%=================
			end %for  EyeCorLoopIndex=StartEyeCorLoopIndex:EndEyeCorLoopIndex	
			close(hProgressMsgbox);
			delete([TotSubFilePath]); %Delete temporary file
			if ~SaveCorStatus
				delete([ActFilePath]); %Delete original file
				[ActFile,ActPath]=SepFilePath(ActFilePath);
				NewFile=['"' ActFile '"'];
				OldFilePath=['"' CorFilePath '"'];
				applescript('arename', 'itemName', OldFilePath, 'newName', NewFile);
			end
			if SavePccStatus
				PolyCoeffFid=fopen(PolyCoeffFilePath,'w','b');
				for LoopInd=1:3
					for PolyInd=1:PolyfitDeg+1
						fprintf(PolyCoeffFid,'%g\t',PolyCoeffMat(LoopInd,:,PolyInd));
						fprintf(PolyCoeffFid,'\n');
					end
					fprintf(PolyCoeffFid,'\n\n');
				end
				fclose(PolyCoeffFid);
			end
		end %if strcmp(action,'RunCalcEyeCorrEgisData')
		if EgisEyeCorrBatchFileNo>0	%Batch
			FileMat=get(hList(127),'Userdata')
			[NFiles,NonUse]=size(FileMat);
			if EgisEyeCorrBatchFileNo==NFiles
				return;	%end batch blink and eye movement correction
			end
			EgisEyeCorrBatchFileNo=EgisEyeCorrBatchFileNo+1;
			set(hList(127),'Value',EgisEyeCorrBatchFileNo); 
			FilePath=FileMat(EgisEyeCorrBatchFileNo,:);
			set(hList(82),'Value',1); % hOpenAvgFile=hList(82); CellSubjectVal==file + CellNo
			emegs2d('OpenAvgFile'); 
			ActFilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
			[ActFile,ActPath]=SepFilePath(ActFilePath);
			EditEgisFigString=['EGIS File: ',ActFile,'; Cell: 1 ; Trial: 1'];
            hEditEgisFig=EditEgisFigHandleVec(1);
			set(hEditEgisFig,'Name',EditEgisFigString);
			figure(hEditEgisFig);
			emegs2d('RunCalcEyeCorrEgisData')
		end
	end %if strcmp(action,'SetBlinkCorrEgisData') | strcmp(action,'RunCalcEyeCorrEgisData')
	%======================================================================================
	if SpecCell==1
		set(EditEgisFigHandleVec(24),'Enable','off'); %LastCell
	else
		set(EditEgisFigHandleVec(24),'Enable','on'); %LastCell
	end
	if NCells==SpecCell
		set(EditEgisFigHandleVec(23),'Enable','off'); %NextCell
	else
		set(EditEgisFigHandleVec(23),'Enable','on'); %NextCell
	end
	AutoStatus=get(EditEgisFigHandleVec(35),'Value');		%hCalcEditEgisDataAutoTrial
	GoodStatus=get(EditEgisFigHandleVec(36),'Value');		%hCalcEditEgisDataAutoGoodTrial
	BadStatus=get(EditEgisFigHandleVec(37),'Value');		%hCalcEditEgisDataAutoBadTrial
	QuestStatus=get(EditEgisFigHandleVec(38),'Value');		%hCalcEditEgisDataAutoQuestTrial
	
	if ~strcmp(action,'TestNextLastCalcEditEgisDataTrialStatus')	
		if strcmp(action,'CalcEditEgisDataGoodTrial')
			LSpecCellVec(SpecTrial)=1;
		elseif strcmp(action,'CalcEditEgisDataBadTrial')
			LSpecCellVec(SpecTrial)=2;
		elseif strcmp(action,'CalcEditEgisDataQuestTrial')
			LSpecCellVec(SpecTrial)=0;	
		end	
		if ~AutoStatus & ~strcmp(action,'CalcEditEgisDataFirstTrial') & ~strcmp(action,'CalcEditEgisDataNextTrial') & ~strcmp(action,'CalcEditEgisDataLastTrial')
			return;
		end
	end
	
	LastTrialStatus=1; 
	NextTrialStatus=1; 
	TestNextCalcEditEgisDataTrialStatus=0;
	TestLastCalcEditEgisDataTrialStatus=0;
	if strcmp(action,'TestNextLastCalcEditEgisDataTrialStatus'); 
		TestNextCalcEditEgisDataTrialStatus=1; 
		TestLastCalcEditEgisDataTrialStatus=1; 
	end
	if ~strcmp(action,'CalcEditEgisDataFirstTrial') 
		if strcmp(action,'CalcEditEgisDataNextTrial')
			TestNextCalcEditEgisDataTrialStatus=1;
		end
		if strcmp(action,'CalcEditEgisDataLastTrial')
			TestLastCalcEditEgisDataTrialStatus=1; 
		end
		if AutoStatus & ~strcmp(action,'CalcEditEgisDataLastTrial')
			TestNextCalcEditEgisDataTrialStatus=1;
		end
	end
	if TestNextCalcEditEgisDataTrialStatus
		if SpecTrial<NTrialsVec(SpecCell)
			if GoodStatus
				TrialIndVec=find(LSpecCellVec(SpecTrial+1:NTrialsVec(SpecCell))==1);
			elseif BadStatus
				TrialIndVec=find(LSpecCellVec(SpecTrial+1:NTrialsVec(SpecCell))==2);
			elseif QuestStatus
				TrialIndVec=find(LSpecCellVec(SpecTrial+1:NTrialsVec(SpecCell))==0);
			else
				TrialIndVec=[1:NTrialsVec(SpecCell)-SpecTrial];
			end
			if ~isempty(TrialIndVec)
				TrialInd=SpecTrial+TrialIndVec(1);
				if length(TrialIndVec)==1; NextTrialStatus=0; end
			else
				TrialInd=0;
			end
		else
			TrialInd=0;
		end
		if TrialInd==0; NextTrialStatus=0; end
	end
	if TestLastCalcEditEgisDataTrialStatus 
		if SpecTrial>1
			if GoodStatus
				TrialIndVec=find(LSpecCellVec(1:SpecTrial-1)==1);			
			elseif BadStatus
				TrialIndVec=find(LSpecCellVec(1:SpecTrial-1)>1);			
			elseif QuestStatus
				TrialIndVec=find(LSpecCellVec(1:SpecTrial-1)==0);			
			else
				TrialIndVec=[1:SpecTrial-1];
			end
			if ~isempty(TrialIndVec)
				TrialInd=TrialIndVec(length(TrialIndVec));
				if length(TrialIndVec)==1; LastTrialStatus=0; end
			else
				TrialInd=0;
			end
		else
			TrialInd=0;
		end
		if TrialInd==0; LastTrialStatus=0; end
	end
	if strcmp(action,'TestNextLastCalcEditEgisDataTrialStatus') & TrialInd~=0 & NextTrialStatus==0 & LastTrialStatus==0
		action='Go2TrialIndTrial';
	end		
	if strcmp(action,'CalcEditEgisDataFirstTrial')
		TrialInd=SpecTrial;
		if SpecTrial==NTrialsVec(SpecCell); NextTrialStatus=0; else; NextTrialStatus=1; end
		if SpecTrial==1; LastTrialStatus=0; else; LastTrialStatus=1; end
	end
	if ~strcmp(action,'TestNextLastCalcEditEgisDataTrialStatus') &  TrialInd~=0	
		NextEditVal=LSpecCellVec(TrialInd);
		if 	NextEditVal==-1; NextEditValColor=[0 0 0]; 	%Not
		elseif NextEditVal==1; NextEditValColor=[0 .5 0]; 	%Good
		elseif NextEditVal>1; NextEditValColor=[1 0 0]; 	%Bad
		elseif NextEditVal==0; NextEditValColor=[0 0 1]; 	%Quest
		else	NextEditValColor=[1 1 1]; 
		end
		LSpecCellMat(:,1)=LSpecCellVec;
		set(hCalcEditEgisData,'Userdata',LSpecCellMat);
		for FileInd=1:NFiles
			ActFileNo=FileNoVec(FileInd);
			set(hList(1),'Value',ActFileNo); 
			emegs2d('setActFileNo');
			EgisRawVec=get(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata');
			EgisRawVec(2)=TrialInd;
			set(hList(NListHdr+(ActFileNo-1).*50+32),'Userdata',EgisRawVec);
			CellTrialVal=1+sum(NTrialsVec(1:SpecCell-1))+TrialInd;
			set(hOpenAvgFile,'Value',CellTrialVal); %CellTrialVal
			if FileInd==NFiles
				emegs2d('OpenAvgFile');	
			else
				emegs2d('OpenAvgFileNoPlot');
			end
		end
		set(EditEgisFigHandleVec(25),'BackgroundColor',NextEditValColor); %GivenStatus
		SpecTrial=TrialInd;
	end
	if ~strcmp(action,'TestNextLastCalcEditEgisDataTrialStatus') 
		EditEgisFigString=['EGIS File: ',ActFile,'; Cell: '  int2str(SpecCell),'; Trial: ',int2str(SpecTrial)];
		set(EditEgisFigHandleVec(1),'Name',EditEgisFigString);
		figure(EditEgisFigHandleVec(1))
	end
	if LastTrialStatus; 
		set(EditEgisFigHandleVec(34),'Enable','on'); %Enable
	else
		set(EditEgisFigHandleVec(34),'Enable','off'); %Enable
	end
	if NextTrialStatus
		set(EditEgisFigHandleVec(33),'Enable','on'); %Enable
	else
		set(EditEgisFigHandleVec(33),'Enable','off'); %Enable
	end
	
	%=============================================================================
	%=============================================================================
	%=============================================================================
	%=============================================================================	
elseif 	strcmp(action,'CalcPolyActAllDeg1') | ...
      strcmp(action,'CalcPolyActAllDeg2') | ...
      strcmp(action,'CalcPolyActAllDeg3') | ...
      strcmp(action,'CalcPolyActBaseDeg1') | ...
      strcmp(action,'CalcPolyActBaseDeg2') | ...
      strcmp(action,'CalcPolyActBaseDeg3') | ...
      strcmp(action,'CalcPolyActFileDeg1') | ...
      strcmp(action,'CalcPolyActFileDeg2') | ...
      strcmp(action,'CalcPolyActFileDeg3') | ...
      strcmp(action,'CalcPolyAllAllDeg1') | ...
      strcmp(action,'CalcPolyAllAllDeg2') | ...
      strcmp(action,'CalcPolyAllAllDeg3') | ...
      strcmp(action,'CalcPolyAllBaseDeg1') | ...
      strcmp(action,'CalcPolyAllBaseDeg2') | ...
      strcmp(action,'CalcPolyAllBaseDeg3') | ...
      strcmp(action,'CalcPolyAllFileDeg1') | ...
      strcmp(action,'CalcPolyAllFileDeg2') | ...
	strcmp(action,'CalcPolyAllFileDeg3')
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
   	NUsedFiles=length(FileNoVec);
   
   	if strcmp(action,'CalcPolyActAllDeg1')  | ...
         		strcmp(action,'CalcPolyActAllDeg2')  | ...
			strcmp(action,'CalcPolyActAllDeg3')  | ...
			strcmp(action,'CalcPolyAllAllDeg1')  | ...
			strcmp(action,'CalcPolyAllAllDeg2')  | ...
			strcmp(action,'CalcPolyAllAllDeg3')
      
      		MinPolyPoint=1;
      		MaxPolyPoint=get(hList(NListHdr+3),'Userdata');%NPoints
     		PolyIntMat=[MinPolyPoint MaxPolyPoint]';
      		NPolyInt=1;

   	elseif strcmp(action,'CalcPolyActBaseDeg1')  | ...
         		strcmp(action,'CalcPolyActBaseDeg2')  | ...
			strcmp(action,'CalcPolyActBaseDeg3')  | ...
			strcmp(action,'CalcPolyAllBaseDeg1')  | ...
			strcmp(action,'CalcPolyAllBaseDeg2')  | ...
			strcmp(action,'CalcPolyAllBaseDeg3')
      
      		MinPolyPoint=get(hList(58),'Value');	%MinBase
      		MaxPolyPoint=get(hList(59),'Value');	%MaxBase
      		PolyIntMat=[MinPolyPoint MaxPolyPoint]';
      		NPolyInt=1;
      
   	elseif strcmp(action,'CalcPolyActFileDeg1')  | ...
         		strcmp(action,'CalcPolyActFileDeg2')  | ...
			strcmp(action,'CalcPolyActFileDeg3')  | ...
			strcmp(action,'CalcPolyAllFileDeg1')  | ...
			strcmp(action,'CalcPolyAllFileDeg2')  | ...
			strcmp(action,'CalcPolyAllFileDeg3')
      
     		[File,Path]=uigetfile('*','Read polyfit intervals from file:');
		FilePath=[Path,File];
		if isempty(find(FilePath)); return; end;
		fid=fopen(FilePath,'r','b');
		PolyIntVec=fscanf(fid,'%g');
		[NPolyInt2,NoUse]=size(PolyIntVec);
		if (NPolyInt2./2-round(NPolyInt2./2))~=0;
			Message=char('Sorry,');
			Message=char(Message,' ');
			Message=char(Message,'the file');
			Message=char(Message,FilePath);
			Message=char(Message,'has to have an even number of elements !');
        		hmsgbox=msgbox(Message,'Info','help');
        		 return;
		else
			NPolyInt=NPolyInt2./2;
		end
		PolyIntMat=reshape(PolyIntVec,2,NPolyInt)
		fclose(fid);
   	end
   
   	NPointsTmpOld=0;
   	for i=1:NPolyInt
      		MinPolyTmp=PolyIntMat(1,i);
      		MaxPolyTmp=PolyIntMat(2,i);
      		NPointsTmpNew=NPointsTmpOld+MaxPolyTmp-MinPolyTmp+1;
     		x=zeros(1,NPointsTmpNew);
      		if i==1
        	 	x(1:NPointsTmpNew)=[MinPolyTmp:MaxPolyTmp];
      		else
        		x(1:NPointsTmpOld)=xTmp;
         		x(NPointsTmpOld+1:NPointsTmpNew)=[MinPolyTmp:MaxPolyTmp];
      		end
      		NPointsTmpOld=NPointsTmpNew;
      		xTmp=x;
   	end
   	NPolyPoints=NPointsTmpNew;
	hTopMenu=get(hList(65),'Userdata');
	hExportMenu=get(hTopMenu(3),'children');	
	hExportUserData=get(hExportMenu(1),'children'); 
	hUserDataInfo=get(hExportUserData(1),'children');
		
	if strcmp(action,'CalcPolyActAllDeg1')  | ...
		strcmp(action,'CalcPolyActAllDeg2')  | ...
      		strcmp(action,'CalcPolyActAllDeg3')  | ...
      		strcmp(action,'CalcPolyActBaseDeg1')  | ...
		strcmp(action,'CalcPolyActBaseDeg2')  | ...
      		strcmp(action,'CalcPolyActBaseDeg3')  | ...
     		strcmp(action,'CalcPolyActFileDeg1')  | ...
		strcmp(action,'CalcPolyActFileDeg2')  | ...
		strcmp(action,'CalcPolyActfileDeg3')

   		FileNoVec=FileNoVec(ActFileNo);
	end
	PolyfitDeg = eval(['[' action(length(action))' ']'],'-1');
  	 if NPolyPoints<PolyfitDeg
     		Message=char('Sorry,');
		Message=char(Message,' ');
		Message=char(Message,'the number of points must not be');
		Message=char(Message,'smaller than the chosen polyfit degree !');
		Message=char(Message,'');
		Message=char(Message,['Polyfit degree = ',int2str(PolyfitDeg),'; Number of points: ',int2str(NPolyPoints)]);
		hmsgbox=msgbox(Message,'Info !','help');
		return;
  	end
	for FileIndex=1:length(FileNoVec)
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		PolyAvgMat=CalcAvgMat;
		[NChan,NPoints]=size(CalcAvgMat);
		PolyCoeffMat=zeros(NChan,PolyfitDeg+1);
		xi=[1:NPoints];
		for ChanInd=1:NChan
			p=polyfit(x,CalcAvgMat(ChanInd,x),PolyfitDeg);
			PolyCoeffMat(ChanInd,:)=p;
			PolyAvgMat(ChanInd,:)=polyval(p,xi);
		end
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',PolyAvgMat);
		emegs2d('PlotData');
		
		set(hList(94),'Userdata',PolyCoeffMat);	%User data 
		UserDataInfoLabel=['Polyfit coefficients of data set number ',int2str(FileNoVec(FileIndex)),'.'];
		set(hUserDataInfo,'Label',UserDataInfoLabel);
		set(hExportUserData,'Enable','on');
		Message=char('Please use now "Export User Data"');
		Message=char(Message,'if you would like to export the polyfit coefficients.');
		Message=char(Message,'');Message=char(Message,'If not, press "Ok" to continue.');
		hmsgbox=msgbox(Message,'Info:','help');uiwait(hmsgbox);
		
		set(hList(94),'Userdata',PolyAvgMat);	%User data 
		UserDataInfoLabel=['Polyfit data of data set number ',int2str(FileNoVec(FileIndex)),'.'];
		set(hUserDataInfo,'Label',UserDataInfoLabel);
		Message=char('Please use now "Export User Data"');
		Message=char(Message,'if you would like to export the polyfit data.');
		Message=char(Message,'');Message=char(Message,'If not, press "Ok" to continue.');
		hmsgbox=msgbox(Message,'Info:','help');uiwait(hmsgbox);
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat-PolyAvgMat);
		
	end
	emegs2d('PlotData');
	
	%=============================================================================
	%=============================================================================
	
elseif  	strcmp(action,'CalcChanGroupLeftRightFrontBack') | ...
		strcmp(action,'CalcChanGroupLeftRightFrontBackAnd') | ...
		strcmp(action,'CalcChanGroupLeftRight') | ...
		strcmp(action,'CalcChanGroupFrontBack') | ...
		strcmp(action,'CalcChanGroupLeftRightBack') | ...
		strcmp(action,'CalcChanGroupLeftRightFront') | ...
		strcmp(action,'CalcChanGroupFrontBackLeft') | ...
		strcmp(action,'CalcChanGroupFrontBackRight') | ...
		strcmp(action,'CalcChanGroupOpen') | ...
		strcmp(action,'CalcChanGroupMean') | ...
		strcmp(action,'CalcChanGroupGP')

	hList=get(hPlot2dMenuFig,'Userdata');
	hTopMenu=get(hList(65),'Userdata');
	hCalcMenu=get(hTopMenu(4),'children');	
	hCalcChanGroup=hCalcMenu(17);
	hCalcChanGroupChildVec=get(hCalcChanGroup,'children');
	
	hExportMenu=get(hTopMenu(3),'children');	
	hExportUserData=get(hExportMenu(1),'children'); 
	hUserDataInfo=get(hExportUserData(1),'children');
	UserDataInfoLabel=get(hUserDataInfo,'Label');
	if ~(strcmp(action,'CalcChanGroupMean') | strcmp(action,'CalcChanGroupGP'))
		if strcmp(action,'CalcChanGroupLeftRightFrontBack') | ...
			strcmp(action,'CalcChanGroupLeftRightFrontBackAnd') | ...
			strcmp(action,'CalcChanGroupLeftRight') | ...
			strcmp(action,'CalcChanGroupFrontBack') | ...
			strcmp(action,'CalcChanGroupLeftRightBack') | ...
			strcmp(action,'CalcChanGroupLeftRightFront') | ...
			strcmp(action,'CalcChanGroupFrontBackLeft') | ...
			strcmp(action,'CalcChanGroupFrontBackRight'),
			
			EPosSpher=get(hList(3),'Userdata');
			[EPosCart]=change_sphere_cart(EPosSpher,[],1);
			if strcmp(action,'CalcChanGroupLeftRightFrontBack') | strcmp(action,'CalcChanGroupLeftRightFrontBackAnd')
				NGroup=0;NTotVec=0;GroupMat=[];
				for i=1:4
					if ~strcmp(action,'CalcChanGroupLeftRightFrontBackAnd')
						if i==1
							Vec=find(EPosCart(:,1)<0);
						elseif i==2
							Vec=find(EPosCart(:,1)>0);
						elseif i==3
							Vec=find(EPosCart(:,2)>0);
						elseif i==4
							Vec=find(EPosCart(:,2)<0);
						end
					else
						if i==1
							Vec=find(EPosCart(:,1)<0 & EPosCart(:,2)>0);
						elseif i==2
							Vec=find(EPosCart(:,1)<0 & EPosCart(:,2)<0);
						elseif i==3
							Vec=find(EPosCart(:,1)>0 & EPosCart(:,2)<0);
						elseif i==4
							Vec=find(EPosCart(:,1)>0 & EPosCart(:,2)>0);
						end
					end
					NVec=length(Vec);
					NTotVec=NTotVec+NVec;
					if NVec>0
						NGroup=NGroup+1;
						GroupMatTmp=NGroup.*ones(NVec,2);
						GroupMatTmp(:,2)=Vec;
						GroupMatNew=zeros(NTotVec,2);
						if isempty(GroupMat)
							GroupMat=GroupMatTmp;
						else
							if NTotVec>NVec
								GroupMatNew(1:NTotVec-NVec,:)=GroupMat;
								GroupMatNew(NTotVec-NVec+1:NTotVec,:)=GroupMatTmp;
							end
							GroupMat=GroupMatNew;
						end		
					end
				end
			else
				if strcmp(action,'CalcChanGroupLeftRight')
					AVec=find(EPosCart(:,1)<0);
					BVec=find(EPosCart(:,1)>0);
				elseif strcmp(action,'CalcChanGroupFrontBack')
					AVec=find(EPosCart(:,2)>0);
					BVec=find(EPosCart(:,2)<0);
				elseif strcmp(action,'CalcChanGroupLeftRightFront')
					AVec=find(EPosCart(:,1)<0 & EPosCart(:,2)>0);
					BVec=find(EPosCart(:,1)>0 & EPosCart(:,2)>0);
				elseif strcmp(action,'CalcChanGroupLeftRightBack')
					AVec=find(EPosCart(:,1)<0 & EPosCart(:,2)<0);
					BVec=find(EPosCart(:,1)>0 & EPosCart(:,2)<0);
				elseif strcmp(action,'CalcChanGroupFrontBackLeft')
					AVec=find(EPosCart(:,2)>0 & EPosCart(:,1)<0);
					BVec=find(EPosCart(:,2)<0 & EPosCart(:,1)<0);
				elseif strcmp(action,'CalcChanGroupFrontBackRight')
					AVec=find(EPosCart(:,2)>0 & EPosCart(:,1)>0);
					BVec=find(EPosCart(:,2)<0 & EPosCart(:,1)>0);
				end
				NA=length(AVec);
				NB=length(BVec);
				GroupMat=ones(length(AVec)+length(BVec),2);
				GroupMat(1:NA,2)=AVec;
				GroupMat(NA+1:NA+NB,2)=BVec;
				GroupMat(NA+1:NA+NB,1)=2.*ones(NB,1);
			end
		elseif strcmp(action,'CalcChanGroupOpen')
			GroupDefPath=which('12Groups129.txt')
			IndSepPathVec=findstr(GroupDefPath,filesep);
			if ~isempty(IndSepPathVec)	
				GroupDefPath=GroupDefPath(1:IndSepPathVec(length(IndSepPathVec)));
				GroupDef=[GroupDefPath,'*.txt'];
			else
				GroupDef='*.txt';
			end
			[GroupFile,GroupPath]=uigetfile(GroupDef,'Open group file (*.txt):');
			GroupFilePath=[GroupPath,GroupFile];
            if GroupFile==0; return; end
			GroupMat=ReadBem(GroupFilePath,1,'Matrix','Ascii');
		end
        if isempty(GroupMat); 
			Message=char('Sorry,');
			Message=char(Message,' ');
			Message=char(Message,'group matrix in file:');
			Message=char(Message,' ');
			Message=char(Message,GroupFilePath);
			Message=char(Message,' ')
			Message=char(Message,'is empty !');
			msgbox(Message,'Info !','help');
			return; 
		end
		SizeGroupMat=size(GroupMat);
		if SizeGroupMat(1)~=2 & SizeGroupMat(2)==2; GroupMat=GroupMat'; end
		SizeGroupMat=size(GroupMat);
		if SizeGroupMat(1)~=2; 
			Message=char('Sorry,')
			Message=char(Message,' ')
			Message=char(Message,'bad size of group matrix file.')
			msgbox(Message,'Info !','help')
			return; 
		end
		set(hCalcChanGroup,'Userdata',GroupMat);
		UserDataInfoLabel='Actual group matrix';
		set(hList(94),'Userdata',GroupMat');	%User data 
		set(hCalcChanGroupChildVec(1:2),'Enable','on');
		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;
				NSensorVec(NGroup)=length(GroupIndVec);
			end
		end
		Message=char(['Load ', int2str(NGroup),' groups !']);
		Message=char(Message,' ');
		for i=1:NGroup
			Message=char(Message,[' Group #',int2str(GroupNoVec(i)),'; ',int2str(NSensorVec(i)),' sensors.']);
			GroupIndVec=find(GroupMat(1,:)==GroupNoVec(i));
			Message=char(Message,[' Sensors:  ',int2str(GroupMat(2,GroupIndVec))]);
			Message=char(Message,'');
		end
		Message=char(Message,'(Change "Line Style" and "Line Width"');
		Message=char(Message,'in order to visualize channels groups)');
		Message=char(Message,'');
		msgbox(Message,'Info:','help');
		pause(3)
		emegs2d('setSensorLineColorGroups')
        hCalcChanGroupMean=findobj('Tag','CalcChanGroupMean');
        hCalcChanGroupGP=findobj('Tag','CalcChanGroupGP');
        set(hCalcChanGroupMean,'Enable','On');
        set(hCalcChanGroupGP,'Enable','On');
	elseif strcmp(action,'CalcChanGroupMean') | strcmp(action,'CalcChanGroupGP')
		ActFileNo=get(hList(1),'Userdata');
		NListHdr=get(hList(51),'Userdata');
		ActAvgMat=get(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata');
		GroupMat=get(hCalcChanGroup,'Userdata');
		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;
				NSensorVec(NGroup)=length(GroupIndVec);
			end
		end
		MinPoint=get(hList(54),'Value');
		MaxPoint=get(hList(55),'Value');
		NPointsTmp=MaxPoint-MinPoint+1;
		CalcMat=zeros(NGroup,NPointsTmp);
		for GroupInd=1:NGroup
			ChanIndVec=find(GroupMat(1,:)==GroupInd);
			if strcmp(action,'CalcChanGroupMean')
				CalcMat(GroupInd,:)=mean(ActAvgMat(GroupMat(2,ChanIndVec),:));
			elseif strcmp(action,'CalcChanGroupGP')
				CalcMat(GroupInd,:)=mean(ActAvgMat(GroupMat(2,ChanIndVec),:).^2);
			end
		end
		if strcmp(action,'CalcChanGroupGP')
			UserDataInfoLabel='Global Power of given groups of actual data set';
			Message='Calculation of global power done.';
			if ~all(NSensorVec==NSensorVec(1));
				Message=char(Message,'');
				Message=char(Message,'Remember:');
				Message=char(Message,'The number of sensors differs across groups ! ');
				Message=char(Message,'');
			end
		elseif strcmp(action,'CalcChanGroupMean')
			UserDataInfoLabel='Mean of given groups of actual data sets';
			Message='Calculation of mean done.';
		end
		Message=char(Message,'Please use "Export User Data"');
		Message=char(Message,'if you would like to export this data.');
		msgbox(Message,'Info:','help');
		set(hList(94),'Userdata',CalcMat);	%User data 
	end
	% User data Info %
	set(hUserDataInfo,'Label',UserDataInfoLabel);
	set(hExportUserData,'Enable','on');
	
	%=============================================================================	
	%=============================================================================	
elseif 	strcmp(action,'CalcUserFileAct') | ...
		strcmp(action,'CalcUserFileAll'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NFiles=length(FileNoVec);
	NListHdr=get(hList(51),'Userdata');
	CalcUserFilePath=which('CalcUserFile.m');
	UserFileFid=fopen(CalcUserFilePath,'r','b');	
	if UserFileFid==-1
		Message=char('Sorry,');
		Message=char(Message,'');
		Message=char(Message,'Can not find the file "CalcUserFile.m"');
		Message=char(Message,'in the Matlab search path.');
		hmsgbox=msgbox(Message,'Info','help'); 
		return;
	else
		fclose(UserFileFid);
	end
	
	if strcmp(action,'CalcUserFileAct')
		FileNoVec=FileNoVec(ActFileNo);
	end
	for FileIndex=1:length(FileNoVec)	
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		if isempty(CalcAvgMat)
			Message=char('Sorry,');
			Message=char(Message,'');
			Message=char(Message,'no data available.');
			Message=char(Message,'Please open a data set first.');
			hmsgbox=msgbox(Message,'Info','help'); 
			return;
		else
			SizeCalcAvgMat=size(CalcAvgMat);
			CalcAvgMat=CalcUserFile(CalcAvgMat); %CalcUserFile.m
			if SizeCalcAvgMat~=size(CalcAvgMat)
				Message=char('Sorry, ');
				Message=char(Message,'bad size of outgoing data matrix in "CalcUserFile.m".');
				Message=char(Message,'');
				Message=char(Message,'The outgoing data matrix must be the same ');
				Message=char(Message,'size as the incoming data matrix.');
				Message=char(Message,'');
				Message=char(Message,'Please check  "CalcUserFile.m". ');
				hmsgbox=msgbox(Message,'Info:','help'); 
				return;
			else
				set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat);
			end
		end
	end
	emegs2d('CalcFirst');
	emegs2d('PlotData');		
	%=============================================================================
	%=============================================================================
elseif 	strcmp(action,'CalcWave') | ...
	strcmp(action,'PlotAmpWave') | ...
	strcmp(action,'PlotPhaseWave'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	if strcmp(action,'CalcWave') 
		ActFileNo=get(hList(1),'Userdata');
		NListHdr=get(hList(51),'Userdata');
		AvgFileFormatVal=get(hList(NListHdr+(ActFileNo-1).*50+22),'Value');	%7==AppScads
		if AvgFileFormatVal~=7
			emegs2d('ClearAllFiles');
			emegs2d('chAppFileSCADS');
			FilePath=[];
		else
			FilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
		end
		[AwaFileMat,PwaFileMat]=WaveApp('InitializeMenu',FilePath)
	elseif strcmp(action,'PlotAmpWave') 
		emegs2d('chAmpWave');
		emegs2d('OpenAvgFile');	
	elseif strcmp(action,'PlotPhaseWave') 
		emegs2d('chPhaseWave');
		emegs2d('OpenAvgFile');	
	end
    %=============================================================================
	%=============================================================================	
elseif 	strcmp(action,'CalcDiffMenu')
        
    hList=get(hPlot2dMenuFig,'Userdata');
    MaxNFiles=hList(140);
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
    %====================================
    % The figure
	DiffFigPosVec=[.7 0 .3 .2];

   	hDiffMenuFig=figure('Tag','DiffMenuFig','MenuBar','none','Units','normal','Position',DiffFigPosVec, ...
	'Name','Difference Menu; Set ? - Set ? = Set ?','Color',[.99 .99 .99], ...
	'NumberTitle','off','Userdata',[]);
	%====================================
	% The Console frame
	FrameColor=[0 0.1 0.99];
   	hConsolFrame=uicontrol( ...
	'Style','frame', ...
	'Units','normalized', ...
	'Position',[0.02 0.02 .96 .96], ...
	'BackgroundColor',FrameColor);
	%====================================
	% The Axes
	hDiffAxes=axes('Position',[0 0 1 1],'Visible','off');
	%===========================================
	%===========================================
    NXButton=3;
    NYButton=MaxNFiles;
    DistLeft=0.05;
	DistRight=DistLeft;
	DistTop=0.05;
	DistBottom=0.05;
	DistXButton=DistLeft;
	DistYButton=DistLeft;
	btnWid=(1-(DistLeft+(DistXButton+NXButton).*DistXButton))./NXButton;
	btnHt=(1-DistBottom-(DistTop+(DistYButton+NYButton).*DistYButton))./NYButton;
	
    %==============================================================
    for XButton=1:3
        for YButton=1:MaxNFiles      
            ActFilePath=get(hList(NListHdr+(YButton-1).*50+4),'Userdata');
            [ActFile,ActPath]=SepFilePath(ActFilePath);
            if ActFile==0; ActFile='O'; end
            btnPos=[DistLeft+(XButton-1)*(DistXButton+btnWid) 1-(DistBottom+YButton*(DistYButton+btnHt)) btnWid btnHt];	
            callbackStr = 'emegs2d(''SetDiffMenu'')';
            h(XButton,YButton) = uicontrol( ...
                'Tag',[int2str(XButton),int2str(YButton)], ...
                'Style','push', ...
                'Units','normalized', ...
                'Callback',callbackStr, ...
                'Position',btnPos, ...
                'Horiz','left', ...
                'Foreground','black', ...
                'String',ActFile, ...
                'Enable','on');
        end
    end
   %=============================================================================	
elseif 	strcmp(action,'SetDiffMenu')
    
    hList=get(hPlot2dMenuFig,'Userdata');
    NListHdr=get(hList(51),'Userdata');
    FileNoVec=get(hList(56),'Userdata');
    XY=get(gco,'Tag')
    x=str2num(XY(1));
    y=str2num(XY(2));
    hDiffMenuFig = findobj('Tag','DiffMenuFig');
    DiffVec=get(hDiffMenuFig,'Userdata');  
    DiffVec(x)=y;
    if length(DiffVec)==1
        DiffMenuName=['Difference Menu; Set ',int2str(DiffVec(1)),' - Set ? = Set ?'];
    elseif length(DiffVec)==2 & DiffVec(1)==0
        DiffMenuName=['Difference Menu; Set ? - Set ',int2str(DiffVec(2)),' = Set ?'];    
    elseif length(DiffVec)==2
        DiffMenuName=['Difference Menu; Set ',int2str(DiffVec(1)),' - Set ',int2str(DiffVec(2)),' = Set ?'];   
    elseif length(DiffVec)==3 & DiffVec(1)==0  & DiffVec(2)==0
        DiffMenuName=['Difference Menu; Set ? - Set ? = Set ',int2str(DiffVec(3))];   
    elseif length(DiffVec)==3 & DiffVec(1)==0
        DiffMenuName=['Difference Menu; Set ? - Set ',int2str(DiffVec(2)),' = Set ',int2str(DiffVec(3))];   
    elseif length(DiffVec)==3 & DiffVec(2)==0
        DiffMenuName=['Difference Menu; Set ',int2str(DiffVec(1)),' - Set ? = Set ',int2str(DiffVec(3))];  
    else
        DiffMenuName=['Difference Menu; Set ',int2str(DiffVec(1)),' - Set ',int2str(DiffVec(1)),' = Set ',int2str(DiffVec(3))];
    end
    set(hDiffMenuFig,'Userdata',DiffVec,'Name',DiffMenuName);
    if length(DiffVec)~=3 | ~any(DiffVec); return; end
    FilePath1=get(hList(NListHdr+(DiffVec(1)-1).*50+4),'Userdata');
    [File1,Path1]=SepFilePath(FilePath1);
    AvgMat1=get(hList(NListHdr+(DiffVec(1)-1).*50+1),'Userdata');        
    AvgMat2=get(hList(NListHdr+(DiffVec(2)-1).*50+1),'Userdata');
    StdMat1=get(hList(NListHdr+(DiffVec(1)-1).*50+6),'Userdata');
    StdMat2=get(hList(NListHdr+(DiffVec(2)-1).*50+6),'Userdata');
    NTrialAvgVec1=get(hList(NListHdr+(DiffVec(1)-1).*50+5),'Userdata');
    NTrialAvgVec2=get(hList(NListHdr+(DiffVec(2)-1).*50+5),'Userdata');
    MedMedRawVec1=get(hList(NListHdr+(DiffVec(1)-1).*50+9),'Userdata');
    MedMedRawVec2=get(hList(NListHdr+(DiffVec(2)-1).*50+9),'Userdata'); 
    MedMedAvgVec1=get(hList(NListHdr+(DiffVec(1)-1).*50+10),'Userdata');
    MedMedAvgVec2=get(hList(NListHdr+(DiffVec(2)-1).*50+10),'Userdata');
    
    if isempty(AvgMat1) & isempty(AvgMat2); return; end
    if isempty(AvgMat1)
        AvgMat1=0.*AvgMat2;
        StdMat1=0.*StdMat2;
        NTrialAvgVec1=0.*NTrialAvgVec2;
        MedMedRawVec1=0.*MedMedRawVec2;
        MedMedAvgVec1=0.*MedMedAvgVec2;
    end
    if isempty(AvgMat2)
        AvgMat2=0.*AvgMat1;
        StdMat2=0.*StdMat1;
        NTrialAvgVec2=0.*NTrialAvgVec1;
        MedMedRawVec2=0.*MedMedRawVec1;
        MedMedAvgVec2=0.*MedMedAvgVec1;
    end
    set(hList(NListHdr+(DiffVec(3)-1).*50+1),'Userdata',AvgMat1-AvgMat2);
    set(hList(NListHdr+(DiffVec(3)-1).*50+24),'Userdata',AvgMat1-AvgMat2); 
    set(hList(NListHdr+(DiffVec(3)-1).*50+6),'Userdata',(StdMat1+StdMat2)./2);
    set(hList(NListHdr+(DiffVec(3)-1).*50+5),'Userdata',NTrialAvgVec1-NTrialAvgVec2);
   
    
    NMedMedRawVec1=length(MedMedRawVec1);
    NMedMedRawVec2=length(MedMedRawVec2);     
    DiffNNMedMedRawVec=NMedMedRawVec2-NMedMedRawVec1;
    if DiffNNMedMedRawVec~=0
        if DiffNNMedMedRawVec>0
            TmpMedMedRawVec1=zeros(NMedMedRawVec2,1);
            TmpMedMedRawVec1(1:NMedMedRawVec1)=MedMedRawVec1;
            MedMedRawVec1=TmpMedMedRawVec1;
        else
            TmpMedMedRawVec2=zeros(NMedMedRawVec1,1);
            TmpMedMedRawVec2(1:NMedMedRawVec2)=MedMedRawVec2;
            MedMedRawVec2=TmpMedMedRawVec2;
        end
    end
    MedMedRawVecTmp=MedMedRawVec1-MedMedRawVec2;   
    set(hList(NListHdr+(DiffVec(3)-1).*50+9),'Userdata',MedMedRawVecTmp);  
   
    NMedMedAvgVec1=length(MedMedAvgVec1);
    NMedMedAvgVec2=length(MedMedAvgVec2);
    DiffNNMedMedAvgVec=NMedMedAvgVec2-NMedMedAvgVec1;
    if DiffNNMedMedAvgVec~=0
        if DiffNNMedMedAvgVec>0
            TmpMedMedAvgVec1=zeros(NMedMedAvgVec2,1);
            TmpMedMedAvgVec1(1:NMedMedAvgVec1)=MedMedAvgVec1;
            MedMedAvgVec1=TmpMedMedAvgVec1;
        else
            TmpMedMedAvgVec2=zeros(NMedMedAvgVec1,1);
            TmpMedMedAvgVec2(1:NMedMedAvgVec2)=MedMedAvgVec2;
            MedMedAvgVec2=TmpMedMedAvgVec2;
        end
    end
    MedMedAvgVecTmp=MedMedAvgVec1-MedMedAvgVec2;
    set(hList(NListHdr+(DiffVec(3)-1).*50+10),'Userdata',MedMedAvgVecTmp);
    set(hList(NListHdr+(DiffVec(3)-1).*50+4),'Userdata',[Path1, 'Set',int2str(DiffVec(1)),'-Set',int2str(DiffVec(2))]);
    ActFileNo=DiffVec(3);
    set(hList(1),'Userdata',ActFileNo,'Value',ActFileNo);
    emegs2d('CalcFirst');
    emegs2d('CalcBase');
    emegs2d('setColor');
    emegs2d('setLineStyle');
    if ~any(FileNoVec==DiffVec(3))
        FileNoVec(length(FileNoVec)+1)=DiffVec(3);
        FileNoVec=sort(FileNoVec);
    end
    set(hList(56),'Userdata',FileNoVec);
    hFileInfoTextVec=get(hList(17),'Userdata');
    hFileInfoText=hFileInfoTextVec(DiffVec(3));
    VisibleStatus=get(hFileInfoText,'Visible');
    if strcmp(VisibleStatus,'on'); emegs2d('DispFileNamesVisible'); end
    %--------- set enable value ----------
    if length(FileNoVec)==1
        set(hList(49),'Value',1);	
    elseif length(FileNoVec)==2
        set(hList(49),'Value',3);
    elseif length(FileNoVec)==4
        set(hList(49),'Value',5);
    else
        set(hList(49),'Value',7);	
    end;		
    emegs2d('EnableOnOff');	
    set(hList(108),'Value',0);						%hOpenAvgFileStatus
    emegs2d('setActAllVisible')
    emegs2d('SetActFileNoLabelString')
    %--------------------------------------
    emegs2d('PlotData');
    close(hDiffMenuFig);
    emegs2d('CalcDiffMenu');
    
	%=============================================================================
	%=============================================================================			
elseif strcmp(action,'CalcAvgNoStdWeight123') | ...
		strcmp(action,'CalcAvgUseStdWeight123') |...
		strcmp(action,'CalcAvgNoStdWeight124') | ...
		strcmp(action,'CalcAvgUseStdWeight124') | ...
		strcmp(action,'CalcXCorr124') ,

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	
    SetNumber1=str2num(action(end-2));
    SetNumber2=str2num(action(end-1));
    TargetSetNumber=str2num(action(end));

	if ~any(FileNoVec==TargetSetNumber)
		FileNoVec(length(FileNoVec)+1)=TargetSetNumber;
		FileNoVec=sort(FileNoVec);
	end
	set(hList(56),'Userdata',FileNoVec);
	
	AvgMat1=get(hList(NListHdr+(SetNumber1-1).*50+1),'Userdata');
	AvgMat2=get(hList(NListHdr+(SetNumber2-1).*50+1),'Userdata');
	
	AvgMatTmp=get(hList(NListHdr+(TargetSetNumber-1).*50+1),'Userdata');
	
	NChan1=get(hList(NListHdr+(SetNumber1-1).*50+2),'Userdata');
	NChan2=get(hList(NListHdr+(SetNumber2-1).*50+2),'Userdata');

	set(hList(NListHdr+(TargetSetNumber-1).*50+2),'Userdata',NChan1);

	NPoints1=get(hList(NListHdr+(SetNumber1-1).*50+3),'Userdata');
	NPoints2=get(hList(NListHdr+(SetNumber2-1).*50+3),'Userdata');
	set(hList(NListHdr+(TargetSetNumber-1).*50+3),'Userdata',NPoints1);

	FilePath1=get(hList(NListHdr+(SetNumber1-1).*50+4),'Userdata');
	[File1,Path1]=SepFilePath(FilePath1);
	FilePath2=get(hList(NListHdr+(SetNumber2-1).*50+4),'Userdata');
	[File2,Path2]=SepFilePath(FilePath2);

	if 	strcmp(action,'CalcAvgNoStdWeight123')| ...
			strcmp(action,'CalcAvgUseStdWeight123') | ...
			strcmp(action,'CalcAvgNoStdWeight124')| ...
			strcmp(action,'CalcAvgNoStdWeight124')
		set(hList(NListHdr+(TargetSetNumber-1).*50+4),'Userdata',[Path1, 'AvgSet1Set2']);
	elseif 	strcmp(action,'CalcXCorr123')  | strcmp(action,'CalcXCorr124') 
		set(hList(NListHdr+(TargetSetNumber-1).*50+4),'Userdata',[Path1, 'X-Corr.Set1Set2']);
	end
	NTrialAvgVec1=get(hList(NListHdr+(SetNumber1-1).*50+5),'Userdata');
	NTrialAvgVec2=get(hList(NListHdr+(SetNumber2-1).*50+3),'Userdata');

	StdChanTimeMat1=get(hList(NListHdr+(SetNumber1-1).*50+6),'Userdata');
	StdChanTimeMat2=get(hList(NListHdr+(SetNumber2-1).*50+6),'Userdata');
	
	SampRate1=get(hList(NListHdr+(SetNumber1-1).*50+7),'Userdata');
	SampRate2=get(hList(NListHdr+(SetNumber2-1).*50+7),'Userdata');

	if SampRate1~=SampRate2;
		Message=char('Warning: ');Message=char(Message,'');
		Message=char(Message,'Sampling rates');
		Message=char(Message,['of data set ',int2str(SetNumber1),' and data set '  int2str(SetNumber2)]);
		Message=char(Message,'are not identical !');
		hmsgbox=msgbox(Message,'Warning','warn'); uiwait(hmsgbox);
	end
	set(hList(NListHdr+(TargetSetNumber-1).*50+7),'Userdata',SampRate1);
	
	AvgRef1=get(hList(NListHdr+(SetNumber1-1).*50+8),'Userdata');
	AvgRef2=get(hList(NListHdr+(SetNumber2-1).*50+8),'Userdata');

	if AvgRef1~=AvgRef2;
		Message=char('Warning: ');Message=char(Message,'');
		Message=char(Message,'The average ref. status');
		Message=char(Message,['of data set ',int2str(SetNumber1),' and data set '  int2str(SetNumber2)]);
		Message=char(Message,'are not identical !');
		hmsgbox=msgbox(Message,'Warning','warn'); uiwait(hmsgbox);
	end
	set(hList(NListHdr+(TargetSetNumber-1).*50+8),'Userdata',AvgRef1);
		
	MedMedRawVec1=get(hList(NListHdr+(SetNumber1-1).*50+9),'Userdata');
	MedMedRawVec2=get(hList(NListHdr+(SetNumber2-1).*50+9),'Userdata');
	NMedMedRawVec1=length(MedMedRawVec1);
	NMedMedRawVec2=length(MedMedRawVec2);

	DiffNNMedMedRawVec=NMedMedRawVec2-NMedMedRawVec1;
	if DiffNNMedMedRawVec~=0
		if DiffNNMedMedRawVec>0
			TmpMedMedRawVec1=zeros(NMedMedRawVec2,1);
			TmpMedMedRawVec1(1:NMedMedRawVec1)=MedMedRawVec1;
			MedMedRawVec1=TmpMedMedRawVec1;
		else
			TmpMedMedRawVec2=zeros(NMedMedRawVec1,1);
			TmpMedMedRawVec2(1:NMedMedRawVec2)=MedMedRawVec2;
			MedMedRawVec2=TmpMedMedRawVec2;
		end
	end
	
	MedMedAvgVec1=get(hList(NListHdr+(SetNumber1-1).*50+10),'Userdata');
	MedMedAvgVec2=get(hList(NListHdr+(SetNumber2-1).*50+10),'Userdata');
	NMedMedAvgVec1=length(MedMedAvgVec1);
	NMedMedAvgVec2=length(MedMedAvgVec2);

    if strcmp(action,'CalcAvgNoStdWeight123') | strcmp(action,'CalcAvgUseStdWeight123') | ...
		strcmp(action,'CalcAvgNoStdWeight124') | strcmp(action,'CalcAvgUseStdWeight124') | ...
		strcmp(action,'CalcXCorr123') | strcmp(action,'CalcXCorr124') 
		MedMedRawVecTmp=zeros(NMedMedRawVec1+NMedMedRawVec2,1);
		MedMedAvgVecTmp=zeros(NMedMedAvgVec1+NMedMedAvgVec2,1);
	end
	[mTmp,nTmp]=size(NTrialAvgVec1);
	if nTmp~=1; NTrialAvgVec1=NTrialAvgVec1'; end
	[mTmp,nTmp]=size(NTrialAvgVec2);
	if nTmp~=1; NTrialAvgVec2=NTrialAvgVec2'; end
    if strcmp(action,'CalcAvgNoStdWeight123') | strcmp(action,'CalcAvgNoStdWeight124')
		AvgMatTmp=(AvgMat1+AvgMat2)./2;
		NTrialAvgVecTmp=NTrialAvgVec2+NTrialAvgVec1;
		StdChanTimeMatTmp=(StdChanTimeMat1+StdChanTimeMat2)./2;
	elseif strcmp(action,'CalcAvgUseStdWeight123') | strcmp(action,'CalcAvgUseStdWeight124')
		AvgMatTmp=(1./StdChanTimeMat1.*AvgMat1+1./StdChanTimeMat2.*AvgMat2)./(1./StdChanTimeMat1+1./StdChanTimeMat2);
		NTrialAvgVecTmp=NTrialAvgVec2+NTrialAvgVec1;
		StdChanTimeMatTmp=(StdChanTimeMat1+StdChanTimeMat2)./2;
	elseif strcmp(action,'CalcXCorr123') | strcmp(action,'CalcXCorr124')
		AvgMatTmp=AvgMat1;
		NPointsXCorr=NPoints1.*2-1;
		XVec=[1:NPointsXCorr];
		XInterVec=linspace(1,NPointsXCorr,NPoints1);
		Tmp1Vec3=zeros(NPoints1.*3,1);
		Tmp2Vec3=Tmp1Vec3;
		for ChanInd=1:NChan1
			for i=1:3
				Tmp1Vec3((i-1).*NPoints1+1:i.*NPoints1)=AvgMat1(ChanInd,:);
			end
			Tmp2Vec3(NPoints1+1:2.*NPoints1)=AvgMat2(ChanInd,:);
			XCorrVec=xcorr(Tmp1Vec3,Tmp2Vec3,'biased');
			XCorrVecOld=XCorrVec;
			XCorrVec=XCorrVec(NPointsXCorr+1:2.*NPointsXCorr);
			if ChanInd==79
				figure; 
				subplot(3,1,1)
				plot(Tmp1Vec3)
				hold on
				plot(Tmp2Vec3,'--')
				axis([1 length(Tmp1Vec3) -6 6])
				hold off
				subplot(3,1,2)
				plot(XCorrVecOld)
				hold on
				plot([NPointsXCorr+1 NPointsXCorr+1],[-3 3],'--')
				plot([2.*NPointsXCorr 2.*NPointsXCorr],[-3 3],'--')
				axis([1 length(XCorrVecOld) -3 3])
				subplot(3,1,3)
				plot(XCorrVec)
				axis([1 length(XCorrVec) -3 3])
			end
			AvgMatTmp(ChanInd,:)=interp1(XVec,XCorrVec,XInterVec);
		end
		NTrialAvgVecTmp=NTrialAvgVec2+NTrialAvgVec1;
		StdChanTimeMatTmp=(StdChanTimeMat1+StdChanTimeMat2)./2;
	end
	ActFileNo=TargetSetNumber;
	set(hList(1),'Userdata',ActFileNo,'Value',ActFileNo);
	if TargetSetNumber==3
		set(hList(61),'Value',1);	%ColorVal=black
	else
		set(hList(61),'Value',5);	%ColorVal=green
	end
	set(hList(NListHdr+(TargetSetNumber-1).*50+1),'Userdata',AvgMatTmp);
	set(hList(NListHdr+(TargetSetNumber-1).*50+24),'Userdata',AvgMatTmp);
	set(hList(NListHdr+(TargetSetNumber-1).*50+5),'Userdata',NTrialAvgVecTmp);
	set(hList(NListHdr+(TargetSetNumber-1).*50+6),'Userdata',StdChanTimeMatTmp);
	set(hList(NListHdr+(TargetSetNumber-1).*50+9),'Userdata',MedMedRawVecTmp);
	set(hList(NListHdr+(TargetSetNumber-1).*50+10),'Userdata',MedMedAvgVecTmp);
	
	emegs2d('CalcFirst');
	emegs2d('CalcBase');
	emegs2d('setColor');
	emegs2d('setLineStyle');
	if ~any(FileNoVec==TargetSetNumber)
		FileNoVec(length(FileNoVec)+1)=TargetSetNumber;
		FileNoVec=sort(FileNoVec);
	end
	set(hList(56),'Userdata',FileNoVec);
	hFileInfoTextVec=get(hList(17),'Userdata');
	hFileInfoText=hFileInfoTextVec(TargetSetNumber);
	VisibleStatus=get(hFileInfoText,'Visible');
	if strcmp(VisibleStatus,'on'); emegs2d('DispFileNamesVisible'); end
	%--------- set enable value ----------
	if length(FileNoVec)==1
		set(hList(49),'Value',1);	
	elseif length(FileNoVec)==2
		set(hList(49),'Value',3);
	elseif length(FileNoVec)==4
		set(hList(49),'Value',5);
	else
		set(hList(49),'Value',7);	
	end;		
	emegs2d('EnableOnOff');	
	set(hList(108),'Value',0);						%hOpenAvgFileStatus
   	emegs2d('setActAllVisible')
   	emegs2d('SetActFileNoLabelString')
	%--------------------------------------
	emegs2d('PlotData');
	
	%=============================================================================
	%=============================================================================	
elseif  strcmp(action,'CalcNormAll0x1') | strcmp(action,'CalcNormAct0x1') | ...
		strcmp(action,'CalcNormAll1x1') | strcmp(action,'CalcNormAct1x1') | ...
		strcmp(action,'CalcNormAllMeanStd') | strcmp(action,'CalcNormActMeanStd') | ...
		strcmp(action,'CalcNormAllMaxAbs') | strcmp(action,'CalcNormActMaxAbs') | ...
		strcmp(action,'CalcNormAllMedAbs') | strcmp(action,'CalcNormActMedAbs') | ...
		strcmp(action,'CalcNormAllMeanAbs') | strcmp(action,'CalcNormActMeanAbs') | ...
        strcmp(action,'CalcNormAllLogE') | strcmp(action,'CalcNormActLogE') | ...
        strcmp(action,'CalcNormAllLog10') | strcmp(action,'CalcNormActLog10') | ...
        strcmp(action,'CalcNormAllSqrt') | strcmp(action,'CalcNormActSqrt'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');

	if strcmp(action(9:11),'Act') 
		FileNoVec=FileNoVec(ActFileNo);
	end
    NormValStatus=1;
	if 	strcmp(action,'CalcNormAll0x1') | strcmp(action,'CalcNormAct0x1'); NormStatus=1; end
	if 	strcmp(action,'CalcNormAll1x1') | strcmp(action,'CalcNormAct1x1'); NormStatus=2; end
	if 	strcmp(action,'CalcNormAllMeanStd') | strcmp(action,'CalcNormActMeanStd'); NormStatus=3; end
	if 	strcmp(action,'CalcNormAllMaxAbs') | strcmp(action,'CalcNormActMaxAbs'); NormStatus=4; NormValStatus=1; end
	if	strcmp(action,'CalcNormAllMedAbs') | strcmp(action,'CalcNormActMedAbs'); NormStatus=4; NormValStatus=2; end
	if	strcmp(action,'CalcNormAllMeanAbs') | strcmp(action,'CalcNormActMeanAbs'); NormStatus=4; NormValStatus=3; end
    if	strcmp(action,'CalcNormAllLogE') | strcmp(action,'CalcNormActLogE'); NormStatus=5; end
    if	strcmp(action,'CalcNormAllLog10') | strcmp(action,'CalcNormActLog10'); NormStatus=6; end
    if	strcmp(action,'CalcNormAllSqrt') | strcmp(action,'CalcNormActSqrt'); NormStatus=7; end
	
	NormVal=0;
	for FileIndex=1:length(FileNoVec)
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		if 	NormStatus==4 & NormValStatus==1
			NormVal=max(max(abs(CalcAvgMat)));
		elseif 	NormStatus==4 & NormValStatus==2
			NormVal=median(median(abs(CalcAvgMat)));
		elseif 	NormStatus==4 & NormValStatus==3
			NormVal=mean(mean(abs(CalcAvgMat)));	
		end
		%	If NormStatus==1 with 0<=x<=1
		%	If NormStatus==2 with -1<=x<=1
		%	If NormStatus==3 with mean=0 and stdv=1
		%	If NormStatus==4 with Minimum<=x<=Maximum
        %	If NormStatus==5 log e transform
        %	If NormStatus==6 log 10 transform
        %	If NormStatus==7 sqrt transform
		%	norm_1(Mat,status,Statusdef,Minimum,Maximum);
		if NormStatus==3; MatStatus=1; else; MatStatus=3; end
		CalcAvgMat=norm_1(CalcAvgMat,NormStatus,[],-NormVal,NormVal,MatStatus);
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat);
	end
	emegs2d('CalcFirst');
	emegs2d('PlotData');
    emegs2d('AdjustAmp');

	%=============================================================================
	%=============================================================================	
elseif strcmp(action,'CalcActReRefAvgRef') | strcmp(action,'CalcAllReRefAvgRef') | ...
	strcmp(action,'CalcActReRefLinkedEars') | strcmp(action,'CalcAllReRefLinkedEars') | ...
	strcmp(action,'CalcActReRefLeftEar') | strcmp(action,'CalcAllReRefLeftEar') | ...
	strcmp(action,'CalcActReRefRightEar') | strcmp(action,'CalcAllReRefRightEar') | ...
    strcmp(action,'CalcActReRefFromFile') | strcmp(action,'CalcAllReRefFromFile') | ...    
	strcmp(action,'CalcActReRefCz') | strcmp(action,'CalcAllReRefCz') | ...
	strcmp(action,'CalcActReRefSpecial') | strcmp(action,'CalcAllReRefSpecial')

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	Domain=get(hList(20),'Value');
	EPosSpher=get(hList(3),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	NChan=get(hList(NListHdr+2),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	
	hTopMenu=get(hList(65),'Userdata');
	hExportMenu=get(hTopMenu(3),'children');	
	hExportUserData=get(hExportMenu(1),'children'); 
	hUserDataInfo=get(hExportUserData(1),'children');
	UserDataInfoLabel=get(hUserDataInfo,'Label');
    ECfgFilePath=get(hList(2),'Userdata');
	[ECfgFile,ECfgPath]=SepFilePath(ECfgFilePath);
    Message1=char('Sorry,');
    Message1=char(Message1,'no default reference electrode numbers');
    Message1=char(Message1,'available for this sensor configuration.');
    Message1=char(Message1,'');
    Message1=char(Message1,'Please use "Rereference - Special" instead.');
    
    Message2=char('Use the default electrode reference positions');
    Message2=char(Message2,'given for this sensor configuration.');
    Message2=char(Message2,'');
    Message2=char(Message2,'Please use "Rereference - Special" if you ');
    Message2=char(Message2,'would like to choose differing positions.');
    
    if ~isempty(findstr(action,'Ear'))
            if ~strcmp(ECfgFile,'64.ecfg') & ~strcmp(ECfgFile,'65.ecfg') & ~strcmp(ECfgFile,'128.ecfg') & ~strcmp(ECfgFile,'129.ecfg') & ~strcmp(ECfgFile,'256.ecfg') & ~strcmp(ECfgFile,'257.ecfg') 
                hMsgbox=msgbox(Message1,'Info:','help');
                return;  
            else
                answer = questdlg(Message2,'Info:','Use default','Cancel','Use default');
                if strcmp(answer,'Cancel')
                    return;
                end
            end
    elseif ~isempty(findstr(action,'Cz'))
         if ~strcmp(ECfgFile,'65.ecfg') & ~strcmp(ECfgFile,'129.ecfg') & ~strcmp(ECfgFile,'257.ecfg')
                hMsgbox=msgbox(Message1,'Info:','help');
                return; 
         else
                answer = questdlg(Message2,'Info:','Use default','Cancel','Use default');
                if strcmp(answer,'Cancel')
                    return;
                end
         end
    end
	if 	strcmp(action,'CalcActReRefAvgRef') | strcmp(action,'CalcActReRefLinkedEars') | ...
		strcmp(action,'CalcActReRefLeftEar') | strcmp(action,'CalcActReRefRightEar') | ...
        strcmp(action,'CalcActReRefFromFile') | ...        
		strcmp(action,'CalcActReRefCz') | strcmp(action,'CalcActReRefSpecial')
    
		ReRefFileNoVec=FileNoVec(ActFileNo);
	else %All
		ReRefFileNoVec=FileNoVec;
	end
	ReRefFig=figure('Units','normal','NumberTitle','off','Position',[0,.75,.5,.25],'Name','Subtract reference:');
	AvgRefMat=zeros(NPoints,length(ReRefFileNoVec));
	MinAmp=10^10;
	MaxAmp=-10^10;
	for FileIndex=1:length(ReRefFileNoVec)
		CalcAvgMat=get(hList(NListHdr+(ReRefFileNoVec(FileIndex)-1).*50+1),'Userdata');
		if strcmp(action,'CalcActReRefAvgRef') | strcmp(action,'CalcAllReRefAvgRef')
			AvgRefVec=(sum(CalcAvgMat(kActAxes,:)))./(length(kActAxes));
			RefChanInd=0;
			TitleString='Average Reference';
		elseif (strcmp(action,'CalcActReRefLinkedEars') | strcmp(action,'CalcAllReRefLinkedEars')),
			if strcmp(ECfgFile,'256.ecfg') | strcmp(ECfgFile,'257.ecfg')
				RefChanInd=[93 191];
			elseif strcmp(ECfgFile,'128.ecfg') | strcmp(ECfgFile,'129.ecfg')
				RefChanInd=[57 101];
			elseif strcmp(ECfgFile,'64.ecfg') | strcmp(ECfgFile,'65.ecfg')
				RefChanInd=[10 61];
			end
			AvgRefVec=(sum(CalcAvgMat(RefChanInd,:)))./2;
			TitleString=['Linked Ears reference; Default sensors: ',int2str(RefChanInd(1)),' & ',int2str(RefChanInd(2))];
		elseif (strcmp(action,'CalcActReRefFromFile') | strcmp(action,'CalcAllReRefFromFile')),
            % these menu is used to rereference the datasets to a sensor
            % array stored in a file. it has been designed to be used when
            % the number of sensors is high, e.g. when you want to
            % rereference a 257 net to the nearest sensors to a 64 net. 
            % 
            % Andrea.De-Cesarei@uni-konstanz.de
            % 
			[ReRefSensorFile,ReRefSensorPath,ReRefSensorFilePath]=ReadFilePath([],'*.txt','Choose a file containing a list of ReRefSensors (with header):');
			ReRefSensorFid=fopen(ReRefSensorFilePath, 'r');
			buf=fgetl(ReRefSensorFid);
			i=1;
			RefChanInd=[];
			while ~feof(ReRefSensorFid)
                buf=fgetl(ReRefSensorFid);
                RefChanInd(i,:)=sscanf(buf, '%d')';
                i=i+1;
			end
			fclose(ReRefSensorFid); 
			AvgRefVec=(sum(CalcAvgMat(RefChanInd,:)))./length(RefChanInd);
			TitleString='User Config reference';                        
		elseif (strcmp(action,'CalcActReRefLeftEar') | strcmp(action,'CalcAllReRefLeftEar')),
			if strcmp(ECfgFile,'256.ecfg') | strcmp(ECfgFile,'257.ecfg')
				RefChanInd=93;
			elseif strcmp(ECfgFile,'128.ecfg') | strcmp(ECfgFile,'129.ecfg')
				RefChanInd=57;
			elseif strcmp(ECfgFile,'64.ecfg') | strcmp(ECfgFile,'65.ecfg')
				RefChanInd=10;
			end
			AvgRefVec=CalcAvgMat(RefChanInd,:);
			TitleString=['Left ear reference; Default sensor: ',int2str(RefChanInd)];
		elseif (strcmp(action,'CalcActReRefRightEar') | strcmp(action,'CalcAllReRefRightEar')),
			if strcmp(ECfgFile,'256.ecfg') | strcmp(ECfgFile,'257.ecfg')
				RefChanInd=191;
			elseif strcmp(ECfgFile,'128.ecfg') | strcmp(ECfgFile,'129.ecfg')
				RefChanInd=101;
			elseif strcmp(ECfgFile,'64.ecfg') | strcmp(ECfgFile,'65.ecfg')
				RefChanInd=61;
			end
			AvgRefVec=CalcAvgMat(RefChanInd,:);
            TitleString=['Right ear reference; Default sensor: ',int2str(RefChanInd)];
		elseif (strcmp(action,'CalcActReRefCz') | strcmp(action,'CalcAllReRefCz')),
			if strcmp(ECfgFile,'257.ecfg')
				RefChanInd=257;
			elseif strcmp(ECfgFile,'129.ecfg')
				RefChanInd=129;
			elseif strcmp(ECfgFile,'65.ecfg')
				RefChanInd=65;  
			end
			AvgRefVec=CalcAvgMat(RefChanInd,:);
            TitleString=['Vertex reference; Default sensor: ',int2str(RefChanInd)];
		elseif (strcmp(action,'CalcActReRefSpecial') | strcmp(action,'CalcAllReRefSpecial')),
			[RefChanInd,NoUse,NoUse]=ChooseChanInd(NChan,1,[],[],[],[],EPosSpher,[],[],[],3,10,0);
			if length(RefChanInd)>1
				AvgRefVec=(sum(CalcAvgMat(RefChanInd,:)))./(length(RefChanInd));
                TitleString='Reference electrodes: '
                for i=1:length(RefChanInd)
				    TitleString=[TitleString,int2str(RefChanInd(i)),', '];
                end
			else
				AvgRefVec=CalcAvgMat(RefChanInd,:);
				TitleString=['Reference electrode:', int2str(RefChanInd)];
			end
		end
		for ChanInd=1:NChan
			CalcAvgMat(ChanInd,:)=CalcAvgMat(ChanInd,:)-AvgRefVec;
		end
		set(hList(NListHdr+(ReRefFileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat);
		subplot(1,length(ReRefFileNoVec),FileIndex)
		plot(AvgRefVec)
		if max(AvgRefVec)>min(AvgRefVec)	
			axis([1 length(AvgRefVec) min(AvgRefVec) max(AvgRefVec)]);
		end
		title(TitleString)
		xlabel('Time')
		ylabel('Potential')
		AvgRefMat(:,FileIndex)=AvgRefVec';
		MinAmpTmp=min(min(CalcAvgMat));
		MaxAmpTmp=max(max(CalcAvgMat));
		MinAmp=min([MinAmpTmp MinAmp]);
		MaxAmp=max([MaxAmpTmp MaxAmp]);
		MinAmpTmp=MinAmp;
		MaxAmpTmp=MaxAmp;
		set(hList(NListHdr+(ReRefFileNoVec(FileIndex)-1).*50+8),'Userdata',RefChanInd);
	end
	set(hList(94),'Userdata',AvgRefMat);	%User data	
	% User data Info %
	UserDataInfoLabel=TitleString;
	set(hUserDataInfo,'Label',UserDataInfoLabel);
	set(hExportUserData,'Enable','on');
	%----------------%
   	MinAmpStr = sprintf('%g',round(MinAmp*100)/100);
	MinAmpVec=get(hList(52),'Userdata');
	MinAmpVec(Domain)=MinAmp;
   	set(hList(52),'Value',MinAmp,'Userdata',MinAmpVec,'String',MinAmpStr);
	%----------------%
	MaxAmpStr = sprintf('%g',round(MaxAmp*100)/100);
	MaxAmpVec=get(hList(53),'Userdata');
	MaxAmpVec(Domain)=MaxAmp;
   	set(hList(53),'Value',MaxAmp,'Userdata',MaxAmpVec,'String',MaxAmpStr);
	%----------------%
	set(hList(NListHdr+(ReRefFileNoVec(FileIndex)-1).*50+11),'Userdata',MinAmp);
	set(hList(NListHdr+(ReRefFileNoVec(FileIndex)-1).*50+12),'Userdata',MaxAmp);
	emegs2d('setMinMaxAmpPoint')
	emegs2d('PlotData');

	%=============================================================================
	%=============================================================================	
elseif  strcmp(action,'setNPoints')

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	NPointsOld=get(hList(50),'Userdata');
	NPointsNewStr=get(hList(50),'String');
	[NPointsNew,NPointsNewStr]=String2Value(NPointsNewStr,NPointsOld,1,[],1,1);
	if NPointsNew==NPointsOld
		return; 
	else
		set(hList(50),'Userdata',NPointsNew,'String',NPointsNewStr);
	end
	for FileIndex=1:length(FileNoVec)
		CalcAvgMatOld=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		OrigAvgMatOld=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+24),'Userdata');
		NChan=size(CalcAvgMatOld,1);
		CalcAvgMatNew=zeros(NChan,NPointsNew);
		OrigAvgMatNew=CalcAvgMatNew;
		x =[1:NPointsOld];
		x1=[1:NPointsNew];
		for ChanInd=1:NChan
			CalcAvgMatNew(ChanInd,:)=interp1(x,CalcAvgMatOld(ChanInd,:),x1,'*linear');
			OrigAvgMatNew(ChanInd,:)=interp1(x,OrigAvgMatOld(ChanInd,:),x1,'*linear');
		end
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMatNew);
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+24),'Userdata',OrigAvgMatNew);
		set(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+3),'Userdata',NPointsNew,'String',NPointsNewStr);
		clear CalcAvgMatNew CalcAvgMatOld OrigAvgMatNew OrigAvgMatOld
	end
	emegs2d('SetFirstVal');
 	%emegs2d('Calc2dTimeAxes');
% 	emegs2d('setView');
% 	emegs2d('InitChanAxes');
	emegs2d('PlotData');
	
	%=============================================================================
	%=============================================================================	
elseif  strcmp(action,'CalcFactorAll') | ...
		strcmp(action,'CalcFactorAct') |...
        strcmp(action,'CalcInvertAll') | ...
		strcmp(action,'CalcInvertAct') |...
		strcmp(action,'CalcAbsAll') | ...
		strcmp(action,'CalcAbsAct') | ...
		strcmp(action,'CalcGradAll') | ...
		strcmp(action,'CalcGradAct') | ...
        strcmp(action,'CalcCumSumGradAll') | ...
		strcmp(action,'CalcCumSumGradAct'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	
    if strcmp(action,'CalcFactorAct') | strcmp(action,'CalcInvertAct') | strcmp(action,'CalcAbsAct') | strcmp(action,'CalcGradAct') 
		FileNoVec=FileNoVec(ActFileNo);
	end	
    NUsedFiles=length(FileNoVec);
    if  strcmp(action,'CalcFactorAll') | strcmp(action,'CalcFactorAct')
        if NUsedFiles==1  
            PromptStr={['Factor set ',int2str(FileNoVec(1))]};
            DefStr={'10^-14'};
        elseif NUsedFiles==2
            PromptStr={['Factor set ',int2str(FileNoVec(1))],['Factor set ',int2str(FileNoVec(2))]};
            DefStr={'10^-14','10^-14'};
        elseif NUsedFiles==3
            PromptStr={['Factor set ',int2str(FileNoVec(1))],['Factor set ',int2str(FileNoVec(2))],['Factor set ',int2str(FileNoVec(3))]};
            DefStr={'10^-14','10^-14','10^-14'};
         elseif NUsedFiles==4
            PromptStr={['Factor set ',int2str(FileNoVec(1))],['Factor set ',int2str(FileNoVec(2))],['Factor set ',int2str(FileNoVec(3))],['Factor set ',int2str(FileNoVec(4))]};
            DefStr={'10^-14','10^-14','10^-14','10^-14'};
        elseif NUsedFiles==5
            PromptStr={['Factor set ',int2str(FileNoVec(1))],['Factor set ',int2str(FileNoVec(2))],['Factor set ',int2str(FileNoVec(3))],['Factor set ',int2str(FileNoVec(4))],['Factor set ',int2str(FileNoVec(5))]};
            DefStr={'10^-14','10^-14','10^-14','10^-14','10^-14'};
        elseif NUsedFiles==6
            PromptStr={['Factor set ',int2str(FileNoVec(1))],['Factor set ',int2str(FileNoVec(2))],['Factor set ',int2str(FileNoVec(3))],['Factor set ',int2str(FileNoVec(4))],['Factor set ',int2str(FileNoVec(5))],['Factor set ',int2str(FileNoVec(6))]};
            DefStr={'10^-14','10^-14','10^-14','10^-14','10^-14','10^-14'};
        end
        FacStr=inputdlg(PromptStr,'Multiply with factor:',1,DefStr);
        FacVec=str2num(char(FacStr));
        if length(FacVec)~=length(FileNoVec) | ~any(isfinite(FacVec))
            Message=char('Sorry,');
            Message=char(Message,'invalid factor.');
            Message=char(Message,'');
            if length(FacVec)~=length(FileNoVec)
                Message=char(Message,'Please insert a factor for each data set.');
                Message=char(Message,'(Choose a factor of 1 in order to retain the current data)');
            end
            if ~any(isfinite(FacVec))
                Message=char(Message,'Please insert a finite factor.');
            end
            hMsgbox=msgbox(Message,'Info:','help');
            return;
        end
    end 
	for FileIndex=1:length(FileNoVec)
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		if strcmp(action,'CalcInvertAct') | strcmp(action,'CalcInvertAll') 
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',-1.*CalcAvgMat);
		elseif strcmp(action,'CalcAbsAct') | strcmp(action,'CalcAbsAll') 
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',abs(CalcAvgMat));
            set(findobj('Tag','CalcAbsClear'),'Userdata',1);
		elseif strcmp(action,'CalcGradAct') | strcmp(action,'CalcGradAll') 
            set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',gradient(CalcAvgMat));
            set(findobj('Tag','CalcGradClear'),'Userdata',1);
        elseif strcmp(action,'CalcCumSumGradAct') | strcmp(action,'CalcCumSumGradAll') 
            set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',cumsum(gradient(CalcAvgMat),2));
        elseif strcmp(action,'CalcFactorAct') | strcmp(action,'CalcFactorAll') 
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',FacVec(FileIndex).*CalcAvgMat);
		end
	end
	emegs2d('PlotData');
	emegs2d('AdjustAmp');
    
    %=============================================================================
	%=============================================================================	
elseif  strcmp(action,'CalcTTestT2P') | ...
        strcmp(action,'CalcTTestT2Z') 
	
    hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
    ActFileNo=get(hList(1),'Userdata');
    FileNoVec=get(hList(56),'Userdata');
    prompt={'Enter the degrees of freedom (df):'};
    def={'20'};
    dlgTitle='Degrees of freedom';
    lineNo=1;
    dfStr=inputdlg(prompt,dlgTitle,lineNo,def);
    if isempty(dfStr); return; end
    df=str2num(char(dfStr));
    tMat=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+1),'Userdata');
    Mat=tMat;
    tMask=find(tMat);        %Mask out t == 0 (z==0)
    Mat(tMask)=1-betainc(df./(df+tMat(tMask).^2),df./2,0.5)./2;
    if strcmp(action,'CalcTTestT2P')
        Mat(tMat<0)=-Mat(tMat<0);
    elseif strcmp(action,'CalcTTestT2Z') 
        Mat=sqrt(2).*erfinv(2*Mat-1);
        Mat(tMat>0)=-Mat(tMat>0);
    end
    set(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+1),'Userdata',Mat);
    emegs2d('PlotData');
	emegs2d('AdjustAmp'); 
 
    
        
	%=============================================================================
	%=============================================================================	
    
elseif  strcmp(action,'ApplyMinClusterSizeRestrictionsActual') 
     
    %collect data
    hList=get(hPlot2dMenuFig,'Userdata');
    ActFileNo=get(hList(1),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NChan=get(hList(NListHdr+2),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
    FileIndex = ActFileNo;
    CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
    EConfigFilePath=GetDefEcfgFile(NChan);
    [NChan_ttest,SpherRadius_ttest,EPosSpher_ttest,ENames_ttest,EConfigFile_ttest,EConfigPath_ttest,EConfigFilePath_ttest]=ReadEConfig(EConfigFilePath);
    hCalcTTestPairesMenu = findobj('tag','hCalcTTestPairesMenu');
    userdatacell = get(hCalcTTestPairesMenu,'Userdata');
    if isempty(userdatacell)
        uiwait(errordlg('You have to set the cluster size restrictions before you can apply them!'));
        return
    end
    minneighbours = userdatacell{1};
    minpointsinrow = userdatacell{2};
    alphavalue = userdatacell{3};
    neighbourspherdist = userdatacell{4};
    
    %find channel neighbours
    global hPlot3dMenuFig
    if isempty(hPlot3dMenuFig)
        emegs3d;
        plot3dmenufig = findobj('tag','plot3dmenufig');
        set(plot3dmenufig,'visible','off');
        pause(0.000001);
        neighbourcell=findchanneighbours(EPosSpher_ttest,SpherRadius_ttest,neighbourspherdist);
        close(plot3dmenufig);
    else
        neighbourcell=findchanneighbours(EPosSpher_ttest,SpherRadius_ttest,neighbourspherdist);
    end
    
    %top quantil
    significancelevelp = 1 - alphavalue;
    
    %progress dialog...
    message={'testing restrictions... '};
	infdlg1 = infdlgsmall('Testing...',message,[],[],[]);
	infdlgtext1 = findobj('tag','infdlgtext1');
	infdlgtext2 = findobj('tag','infdlgtext2');
    infdlg1 = findobj('tag','infdlg');
    
    %make zeros-copy of data
    MiCsAvgMatOut = zeros(size(CalcAvgMat));
        
    %test restrictions
    for r=1:NPoints-minpointsinrow
        set(infdlgtext1,'String',[num2str(r),'   of ']);
        set(infdlgtext2,'String',num2str(NPoints-minpointsinrow));
        pause(0.001);
        for s=1:NChan
            g=0;
            minneighbourscriterium = 1;
            minpointscriterium = 1;
            while g<minpointsinrow
                if  CalcAvgMat(s,r+g)>significancelevelp | CalcAvgMat(s,r+g)<-significancelevelp
                    nrsigneighbours = 0;
                    for z=1:length(neighbourcell{s})
                        if CalcAvgMat(s,r+g)>significancelevelp | CalcAvgMat(s,r+g)<-significancelevelp
                           nrsigneighbours = nrsigneighbours+1;
                       end
                    end
                    if nrsigneighbours < minneighbours + 1
                       minneighbourscriterium = 0;
                    end
                else 
                    minpointscriterium = 0;
                    break;
                end
                g=g+1;
             end
             if minpointscriterium & minneighbourscriterium
                 %set to p-value other than zero
                 MiCsAvgMatOut(s,r) = CalcAvgMat(s,r);
             end 
        end
    end
    
    %all those, that are still zero in the copy, set to zero
    CalcAvgMat(find(MiCsAvgMatOut==0))=0;
    
    %just for scaling
	if min(min(CalcAvgMat))==0 & max(max(CalcAvgMat))==0
	    CalcAvgMat(1,1)=0.001;
	end
    
    %close progress dialog 
    close (infdlg1);
    
    %reload data
    set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat);
    emegs2d('PlotData');
    
    
	%=============================================================================
	%=============================================================================	
elseif  strcmp(action,'ApplyMinClusterSizeRestrictionsAll')    
    
    
     %collect data
    hList=get(hPlot2dMenuFig,'Userdata');
    ActFileNo=get(hList(1),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NChan=get(hList(NListHdr+2),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
    FileIndex = ActFileNo;
    CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
    EConfigFilePath=GetDefEcfgFile(NChan);
    [NChan_ttest,SpherRadius_ttest,EPosSpher_ttest,ENames_ttest,EConfigFile_ttest,EConfigPath_ttest,EConfigFilePath_ttest]=ReadEConfig(EConfigFilePath);
    hCalcTTestPairesMenu = findobj('tag','hCalcTTestPairesMenu');
    userdatacell = get(hCalcTTestPairesMenu,'Userdata');
    minneighbours = userdatacell{1};
    minpointsinrow = userdatacell{2};
    alphavalue = userdatacell{3};
    neighbourspherdist = userdatacell{4};
    
    %find channel neighbours
    global hPlot3dMenuFig
    if isempty(hPlot3dMenuFig)
        emegs3d;
        plot3dmenufig = findobj('tag','plot3dmenufig');
        set(plot3dmenufig,'visible','off');
        pause(0.000001);
        neighbourcell=findchanneighbours(EPosSpher_ttest,SpherRadius_ttest,neighbourspherdist);
        close(plot3dmenufig);
    else
        neighbourcell=findchanneighbours(EPosSpher_ttest,SpherRadius_ttest,neighbourspherdist);
    end
    
    %top quantil
    significancelevelp = 1 - alphavalue;
    
         
    
    for FileIndex=1:length(FileNoVec)
        
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		MiCsAvgMatOut = zeros(size(CalcAvgMat));
		
        %progress dialog...
		message={'testing restrictions... '};
		infdlg1 = infdlgsmall('Testing...',message,[],[],[]);
		infdlgtext1 = findobj('tag','infdlgtext1');
		infdlgtext2 = findobj('tag','infdlgtext2');
		infdlg1 = findobj('tag','infdlg');
    
		%test restrictions
		for r=1:NPoints-minpointsinrow
            set(infdlgtext1,'String',[num2str(r),'   of ']);
            set(infdlgtext2,'String',num2str(NPoints-minpointsinrow));
            pause(0.001);
            for s=1:NChan
                g=0;
                minneighbourscriterium = 1;
                minpointscriterium = 1;
                while g<minpointsinrow
                    if  CalcAvgMat(s,r+g)>significancelevelp | CalcAvgMat(s,r+g)<-significancelevelp
                        nrsigneighbours = 0;
                        for z=1:length(neighbourcell{s})
                            if CalcAvgMat(s,r+g)>significancelevelp | CalcAvgMat(s,r+g)<-significancelevelp
                               nrsigneighbours = nrsigneighbours+1;
                           end
                        end
                        if nrsigneighbours < minneighbours + 1
                           minneighbourscriterium = 0;
                        end
                    else 
                        minpointscriterium = 0;
                        break;
                    end
                    g=g+1;
                 end
                 if minpointscriterium & minneighbourscriterium
                     %set to p-value other than zero
                     MiCsAvgMatOut(s,r) = CalcAvgMat(s,r);
                 end 
            end
		end
		
		%all those, that are still zero in the copy, set to zero
		CalcAvgMat(find(MiCsAvgMatOut==0))=0;
		
		%just for scaling
		if min(min(CalcAvgMat))==0 & max(max(CalcAvgMat))==0
            CalcAvgMat(1,1)=0.001;
		end
		
		%close progress dialog 
		close (infdlg1);
		
		%reload data
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat);
        
    end
        
    emegs2d('PlotData');
    
    
    
    
    %=============================================================================
	%=============================================================================	
elseif  strcmp(action,'OpfigTTestPaiRestrictions') 

    hCalcTTestPairesMenu = findobj('tag','hCalcTTestPairesMenu');
    restrictions = get(hCalcTTestPairesMenu,'Userdata');
    if isempty(restrictions)
       fig = openfig('defttestres.fig','new');
    else
        fig = openfig('defttestres.fig','new');
        userdatacell = get(hCalcTTestPairesMenu,'Userdata');
        minneighbours = userdatacell{1};
        minpointsinrow = userdatacell{2};
        alphavalue = userdatacell{3};
        neighbourspherdist = userdatacell{4};
        alphapopup=findobj('tag','alphapopup');
        minneighbourspopup = findobj('tag','minneighbourspopup');
        spherdistedit = findobj('tag','spherdistedit');
        minpointsinrowpopup = findobj('tag','minpointsinrowpopup');
        alphavec = [0.9900,0.9500,0.9000,0.8000,0.5000,0.2000,0.1000,0.0500,0.0100,0.0050,0.0010,0.0005,0.0001,0.00005,0.00001];
        alphanumber = find(alphavec==alphavalue);
        set(alphapopup,'Value',alphanumber);
        set(minneighbourspopup,'Value',minneighbours);
        set(minpointsinrowpopup,'Value',minpointsinrow);
        set(spherdistedit,'String',num2str(neighbourspherdist));
    end
       
    
    
	%=============================================================================
	%=============================================================================	
elseif  strcmp(action,'DefTTestPaiRestrictions') 
     
    defrestrictionsfig = findobj('tag','defrestrictionsfig');
    minneighbourspopup = findobj('tag','minneighbourspopup');
    minpointsinrowpopup = findobj('tag','minpointsinrowpopup');
    spherdistedit = findobj('tag','spherdistedit');
    alphapopup = findobj('tag','alphapopup');
    minneighboursstring = get(minneighbourspopup,'String');
    minpointsstring = get(minpointsinrowpopup,'String');
    alphastring = get(alphapopup,'String');
    spherdist= str2num(get(spherdistedit,'String'));
    minneighbours = str2num(minneighboursstring{get(minneighbourspopup,'Value')});
    minpointsinrow = str2num(minpointsstring{get(minpointsinrowpopup,'Value')});
    alphavalue = str2num(alphastring{get(alphapopup,'Value')});
    userdatacell = {minneighbours;minpointsinrow;alphavalue;spherdist};
    hCalcTTestPairesMenu = findobj('tag','hCalcTTestPairesMenu');
    set(hCalcTTestPairesMenu,'Userdata',userdatacell);
    close(defrestrictionsfig);
    
	%=============================================================================
	%=============================================================================	
    
elseif strcmp(action,'GetCustomContrastCoeff')
    
    hList=get(hPlot2dMenuFig,'Userdata');
    RepConFile=['RepConDef.txt'];
    RepConFilePath=which(RepConFile)
    if ~exist(RepConFilePath); 
        RepConFilePath=[];
        Message=char('Sorry,');
        Message=char(Message,'can not find RepConDef.txt in Matlab path.');
        Message=char(Message,'');
        Message=char(Message,'Please open a different file of proper format.');
        hMsgbox=msgbox(Message,'Info:','help');
    end
	[ContMat,ContStr,ContFile,ContPath,ContFilePath]=ReadRepCon(RepConFilePath,['Search for ',RepConFilePath,':'],RepConFile);
    NCont=size(ContMat,1);
    hRepConMenuFig=figure('MenuBar','none','Units','normal','Position',[.35 0 .3 NCont.*.025],'Name',['Contrast file: ',ContFile],'Color',[1 1 1],'NumberTitle','off','tag','repcondeffig');
    hContFilePath = uicontrol(hRepConMenuFig,'visible','off');
    hContMat = uicontrol(hRepConMenuFig,'visible','off');
    set(hContFilePath,'userdata',hContFilePath);
    set(hContMat,'userdata',ContMat);
    RepConList =[hContFilePath hContMat];
    
    for ContInd=1:NCont
        btnPos=[0 1-ContInd./NCont 1 1/NCont];
        callbackStr='emegs2d(''ReturnCustomContrastCoeff'')'; 
        hRepConListMenu(ContInd)=uicontrol( ...
            'Style','radiobutton', ...
            'Units','normalized', ...
            'Position',btnPos, ...
            'String',ContStr(ContInd,:), ...
            'FontWeight','bold', ...
            'FontSize',12, ...
            'HorizontalAlignment','Right', ...
            'Value',0, ...
            'Callback',callbackStr,...
            'Enable','on');
        RepConList =[RepConList hRepConListMenu(ContInd)];
    end
  
    set(hRepConMenuFig,'userdata',RepConList);
    editmenu = uimenu(hRepConMenuFig,'Label','edit');
    editfilemenuitem = uimenu('Parent',editmenu,'Label','edit contrasts','Callback','edit(''RepConDef.txt'');');
    reloadfilemenuitem = uimenu('Parent',editmenu,'Label','reload contrasts','Callback','emegs2d(''UpdateRepConDef'');');
    contrastdeffigure = findobj('tag','contrastdeffigure');
    tmppos = get(contrastdeffigure,'position');
    tmppos(4) = NCont*0.025;
    set(contrastdeffigure,'position',tmppos);
    set(contrastdeffigure,'visible','on');
    
    %=============================================================================
	%=============================================================================	
elseif  strcmp(action,'CalcRepConList') 
   
    uiresume
    %=============================================================================
	%=============================================================================	
elseif  strcmp(action,'ReturnCustomContrastCoeff') 
    
    contrastdeffigure = findobj('tag','contrastdeffigure');
    repcondeffig = findobj('tag','repcondeffig');
    RepConList = get(repcondeffig,'userdata');
    ContMat = get(RepConList(2),'userdata');
    NCont = size(ContMat,1);
    for ContInd=1:NCont
        ContVec(ContInd)=get(RepConList(ContInd+2),'Value');
    end
    ContInd=find(ContVec);
    Weights=ContMat(ContInd,2:ContMat(ContInd,1)+1)
    close(repcondeffig);
    close(contrastdeffigure);
    pause(0.1);
    anovadraw('customcontrast',Weights);
    return;
    %=============================================================================
	%=============================================================================	
elseif  strcmp(action,'UpdateRepConDef')  
    
    repcondeffig = findobj('tag','repcondeffig');
    close(repcondeffig);
    
    hList=get(hPlot2dMenuFig,'Userdata');
    RepConFile=['RepConDef.txt'];
    RepConFilePath=which(RepConFile)
    if ~exist(RepConFilePath); 
        RepConFilePath=[];
        Message=char('Sorry,');
        Message=char(Message,'can not find RepConDef.txt in Matlab path.');
        Message=char(Message,'');
        Message=char(Message,'Please open a different file of proper format.');
        hMsgbox=msgbox(Message,'Info:','help');
    end
	[ContMat,ContStr,ContFile,ContPath,ContFilePath]=ReadRepCon(RepConFilePath,['Search for ',RepConFilePath,':'],RepConFile);
    NCont=size(ContMat,1);
    hRepConMenuFig=figure('MenuBar','none','Units','normal','Position',[.4 .3 .3 NCont.*.025],'Name',['Contrast file: ',ContFile],'Color',[1 1 1],'NumberTitle','off','tag','repcondeffig');
    hContFilePath = uicontrol(hRepConMenuFig,'visible','off');
    hContMat = uicontrol(hRepConMenuFig,'visible','off');
    set(hContFilePath,'userdata',hContFilePath);
    set(hContMat,'userdata',ContMat);
    RepConList =[hContFilePath hContMat];
    
    for ContInd=1:NCont
        btnPos=[0 1-ContInd./NCont 1 1/NCont];
        callbackStr='emegs2d(''ReturnCustomContrastCoeff'')'; 
        hRepConListMenu(ContInd)=uicontrol( ...
            'Style','radiobutton', ...
            'Units','normalized', ...
            'Position',btnPos, ...
            'String',ContStr(ContInd,:), ...
            'FontWeight','bold', ...
            'FontSize',12, ...
            'HorizontalAlignment','Right', ...
            'Value',0, ...
            'Callback',callbackStr,...
            'Enable','on');
        RepConList =[RepConList hRepConListMenu(ContInd)];
    end

    set(hRepConMenuFig,'userdata',RepConList);
    editmenu = uimenu(hRepConMenuFig,'Label','edit');
    editfilemenuitem = uimenu('Parent',editmenu,'Label','edit contrasts','Callback','edit(''RepConDef.txt'');');
    reloadfilemenuitem = uimenu('Parent',editmenu,'Label','reload contrasts','Callback','emegs2d(''UpdateRepConDef'');');
    contrastdeffigure = findobj('tag','contrastdeffigure');
    tmppos = get(contrastdeffigure,'position');
    tmppos(2) = 0.3 + NCont*0.025+0.04;
    set(contrastdeffigure,'position',tmppos);
    set(contrastdeffigure,'visible','on');
    return;
    %=============================================================================
	%=============================================================================	
    
elseif  strcmp(action,'CalcRepConListNorm') | ...
    strcmp(action,'CalcRepConListPerm')| ... 
    strcmp(action,'CalcRepConManuNorm')| ... 
    strcmp(action,'CalcRepConManuPerm') | ...       
    strcmp(action,'CalcCorrCoefList') | ...       
    strcmp(action,'CalcCorrCoefManu')
    
    hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
    MinPoint=get(hList(54),'Value');
	MaxPoint=get(hList(55),'Value');
	CalcBaseStatus=get(hList(57),'Value');	
	MinBase=get(hList(58),'Value');	
	MaxBase=get(hList(59),'Value');
	NChan=get(hList(NListHdr+2),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
    FileNoVec=get(hList(56),'Userdata');
    MaxNFiles=hList(140);
    AvgFileFormatExt=get(hList(NListHdr+(ActFileNo-1).*50+22),'String');	
    TargetSetNumber=ActFileNo;
    SampRate=get(hList(NListHdr+(TargetSetNumber-1).*50+7),'Userdata');
    ContName='Manu';

    if ~isempty(findstr(action,'List')); %Disabled
        %=====================Read ContMat from file=========================
        if ~isempty(findstr(action,'RepCon'))  
            RepConFile=['RepConDef.txt'];
        else
            RepConFile=['CorrCoefDef.txt'];
        end
        RepConFilePath=which(RepConFile)
        if ~exist(RepConFilePath); 
            RepConFilePath=[];
            Message=char('Sorry,');
            Message=char(Message,['can not find ',RepConFile,' in the Matlab path.']);
            Message=char(Message,'');
            Message=char(Message,'Please open a different file of proper format.');
            hMsgbox=msgbox(Message,'Info:','help');
        end
        
		[ContMat,ContStr,ContFile,ContPath,ContFilePath,ContNameMat]=ReadRepCon(RepConFilePath,['Search for ',RepConFilePath,':'],RepConFile);
        NCont=size(ContMat,1);
        hRepConMenuFig=figure('Units','normal','Position',[.35 0 .3 NCont.*.025],'Name',['Contrast file: ',ContFile],'Color',[1 1 1],'NumberTitle','off');
        for ContInd=1:NCont
            btnPos=[0 1-ContInd./NCont 1 1/NCont];
            callbackStr='emegs2d(''CalcRepConList'')'; 
            hRepConListMenu(ContInd)=uicontrol( ...
                'Style','radiobutton', ...
                'Units','normalized', ...
                'Position',btnPos, ...
                'String',ContStr(ContInd,:), ...
                'FontWeight','bold', ...
                'FontSize',12, ...
                'HorizontalAlignment','Right', ...
                'Value',0, ...
                'Callback',callbackStr,...
                'Enable','on');
        end
        uiwait; 
        for ContInd=1:NCont
            ContVec(ContInd)=get(hRepConListMenu(ContInd),'Value');
        end
        close(hRepConMenuFig);
        ContInd=find(ContVec==1);
        Weights=ContMat(ContInd,2:ContMat(ContInd,1)+1);
        ContName=deblank(ContNameMat(ContInd,:));
        if ~isempty(findstr(action,'RepCon')) & sum(Weights)~=0
            Message=char('Attention !!!');
            Message=char(Message,'');
            Message=char(Message,'Sum of weights has to be zero.');
            Message=char(Message,'');
            Message=char(Message,['Weights of contrast ',ContName,':']);
            Message=char(Message,'');
            Message=char(Message,num2str(WeightVec));
            hMsgbox=msgbox(Message,'Warning:','warn');
            uiwait;
        end  
    else
        WeightsStr=inputdlg({'Contrast weights:'},'Insert contrast weights:',1,{'1 -1'});
        Weights=str2num(char(WeightsStr));
    end
    PermStatus=0;
    if ~isempty(findstr(action,'Perm'));           
        PermStatus=1;
    end
    DataSetOrder=zeros(4,1);
    if ~isempty(findstr(action,'RepCon'))  
        NDataSetOrder=4;
        Str=inputdlg({'F, t, pF, pt data set order (1-6); Use i.e. [0 0 0 1] for pt at set 1; [0 2 0 5] for t at set 2 and pt at set 5'},'Insert data set order:',1,{'1 2 3 4'});
    else
        NDataSetOrder=2;
        Str=inputdlg({'r, p data set order (1-6); Use i.e. [0 1] for p at set 1; [6 5] for r at set 5 and p at set 6'},'Insert data set order:',1,{'1 2'});
    end
    Tmp=round(str2num(char(Str)));
    DataSetOrder(1:length(Tmp))=Tmp;
    DataSetIndVec=find(DataSetOrder>0 & DataSetOrder<=MaxNFiles)
    DataSetValVec=DataSetOrder(DataSetIndVec)
    NDataSets=length(DataSetIndVec)
    Tmp=find(DataSetOrder<1 | DataSetOrder>MaxNFiles);
    if ~isempty(Tmp)
        DataSetOrder(Tmp)=zeros(size(Tmp));
    end
    TempFiltStruc=get(hList(134),'Userdata');
    SpatFiltStruc=get(hList(135),'Userdata');
    CalcGradStatus=get(findobj('Tag','CalcGradClear'),'Userdata');
    CalcAbsStatus=get(findobj('Tag','CalcAbsClear'),'Userdata');
    if ~isempty(findstr(action,'RepCon'))
        [FMat,TMat,PFNMat,PTNMat,PFPMat,PTPMat,RMat,BatchFilePath,NChanExtra]= ...
        RepCon([],[],Weights,PermStatus,MinPoint,MaxPoint,CalcBaseStatus,MinBase,MaxBase,TempFiltStruc,SpatFiltStruc,CalcGradStatus,CalcAbsStatus);	
        if isempty(FMat); return; end
        if PermStatus==1;
            PFMat=PFPMat;
            PTMat=PTPMat;
        else
            PFMat=PFNMat;
            PTMat=PTNMat;
        end
    else
        PermStatus==1;
        [FMat,TMat,BatchFilePath,NChanExtra]= ...
        CalcAvgScadsCorrCoef([],Weights,MinPoint,MaxPoint,CalcBaseStatus,MinBase,MaxBase,TempFiltStruc,SpatFiltStruc,CalcGradStatus,CalcAbsStatus); 
        if isempty(FMat); return; end
   end
    [NChan,NPoints]=size(FMat);
    if DataSetOrder(1)~=0
        set(hList(NListHdr+(DataSetOrder(1)-1).*50+1),'Userdata',FMat(1:NChan,:));
	    set(hList(NListHdr+(DataSetOrder(1)-1).*50+24),'Userdata',FMat(1:NChan,:));
        set(hList(NListHdr+(DataSetOrder(1)-1).*50+2),'Userdata',NChan);
	    set(hList(NListHdr+(DataSetOrder(1)-1).*50+3),'Userdata',NPoints);
    end
    if DataSetOrder(2)~=0
        set(hList(NListHdr+(DataSetOrder(2)-1).*50+1),'Userdata',TMat(1:NChan,:));
	    set(hList(NListHdr+(DataSetOrder(2)-1).*50+24),'Userdata',TMat(1:NChan,:));
        set(hList(NListHdr+(DataSetOrder(2)-1).*50+2),'Userdata',NChan);
	    set(hList(NListHdr+(DataSetOrder(2)-1).*50+3),'Userdata',NPoints);
    end
    if DataSetOrder(3)~=0
        set(hList(NListHdr+(DataSetOrder(3)-1).*50+1),'Userdata',PFMat(1:NChan,:));
	    set(hList(NListHdr+(DataSetOrder(3)-1).*50+24),'Userdata',PFMat(1:NChan,:));
        set(hList(NListHdr+(DataSetOrder(3)-1).*50+2),'Userdata',NChan);
	    set(hList(NListHdr+(DataSetOrder(3)-1).*50+3),'Userdata',NPoints);
    end
    if DataSetOrder(4)~=0
        set(hList(NListHdr+(DataSetOrder(4)-1).*50+1),'Userdata',PTMat(1:NChan,:));
	    set(hList(NListHdr+(DataSetOrder(4)-1).*50+24),'Userdata',PTMat(1:NChan,:));
        set(hList(NListHdr+(DataSetOrder(4)-1).*50+2),'Userdata',NChan);
	    set(hList(NListHdr+(DataSetOrder(4)-1).*50+3),'Userdata',NPoints);
    end
    for i=1:NDataSets
        TargetSetNumber=DataSetValVec(i);
        if ~isempty(findstr(action,'RepCon'))
            if i==1
                Ext=['.',ContName,'.F'];
            elseif i==2
                Ext=['.',ContName,'.t'];
            elseif i==3
                Ext=['.',ContName,'.pF'];
            elseif i==4
                Ext=['.',ContName,'.pt'];
            end
        else
            if i==1
                Ext=['.',ContName,'.r'];
            elseif i==2
                Ext=['.',ContName,'.pr'];
            end
        end
        TargetFilePath=[BatchFilePath,Ext];
        set(hList(1),'Value',TargetSetNumber);	   %ActFileNumber
        emegs2d('setActFileNo');
        emegs2d('setColor');
        emegs2d('setLineStyle');
        if ~any(FileNoVec==TargetSetNumber)
            FileNoVec(length(FileNoVec)+1)=TargetSetNumber;
            FileNoVec=sort(FileNoVec);
        end
        set(hList(56),'Userdata',FileNoVec);
        hFileInfoTextVec=get(hList(17),'Userdata');
        hFileInfoText=hFileInfoTextVec(TargetSetNumber);
        VisibleStatus=get(hFileInfoText,'Visible');
        %--------- set enable value ----------
        if length(FileNoVec)==1
            set(hList(49),'Value',1);	
        elseif length(FileNoVec)==2
            set(hList(49),'Value',3);
        elseif length(FileNoVec)==4
            set(hList(49),'Value',5);
        else
            set(hList(49),'Value',7);	
        end;		
        emegs2d('EnableOnOff');	
        set(hList(108),'Value',0);						%hOpenAvgFileStatus
        emegs2d('setActAllVisible')
        set(hList(NListHdr+(TargetSetNumber-1).*50+4),'Userdata',TargetFilePath); %FilePath
        set(hList(NListHdr+(TargetSetNumber-1).*50+7),'Userdata',SampRate);
        emegs2d('SetActFileNoLabelString')
        if strcmp(VisibleStatus,'on'); emegs2d('DispFileNamesVisible'); end
        %--------------------------------------
    end
	emegs2d('PlotData');
    emegs2d('AdjustAmp');
    set(hList(1),'Value',1);	   %ActFileNumber
	emegs2d('setActFileNo');
    
    %=============================================================================
	%=============================================================================	

elseif  strcmp(action,'CalcTTestOne') | ...
        strcmp(action,'CalcTTestTwo') | ...
        strcmp(action,'CalcTTestPai') | ...
		strcmp(action,'CalcTTestSymLR') | ...
		strcmp(action,'CalcTTestSymFB') | ...
		strcmp(action,'CalcTTestPaires') | ...
        strcmp(action,'CalcTTestPairesp') | ...
        strcmp(action,'CalcTTestPaires10') | ...
        strcmp(action,'CalcTTestPai10') | ...
		strcmp(action,'CalcTTestPaip')

    if  strcmp(action,'CalcTTestPai10') |   strcmp(action,'CalcTTestPaires10') 
        displaymode = 1;
    elseif strcmp(action,'CalcTTestPaip') |   strcmp(action,'CalcTTestPairesp') 
        displaymode = 2;
    else
        displaymode = 0;
    end

    hCalcTTestPairesMenu = findobj('tag','hCalcTTestPairesMenu');
    restrictions = get(hCalcTTestPairesMenu,'Userdata');
    if ((strcmp(action,'CalcTTestPaires') | ...
        strcmp(action,'CalcTTestPairesp') | ...
        strcmp(action,'CalcTTestPaires10')) & isempty(restrictions))
        answer = questdlg('Cannot find user-defined restrictions! Do you want to use the default restrictions?','Error:','yes','exit','yes');
        if strcmp(answer,'yes')
            userdatacell = cell(1);
            minneighbours = 3;
            minpointsinrow = 4;
            alphavalue = 0.05;
            spherdist = 40;
            userdatacell = {minneighbours;minpointsinrow;alphavalue;spherdist};
            set(hCalcTTestPairesMenu,'Userdata',userdatacell);
            restrictedstatus = 1;
        else
            return;
        end
        
    elseif ((strcmp(action,'CalcTTestPaires') | ...
            strcmp(action,'CalcTTestPairesp') | ...
            strcmp(action,'CalcTTestPaires10')) & ~isempty(restrictions))
        
        if strcmp(action,'CalcTTestPaires') | strcmp(action,'CalcTTestPaires')
            restrictedstatus  = 1;
        elseif   strcmp(action,'CalcTTestPairesp') 
            restrictedstatus  = 2;
        elseif  strcmp(action,'CalcTTestPaires10') 
            restrictedstatus  = 3;
        end
    else
        restrictedstatus = 0;
    end
    
    
	hList=get(hPlot2dMenuFig,'Userdata');
	Domain=get(hList(20),'Value');
	NListHdr=get(hList(51),'Userdata');
	CalcBaseStatus=get(hList(57),'Value');	
	MinBase=get(hList(58),'Value');	
	MaxBase = get(hList(59),'Value');
	NChan=get(hList(NListHdr+2),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	AvgFileFormatExt=get(hList(NListHdr+(ActFileNo-1).*50+22),'String');	

    FlipMat=[];
	if strcmp(action(10:12),'One');
		TStatus=1;
        TTestStr=['One-sample-t-test'];
    elseif strcmp(action(10:12),'Two');
        TStatus=2;
        TTestStr=['Two-sample-t-test'];
    elseif strcmp(action(10:12),'Pai');
        TStatus=3;
        TTestStr=['Paired-t-test'];
    elseif strcmp(action(10:12),'Sym');
        TStatus=4;
        TTestStr=['Paired-t-test-of-',action(16:17),'-asymmetry'];
        FlipFile=['Flip',action(13:14),int2str(NChan),'.txt'];
        FlipFilePath=which(FlipFile);
        if ~exist(FlipFilePath); FlipFilePath=[]; end
		FlipMat=ReadAscii(FlipFilePath,['Search for ',FlipFile,':'],FlipFile);
		if isempty(FlipMat); return; end
    else
        error('Unknown TStatus')
    end
	[DefFilePath]=SetDefPath('r','*.rep');
    [DefFilePath]=SwitchGrandBatch(DefFilePath,'Grand2Batch',1);

	if TStatus==3
        if Domain==8
            [NFilesIn,InFileMat,NonUse,BatchFilePath]=ReadFileNames([],DefFilePath,'Choose an even number of wavelet files or batch file:');
			if NFilesIn==0; return; end
            if mod(NFilesIn,2)~=0
				Message=char(['The number of files chosen (',int2str(NFilesIn),') is not even.']);
				Message=char(Message,'');
				hmsgbox=msgbox(Message,'Info','help'); 
				return
			end
        else
			[NFilesIn,InFileMat,NonUse,BatchFilePath]=ReadFileNames([],DefFilePath,'Choose an even number of avg files or batch file:');
			if NFilesIn==0; return; end
            if mod(NFilesIn,2)~=0
				Message=char(['The number of files chosen (',int2str(NFilesIn),') is not even.']);
				Message=char(Message,'');
				hmsgbox=msgbox(Message,'Info','help'); 
				return
			end
        end
	else
		[NFilesIn,InFileMat,NonUse,BatchFilePath]=ReadFileNames([],DefFilePath,'Choose avg files or batch file:');
        if NFilesIn==0; return; end
	end
	if NFilesIn<2;
		Message=char('The minimum number of files is 2 !');
		Message=char(Message,'');
		hmsgbox=msgbox(Message,'Info','help'); 
		return
	end
	[BatchFile,BatchPath]=SepFilePath(BatchFilePath);
	TTestStr=[BatchFile,';-',TTestStr];
	SetDefPath(2,BatchPath);
	fprintf(1,'\n'); clc;
    if TStatus==2 | TStatus==3
        FileOrderStr=questdlg('File order ?','Please identify the file order ?','Paired (1 2, 1 2, ...)','Block (1 1 ..., 2 2 ...)','Cancel','Block (1 1 ..., 2 2 ...)');
        switch FileOrderStr
            case 'Paired (1 2, 1 2, ...)', 
                FileOrder=1;
            case 'Block (1 1 ..., 2 2 ...)', 
                FileOrder=2;
            case 'Cancel'
                return;
        end %Switch
        if FileOrder==1
            SampleVec1=[1:2:NFilesIn-1];
            SampleVec2=[2:2:NFilesIn];
        elseif FileOrder==2
            SampleVec1=[1:NFilesIn./2];
            SampleVec2=[NFilesIn./2+1:NFilesIn];
        end
        Message=char(['The actual file matrix contains the following ',int2str(NFilesIn./2),' pairs:']);
        fprintf(1,'The actual file matrix contains the following %g pairs:\n\n',NFilesIn./2);
		for PairInd=1:NFilesIn./2
            PairIndStr=int2str(PairInd);
            if PairInd<10; PairIndStr=['0',PairIndStr]; end
			Message=char(Message,'');
			Message=char(Message,[PairIndStr,': ',InFileMat(SampleVec1(PairInd),:)]);
			Message=char(Message,['   ',InFileMat(SampleVec2(PairInd),:)]);
		end
	else
        FileOrder=2;
		Message=char(['The actual file matrix contains the following ',int2str(NFilesIn),' files:']);
		fprintf(1,'The actual file matrix contains the following %g files:\n\n',NFilesIn);
		Message=char(Message,'');
        for FileInd=1:NFilesIn
            FileIndStr=int2str(FileInd);
            if FileInd<10; FileIndStr=['0',FileIndStr]; end
		    Message=char(Message,[FileIndStr,': ',InFileMat(FileInd,:)]);
        end
	end
	Message=char(Message,'');
	Message=char(Message,'');
	hmsgbox=msgbox(Message,'Info','help'); 
    set(hmsgbox,'Units','Normal');
    MsgBoxPos=get(hmsgbox,'Position');
    MsgBoxPos(1:2)=[0.1 0];
    set(hmsgbox,'Position',MsgBoxPos);
	pause(.001)
	disp(Message)
	OutFilePath=[];AddFileExt=[];SaveStatus=0;displaymode=0;
    TempFiltStruc=get(hList(134),'Userdata');
    SpatFiltStruc=get(hList(135),'Userdata');
    CalcGradStatus=get(findobj('Tag','CalcGradClear'),'Userdata');
    CalcAbsStatus=get(findobj('Tag','CalcAbsClear'),'Userdata');

	[OutFilePath,MiCsAvgMat,NTrialAvgVec,MiCsStdMat,SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra]=...
	CalcAvgScadsTStat(InFileMat,CalcBaseStatus,MinBase,MaxBase,SaveStatus,OutFilePath,AddFileExt,TStatus,CalcAbsStatus,FlipMat,...
    restrictedstatus,displaymode,TempFiltStruc,SpatFiltStruc,Domain,CalcGradStatus,FileOrder);
	TargetSetNumber=ActFileNo;

	set(hList(1),'Value',TargetSetNumber);	   %ActFileNumber
	emegs2d('setActFileNo');
	
    if Domain==8
        [NChanTot,NPoints,NFreq]=size(MiCsAvgMat);
		NChan=NChanTot-NChanExtra;
        
        WaveMat=get(hList(NListHdr+(ActFileNo-1).*50+36),'Userdata');
		set(hList(NListHdr+(TargetSetNumber-1).*50+1),'Userdata',MiCsAvgMat);
		set(hList(NListHdr+(TargetSetNumber-1).*50+24),'Userdata',MiCsAvgMat);
        set(hList(NListHdr+(TargetSetNumber-1).*50+36),'Userdata',MiCsAvgMat);
		set(hList(NListHdr+(TargetSetNumber-1).*50+2),'Userdata',NChan);
		set(hList(NListHdr+(TargetSetNumber-1).*50+3),'Userdata',NPoints);
		
		set(hList(NListHdr+(TargetSetNumber-1).*50+4),'Userdata',[BatchPath,TTestStr]);
		set(hList(NListHdr+(TargetSetNumber-1).*50+5),'Userdata',NTrialAvgVec);
		set(hList(NListHdr+(TargetSetNumber-1).*50+6),'Userdata',MiCsStdMat);
		set(hList(NListHdr+(TargetSetNumber-1).*50+7),'Userdata',SampRate);
    else
        [NChanTot,NPoints]=size(MiCsAvgMat);
        NChan=NChanTot-NChanExtra;
        set(hList(NListHdr+(TargetSetNumber-1).*50+1),'Userdata',MiCsAvgMat(1:NChan,:));
        set(hList(NListHdr+(TargetSetNumber-1).*50+24),'Userdata',MiCsAvgMat(1:NChan,:));
        set(hList(NListHdr+(TargetSetNumber-1).*50+2),'Userdata',NChan);
        set(hList(NListHdr+(TargetSetNumber-1).*50+3),'Userdata',NPoints);
        
        set(hList(NListHdr+(TargetSetNumber-1).*50+4),'Userdata',[BatchPath,TTestStr]);
        set(hList(NListHdr+(TargetSetNumber-1).*50+5),'Userdata',NTrialAvgVec);
        set(hList(NListHdr+(TargetSetNumber-1).*50+6),'Userdata',MiCsStdMat);
        set(hList(NListHdr+(TargetSetNumber-1).*50+7),'Userdata',SampRate);

    end
    emegs2d('setColor');
	emegs2d('setLineStyle');
	if ~any(FileNoVec==TargetSetNumber)
		FileNoVec(length(FileNoVec)+1)=TargetSetNumber;
		FileNoVec=sort(FileNoVec);
	end
	set(hList(56),'Userdata',FileNoVec);
	hFileInfoTextVec=get(hList(17),'Userdata');
	hFileInfoText=hFileInfoTextVec(TargetSetNumber);
	VisibleStatus=get(hFileInfoText,'Visible');
	if strcmp(VisibleStatus,'on'); emegs2d('DispFileNamesVisible'); end
	%--------- set enable value ----------
	if length(FileNoVec)==1
		set(hList(49),'Value',1);	
	elseif length(FileNoVec)==2
		set(hList(49),'Value',3);
	elseif length(FileNoVec)==4
		set(hList(49),'Value',5);
	else
		set(hList(49),'Value',7);	
	end;		
	emegs2d('EnableOnOff');	
	set(hList(108),'Value',0);						%hOpenAvgFileStatus
   	emegs2d('setActAllVisible')
   	emegs2d('SetActFileNoLabelString')
	%--------------------------------------
	emegs2d('PlotData');
    emegs2d('AdjustAmp');
	
	%=============================================================================
	%=============================================================================	
elseif  strcmp(action,'CalcMinMaxAllMaxAbs') | ...
		strcmp(action,'CalcMinMaxActMaxAbs') | ...
		strcmp(action,'CalcMinMaxAllMinAbs') | ...
		strcmp(action,'CalcMinMaxActMinAbs') | ...
		strcmp(action,'CalcMinMaxAllMMxAbs') | ...
		strcmp(action,'CalcMinMaxActMMxAbs') | ...
		strcmp(action,'CalcMinMaxAllMaxRel') | ...
		strcmp(action,'CalcMinMaxActMaxRel') | ...
		strcmp(action,'CalcMinMaxAllMinRel') | ...
		strcmp(action,'CalcMinMaxActMinRel') | ...
		strcmp(action,'CalcMinMaxAllMMxRel') | ...
		strcmp(action,'CalcMinMaxActMMxRel') | ...
		strcmp(action,'CalcMinMaxAllMaxARe') | ...
		strcmp(action,'CalcMinMaxActMaxARe') | ...
		strcmp(action,'CalcMinMaxAllMinARe') | ...
		strcmp(action,'CalcMinMaxActMinARe') | ...
		strcmp(action,'CalcMinMaxAllMMxARe') | ...
		strcmp(action,'CalcMinMaxActMMxARe'),
		
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	MinPoint=get(hList(54),'Value');
	MaxPoint=get(hList(55),'Value');
	hTopMenu=get(hList(65),'Userdata');
	hExportMenu=get(hTopMenu(3),'children');	
	hExportUserData=get(hExportMenu(1),'children'); 
	hUserDataInfo=get(hExportUserData(1),'children');
	
	if strcmp(action(11:13),'Act') 
		FileNoVec=FileNoVec(ActFileNo);
	end
	for FileIndex=1:length(FileNoVec)
		AvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		CalcAvgMat=AvgMat(:,MinPoint:MaxPoint);
		[NChan,NPoints]=size(CalcAvgMat);		
		UserDataMat=[];
		if strcmp(action(17:19),'Rel') | strcmp(action(17:19),'ARe')
			GradMat=gradient(CalcAvgMat);
			BinGradMat=(GradMat>0);
			DiffBinGradMat=diff(BinGradMat,1,2);
			CalcAvgMatMax=0.*CalcAvgMat;
			CalcAvgMatMin=0.*CalcAvgMat;
			if  strcmp(action(14:16),'Max') | strcmp(action(14:16),'MMx')
				DiffBinGradMatTmp=abs((DiffBinGradMat<0));
				CalcAvgMat1=CalcAvgMat(:,1:NPoints-1).*DiffBinGradMatTmp;
				CalcAvgMat2=CalcAvgMat(:,2:NPoints).*DiffBinGradMatTmp;
				Max1=(CalcAvgMat1>=CalcAvgMat2);
				Max2=(CalcAvgMat1<=CalcAvgMat2);
				CalcAvgMatMax(:,1:NPoints-1)=CalcAvgMat1.*Max1;
				CalcAvgMatMax(:,2:NPoints)=CalcAvgMatMax(:,2:NPoints)+CalcAvgMat2.*Max2;
				if strcmp(action(17:19),'ARe') 
					[MaxValVec,MaxIndVec]=max(CalcAvgMatMax,[],2);
					CalcAvgMatMax=0.*CalcAvgMatMax;
					for ChanInd=1:NChan
						CalcAvgMatMax(ChanInd,MaxIndVec(ChanInd))=MaxValVec(ChanInd);
					end
				end
			end
			if  strcmp(action(14:16),'Min') | strcmp(action(14:16),'MMx')
				DiffBinGradMatTmp=(DiffBinGradMat>0);
				CalcAvgMat1=CalcAvgMat(:,1:NPoints-1).*DiffBinGradMatTmp;
				CalcAvgMat2=CalcAvgMat(:,2:NPoints).*DiffBinGradMatTmp;
				Min1=(CalcAvgMat1<=CalcAvgMat2);
				Min2=(CalcAvgMat1>=CalcAvgMat2);
				CalcAvgMatMin(:,1:NPoints-1)=CalcAvgMat1.*Min1;
				CalcAvgMatMin(:,2:NPoints)=CalcAvgMatMin(:,2:NPoints)+CalcAvgMat2.*Min2;
				if strcmp(action(17:19),'ARe') 
					[MinValVec,MinIndVec]=min(CalcAvgMatMin,[],2);
					CalcAvgMatMin=0.*CalcAvgMatMin;
					for ChanInd=1:NChan
						CalcAvgMatMin(ChanInd,MinIndVec(ChanInd))=MinValVec(ChanInd);
					end
				end
			end			
		elseif strcmp(action(17:19),'Abs')	
			if  strcmp(action(14:16),'Max') | strcmp(action(14:16),'MMx')
				[MaxValVec,MaxIndVec]=max(CalcAvgMat,[],2);
				CalcAvgMatMax=0.*CalcAvgMat;
				for ChanInd=1:NChan
					CalcAvgMatMax(ChanInd,MaxIndVec(ChanInd))=MaxValVec(ChanInd);
				end
			end
			if  strcmp(action(14:16),'Min') | strcmp(action(14:16),'MMx')
				[MinValVec,MinIndVec]=min(CalcAvgMat,[],2);
				CalcAvgMatMin=0.*CalcAvgMat;
				for ChanInd=1:NChan
					CalcAvgMatMin(ChanInd,MinIndVec(ChanInd))=MinValVec(ChanInd);
				end
			end
			if strcmp(action(14:16),'MMx')
				UserDataMat=zeros(NChan,4);
				UserDataMat(:,1)=MaxValVec;
				UserDataMat(:,2)=MaxIndVec;
				UserDataMat(:,3)=MinValVec;
				UserDataMat(:,4)=MinIndVec;
			elseif strcmp(action(14:16),'Max')
				UserDataMat=zeros(NChan,2);
				UserDataMat(:,1)=MaxValVec;
				UserDataMat(:,2)=MaxIndVec;
			elseif strcmp(action(14:16),'Min')
				UserDataMat=zeros(NChan,2);
				UserDataMat(:,1)=MinValVec;
				UserDataMat(:,2)=MinIndVec;
			end
		end
		AvgMat=0.*AvgMat;
		AvgMat(:,MinPoint:MaxPoint)=CalcAvgMatMax+CalcAvgMatMin;
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',AvgMat);
	end
	if ~isempty(UserDataMat)
		set(hList(94),'Userdata',UserDataMat);
		set(hUserDataInfo,'Label',action);
		set(hExportUserData,'Enable','on');	%Export User data enable on
	end
	emegs2d('PlotData');
    
    %=============================================================================
	%=============================================================================	
elseif  ~isempty(findstr(action,'FiltSpat'))

	hList=get(hPlot2dMenuFig,'Userdata');
    if ~isempty(findstr(action,'Clear'))
        set(hList(135),'Userdata',[]);
        return;
    end
	NListHdr=get(hList(51),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	ECfgFilePath=get(hList(2),'Userdata');
	EPosSpher=get(hList(3),'Userdata');
	EPosCart=change_sphere_cart(EPosSpher,[],1);
	[ECfgFile,ECfgPath]=SepFilePath(ECfgFilePath);
	if strcmp(ECfgFile(length(ECfgFile)-4:length(ECfgFile)),'.ecfg')
		Ecfg=ECfgFile(1:length(ECfgFile)-5);
	else
		Ecfg=ECfgFile;
	end
	FileNoVec=get(hList(56),'Userdata');
	[NoUse,BasePath]=SepFilePath(which('emegs2d.m'));
	PathCoeff=[BasePath,'emegs3dCoeff40'];
	CosPhiMat=ExistCalcPhiMat(-1,EPosCart,EPosCart,PathCoeff,Ecfg);
	PhiMat=acos(CosPhiMat);
	SpatFiltStruc.PhiMat=PhiMat;
    MinDist=min(min(PhiMat+eye(size(PhiMat))))./pi.*180;
    PromptStr={['Please insert FWHM [deg]: (Minimum sensor distance: ',num2str(round(MinDist.*100)./100),')']};
    MinDist=round(max([MinDist,5]));
    DefStr={num2str(MinDist)};
    SigmaStr=inputdlg(PromptStr,'Sperical FWHM:',1,DefStr);
    Sigma=str2num(char(SigmaStr))./180.*pi;
    SpatFiltStruc.Sigma=Sigma;
	set(hList(135),'Userdata',SpatFiltStruc);
	if ~isempty(findstr(action,'Act'))
		FileNoVec=FileNoVec(ActFileNo);
	end	
	for FileIndex=1:length(FileNoVec)
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		CalcAvgMat=SpatFilt(CalcAvgMat,PhiMat,Sigma,1);
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat);
	end
	emegs2d('PlotData');
	emegs2d('AdjustAmp');

    %=============================================================================
	%=============================================================================	
    
elseif  strcmp(action,'FiltCoeffClear') | strcmp(action,'FiltSpatClear') | strcmp(action,'CalcGradClear')  | strcmp(action,'CalcAbsClear') 
    
    hList=get(hPlot2dMenuFig,'Userdata');
    if  strcmp(action,'FiltCoeffClear')
        set(hList(134),'Userdata',[]);
    elseif  strcmp(action,'FiltSpatClear')
        set(hList(135),'Userdata',[]);
    elseif  strcmp(action,'CalcGradClear')
        set(findobj('Tag','CalcGradClear'),'Userdata',0);
    elseif  strcmp(action,'CalcAbsClear')
        set(findobj('Tag','CalcAbsClear'),'Userdata',0);
    end
	%=============================================================================
	%=============================================================================	
elseif  strcmp(action,'SetHighFiltCoeff') | ...
		strcmp(action,'SetLowFiltCoeff') |...
		strcmp(action,'SetHighLowFiltCoeff') | ...
		strcmp(action,'SaveHighFiltCoeff') | ...
		strcmp(action,'SaveLowFiltCoeff') | ...
		strcmp(action,'SaveHighLowFiltCoeff') | ...
		strcmp(action,'OpenHighFiltCoeff') | ...
		strcmp(action,'OpenLowFiltCoeff') | ...
		strcmp(action,'OpenHighLowFiltCoeff') | ...
		strcmp(action,'CalcActFiltHigh') | ...
		strcmp(action,'CalcActFiltLow') | ...
		strcmp(action,'CalcActFiltHighLow') | ...
		strcmp(action,'CalcAllFiltLow') | ...
		strcmp(action,'CalcAllFiltHigh') | ...
		strcmp(action,'CalcAllFiltHighLow'),
		
	hList=get(hPlot2dMenuFig,'Userdata');
	hTopMenu=get(hList(65),'Userdata');
	hCalcMenu=get(hTopMenu(4),'children');
	hFilterMenu=hCalcMenu(12);
	Tmp=get(hFilterMenu,'children');
	
	hFilterData=Tmp(1);
	hOpenFilterFile=Tmp(2);
	hSaveFilterFile=Tmp(3);
	hSetFilterFile=Tmp(4);
	
	Tmp=get(hFilterData,'children');
	hFilterDataAct=Tmp(1);
	hFilterDataAll=Tmp(2);
	
	Tmp=get(hFilterDataAct,'children');
	hFilterDataActHighLow=Tmp(1);
	hFilterDataActLow=Tmp(2);
	hFilterDataActHigh=Tmp(3);
	
	Tmp=get(hFilterDataAll,'children');
	hFilterDataAllHighLow=Tmp(1);
	hFilterDataAllLow=Tmp(2);
	hFilterDataAllHigh=Tmp(3);
	
	Tmp=get(hSaveFilterFile,'children');
	hSaveFilterFileHighLow=Tmp(1);
	hSaveFilterFileLow=Tmp(2);
	hSaveFilterFileHigh=Tmp(3);
	
	MainMatlabVersion=get(hList(100),'Userdata');
    
	%peter
	ActFileNo=get(hList(1),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	SampRate=get(hList(60),'Userdata');
	hhFiltVec=get(hList(92),'Userdata');
	DefFreqsRipMat=get(hhFiltVec(1),'Userdata');
	NUsedFiles=length(FileNoVec);
	Tmp=get(hList(16),'Userdata'); NChan=Tmp(1);
	
    LowFiltCoeff=[];
    HighFiltCoeff=[];
    
	if strcmp(action,'SetLowFiltCoeff') | strcmp(action,'SetHighLowFiltCoeff') 
		DefFreqsRipMat(1,:)=DefFreqsRipMat(3,:);
		DefFreqsRipMat(2,:)=DefFreqsRipMat(4,:);
		set(hhFiltVec(1),'Userdata',DefFreqsRipMat);
		[NonUse,NonUse,NonUse,figNumber]=GetLowFiltCoeff('initialize');
		uiwait(figNumber);
		LowFiltCoeff=get(hhFiltVec(2),'Userdata');
		if ~isempty(LowFiltCoeff)
			set(hFilterData,'Enable','on')
			set(hFilterDataAllLow,'Enable','on')
			set(hFilterDataActLow,'Enable','on')
			set(hSaveFilterFile,'Enable','on')
			set(hSaveFilterFileLow,'Enable','on')
			HighFiltCoeff=get(hhFiltVec(3),'Userdata');
			if ~isempty(HighFiltCoeff)
				set(hFilterDataAllHighLow,'Enable','on')
				set(hFilterDataActHighLow,'Enable','on')
			end
		end
	end
	if strcmp(action,'SetHighFiltCoeff')  | strcmp(action,'SetHighLowFiltCoeff') 
		DefFreqsRipMat(1,:)=DefFreqsRipMat(5,:);
		DefFreqsRipMat(2,:)=DefFreqsRipMat(6,:);
		set(hhFiltVec(1),'Userdata',DefFreqsRipMat);
		[NonUse,NonUse,NonUse,figNumber]=GetHighFiltCoeff('initialize');
        uiwait(figNumber);
		HighFiltCoeff=get(hhFiltVec(3),'Userdata');
		if ~isempty(HighFiltCoeff)
			set(hFilterData,'Enable','on')
			set(hFilterDataAllHigh,'Enable','on')
			set(hFilterDataActHigh,'Enable','on')
			set(hSaveFilterFile,'Enable','on')
			set(hSaveFilterFileHigh,'Enable','on')
			LowFiltCoeff=get(hhFiltVec(2),'Userdata');
			if ~isempty(LowFiltCoeff)
				set(hFilterDataAllHighLow,'Enable','on')
				set(hFilterDataActHighLow,'Enable','on')
			end
		end
	end
	Return2OldPathStatus=0;
	if ~isempty(findstr(action,'Save')) | ~isempty(findstr(action,'Open')); 
		FullFilePath=which('20HzPass25HzStopButter250.lf');
		if ~isempty(FullFilePath);
            [FullFile,FullPath]=SepFilePath(FullFilePath);
			if FullPath(end)==filesep
				FullPath=FullPath(1:length(FullPath)-1);
			end
			OldPath=pwd;
		 	eval(['cd ',FullPath]); 
			Return2OldPathStatus=1;
		end
	end
	if strcmp(action,'SaveHighLowFiltCoeff') | strcmp(action,'SaveLowFiltCoeff') 
		LowFiltCoeff=get(hhFiltVec(2),'Userdata');
		[LowFiltFile,LowFiltPath,LowFiltFilePath]=WriteFilePath(['*',int2str(SampRate),'.lf'],'Save LowFiltCoeff to file:');
		[LowFiltCoeffFilePath]=Save2Bem(LowFiltCoeff,[],LowFiltFilePath,1,'Matrix','Ascii',[],10);
	end
	if strcmp(action,'SaveHighLowFiltCoeff') | strcmp(action,'SaveHighFiltCoeff') 
		HighFiltCoeff=get(hhFiltVec(3),'Userdata');
		[HighFiltFile,HighFiltPath,HighFiltFilePath]=WriteFilePath(['*',int2str(SampRate),'.hf'],'Save HighFiltCoeff to file:');
		[HighFiltCoeffFilePath]=Save2Bem(HighFiltCoeff,[],HighFiltFilePath,1,'Matrix','Ascii',[],10);
	end
	if strcmp(action,'OpenHighLowFiltCoeff') | strcmp(action,'OpenLowFiltCoeff')
		[LowFiltFile,LowFiltPath,LowFiltFilePath]=ReadFilePath([],['*',int2str(SampRate),'.lf'],'Open lowpass file:');
		if LowFiltFile==0; return; end
		[LowFiltCoeff] = ReadBem(LowFiltFilePath,1,'Matrix','Ascii');
		if isempty(LowFiltCoeff); return; end
		SizeLowFiltCoeff=size(LowFiltCoeff);
		if SizeLowFiltCoeff(1)~=2 & SizeLowFiltCoeff(2)==2; LowFiltCoeff=LowFiltCoeff'; end
		set(hhFiltVec(2),'Userdata',LowFiltCoeff);
		set(hFilterData,'Enable','on')
		set(hFilterDataAllLow,'Enable','on')
		set(hFilterDataActLow,'Enable','on')
		set(hSaveFilterFile,'Enable','on')
		set(hSaveFilterFileLow,'Enable','on')
		HighFiltCoeff=get(hhFiltVec(3),'Userdata')
		if ~isempty(HighFiltCoeff)
			set(hFilterDataAllHighLow,'Enable','on')
			set(hFilterDataActHighLow,'Enable','on')
		end
	end
	if strcmp(action,'OpenHighLowFiltCoeff') | strcmp(action,'OpenHighFiltCoeff')
		[HighFiltFile,HighFiltPath,HighFiltFilePath]=ReadFilePath([],['*',int2str(SampRate),'.hf'],'Open highpass file:');
		if HighFiltFile==0; return; end
		HighFiltCoeff=ReadBem(HighFiltFilePath,1,'Matrix','Ascii')
		SizeHighFiltCoeff=size(HighFiltCoeff);
		if SizeHighFiltCoeff(1)~=2 & SizeHighFiltCoeff(2)==2; HighFiltCoeff=HighFiltCoeff'; end
		set(hhFiltVec(3),'Userdata',HighFiltCoeff);
		set(hFilterData,'Enable','on')
		set(hFilterDataAllHigh,'Enable','on')
		set(hFilterDataActHigh,'Enable','on')
		set(hSaveFilterFile,'Enable','on')
		set(hSaveFilterFileHigh,'Enable','on')
		LowFiltCoeff=get(hhFiltVec(2),'Userdata');
		if ~isempty(LowFiltCoeff)
			set(hFilterDataAllHighLow,'Enable','on')
			set(hFilterDataActHighLow,'Enable','on')
		end
	end
	if strcmp(action,'CalcActFiltHigh') | ...
		strcmp(action,'CalcActFiltLow') | ...
		strcmp(action,'CalcActFiltHighLow') | ...
		strcmp(action,'CalcAllFiltHigh') | ...
		strcmp(action,'CalcAllFiltLow') | ...
		strcmp(action,'CalcAllFiltHighLow'),
		
		LowFiltCoeff=get(hhFiltVec(2),'Userdata');
		HighFiltCoeff=get(hhFiltVec(3),'Userdata');
		
		if strcmp(action,'CalcActFiltHigh') | ...
			strcmp(action,'CalcActFiltLow') | ...
			strcmp(action,'CalcActFiltHighLow')
			
			FileNoVec=FileNoVec(ActFileNo);
		end
		for FileIndex=1:length(FileNoVec)
			CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
			if strcmp(action,'CalcActFiltLow') | ...
				strcmp(action,'CalcActFiltHighLow') | ...
				strcmp(action,'CalcAllFiltLow') | ...
				strcmp(action,'CalcAllFiltHighLow'),
				if length(LowFiltCoeff)~=0
					for i=1:NChan
						CalcAvgMat(i,:)=(filtfilt(LowFiltCoeff(1,:),LowFiltCoeff(2,:),CalcAvgMat(i,:)'))';
					end
				end
			end
			if strcmp(action,'CalcActFiltHigh') | ...
				strcmp(action,'CalcActFiltHighLow') | ...
				strcmp(action,'CalcAllFiltHigh') | ...
				strcmp(action,'CalcAllFiltHighLow'),
				if length(HighFiltCoeff)~=0
					for i=1:NChan
						CalcAvgMat(i,:)=(filtfilt(HighFiltCoeff(1,:),HighFiltCoeff(2,:),CalcAvgMat(i,:)'))';
					end
				end
			end
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat);
		end
		emegs2d('PlotData');
	end
	if Return2OldPathStatus
		eval(['cd ',OldPath]); 
	end
    TempFiltStruc.LowFiltCoeff=LowFiltCoeff;
    TempFiltStruc.HighFiltCoeff=HighFiltCoeff;
    set(hList(134),'Userdata',TempFiltStruc);
    if strcmp(action,'SetHighFiltCoeff') | ...
            strcmp(action,'SetHighLowFiltCoeff') | ...
            strcmp(action,'OpenHighFiltCoeff') | ...
            strcmp(action,'OpenHighLowFiltCoeff')
        answer = questdlg('Filter data highpass ?','Info:','Actual set','All sets','Cancel','All sets');
        switch answer,
            case 'Actual set', 
                emegs2d('CalcActFiltHigh')
            case 'All sets',
                emegs2d('CalcAllFiltHigh')
        end % switch
    end
    if strcmp(action,'SetLowFiltCoeff') |...
            strcmp(action,'SetHighLowFiltCoeff') | ...
            strcmp(action,'OpenLowFiltCoeff') | ...
            strcmp(action,'OpenHighLowFiltCoeff')
        answer = questdlg('Filter data lowpass ?','Info:','Actual set','All sets','Cancel','All sets');
        switch answer,
            case 'Actual set', 
                emegs2d('CalcActFiltLow')
            case 'All sets',
                emegs2d('CalcAllFiltLow')
        end % switch
    end
    
	%=============================================================================
	%=============================================================================	
elseif  strcmp(action,'setCalcSampleStatus') 

	hList=get(hPlot2dMenuFig,'Userdata');
	CalcSampleStatus=get(hList(60),'Value');	
	hTopMenu=get(hList(65),'Userdata');
	hCalcMenu=get(hTopMenu(4),'children');
	SampleLabel=get(hCalcMenu(5),'Label');
	PointPos=get(hCalcMenu(5),'Userdata');
	pointer=get(hList(83),'Userdata');	
	if CalcSampleStatus==0;
		CalcSampleStatus=1; 
		SampleLabel(PointPos)=setstr(pointer);
	elseif CalcSampleStatus==1; 
		CalcSampleStatus=0; 
		SampleLabel(PointPos)=' ';
	end
	SampleLabel
	set(hCalcMenu(5),'Label',SampleLabel);
	set(hList(60),'Value',CalcSampleStatus);	
	

	%=============================================================================
	%============ setSampRate
	%=============================================================================	
	
elseif strcmp(action,'setSampRate'),

   	hList=get(hPlot2dMenuFig,'Userdata');
  	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');

	SampRate = get(hList(60),'Userdata');
   	SampRateString = get(hList(60),'String');
	CalcSampleStatus=get(hList(60),'Value');
	
    ind = find(abs(SampRateString)<32);
    SampRateString(ind) = 32*ones(size(ind));
    SampRateString = SampRateString';	
    SampRateTmp = eval(['[' SampRateString(:)' ']'],'-1')';
	if SampRateTmp<=0
		SampRateTmp=SampRate;
	end
	if ~CalcSampleStatus;
		SampRateString = sprintf('%g',SampRateTmp);
		set(hList(60),'Userdata',SampRateTmp,'String',SampRateString);
		set(hList(NListHdr+(ActFileNo-1).*50+7),'Userdata',SampRateTmp);
		emegs2d('setMinMaxAmpPoint')
		return; 
	end
	
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	NChan=get(hList(NListHdr+2),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	FacSampNewOld=SampRateTmp./SampRate;
	NPointsTmp=floor(NPoints.*FacSampNewOld);
	set(hList(NListHdr+3),'Userdata',NPointsTmp);
	XVec=[1:NPoints];
	XInterVec=linspace(1,NPoints,NPointsTmp);
	for FileIndex=1:length(FileNoVec)
		SampRate=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+7),'Userdata');
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		AvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+24),'Userdata');
		StdChanTimeMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+6),'Userdata');			
		CalcAvgMatTmp=zeros(NChan,NPointsTmp);
		AvgMatTmp=zeros(NChan,NPointsTmp);
		StdChanTimeMatTmp=zeros(NChan,NPointsTmp);
		for ChanInd=1:NChan
			CalcAvgMatTmp(ChanInd,:)=interp1(XVec,CalcAvgMat(ChanInd,:),XInterVec);
			AvgMatTmp(ChanInd,:)=interp1(XVec,AvgMat(ChanInd,:),XInterVec);
			StdChanTimeMatTmp(ChanInd,:)=interp1(XVec,StdChanTimeMat(ChanInd,:),XInterVec);
		end
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+3),'Userdata',NPointsTmp);
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+7),'Userdata',SampRate);
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMatTmp);
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+24),'Userdata',AvgMatTmp);
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+6),'Userdata',StdChanTimeMatTmp);
	end
	SampRateString = sprintf('%g',SampRateTmp);
	set(hList(60),'Userdata',SampRateTmp,'String',SampRateString);
	NPointsString=sprintf('%g',NPointsTmp);
	set(hList(302),'Userdata',NPointsTmp,'String',NPointsString);
	emegs2d('SetFirstVal');
	emegs2d('CalcFirst');
	emegs2d('CalcBase');%%
	emegs2d('SetColor');
	emegs2d('SetLineStyle');
	emegs2d('InitChanAxes')
	emegs2d('PlotData');

	%=============================================================================
	%=============================================================================		
elseif strcmp(action,'PlotData'),

	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	Domain=get(hList(20),'Value');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	ActFileNo=get(hList(1),'Userdata');
	Spec1Axes=get(hList(76),'Userdata');
	set(Spec1Axes,'Visible','on');
	Spec1ZeroLine=get(hList(77),'Userdata');
	set(Spec1ZeroLine,'Visible','on');
	hAxesVec=get(hList(6),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	if Domain==6 | Domain==7		%Wavelet
		hDataVec=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+25),'Userdata');
		NActChan=length(hDataVec);
		WaveVec=get(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata');
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+36),'Userdata');
		MinPoint=get(hList(54),'Value');
		MaxPoint=get(hList(55),'Value');
		MinF0Point=WaveVec(12);
		MaxF0Point=WaveVec(13);
		MinAmp=get(hList(52),'Value');
		MaxAmp=get(hList(53),'Value');
        for ChanInd=1:NActChan
			axes(hAxesVec(ChanInd));
			TmpMat=squeeze(CalcAvgMat(ChanInd,:,:));
			hDataVec(ChanInd)=surf(TmpMat');
            axis([MinPoint,MaxPoint,MinF0Point,MaxF0Point,MinAmp,MaxAmp]);
			set(gca,'CLim',[MinAmp,MaxAmp]);
			view(0,90);
			shading interp;
			axis('off');
			pause(.001)
		end
		set(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+25),'Userdata',hDataVec);
		return
	end
    if Domain == 8
        if length(FileNoVec)>=ActFileNo
            hDataVec=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+25),'Userdata');
			NActChan=length(hDataVec);
			WaveVec=get(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata');
            WaveMat=get(hList(NListHdr+(ActFileNo-1).*50+36),'Userdata');
            
			MinPoint=get(hList(54),'Value');
			MaxPoint=get(hList(55),'Value');
			MinF0Point=WaveVec(12);
			MaxF0Point=WaveVec(13);
			MinAmp=get(hList(52),'Value');
			MaxAmp=get(hList(53),'Value');
            if MaxAmp<MinAmp
                emegs2d('AdustAmp');
				MinAmp=get(hList(52),'Value');
				MaxAmp=get(hList(53),'Value');
            end
            if any(strcmp(who('global'),'hGetFrequIntervalMenuFig'))
				global hGetFrequIntervalMenuFig
			end
			GetFrequIntervalMenuList=get(hGetFrequIntervalMenuFig,'Userdata'); 
			MinF0Point=get(GetFrequIntervalMenuList(4),'Value');
			MaxF0Point=get(GetFrequIntervalMenuList(7),'Value');
            
			MinF0Val=str2num(get(GetFrequIntervalMenuList(3),'String'));
			MaxF0Val=str2num(get(GetFrequIntervalMenuList(6),'String'));
            CalcAvgMat=WaveMat(:,MinPoint:MaxPoint,MinF0Point:MaxF0Point);
            if ~isempty(findobj('tag','waveletimg'))
                delete(findobj('tag','waveletimg'))
            end
            for ChanInd=1:NActChan
                axes(hAxesVec(ChanInd));
                holdstatus = ishold;
                if holdstatus == 0
                    hold on
                end
				TmpMat=squeeze(CalcAvgMat(ChanInd,:,:));
                himage = image('XData',[MinPoint MaxPoint],'YData',[MinF0Val MaxF0Val], 'CData',TmpMat','CDataMapping','scaled',...
                    'ButtonDownFcn',['emegs2d(''ZoomSpecChan'',',num2str(ChanInd),');'],'tag','waveletimg');
                set(gca,'CLim',[MinAmp MaxAmp],'XLim',[MinPoint MaxPoint],'YLim',[MinF0Val MaxF0Val]);           
                view(0,90);
				axis('off');
                if holdstatus == 0
                    hold off
                end
			end
			set(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+25),'Userdata',hDataVec);
			return
        end
    end
	for FileIndex=1:NUsedFiles
		hDataVec=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+25),'Userdata');
		NActChan=length(hDataVec);
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		[NChan,NPoints]=size(CalcAvgMat);
		ActColor=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+16),'Userdata');
		ActLineStyle=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+17),'Userdata');
        kActAxes=get(hList(27),'Userdata');
        VisibleStatusVec=get(hDataVec,'Visible');
		for ChanInd=1:NActChan
			set(hDataVec(ChanInd),'XData',[1:NPoints],'YData',CalcAvgMat(kActAxes(ChanInd),:),'Color',ActColor,'LineStyle',ActLineStyle);
			if strcmp(VisibleStatusVec(ChanInd,:),'off')
				set(hDataVec(ChanInd),'Visible','off')
			else
				set(hDataVec(ChanInd),'Visible','on')
			end
		end
	end
	figure(hPlot2dMenuFig);
	
	%=============================================================================
	%============ InitializeGlobPowMenue: figure and menu for global power graph
	%============ call: CalcGlobalPower
	%=============================================================================	
elseif strcmp(action,'InitializeGlobPowMenue'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	Domain=get(hList(20),'Value');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	kActAxes=get(hList(27),'Userdata');
	NActChan=length(kActAxes);

	MinAmp=get(hList(52),'Value');
	MaxAmp=get(hList(53),'Value');
	MinPoint=get(hList(54),'Value');
	MSMinPointString=get(hList(54),'String');
	MaxPoint=get(hList(55),'Value');
	MSMaxPointString=get(hList(55),'String');
	NChan=get(hList(NListHdr+2),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	SampRate=get(hList(60),'Userdata');	
	TrigPoint=get(hList(22),'Value');
	CursorPoint=get(hList(23),'Value');
	CursorPointString=get(hList(23),'String');    
	if CursorPoint<MinPoint
		CursorPoint=MinPoint;
		CursorPointString=MSMinPointString;
	elseif CursorPoint>MaxPoint
		CursorPoint=MaxPoint;
		CursorPointString=MSMaxPointString;
	end 
	hhGPVec=get(hList(66),'Userdata');	
	
	kActAxes=get(hList(27),'Userdata');
	ActAxes=get(hList(28),'Userdata');
	TrigLength=1;		%TrigLength=get(hList(29),'Userdata');
	CursorLength=1;	%CursorLength=get(hList(30),'Userdata'); 
	BGColor=get(hList(93),'Color');
	
	MainMatlabVersion=get(hList(100),'Userdata');
	SegmentMS=get(hList(101),'Userdata');
	hSetEegMegStatus=hList(110);
	%===================================
	%===================================
	%===================================
	
	 if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
	    ChanFigPosVec=[0.01,.5,.33,.5];	
		if Domain<3 | Domain==6 | Domain==7
      		MenuFigPosVec=[.01,.01,.175,.4];
		else
      		MenuFigPosVec=[.01,.155,.25,.275];
		end
    elseif strcmp(computer,'PCWIN') 
	    ChanFigPosVec=[0.11,.45,.33,.5];	
		if Domain<3 | Domain==6 | Domain==7 | Domain==8
      		MenuFigPosVec=[.11,.01,.2,.42];
		else
      		MenuFigPosVec=[.11,.155,.25,.275];
		end
   	elseif strcmp(computer,'SOL2') | strcmp(computer,'LNX86') | strcmp(computer,'GLNX86')
      	ChanFigPosVec=[0.01,.42,.33,.5];	
		if Domain<3 | Domain==6 | Domain==7
      		MenuFigPosVec=[.01,.055,.175,.275];
		else
      		MenuFigPosVec=[.01,.055,.225,.275];
		end
   	end
    CloseRequestFcnStr='emegs2d(''CloseGpPlot'')';
	hGlobPowFig=figure('Units','normal','NumberTitle','off','Position',ChanFigPosVec,'Tag','GpPlot','Name','GP / RMS Plot','CloseRequestFcn',CloseRequestFcnStr);
	hhGPVec(15)=hGlobPowFig;
	hGlobPowMenu=figure('Units','normal','NumberTitle','off','Position',MenuFigPosVec,'Tag','GpMenu','Name','GP / RMS Menu');
	hhGPVec(16)=hGlobPowMenu;

	hList(71)=hGlobPowFig;
	% Information for all global power buttons
	labelColor=[0.8 0.8 0.8];
	yInitPos=0.90;
	menutop=0.95;
	btnTop = 0.6;
	top=0.75;
	left=0.125;
	btnWid=0.8;
	btnHt=0.105;
	textHeight = 0.05;
	textWidth = 0.06;
	% Spacing between the button and the next command's label
	spacing=0.01;

	% The CONSOLE frame
	frmBorder=0.019; frmBottom=0.04; 
	frmHeight = 0.92; frmWidth = btnWid;
	yPos=frmBottom-frmBorder;
	frmPos=[left-frmBorder yPos frmWidth+2*frmBorder frmHeight+2*frmBorder];
	h=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',frmPos, ...
	    'BackgroundColor',[0 0 0.3]);
	
	%===== Time <-> Frequency =========
	EegMegStatusString=get(hSetEegMegStatus,'String');
	if strcmp(EegMegStatusString,'EEG'); EegMegString='µV^2'; else; EegMegString='fT^2'; end
	if Domain<3 | Domain==6 | Domain==7 | Domain == 8
		MenuTextString1=['Min. amp [',EegMegString,']'];
		MenuTextString2=['Max. amp [',EegMegString,']'];	
		MenuTextString3=['Min. time [ms]; #',int2str(MinPoint)];
		MenuTextString4=['Max. time [ms]; #',int2str(MaxPoint)];
		MenuTextString5=['Cursor [ms]; #',int2str(CursorPoint)];
	else
		MenuTextString1=['Min. amp [',EegMegString,'/Hz]'];
		MenuTextString2=['Max. amp [',EegMegString,'/Hz]'];
		MenuTextString3=['Min.frquz. [Hz]; #',int2str(MinPoint)];
		MenuTextString4=['Max.frquz. [Hz]; #',int2str(MaxPoint)];
		MenuTextString5=['Cursor [Hz]; #',int2str(CursorPoint)];
	end
	%===================================
	% MinGlobPowAmpHandle
	btnNumber=1;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
    
	hGPMinAmpText= uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String',MenuTextString1);
	hhGPVec(11)=hGPMinAmpText;
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
	callbackStr = 'emegs2d(''setGlobPowMinAmp'')';
    
	hGPMinAmp = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String','0',...
	'Value',0, ...
	'callback',callbackStr);
	hhGPVec(1)=hGPMinAmp;
	
	%===================================
  	
	% MaxGlobPowAmpHandle
	btnPos=[left yPos-btnHt 2.*btnWid./3 btnHt./2];
    
	hGPMaxAmpText= uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String',MenuTextString2);
	hhGPVec(12)=hGPMaxAmpText;
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt btnWid./3 1.*btnHt./2];
	callbackStr = 'emegs2d(''setGlobPowMaxAmp'')';
    
	hGPMaxAmp = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String','10',...
	'Value',10, ...
	'callback',callbackStr);
	hhGPVec(2)=hGPMaxAmp;
	
	%===================================
	btnNumber=2;     	
	% Adjust GlobPow Amplitude
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 2*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''AdjustGlobPowAmp'')';
	hAdjustGlobPowAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Adjust', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	
	% Center GlobPow Amplitude
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt 2*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''CenterGlobPowAmp'')';
	hCenterGlobPowAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Center', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	
	% Decrease/Increase  GlobPow Status
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+2.*btnWid./8 yPos-btnHt./2 2.*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''DecIncGlobPowSta'')';
	hDecIncGlobPowStaAmp = uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Userdata',[1 1],...
	'String','+ 1',...
	'Callback',callbackStr,...
	'Enable','on');
	hhGPVec(18)=hDecIncGlobPowStaAmp;
	
	% Invert View
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+2.*btnWid./8 yPos-btnHt 2*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''InvertGlobPowView'')';
	hInvertGlobPowView=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','View', ...
	'Userdata',1,...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	hhGPVec(19)=hInvertGlobPowView;
	%==================================================
	
	%Decrease  of GlobPow Amplitude
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+4.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''DecGlobPowAmp'')';
	hDecGlobPowAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','<', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	
	% Decrease Decrease/Increase  Amplitude of GlobPow 
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+5.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''DecDecIncGlobPowAmp'')';
	hDecDecIncAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','<<', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	
	%Increase Decrease/Increase Amplitude
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+6.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''IncDecIncGlobPowAmp'')';
	hIncDecIncGlobPowAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','>>', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	
	% Slow Increase of GlobPow Amplitude
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+7.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''IncGlobPowAmp'')';
	hIncGlobPowAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','>', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	%===================================
	
	%===================================
	% MinGlobPowPointHandle
	btnNumber=3;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
    
	hGPMinPointText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String',MenuTextString3);
	hhGPVec(13)=hGPMinPointText;
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
	callbackStr = 'emegs2d(''setGPMinPoint'')';
    
	hGPMinPoint = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String',MSMinPointString,...		% '0'	
	'Value',MinPoint, ...				%  1		
	'callback',callbackStr);
	hhGPVec(3)=hGPMinPoint;
	
	NPointsTmp=MaxPoint-MinPoint+1;
	if NPointsTmp>=10
		SliderStep=[1./NPointsTmp 10./NPointsTmp];
	else
		SliderStep=[.1 1];
	end
	btnPos=[left yPos-btnHt btnWid btnHt./2];
	callbackStr = 'emegs2d(''setGPMinPointSlider'')';
	hGPMinPointSlider=uicontrol( ...
	'Style','slider', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Cursor', ...
	'HorizontalAlignment','center',...
	'Userdata',[], ...
	'Min',1, ...
	'Max',NPoints, ...
	'SliderStep',SliderStep, ...
	'Value',MinPoint, ...
	'Callback',callbackStr,...
	'Enable','on');
	hhGPVec(22)=hGPMinPointSlider;
	%===================================
  	% MaxGlobPowPointHandle
	btnNumber=4;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
    
	hGPMaxPointText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String',MenuTextString4);
	hhGPVec(14)=hGPMaxPointText;
    
	btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
	callbackStr = 'emegs2d(''setGPMaxPoint'')';
    
	hGPMaxPoint = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String',MSMaxPointString,...		
	'Value',MaxPoint,...			% NPoints
	'callback',callbackStr);
	hhGPVec(4)=hGPMaxPoint;
		
	btnPos=[left yPos-btnHt btnWid btnHt./2];
	callbackStr = 'emegs2d(''setGPMaxPointSlider'')';
	hGPMaxPointSlider=uicontrol( ...
	'Style','slider', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Cursor', ...
	'HorizontalAlignment','center',...
	'Userdata',[], ...
	'Min',1, ...
	'Max',NPoints, ...
	'SliderStep',SliderStep, ...
	'Value',MaxPoint, ...
	'Callback',callbackStr,...
	'Enable','on');
	hhGPVec(23)=hGPMaxPointSlider;
	
	if Domain ==6 | Domain==7	| Domain==8 
		
		WaveVec=get(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata');
		NFrequ=WaveVec(4);
		StartF0=WaveVec(7);
		EndF0=WaveVec(8);
		DeltaF0=WaveVec(9);
		F0Vec=[StartF0:DeltaF0:EndF0];
		StartF0IndPlot=WaveVec(12);
		EndF0IndPlot=WaveVec(13);
	
		if NFrequ>=10
			SliderStep=[1./NFrequ 10./NFrequ];
		else
			SliderStep=[.1 1];
		end
		%============MinFrequHandle ================================= 
		btnNumber=5;    
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
		
		hGPMinFrequText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String','Min. frequency [Hz]');
		
		btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
		callbackStr = 'emegs2d(''setGPMinFrequPoint'')';
		
		hGPMinFrequPoint = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String',num2str(round(F0Vec(StartF0IndPlot).*100)./100),...
		'Value',StartF0IndPlot, ...
		'callback',callbackStr);
		
		hhGPVec(24)=hGPMinFrequPoint;
		
		btnPos=[left yPos-btnHt btnWid btnHt./2];
		callbackStr = 'emegs2d(''setGPMinFrequPointSlider'')';
		hGPMinFrequPointSlider=uicontrol( ...
		'Style','slider', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','Cursor', ...
		'HorizontalAlignment','center',...
		'Userdata',[], ...
		'Min',1, ...
		'Max',NFrequ, ...
		'SliderStep',SliderStep, ...
		'Value',StartF0IndPlot, ...
		'Callback',callbackStr);
		hhGPVec(25)=hGPMinFrequPointSlider;
		
		%============MaxFrequHandle ================================= 
		btnNumber=6;    
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
		
		hGPMaxFrequText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String','Max. frequency [Hz]');
		
		btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
		callbackStr = 'emegs2d(''setGPMaxFrequPoint'')';
		
		hGPMaxFrequPoint = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String',num2str(round(F0Vec(EndF0IndPlot).*100)./100),...
		'Value',EndF0IndPlot, ...
		'callback',callbackStr);
		
		hhGPVec(26)=hGPMaxFrequPoint;
		
		btnPos=[left yPos-btnHt btnWid btnHt./2];
		callbackStr = 'emegs2d(''setGPMaxFrequPointSlider'')';
		
		hGPMaxFrequPointSlider=uicontrol( ...
		'Style','slider', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','Cursor', ...
		'HorizontalAlignment','center',...
		'Userdata',[], ...
		'Min',1, ...
		'Max',NFrequ, ...
		'SliderStep',SliderStep, ...
		'Value',EndF0IndPlot, ...
		'Callback',callbackStr);
		hhGPVec(27)=hGPMaxFrequPointSlider;
	end
  	%====================================
	%====================================
	% GlobPowCursorPointHandle
	if Domain ==6 | Domain==7 | Domain==8
		btnNumber=7;
	else
		btnNumber=5;
	end
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
    
	hGPCursorPointText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String',MenuTextString5);
	hhGPVec(15)=hGPCursorPointText;
    
	btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
	callbackStr = 'emegs2d(''setGPCursorPoint'')';
    
	hGPCursorPoint = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String',CursorPointString,...
	'Value',CursorPoint, ...
	'callback',callbackStr);
	hList(68)=hGPCursorPoint;
	hhGPVec(5)=hGPCursorPoint;
	
	NPoints=MaxPoint-MinPoint+1;
	if NPoints>=10
		SliderStep=[1./NPoints 10./NPoints];
	else
		SliderStep=[.1 1];
	end

 	btnPos=[left yPos-btnHt btnWid btnHt./2];
	callbackStr = 'emegs2d(''setGPCursorPointSlider'')';
	hGPCursorPointSlider=uicontrol( ...
	'Style','slider', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Cursor', ...
	'HorizontalAlignment','center',...
	'Userdata',[], ...
	'Min',MinPoint, ...
	'Max',MaxPoint, ...
	'SliderStep',SliderStep, ...
	'Value',CursorPoint, ...
	'Callback',callbackStr,...
	'Enable','on');
	hhGPVec(20)=hGPCursorPointSlider;
	
	%====================================
	%====================================
	% Take WeightMat radio GlobPower 
	if Domain ==6 | Domain==7 | Domain==8
		btnNumber=8;
	else
		btnNumber=6;
	end  
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 btnWid/2 btnHt./2];
	callbackStr = 'emegs2d(''CalcGlobalPower'')';
	hTakeGlobPowStdWeight=uicontrol( ...
	'Style','radiobutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Std weight:', ...
	'Value',0,'Userdata',0, ...
	'Callback',callbackStr);
	hList(69)=hTakeGlobPowStdWeight;
	hhGPVec(6)=hTakeGlobPowStdWeight;
	
	%====================================
	%====================================
	% The Global Power / RMS popupmenu
	if Domain ==6 | Domain==7 | Domain==8
		btnNumber=8;
	else
		btnNumber=6;
	end      
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid/2 yPos-btnHt/2 btnWid/2 btnHt./2];
	labelStr='Global Power|Root Mean Square';
	callbackStr='emegs2d(''chGPRMSStatus'')';
	
	hGP_RMS=uicontrol( ...
	'Style','popupmenu', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',labelStr, ...
	'Interruptible','on', ...
	'Userdata','Global Power',...
	'Value',1,...
	'Callback',callbackStr);
	
	hList(70)=hGP_RMS;
	hhGPVec(7)=hGP_RMS;
    
    %====================================
	%====================================
	% The Update & Adjust Data popupmenu
 
	% Update Data
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt btnWid./2 btnHt/2];
	callbackStr = 'emegs2d(''CalcGlobalPower'')';
	hUpdateGlobPow=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Update', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	hhGPVec(21)=hUpdateGlobPow;
    
	% Update And Adjust Data
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt/2];
	callbackStr = 'emegs2d(''UpdateAdjustGlobPow'')';
	hUpdateAdjustGlobPow=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','& Adjust Data', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	hhGPVec(31)=hUpdateAdjustGlobPow;
    
    %====================================
	%====================================
	% The setGP2Emegs2dCursor / setGP2Emegs3dCursor
	if Domain ==6 | Domain==7 | Domain==8
		btnNumber=9;
	else
		btnNumber=7;
	end      
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt/2 btnWid/2 btnHt./2];
	labelStr='Emegs2d Cursor';
	callbackStr='emegs2d(''setGP2Emegs2dCursor'')';
	
	hsetGP2Emegs2dCursor=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',labelStr, ...
	'Interruptible','on', ...
	'Callback',callbackStr);

    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid/2 yPos-btnHt/2 btnWid/2 btnHt./2];
	labelStr='Emegs3d Point';
	callbackStr='emegs2d(''setGP2Emegs3dCursor'')';
	
	hsetGP2Emegs3dCursor=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',labelStr, ...
	'Interruptible','on', ...
	'Callback',callbackStr);

  %====================================
	%====================================
	% The setGP2Emegs2dCursor / setGP2Emegs3dCursor
	if Domain ==6 | Domain==7 | Domain==8
		btnNumber=9.5;
	else
		btnNumber=7.5;
	end      
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt/2 btnWid/2 btnHt./2];
	labelStr='Movie';
	callbackStr='emegs2d(''Toggle3dMovie'')';
	
	hToggle3dMovie=uicontrol( ...
	'Style','radiobutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String',labelStr, ...
	'Interruptible','on', ...
	'Callback',callbackStr,...
    'Value',0,...
    'tag','Toggle3dMovie',...
    'HandleVisibility','on');

   

	%======= Glob Pow axes =============================	
	figure(hGlobPowFig);
	hGlobPowAxes=axes('Units','normal','Position',[.1 .15 .85 .7],'Color',BGColor,'Box','on','XLim',[MinPoint MaxPoint],'YLim',[0 10]);
	hhGPVec(17)=hGlobPowAxes;
	set(hList(66),'Userdata',hhGPVec);	
	if Domain<3 | Domain==6 | Domain==7 | Domain==8
		Segment=(SegmentMS.*SampRate./1000);
		if TrigPoint>MinPoint & TrigPoint<MaxPoint	% trigger time between minimum and maximum time
			XTickVec1=TrigPoint:Segment:MaxPoint;
			XTickVec2=sort(TrigPoint:(-1)*Segment:MinPoint);
			XTickVec=[XTickVec2 XTickVec1(2:length(XTickVec1))];
			XTickLabelVec1=0:SegmentMS:(round((MaxPoint-TrigPoint).*1000./SampRate));
			XTickLabelVec2=sort(0:(-1)*SegmentMS:(round((MinPoint-TrigPoint).*1000./SampRate)));
			XTickLabelVec=[XTickLabelVec2 XTickLabelVec1(2:length(XTickLabelVec1))];
		else
			if TrigPoint<=MinPoint
				XTickVec1=TrigPoint:Segment:MaxPoint;
				ind=find(XTickVec1>=MinPoint);
				XTickVec=XTickVec1(ind(1):length(XTickVec1));
				XTickLabelVec1=0:SegmentMS:(round((MaxPoint-TrigPoint).*1000./SampRate));
				XTickLabelVec=XTickLabelVec1(ind(1):length(XTickLabelVec1));
			elseif TrigPoint>=MaxPoint;	
				XTickVec1=sort(TrigPoint:(-1)*Segment:MinPoint);
				ind=find(XTickVec1>MaxPoint);
				XTickVec=XTickVec1(1:(ind(1)-1));
				XTickLabelVec1=sort(0:(-1)*SegmentMS:round((MinPoint-TrigPoint).*1000./SampRate));			
				XTickLabelVec=XTickLabelVec1(1:(ind(1)-1));
			end;
		end;
	else 	% frequency
		Segment=(SegmentMS.*(2.*NPoints)./SampRate);
		XTickVec=MinPoint:Segment:MaxPoint;
		xTickMin=(MinPoint-TrigPoint).*(NPoints+1).*(SampRate./2)./NPoints.^2;
		xTickMax=(MaxPoint-TrigPoint).*(NPoints+1).*(SampRate./2)./NPoints.^2;
		XTickLabelVec=round([xTickMin:SegmentMS:xTickMax].*1000)./1000;
	 end;
	
	set(hGlobPowAxes,'xtick',XTickVec,'XTickLabel',XTickLabelVec);		

	EegMegStatusString=get(hList(110),'String');
	if strcmp(EegMegStatusString,'EEG'); EegMegString='Potential [µV]'; else; EegMegString='Filed [fT]'; end
	if Domain<3 | Domain==6 | Domain==7 | Domain==8
		xlabel('Time [ms]');ylabel([EegMegString]);
        if Domain == 8
            zlabel('Frequency [Hz]');
        end
	else
		xlabel('Frequency [Hz]');ylabel([EegMegString,'/sqrt(Hz)]']);
	end;
	hList(72)=hGlobPowAxes;
	if Domain~=6 & Domain~=7 
        % trigger line
		hTriggerLine=get(hList(9),'Userdata');
		TriggerLineColor=get(hTriggerLine(1),'Color');
		TriggerLineStyle=get(hTriggerLine(1),'LineStyle');
		hGlobPowTrigLine=line('XData',[TrigPoint TrigPoint],'YData',[0 inf],'Color',TriggerLineColor,'LineStyle',TriggerLineStyle);
		hList(73)=hGlobPowTrigLine;
		% cursor line
		hCursorLine=get(hList(10),'Userdata');
		CursorLineColor=get(hCursorLine(1),'Color');
		CursorLineStyle=get(hCursorLine(1),'LineStyle');
		hGlobPowCursorLine=line('XData',[CursorPoint CursorPoint],'YData',[0 inf],'Color',CursorLineColor,'LineStyle',CursorLineStyle);
		hList(74)=hGlobPowCursorLine;
	end
	NListHdr=get(hList(51),'Userdata');
	
	hGlobPowTimeText=text('FontSize',[10],'Color',[0 0 0],'HorizontalAlignment','left','Visible','off');
	hList(75)=hGlobPowTimeText;
	hGlobPowAmpText1=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
	hList(NListHdr+27+(50*0))=hGlobPowAmpText1;
	hGlobPowAmpText2=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
	hList(NListHdr+27+(50*1))=hGlobPowAmpText2;
	hGlobPowAmpText3=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
	hList(NListHdr+27+(50*2))=hGlobPowAmpText3;
	hGlobPowAmpText4=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
	hList(NListHdr+27+(50*3))=hGlobPowAmpText4;
    hGlobPowAmpText5=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
	hList(NListHdr+27+(50*4))=hGlobPowAmpText5;
    hGlobPowAmpText6=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
	hList(NListHdr+27+(50*5))=hGlobPowAmpText6;
	
	hGlobPowData1=line('XData',[1:NPoints],'Visible','off');
	hList(NListHdr+26+(50*0))=hGlobPowData1;
	hGlobPowData2=line('XData',[1:NPoints],'Visible','off');
	hList(NListHdr+26+(50*1))=hGlobPowData2;
	hGlobPowData3=line('XData',[1:NPoints],'Visible','off');
	hList(NListHdr+26+(50*2))=hGlobPowData3;
	hGlobPowData4=line('XData',[1:NPoints],'Visible','off');
	hList(NListHdr+26+(50*3))=hGlobPowData4;
    hGlobPowData5=line('XData',[1:NPoints],'Visible','off');
	hList(NListHdr+26+(50*4))=hGlobPowData5;
    hGlobPowData6=line('XData',[1:NPoints],'Visible','off');
	hList(NListHdr+26+(50*5))=hGlobPowData6;
	
	set(hPlot2dMenuFig,'Userdata',hList);

	emegs2d('CalcGlobalPower');
	clear;
 
        
	%=============================================================================
	%============ setGP2Emegs2dCursor
	%=============================================================================  
elseif strcmp(action,'setGP2Emegs2dCursor') | ...
        strcmp(action,'setGP2Emegs3dCursor')| ... 
        strcmp(action,'setBut2Emegs2dCursor')| ... 
        strcmp(action,'setBut2Emegs3dCursor')| ... 
        strcmp(action,'setSpecChan2Emegs2dCursor')| ... 
        strcmp(action,'setSpecChan2Emegs3dCursor'),

    hList=get(hPlot2dMenuFig,'Userdata');
    if  strcmp(action,'setGP2Emegs2dCursor') | strcmp(action,'setGP2Emegs3dCursor'),
		hhVec=get(hList(66),'Userdata');   
	elseif  strcmp(action,'setBut2Emegs2dCursor') | strcmp(action,'setBut2Emegs3dCursor'),
		hhVec=get(hList(63),'Userdata');
	elseif strcmp(action,'setSpecChan2Emegs2dCursor') | strcmp(action,'setSpecChan2Emegs3dCursor'),
		hhVec=get(hList(64),'Userdata'); 
	end;
    CursPoint=get(hhVec(5),'Value');
    if ~isempty(findstr(action,'2d'))
        set(hList(132),'Value',CursPoint);
	    emegs2d('setCursorPointSlider');
    elseif ~isempty(findstr(action,'3d'))
        if isempty(findobj('tag','emegs3dmenufig')) 
            Emegs3d('Initialize');
        end
        global hPlot3dMenuFig
        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        set(hPlot3dList(47),'Value',CursPoint); 		%MinPoint
        emegs3d('setMinPointString')
        set(hPlot3dList(49),'Value',CursPoint);	        %MaxPoint
        emegs3d('setMaxPointString')
        ApplyVec=get(hPlot3dList(33),'Userdata');
        ApplyVec(1)=1; %Recalculate
        set(hPlot3dList(33),'Userdata',ApplyVec);		%hApply
        targetfig = findobj('tag','GP2Emegs3dCursFig');
        updatestatus = 1;
        emegs3d('Apply',1,updatestatus,targetfig);
    end
    
elseif strcmp(action,'UpdateAdjustGlobPow'),

        emegs2d('CalcGlobalPower');
        emegs2d('AdjustGlobPowAmp');
        
	%=============================================================================
	%============ chGPRMSStatus 	ChangeGlobalPowerRootMeanSquareStatus
	%============ call: PlotGlobalPower
	%=============================================================================	
elseif strcmp(action,'chGPRMSStatus'),

	hList=get(hPlot2dMenuFig,'Userdata');
	hhGPVec=get(hList(66),'Userdata');	
	GP_RMS=get(hhGPVec(7),'Value');
	Domain=get(hList(20),'Value');
	EegMegStatusString=get(hList(110),'String');
	if strcmp(EegMegStatusString,'EEG'); EegMegString='µV'; else; EegMegString='fT'; end
	
	if GP_RMS==1	%GP
		if Domain<3 | Domain==6 | Domain==7
			set(hhGPVec(11),'String',['Min. amp. [',EegMegString,'^2]'])	%hGPMinAmpText
			set(hhGPVec(12),'String',['Max. amp. [',EegMegString,'^2]'])	%hGPMaxAmpText
		else
			set(hhGPVec(11),'String',['Min. amp. [',EegMegString,'^2/Hz]'])		%hGPMinAmpText
			set(hhGPVec(12),'String',['Max. amp. [',EegMegString,'^2/Hz]'])	%hGPMaxAmpText
		end
	elseif GP_RMS==2	%RMS
		if Domain<3 | Domain==6 | Domain==7
			set(hhGPVec(11),'String',['Min. amp. [',EegMegString,']'])		%hGPMinAmpText
			set(hhGPVec(12),'String',['Max. amp. [',EegMegString,']'])		%hGPMaxAmpText
		else
			set(hhGPVec(11),'String',['Min. amp. [',EegMegString,'/sqrt(Hz)]'])	%hGPMinAmpText
			set(hhGPVec(12),'String',['Max. amp. [',EegMegString,'/sqrt(Hz)]'])	%hGPMaxAmpText
		end
	end
	emegs2d('CalcGlobalPower');
	%=============================================================================
	%============ CalcGlobalPower
	%============ call: PlotGlobalPower
	%=============================================================================	
elseif strcmp(action,'CalcGlobalPower'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	Domain=get(hList(20),'Value');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	kActAxes=get(hList(27),'Userdata');
	NActChan=length(kActAxes);
	NPoints=get(hList(NListHdr+3),'Userdata');
	hhGPVec=get(hList(66),'Userdata');
	GPMinPoint=get(hhGPVec(3),'Value');	
	GPMaxPoint=get(hhGPVec(4),'Value');	
	TakeGPStdWeight=get(hList(69),'Value');
	GP_RMS=get(hList(70),'Value');
	
	%============== GlobalPower calculation for all opened files ===============
	for FileIndex=1:NUsedFiles
		if Domain==6 | Domain==7 
			CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+36),'Userdata');
			TakeGPStdWeight=0;
        elseif Domain == 8
            CalcAvgMat=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+36),'Userdata');
			TakeGPStdWeight=0;
		else
			CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		end
		hDataVec=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+25),'Userdata');
		VisibleVec=ones(NActChan,1);
        
		for ChanInd=1:NActChan
			VisibleStatus=get(hDataVec(ChanInd),'Visible');
			if strcmp(VisibleStatus,'off')
				VisibleVec(ChanInd)=0;
			end
		end
		VisibleOnVec=find(VisibleVec==1);
      
        NUsedChan=length(VisibleOnVec);
		if TakeGPStdWeight
			StdChanTimeMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+6),'Userdata');
			WStdChanTimeMat=1./StdChanTimeMat;
			GPData=(sum(WStdChanTimeMat(kActAxes(VisibleOnVec),:).*CalcAvgMat(kActAxes(VisibleOnVec),:).^2))./sum(WStdChanTimeMat(kActAxes(VisibleOnVec),:));
		else
			if Domain==6 | Domain==7	 | Domain==8
                CalcAvgMatsq = CalcAvgMat.^2;
				GPData=squeeze(mean(CalcAvgMatsq,1));
			else
				GPData=(sum(CalcAvgMat(kActAxes(VisibleOnVec),:).^2))./NUsedChan;
			end
		end
		if GP_RMS==2 %RMS
			GPData=sqrt(GPData);
		end  
        if Domain == 8
            GPMaxAmp=1.1.*max(max(GPData(GPMinPoint:GPMaxPoint,:)));
        else
		    GPMaxAmp=1.1.*max(GPData(GPMinPoint:GPMaxPoint));
        end
        try
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+26),'Userdata',GPData);
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+28),'Userdata',GPData);
        catch
            uiwait(errordlg('Unable to store Global Power Data as uicontrol userdata! Amplitude and time adjustments may not work!'));
        end
        if Domain == 8
            break;
        end
	end
	%=============================================================================
	GPMaxAmp=GPMaxAmp.*1.1;
	GPMaxAmpString = sprintf('%g',GPMaxAmp);
	set(hhGPVec(2),'Value',GPMaxAmp,'String',GPMaxAmpString);
	if Domain==6 | Domain==7 | Domain==8
		set(hList(72),'CLim',[0 GPMaxAmp]);
	else
		set(hList(72),'YLim',[0 GPMaxAmp]);
		set(hList(73),'YData',[0 GPMaxAmp]);	% trigger line
		set(hList(74),'YData',[0 GPMaxAmp]);	% cursor line
	end
	EnableValue=3;
	set(hList(49),'Value',EnableValue);
	emegs2d('EnableOnOff');	
	emegs2d('PlotGlobalPower');
	clear;
	
	%=============================================================================
	%============ PlotGlobalPower
	%============ call: setGlobPowCursorText
	%=============================================================================	
elseif strcmp(action,'PlotGlobalPower'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	Domain=get(hList(20),'Value');
	TrigPoint=get(hList(22),'Value');
    hGPFig=hList(71);
    hGPAxes=hList(72);
	NListHdr=get(hList(51),'Userdata');
	hhGPVec=get(hList(66),'Userdata');
	GPMinPoint=get(hhGPVec(3),'Value');
	GPMaxPoint=get(hhGPVec(4),'Value');
    if Domain == 7 | Domain == 8
        GPMinAmp  = str2num(get(hhGPVec(1),'String'));
		GPMaxAmp  = str2num(get(hhGPVec(2),'String'));
        
        GPMinTimeVal = str2num(get(hhGPVec(3),'String'));
        GPMaxTimeVal = str2num(get(hhGPVec(4),'String'));
        
		GPMinFreqPoint = get(hhGPVec(25),'Value');
		GPMaxFreqPoint = get(hhGPVec(27),'Value');
        
		GPMinFreqVal = str2num(get(hhGPVec(24),'String'));
		GPMaxFreqVal = str2num(get(hhGPVec(26),'String'));
    end
	SampRate=get(hList(60),'Userdata');	
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	GP_RMS=get(hList(70),'Value');
	MainMatlabVersion=get(hList(100),'Userdata');
	hTopMenu=get(hList(65),'Userdata');
	hCalcMenu=get(hTopMenu(4),'children');	
	hGPRMSMenu=get(hCalcMenu(5),'children');
	hGPRMSDiffMenu=get(hGPRMSMenu(3),'children');
	GPRMSDiff12Status=get(hGPRMSDiffMenu(2),'Userdata');
	GPRMSDiff21Status=get(hGPRMSDiffMenu(1),'Userdata');
	LineWidthVec=get(hList(98),'Userdata');

	figure(hList(71));
	EegMegStatusString=get(hList(110),'String');
	if strcmp(EegMegStatusString,'EEG'); EegMegString='[µV]'; else; EegMegString='[fT]'; end
	if GP_RMS==1
		set(hGPFig,'Name','Global Power Plot');				%hGlobPowFig;
		%set(hGPAxes,'Title','Global Power Plot');
		if Domain<3 | Domain==6 | Domain==7 | Domain == 8
            if Domain == 7 | Domain == 8
                ylabel(['Frequency [Hz]']);		
            else
                ylabel(['Amplitude [',EegMegString,'^2]']);		
            end
		else
			ylabel(['Amplitude [',EegMegString,'^2/Hz]']);		%hGlobPowAxes;
		end
	else
		set(hGPFig,'Name','Root Mean Square Plot');				%hGlobPowFig;
		%set(hGPAxes,'Title','Root Mean Square Plot');
		if Domain<3 | Domain==6 | Domain==7 | Domain == 8
			ylabel(['Amplitude [',EegMegString,']']);			%hGlobPowAxes;
		else
			ylabel(['Amplitude [',EegMegString,'/sqrt(Hz)]']);	%hGlobPowAxes;
		end
	end
	GlobPowData1=[];GlobPowData2=[];
        
	for FileIndex=1:NUsedFiles
		GlobPowData=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+28),'Userdata');
		if (GPRMSDiff12Status | GPRMSDiff21Status) & FileIndex==1
			GlobPowData1=GlobPowData;
		end
		if (GPRMSDiff12Status | GPRMSDiff21Status) & FileIndex==2
			GlobPowData2=GlobPowData;
		end
        if Domain == 7 | Domain == 8
            holdstatus = ishold;
            if holdstatus == 0
                hold on
            end
            GlobPowData=get(hList(NListHdr+(FileNoVec(1)-1).*50+28),'Userdata');
            GlobPowDataSub = GlobPowData(GPMinPoint:GPMaxPoint,GPMinFreqPoint:GPMaxFreqPoint);
            himage = image('XData',[GPMinPoint GPMaxPoint],'YData',[GPMinFreqVal GPMaxFreqVal], 'CData',GlobPowDataSub','CDataMapping','scaled');
            set(gca,'CLim',[GPMinAmp GPMaxAmp],'XLim',[GPMinPoint GPMaxPoint],'YLim',[GPMinFreqVal GPMaxFreqVal]);
            if holdstatus == 0
                hold off
            end
       else
			GlobPowData=GlobPowData(GPMinPoint:GPMaxPoint);
			ActColor=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+16),'Userdata');
			ActLineStyle=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+17),'Userdata');
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+26),'XData',[GPMinPoint:GPMaxPoint],'YData',GlobPowData,...
			'Visible','on','Color',ActColor,'LineStyle',ActLineStyle,'LineWidth',LineWidthVec(FileNoVec(FileIndex)));
        end
        
        if Domain == 7 | Domain ==8 
            return;
        end
	end
	if GPRMSDiff12Status & ~isempty(GlobPowData1) & ~isempty(GlobPowData2)
		FileIndex=3; GlobPowData12=GlobPowData1-GlobPowData2;
		ActColor=get(hList(NListHdr+(FileIndex-1).*50+16),'Userdata');
		ActLineStyle=get(hList(NListHdr+(FileIndex-1).*50+17),'Userdata');
		set(hList(NListHdr+(FileIndex-1).*50+26),'XData',[GPMinPoint:GPMaxPoint],'YData',GlobPowData12,'Visible','on','Color',ActColor,'LineStyle',ActLineStyle);
	end
	if GPRMSDiff21Status & ~isempty(GlobPowData1) & ~isempty(GlobPowData2)
		FileIndex=4; GlobPowData21=GlobPowData2-GlobPowData1;
		ActColor=get(hList(NListHdr+(FileIndex-1).*50+16),'Userdata');
		ActLineStyle=get(hList(NListHdr+(FileIndex-1).*50+17),'Userdata');
		set(hList(NListHdr+(FileIndex-1).*50+26),'XData',[GPMinPoint:GPMaxPoint],'YData',GlobPowData21,'Visible','on','Color',ActColor,'LineStyle',ActLineStyle);
	end
	if (GPRMSDiff12Status | GPRMSDiff21Status) & ~isempty(GlobPowData1) & ~isempty(GlobPowData2)
		hhGPVec=get(hList(66),'Userdata');
		if GPRMSDiff12Status & ~GPRMSDiff21Status
			GlobPowMinAmp=round(min([min(GlobPowData1), min(GlobPowData2), min(GlobPowData12)]).*11)./10;
			GlobPowMaxAmp=round(max([max(GlobPowData1), max(GlobPowData2), max(GlobPowData12)]).*11)./10;
		elseif GPRMSDiff21Status & ~GPRMSDiff12Status
			GlobPowMinAmp=round(min([min(GlobPowData1), min(GlobPowData2), min(GlobPowData21)]).*11)./10;
			GlobPowMaxAmp=round(max([max(GlobPowData1), max(GlobPowData2), max(GlobPowData21)]).*11)./10;
		elseif GPRMSDiff12Status & GPRMSDiff21Status
			GlobPowMinAmp=round(min([min(GlobPowData1), min(GlobPowData2), min(GlobPowData12), min(GlobPowData21)]).*11)./10;
			GlobPowMaxAmp=round(max([max(GlobPowData1), max(GlobPowData2), max(GlobPowData12), max(GlobPowData21)]).*11)./10;
		end
		set(hhGPVec(1),'Value',GlobPowMinAmp,'String',sprintf('%g',GlobPowMinAmp));
		set(hhGPVec(2),'Value',GlobPowMaxAmp,'String',sprintf('%g',GlobPowMaxAmp));
		set(hList(72),'YLim',[GlobPowMinAmp GlobPowMaxAmp]);
	end
	emegs2d('setGlobPowCursorText');
	clear;	
	
	%=============================================================================
	%============ setGPMinMaxAmpPoint
	%============ call: PlotGlobalPower
	%=============================================================================	
elseif strcmp(action,'setGPMinMaxAmpPoint'),

	hList=get(hPlot2dMenuFig,'Userdata');
	
	hhGPVec=get(hList(66),'Userdata');
	GPMinAmp=get(hhGPVec(1),'Value');
	GPMaxAmp=get(hhGPVec(2),'Value');
	MinPoint=get(hhGPVec(3),'Value');
	MaxPoint=get(hhGPVec(4),'Value');
	TrigPoint=get(hList(22),'Value');
	SampRate=get(hList(60),'Userdata');	
	NListHdr=get(hList(51),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	Domain=get(hList(20),'Value');
	MainMatlabVersion=get(hList(100),'Userdata');
	
	SegmentMS=get(hList(101),'Userdata');
	hAxes=hList(72);

	set(hAxes,'XLim',[MinPoint MaxPoint]);
    if Domain==8
        set(hAxes,'CLim',[GPMinAmp GPMaxAmp]);
    else
	    set(hAxes,'YLim',[GPMinAmp GPMaxAmp]);
    end
    if Domain ~= 7 & Domain ~= 8
		set(hList(73),'YData',[GPMinAmp GPMaxAmp]);	% trigger line
		set(hList(74),'YData',[GPMinAmp GPMaxAmp]);	% cursor line
    end
	
	if Domain<3 | Domain==6 | Domain==7	| Domain==8 %Time
		Segment=(SegmentMS.*SampRate./1000);
		if TrigPoint>MinPoint & TrigPoint<MaxPoint
			XTickVec1=TrigPoint:Segment:MaxPoint;
			XTickVec2=sort(TrigPoint:(-1)*Segment:MinPoint);
			XTickVec=[XTickVec2 XTickVec1(2:length(XTickVec1))];
			XTickLabelVec1=0:SegmentMS:(round((MaxPoint-TrigPoint).*1000./SampRate));
			XTickLabelVec2=sort(0:(-1)*SegmentMS:(round((MinPoint-TrigPoint).*1000./SampRate)));
			XTickLabelVec=[XTickLabelVec2 XTickLabelVec1(2:length(XTickLabelVec1))];
		else
			if TrigPoint<=MinPoint
				XTickVec1=TrigPoint:Segment:MaxPoint;
				ind=find(XTickVec1>=MinPoint);
				XTickVec=XTickVec1(ind(1):length(XTickVec1));
				XTickLabelVec1=0:SegmentMS:(round((MaxPoint-TrigPoint).*1000./SampRate));
				XTickLabelVec=XTickLabelVec1(ind(1):length(XTickLabelVec1));
			elseif TrigPoint>=MaxPoint;	
				XTickVec1=sort(TrigPoint:(-1)*Segment:MinPoint);
				ind=find(XTickVec1>MaxPoint);
				XTickVec=XTickVec1(1:(ind(1)-1));
				XTickLabelVec1=sort(0:(-1)*SegmentMS:round((MinPoint-TrigPoint).*1000./SampRate));
				XTickLabelVec=XTickLabelVec1(1:(ind(1)-1));
			end;	
		end
	else		% Frequency
		Segment=(SegmentMS.*(2.*NPoints)./SampRate);
		XTickVec=MinPoint:Segment:MaxPoint;
		xTickMin=(MinPoint-TrigPoint).*(NPoints+1).*(SampRate./2)./NPoints.^2;
		xTickMax=(MaxPoint-TrigPoint).*(NPoints+1).*(SampRate./2)./NPoints.^2;
		XTickLabelVec=round([xTickMin:SegmentMS:xTickMax].*1000)./1000;
	end;
	set(hAxes,'xtick',XTickVec,'XTickLabel',XTickLabelVec);		
	emegs2d('PlotGlobalPower')
	
	%=============================================================================
	%============ setGlobPowCursorText
	%=============================================================================
elseif strcmp(action,'setGlobPowCursorText'),

	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	hhGPVec=get(hList(66),'Userdata');
	MinAmp=get(hhGPVec(1),'Value');
	MaxAmp=get(hhGPVec(2),'Value');
	MinPoint=get(hhGPVec(3),'Value');
	MaxPoint=get(hhGPVec(4),'Value');
	CursorPoint = get(hhGPVec(5),'Value');
	CursorString = get(hhGPVec(5),'String');
	set(hList(75),'Position',[CursorPoint+(MaxPoint-MinPoint)/100 MinAmp+(MaxAmp-MinAmp)/20],'Visible','on','String',CursorString);
	for FileIndex=1:NUsedFiles
		ActColor=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+16),'Userdata');
		GlobPowData=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+26),'Userdata');
		set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+27), ...
		'Position',[CursorPoint (0.95-(FileNoVec(FileIndex)-1).*0.075).*MaxAmp], ...
		'Visible','on', ...
		'String',num2str(round(GlobPowData(CursorPoint).*100)./100), ...
		'Color',ActColor);
	end
	
	%=============================================================================
	%============ ExportAllGlobalPower
	%=============================================================================
elseif strcmp(action,'ExportAllGlobalPower'),

	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);

	MinPoint=get(hList(54),'Value');
	MaxPoint=get(hList(55),'Value');
	
	GP_RMS=get(hList(70),'value');
	clc;
	fprintf('Export GP/RMS data to file(s):\n\n');
	Message=char('Export GP/RMS data to file(s):');
	Message=char(Message,'');
	for FileIndex=1:NUsedFiles
		GlobPowData=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+26),'Userdata');
		FilePath=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+4),'Userdata');
		if GP_RMS==1
			GlobPowFilePath=[FilePath '.gpa'];
		else
			GlobPowFilePath=[FilePath '.rmsa'];
		end
		fprintf(GlobPowFilePath);fprintf('\n');
		Message=char(Message,GlobPowFilePath);
		GPFid=fopen(GlobPowFilePath,'w','b');
		fprintf(GPFid,'1\t');
		fprintf(GPFid,'%g\n',MaxPoint-MinPoint+1);
		fprintf(GPFid,'%g\n',GlobPowData(MinPoint:MaxPoint));
		fclose(GPFid);
	end
	hmsgbox=msgbox(Message,'Info','help'); 
	%=============================================================================
	%============ ExportCursorGlobalPower
	%=============================================================================	
elseif strcmp(action,'ExportCursorGlobalPower'),

	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);

   GlobPowCursorPoint=get(hList(68),'Userdata');
   GP_RMS=get(hList(70),'value');
   FilePath=get(hList(NListHdr+(FileNoVec(1)-1).*50+4),'Userdata');
	if GP_RMS==1
		GlobPowFilePath=[FilePath '.gpc'];
	else
      GlobPowFilePath=[FilePath '.rmsc'];
   end
	GPFid=fopen(GlobPowFilePath,'w','b');
	fprintf(GPFid,'1\t');
	fprintf(GPFid,[int2str(NUsedFiles),'\n']);
	for FileIndex=1:NUsedFiles
      		GlobPowData=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+26),'Userdata')
      		GPVec(FileIndex)=GlobPowData(GlobPowCursorPoint)
     		fprintf(GPFid,'%g\n',GPVec(FileIndex));
  	 end
   	fclose(GPFid);
   if NUsedFiles==1
   	Message=char(['Export GP/RMS value ',sprintf('%g',GPVec),' to file:'])
   else  
      ValString=[];
      for FileIndex=1:NUsedFiles
         ValString=[ValString,sprintf('%g',GPVec(FileIndex))];
         if FileIndex<NUsedFiles
            ValString=[ValString,'; '];
         end
      end
   	Message=char(['Export GP/RMS values [',ValString,'] to file:'])
	end
   	Message=char(Message,GlobPowFilePath);
	hmsgbox=msgbox(Message,'Info','help'); 

	%=============================================================================
	%============ CalcGPDiff12 and CalcGPDiff21...
	%=============================================================================	
elseif 	strcmp(action,'CalcGPDiff12') | ...
		strcmp(action,'CalcGPDiff21') 
		
		hList=get(hPlot2dMenuFig,'Userdata');
		hTopMenu=get(hList(65),'Userdata');
		hCalcMenu=get(hTopMenu(4),'children');	
		hGPRMSMenu=get(hCalcMenu(5),'children');
		hGPRMSDiffMenu=get(hGPRMSMenu(3),'children');
		
		if strcmp(action,'CalcGPDiff12')
			GPRMSDiff12Status=get(hGPRMSDiffMenu(2),'Userdata');
			if GPRMSDiff12Status
				GPRMSDiff12Status=0;
			else
				GPRMSDiff12Status=1;
			end
			set(hGPRMSDiffMenu(2),'Userdata',GPRMSDiff12Status);
		elseif strcmp(action,'CalcGPDiff21')
			GPRMSDiff21Status=get(hGPRMSDiffMenu(1),'Userdata');
			if GPRMSDiff21Status
				GPRMSDiff21Status=0;
			else
				GPRMSDiff21Status=1;
			end
			set(hGPRMSDiffMenu(1),'Userdata',GPRMSDiff21Status);
		end
		
	%=============================================================================
	%============ CalcGPIntegral... and CalcGPMean...
	%=============================================================================	
elseif 	strcmp(action,'CalcGPIntegralInteractiv') | ...
		strcmp(action,'CalcGPIntegralFile') | ...
		strcmp(action,'CalcGPIntegralDefault') | ...
		strcmp(action,'CalcGPMeanInteractiv') | ...
		strcmp(action,'CalcGPMeanFile') | ...
		strcmp(action,'CalcGPMeanDefault'),

	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	SampRate=get(hList(60),'Userdata');
	GP_RMS=get(hList(70),'value');

	hTopMenu=get(hList(65),'Userdata');
	hExportMenu=get(hTopMenu(3),'children');	
	hExportUserData=get(hExportMenu(1),'children'); 
	hUserDataInfo=get(hExportUserData(1),'children');
	
	NUsedFiles=length(FileNoVec);
	if NUsedFiles==0
		Message=char('Sorry,');
		Message=char(Message,'');
		Message=char(Message,'no data available.');
		Message=char(Message,'Please open a data set first.');
		hmsgbox=msgbox(Message,'Info','help'); 
		return;
	end
	hhGPVec=get(hList(66),'Userdata');
	MinPoint=get(hhGPVec(3),'Value');
	MaxPoint=get(hhGPVec(4),'Value');
	%MinPoint=get(hList(54),'Value');
	%MaxPoint=get(hList(55),'Value');
	EegMegStatusString=get(hList(110),'String');
	if strcmp(EegMegStatusString,'EEG'); EegMegString='µV'; else; EegMegString='fT'; end
	
	if strcmp(action,'CalcGPIntegralInteractiv') | strcmp(action,'CalcGPMeanInteractiv')
		Message=char('Please open the');
		Message=char(Message,'Matlab command window');
		Message=char(Message,'to choose the interval parameters:');
		msgbox(Message,'Info:','help')
		[GPIntMat(1)]=IfEmptyInputValInt('Insert start of integral (sample point No.):' ,[],[],MinPoint,MinPoint,MaxPoint,1);
		[GPIntMat(2)]=IfEmptyInputValInt('Insert end of integral (sample point No.):' ,[],[],MaxPoint,GPIntMat(1),MaxPoint,0);
		GPIntMat=GPIntMat';
		set(hList(81),'Userdata',GPIntMat);
	elseif strcmp(action,'CalcGPIntegralFile') | strcmp(action,'CalcGPMeanFile')
		[File,Path]=uigetfile('*','Read data from file:');
		FilePath=[Path,File];
		if isempty(find(FilePath)); return; end;
		fid=fopen(FilePath,'r','b');
		GPIntVec=fscanf(fid,'%g');
		[NGPInt2,NoUse]=size(GPIntVec);
		if (NGPInt2./2-round(NGPInt2./2))~=0;
			Message=char('Sorry,')
			Message=char(Message,' ');
			Message=char(Message,'the file');
			Message=char(Message,FilePath);
			Message=char(Message,'has to have an even number of elements !');
			hmsgbox=msgbox(Message,'Info !',' help');
			return;
		else
			NGPInt=NGPInt2./2;
		end
		GPIntMat=reshape(GPIntVec,2,NGPInt);
		fclose(fid);
		set(hList(81),'Userdata',GPIntMat);
	elseif strcmp(action,'CalcGPIntegralDefault') | strcmp(action,'CalcGPMeanDefault')
		GPIntMat=get(hList(81),'Userdata');
		if isempty(GPIntMat)
			Message=char('Sorry,');
			Message=char(Message,'');
			Message=char(Message,'No given default interval.');
			Message=char(Message,'Please set one first.');
			hmsgbox=msgbox(Message,'Info','help'); 
			return;
		end
	end
	
	if 	strcmp(action,'CalcGPMeanInteractiv') | ...
		strcmp(action,'CalcGPMeanFile') | ...
		strcmp(action,'CalcGPMeanDefault')
		
		if GP_RMS==1
			UserDataInfoLabel=['Global Power Mean [',EegMegString,'^2]'];
		else
			UserDataInfoLabel=['RMS Mean [',EegMegString,']'];
		end
	else
		if GP_RMS==1
			UserDataInfoLabel=['Global Power Integral [',EegMegString,'^2 x ms]'];
		else
			UserDataInfoLabel=['RMS Integral [',EegMegString,' x ms]'];
		end
	end
	[NoUse,NGPInt]=size(GPIntMat);
	clc;
	for FileIndex=1:NUsedFiles
		GlobPowData=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+28),'Userdata');
		if isempty(GlobPowData)
			Message=char('Sorry,');
			Message=char(Message,'');
			Message=char(Message,'please calculate global power data first.');
			Message=char(Message,'(use GP/RMS in the Plot2d main menu)');
			hmsgbox=msgbox(Message,'Info','help'); 
			return;
		end
		NChan=get(hList(NListHdr+(FileNoVec(FileIndex)-1)*50+2),'Userdata');
		UserDataMat=zeros(NChan,NGPInt);
		FilePath=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+4),'Userdata');
		fprintf('\n');
		fprintf('File: '); fprintf(FilePath); fprintf('\n\n')
		fprintf(UserDataInfoLabel)
		fprintf('\n\n')

		for GPIntIndex=1:NGPInt
			SumGlobPow=sum(GlobPowData(GPIntMat(1,GPIntIndex):GPIntMat(2,GPIntIndex)));
			NIntPoints=GPIntMat(2,GPIntIndex)-GPIntMat(1,GPIntIndex)+1;
			if 	strcmp(action,'CalcGPMeanInteractiv') | ...
				strcmp(action,'CalcGPMeanFile') | ...
				strcmp(action,'CalcGPMeanDefault')
					
				SumGlobPow=SumGlobPow./NIntPoints;
				fprintf('Interval: %g - %g :  %g\n\n',GPIntMat(:,GPIntIndex),SumGlobPow);
			else
				SumGlobPow=SumGlobPow.*1000./SampRate;
				fprintf('Interval: %g - %g :   %g\n\n',GPIntMat(:,GPIntIndex),SumGlobPow);
			end
			UserDataMat(:,GPIntIndex)=SumGlobPow;
		end
		set(hList(94),'Userdata',UserDataMat);
		set(hUserDataInfo,'Label',UserDataInfoLabel);
		set(hExportUserData,'Enable','on');	%Export User data enable on
	end
	%=============================================================================
	%============ CalcPot...
	%=============================================================================		
elseif 	strcmp(action,'CalcPotIntegralInteractiv') | ...
		strcmp(action,'CalcPotIntegralFile') | ...
		strcmp(action,'CalcPotIntegralDefault') |...
		strcmp(action,'CalcPotMeanInteractiv') | ...
		strcmp(action,'CalcPotMeanFile') | ...
		strcmp(action,'CalcPotMeanDefault'),

	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	SampRate=get(hList(60),'Userdata');
	
	hTopMenu=get(hList(65),'Userdata');
	hExportMenu=get(hTopMenu(3),'children');	
	hExportUserData=get(hExportMenu(1),'children'); 
	hUserDataInfo=get(hExportUserData(1),'children');
	
	NUsedFiles=length(FileNoVec);
	if NUsedFiles==0
		Message=char('Sorry,');
		Message=char(Message,'');
		Message=char(Message,'no data available.');
		Message=char(Message,'Please open a data set first.');
		hmsgbox=msgbox(Message,'Info','help'); 
		return;
	end
	
	MinPoint=get(hList(54),'Value');
	MaxPoint=get(hList(55),'Value');
	EegMegStatusString=get(hList(110),'String');
	if strcmp(EegMegStatusString,'EEG'); EegMegString='µV'; else; EegMegString='fT'; end
	
	if strcmp(action,'CalcPotIntegralInteractiv') | strcmp(action,'CalcPotMeanInteractiv')
		Message=char('Please open the');
		Message=char(Message,'Matlab command window');
		Message=char(Message,'to choose the interval parameters:');
		msgbox(Message,'Info:','help')
		[PotIntMat(1)]=IfEmptyInputValInt('Insert start of integral:' ,[],[],MinPoint,MinPoint,MaxPoint,1);
		[PotIntMat(2)]=IfEmptyInputValInt('Insert end of integral:' ,[],[],MaxPoint,PotIntMat(1),MaxPoint,0);
		PotIntMat=PotIntMat';
		set(hList(85),'Userdata',PotIntMat);
	elseif strcmp(action,'CalcPotIntegralFile') | strcmp(action,'CalcPotMeanFile')
		[File,Path]=uigetfile('*','Read data from file:');
		FilePath=[Path,File];
		if isempty(find(FilePath)); return; end;
		fid=fopen(FilePath,'r','b');
		PotIntVec=fscanf(fid,'%g');
		[NPotInt2,NoUse]=size(PotIntVec);
		if (NPotInt2./2-round(NPotInt2./2))~=0;
			Message=char('Sorry,');
			Message=char(Message,'');
			Message=char(Message,'the file');
			Message=char(Message,[File]);
			Message=char(Message,'has to have an even number of elements !');
			hmsgbox=msgbox(Message,'Info','help'); 
			return;
		else
			NPotInt=NPotInt2./2;
		end
		PotIntMat=reshape(PotIntVec,2,NPotInt);
		fclose(fid);
		set(hList(85),'Userdata',PotIntMat);
	elseif strcmp(action,'CalcPotIntegralDefault') | strcmp(action,'CalcPotMeanDefault')
		PotIntMat=get(hList(85),'Userdata');
		if isempty(PotIntMat)
			Message=char('Sorry,');
			Message=char(Message,'');
			Message=char(Message,'no given default interval.');
			Message=char(Message,'Please set one first.');
			hmsgbox=msgbox(Message,'Info','help'); 
			return;
		end
	end
	[NoUse,NPotInt]=size(PotIntMat);
	clc;
	if 	strcmp(action,'CalcPotMeanInteractiv') | ...
		strcmp(action,'CalcPotMeanFile') | ...
		strcmp(action,'CalcPotMeanDefault')
		
		UserDataInfoLabel=['Potential Mean  [',EegMegString,']'];
	else
		UserDataInfoLabel=['Potential Integral  [',EegMegString,' x ms]'];
	end
	fprintf('\n');clc;
	for FileIndex=1:NUsedFiles
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		if isempty(CalcAvgMat)
			Message=char('Sorry,');
			Message=char(Message,'');
			Message=char(Message,'no data available.');
			Message=char(Message,'Please open a data set first.');
			hmsgbox=msgbox(Message,'Info','help'); 
			return;
		end
		NChan=get(hList(NListHdr+(FileNoVec(FileIndex)-1)*50+2),'Userdata');
		FilePath=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+4),'Userdata');
		fprintf('File: '); fprintf(FilePath); fprintf('\n\n')
		UserDataMat=zeros(NChan,NPotInt);
		for PotIntIndex=1:NPotInt
			SumPot=sum(CalcAvgMat(:,PotIntMat(1,PotIntIndex):PotIntMat(2,PotIntIndex))');
			NIntPoints=PotIntMat(2,PotIntIndex)-PotIntMat(1,PotIntIndex)+1;
			if 	strcmp(action,'CalcPotMeanInteractiv') | ...
				strcmp(action,'CalcPotMeanFile') | ...
				strcmp(action,'CalcPotMeanDefault')
					
				SumPot=SumPot./NIntPoints;
			else
				SumPot=SumPot.*1000./SampRate;
			end
			fprintf(UserDataInfoLabel);
			fprintf('\n\n')
			fprintf('Interval: %g - %g\n\n',PotIntMat(:,PotIntIndex));
			disp(SumPot')
			UserDataMat(:,PotIntIndex)=SumPot';
		end
		set(hList(94),'Userdata',UserDataMat);
		set(hUserDataInfo,'Label',UserDataInfoLabel);
		set(hExportUserData,'Enable','on');	%Export User data enable on
	end

	%=============================================================================
	%============ setViewCorPicStatus
elseif 	strcmp(action,'setViewCorPicStatus')

	hList=get(hPlot2dMenuFig,'Userdata');
	ViewCorPicStatus=get(hList(130),'Value');
	Pointer=get(hList(83),'Userdata');
	hTopMenu=get(hList(65),'Userdata'); %hTopMenu=[hFileMenu hStyleMenu hExportMenu hCalcMenu hViewMenu hSynthMenu hSurfMenu];
	hViewMenu=get(hTopMenu(5),'children');
	CorPicLabel=get(hViewMenu(2),'Label');
	PointPosBeg=length(CorPicLabel)+1;
	PointPosEnd=get(hViewMenu(2),'Userdata');
	if isempty(PointPosEnd)	%Start first time
		PointPosEnd=PointPosBeg+2;
		set(hViewMenu(2),'Userdata',PointPosEnd);
		CorPicLabel(PointPosBeg:PointPosEnd)=' ';
	end
	if ViewCorPicStatus==0
		ViewCorPicStatus=1;
		CorPicLabel(PointPosEnd)=setstr(Pointer);
		FilterSpec='*.i*';
		[DefFilePath] = SetDefPath(1,FilterSpec);
		[ViewCorPicIndVec,ViewCorPicIndFile,ViewCorPicIndPath,ViewCorPicIndFilePath,ViewCorPicIndSizeData]=ReadAscii([],'Choose trial index file:',[],[],DefFilePath,FilterSpec);
		if isempty(ViewCorPicIndVec)
			return;
		end		
		FilterSpec='*.jpg*';
		[DefFilePath]=SetDefPath(1,FilterSpec);
		[Tmp,ViewCorPicPath]=ReadFilePath([],DefFilePath,'Choose a picture (*.jpg) file:');
		if Tmp==0
			return;
		end
	else
		ViewCorPicStatus=0;
		ViewCorPicIndVec=[];
		ViewCorPicPath=[];
		CorPicLabel(PointPosEnd)=' ';
	end	
	set(hList(130),'Userdata',ViewCorPicIndVec,'Value',ViewCorPicStatus);
	set(hList(131),'Userdata',ViewCorPicPath);
	set(hViewMenu(2),'Label',CorPicLabel);
	%=============================================================================	
	%============ setViewCorPicStatus
elseif strcmp(action,'setViewCorPic')

	hList=get(hPlot2dMenuFig,'Userdata');
	ViewCorPicStatus=get(hList(130),'Value');
	ViewCorPicIndVec=get(hList(130),'Userdata');
	ViewCorPicPath=get(hList(131),'Userdata');
	PicIndTmp=get(hList(82),'Value')-1
	if PicIndTmp<1 | PicIndTmp>length(ViewCorPicIndVec)
		fprintf(1,' PicInd<1 | PicInd>length(ViewCorPicIndVec) in setViewCorPic; PicInd=%g',PicIndTmp)
		return;
	end
	NBasePic=10
	PicInd=NBasePic+ViewCorPicIndVec(PicIndTmp)
	PicIndStr=AddZeros2CountStr(PicInd,3);
	PicFile=[PicIndStr,'.jpg'];
	PicFilePath=[ViewCorPicPath,PicFile]
	ImMat=imread(PicFilePath,'jpg');
	SizeImMat=size(ImMat);
	if isempty(hCorPicFig)
		hCorPicFig=figure('Units','normal','NumberTitle','off','Position',[.85 .3 .15 .15],'Name',PicFile);
		hCorPicAxes=axes('Units','Normal','Position',[0 0 1 1]);
	else
		figure(hCorPicFig);
		set(hCorPicFig,'Name',PicFile,'Position',[.85 .3 .15 .15]);
	end
	image(ImMat); 
	axis('off');
	hold off
		
	%=============================================================================
	%============ setNegativUp/Down
	%=============================================================================	
elseif 	strcmp(action,'setNegativUp') | ...
		strcmp(action,'setNegativDown'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	hAxesVec=get(hList(6),'Userdata');
	hSpec1Axes=get(hList(76),'Userdata');

	if strcmp(action,'setNegativUp')
		set(hAxesVec,'YDir','Reverse');
		set(hSpec1Axes,'YDir','Reverse');
	elseif strcmp(action,'setNegativDown')
		set(hAxesVec,'YDir','Normal');
		set(hSpec1Axes,'YDir','Normal');
	end

elseif strcmp(action,'InvertViewAmp') 

	hList=get(hPlot2dMenuFig,'Userdata');
	InvertViewAmpVal=get(hList(125),'Userdata');
	if InvertViewAmpVal==1
		InvertViewAmpVal=-1;
		emegs2d('setNegativUp');
	elseif InvertViewAmpVal==-1
		InvertViewAmpVal=1;
		emegs2d('setNegativDown');
	end
	set(hList(125),'Userdata',InvertViewAmpVal);
	%=============================================================================
	%============ setColor
	%============ call: setCursorTextColor
	%=============================================================================	
elseif strcmp(action,'setColor'),
	  
	hList=get(hPlot2dMenuFig,'Userdata'); 
	NListHdr=get(hList(51),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	hDataVec=get(hList(NListHdr+(ActFileNo-1).*50+25),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NActChan=length(hDataVec);
	if isempty(FileNoVec); return; end;	
	
	%-------- default color ---------------------------
   	DefFileNoVec = get(hList(90),'Userdata');
	if (~isempty(DefFileNoVec) & (ActFileNo <= length(DefFileNoVec)))
        DefColSetVal=get(hList(NListHdr+(ActFileNo-1).*50+19),'value');
		if ~DefColSetVal
			ColorVal = get(hList(NListHdr+(ActFileNo-1).*50+19),'Userdata');
			set(hList(NListHdr+(ActFileNo-1).*50+19),'value',1);
            set(hList(61),'value',ColorVal);            % actualize popupmenu
	  	else
            ColorVal=get(hList(61),'value');
        end;    
   	 else
		ColorVal=get(hList(61),'value');
	end;	
	if ColorVal==10; return; end %NonUse ----------
	PrevColorRGB=get(hList(61),'Userdata');
	hSpec2Axes=get(hList(104),'Userdata');
	if hSpec2Axes~=0
		hSpec2AxesChildVec=get(hSpec2Axes,'Children');
		for i=1:length(hSpec2AxesChildVec)
			set(hSpec2AxesChildVec(i),'Visible','off');
		end
		set(hSpec2Axes,'Visible','off');
	end
	if ColorVal<10
    		% The Kind of thres fac Selection Menu
		if 	ColorVal==1; 
			ColorRGB=[0 0 0]; 
		elseif 	ColorVal==2; 
			ColorRGB=[1 1 1]; 	
		elseif 	ColorVal==3; 
			ColorRGB=[1 1 0]; 
		elseif 	ColorVal==4; 
			ColorRGB=[1 0 0]; 
		elseif 	ColorVal==5; 
            ColorRGB=[0 1 0]; 
        elseif 	ColorVal==6; 
            ColorRGB=[0 0 1]; 
        elseif 	ColorVal==7; 
            ColorRGB=[1 0 1]; 
        elseif 	ColorVal==8; 
            ColorRGB=[0 1 1]; 
        elseif ColorVal==9 % insert RGB
            ColorRGBStr=inputdlg({'Please insert RedGreenBlue values (e.g. [0 1 0] is green):'},'Please insert RGB values:',1,{'0 0 0'});
            ColorRGB=str2num(char(ColorRGBStr));
            if length(ColorRGB)>3; ColorRGB=ColorRGB(1:3); end
            if length(ColorRGB)<3; ColorRGBTmp=zeros(1,3); ColorRGBTmp(1:length(ColorRGB))=ColorRGB; ColorRGB=ColorRGBTmp; end
            Tmp=find(ColorRGB<0);
            if ~isempty(Tmp); ColorRGB(Tmp)=zeros(size(Tmp)); end
            Tmp=find(ColorRGB>1);
            if ~isempty(Tmp); ColorRGB=ColorRGB/max(ColorRGB); end
        end
        set(hList(61),'Userdata',ColorRGB);
        set(hList(NListHdr+(ActFileNo-1).*50+16),'Value',ColorVal,'Userdata',ColorRGB);
        for ChanInd=1:NActChan
            set(hDataVec(ChanInd),'Color',ColorRGB);
        end
        if sum(abs(PrevColorRGB-ColorRGB))~=0 %PrevColorRGB~=ColorRGB
            hFileInfoTextVec=get(hList(17),'Userdata');
            hFileInfoText=hFileInfoTextVec(ActFileNo);
            set(hFileInfoText,'Color',ColorRGB);
        end
        emegs2d('setCursorTextColor');     
	else
		hTopMenu=get(hList(65),'Userdata');
		hStyleMenu=get(hTopMenu(2),'children');
		hSensorLineColor=get(hStyleMenu(7),'children');
		ColorVec=get(hList(NListHdr+(ActFileNo-1).*50+33),'Userdata');
		pointer=get(hList(83),'Userdata');
		SensorLineColorFlipudLabel=get(hSensorLineColor(5),'Label');
		SensorLineColorFlipudPointPos=get(hSensorLineColor(5),'Userdata');
		if strcmp(SensorLineColorFlipudLabel(SensorLineColorFlipudPointPos),' ');
			FlipColorMapStatus=0;   
		else
			FlipColorMapStatus=1; 
		end
		if ColorVal==11
			ColorMat=hsv(256);
		elseif ColorVal==12
			ColorMat=hot(256);
		elseif ColorVal==13
			ColorMat=cool(256);
		elseif ColorVal==14
			ColorMat=jet(256);
		elseif ColorVal==15
			ColorMat=pink(256);
		elseif ColorVal==16
			ColorMat=flag(256);
		elseif ColorVal==17
			ColorMat=copper(256);
		elseif ColorVal==18
			ColorMat=gray(256);
		end
		if FlipColorMapStatus; ColorMat=flipud(ColorMat); end	
		colormap(ColorMat);
		Map=colormap;
		InterpMap=zeros(length(ColorVec),3);
		MinColorVec=min(ColorVec);
      		MaxColorVec=max(ColorVec);
      		[m,n]=size(ColorVec);
      		if n==1 & m~=1
         		ColorVec=ColorVec';
     		 end
      		if all(ColorVec==ColorVec(1))
        		Message=char('Sorry,');
			    Message=char(Message,'');
			    Message=char(Message,'all values in the line color vector are identical.');
         		Message=char(Message,'This is not permitted');
        		 hmsgbox=msgbox(Message,'Info','help'); 
         		return;
     	 	end
		for i=1:3
			InterpMap(:,i)=interp1(linspace(MinColorVec,MaxColorVec,256),Map(:,i),ColorVec,'spline')';
		end
		[Row,Col] = find(InterpMap<0);
		for i=1:length(Row)
			InterpMap(Row(i),Col(i))=0;
		end
		[Row,Col] = find(InterpMap>1);
		for i=1:length(Row)
			InterpMap(Row(i),Col(i))=1;
		end
		for ChanInd=1:NActChan
			set(hDataVec(ChanInd),'Color',InterpMap(ChanInd,:));
		end
		hPlot2dChanFig=hList(93);
		ChanFigBGColor=get(hPlot2dChanFig,'Color');
		if ChanFigBGColor==[0 0 0]; %black
			ChanFigFGColor=[1 1 1]; %white
		else
			ChanFigFGColor=[0 0 0];
		end
		figure(hPlot2dChanFig);
		if hSpec2Axes~=0; axes(hSpec2Axes);cla; end
		hSpec2Axes=axes('Units','normal','Position',[0.05 0.90 .15 .025],'Box','off');
		Spec2AxesVal=get(hList(106),'Userdata');	
		XPColor=linspace(0,1);
		pcolor(XPColor,[0 1],ones(2,1)*XPColor); 
		shading interp; 	
		set(hSpec2Axes,'XTick',[0 1],'XTickLabel',[round(MinColorVec.*100)./100 round(MaxColorVec.*100)./100], 'YTick',[],'YTickLabel',[],'FontSize',12,'XColor',ChanFigFGColor);
		if 		Spec2AxesVal==1; 		String1='Color versus sensor number ';	String2='Sensor';
		elseif 	Spec2AxesVal==2;		String1='Color versus  number of trials ';	String2='Trials';
		elseif 	Spec2AxesVal==3;		String1='Color versus  std value ';		String2='Std []';
		elseif 	Spec2AxesVal==4;		String1='Color versus  given value ';		String2=' ';
		end
		text('Units','normal','Position',[.5 1.4],'Color',ChanFigFGColor,'String',String1,'FontSize',12,'Horiz','center');
		text('Units','normal','Position',[.5 -0.4],'Color',ChanFigFGColor,'String',String2,'FontSize',12,'Horiz','center');
		set(hList(104),'Userdata',hSpec2Axes);
		colormap(Map)
	end
	figure(hPlot2dMenuFig);

	%=============================================================================
	%============ setLineStyle
	%=============================================================================		
elseif strcmp(action,'setLineStyle'),
  
	hList=get(hPlot2dMenuFig,'Userdata'); 
	NListHdr=get(hList(51),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	hDataVec=get(hList(NListHdr+(ActFileNo-1).*50+25),'Userdata');
	DefFileNoVec=get(hList(90),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NActChan=length(hDataVec);
	
	if isempty(FileNoVec); return; end;		
	%-------- default line style ---------------------------
    	DefFileNoVec = get(hList(90),'Userdata');
	if (~isempty(DefFileNoVec) & (ActFileNo <= length(DefFileNoVec)) )
        	DefLineStyleSetVal=get(hList(NListHdr+(ActFileNo-1).*50+20),'Value');
		if ~DefLineStyleSetVal
			LineStyleVal = get(hList(NListHdr+(ActFileNo-1).*50+20),'Userdata');
			set(hList(NListHdr+(ActFileNo-1).*50+20),'Value',1);
            		set(hList(62),'value',LineStyleVal);
	    	else
            		LineStyleVal=get(hList(62),'value');
        	end;    
    	else
		LineStyleVal=get(hList(62),'Value');
	end;	
	PrevLineStyleStr=get(hList(62),'Userdata');
	if LineStyleVal==1
		LineStyleStr='-';	%solid
	elseif LineStyleVal==2
		LineStyleStr='--';	%dashed
	elseif LineStyleVal==3
		LineStyleStr='-.';	%dashdot
	elseif LineStyleVal==4
		LineStyleStr=':';	%dotted
	end
	set(hList(NListHdr+(ActFileNo-1).*50+17),'Userdata',LineStyleStr,'Value',LineStyleVal);
	for ChanInd=1:NActChan
		set(hDataVec(ChanInd),'LineStyle',LineStyleStr);
	end
	if ~strcmp(PrevLineStyleStr,LineStyleStr)
		hFileInfoTextVec=get(hList(17),'Userdata');
		hFileInfoText=hFileInfoTextVec(ActFileNo);
		VisibleStatus=get(hFileInfoText,'Visible');
		if strcmp(VisibleStatus,'on'); emegs2d('DispFileNamesVisible'); end
	end

	%=============================================================================
	%============ setLineWidth
	%=============================================================================		
elseif strcmp(action,'setLineWidth'),
  
	hList=get(hPlot2dMenuFig,'Userdata'); 
	NListHdr=get(hList(51),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	hDataVec=get(hList(NListHdr+(ActFileNo-1).*50+25),'Userdata');
	DefFileNoVec=get(hList(90),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NActChan=length(hDataVec);
	MaxNFiles=hList(140);
	
	if isempty(FileNoVec); return; end;
    LineWidthVal=get(hList(98),'Value');
	LineWidthVec=get(hList(98),'Userdata');
    LineWidthString=get(hList(98),'String');
    LineWidthText=LineWidthString(LineWidthVal,:);
    if ~isempty(findstr(LineWidthText,'All'));
		FileNoVec=1:MaxNFiles;
        NUsedFiles=MaxNFiles;
    else
        FileNoVec=ActFileNo;
        NUsedFiles=1;
    end
    LineWidth=str2num(LineWidthText(1:4));
    for FileInd=1:NUsedFiles
        hDataVec=get(hList(NListHdr+(FileNoVec(FileInd)-1).*50+25),'Userdata');
		LineWidthVec(FileNoVec(FileInd))=LineWidth;
	    for ChanInd=1:NActChan
		    set(hDataVec(ChanInd),'LineWidth',LineWidth);
	    end
    end 
	set(hList(98),'Userdata',LineWidthVec);
	
	%=============================================================================
	%============ setMinBase
	%=============================================================================	
elseif strcmp(action,'setMinBase') | ...
	strcmp(action,'setMinBaseNoComp') | ...
	strcmp(action,'setMinBaseNoCall') | ...
	strcmp(action,'setMinBaseNoCompNoCall') | ...
    strcmp(action,'setMaxBaseTrig')

	hList=get(hPlot2dMenuFig,'Userdata');
	Domain=get(hList(20),'Value');
	NListHdr=get(hList(51),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	
	NPoints=get(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata');
	MaxBase=get(hList(59),'Value');
	MaxBaseVec=get(hList(59),'Userdata');

	TrigPoint=get(hList(22),'Value');
	MinPoint=get(hList(54),'Value');
	MaxPoint=get(hList(55),'Value');
	SampRate=get(hList(60),'Userdata');

	CalcBaseStatus=get(hList(57),'Value');	
% 	if ~strcmp(action,'setMinBaseNoCall') & ~strcmp(action,'setMinBaseNoCompNoCall') & CalcBaseStatus==0
% 		set(hList(57),'Value',1);	%CalcBaseStatus
% 	end
	MinBase=get(hList(58),'Value');	
	MinBaseVec=get(hList(58),'Userdata');
    MsHzMinBaseString=get(hList(58),'String');
   	ind=find(abs(MsHzMinBaseString)<32);
    MsHzMinBaseString(ind)=32*ones(size(ind));
   	MsHzMinBaseString=MsHzMinBaseString';	
    MsHzMinBaseTmp=eval(['[' MsHzMinBaseString(:)' ']'],'-1')';
	if Domain<3 | Domain==6 | Domain==7  %Time, Std
		MinBaseTmp=round(MsHzMinBaseTmp.*SampRate./1000+TrigPoint);
	elseif Domain>2 & Domain<5
		MinBaseTmp=round(MsHzMinBaseTmp.*NPoints.*2./SampRate);
	elseif Domain==5 %PCA
		MinBaseTmp=round(MsHzMinBaseTmp)+TrigPoint-1;
	end
    if ~strcmp(action,'setMinBaseNoComp') & ~strcmp(action,'setMinBaseNoCompNoCall')
		if  length(MinBaseTmp)~=1; MinBaseTmp=MinBase; end
		if MinBaseTmp>=NPoints; MinBaseTmp=NPoints; end
		if MinBaseTmp<1; MinBaseTmp=1; end
		if MaxBase==0; 
			MaxBaseTmp=MinBaseTmp;
		else
            if strcmp(action,'setMaxBaseTrig')
                MaxBaseTmp = TrigPoint;
            else
			    MaxBaseTmp=MaxBase;
            end
		end
		if MinBaseTmp>MaxBaseTmp; MinBaseTmp=MaxBase; end
		if Domain<3  | Domain==6 | Domain==7	%Time, Std
			MsHzMinBaseTmp=round((MinBaseTmp-TrigPoint).*1000./SampRate);
			MsHzMaxBaseTmp=round((MaxBaseTmp-TrigPoint).*1000./SampRate);
		elseif Domain>2 & Domain<5
			MsHzMinBaseTmp=round(MinBaseTmp.*SampRate./(2.*NPoints));
			MsHzMaxBaseTmp=round(MaxBaseTmp.*SampRate./(2.*NPoints));
		elseif Domain==5
				MsHzMinBaseTmp=round(MinBaseTmp)-TrigPoint+1;
		MsHzMaxBaseTmp=round(MaxBaseTmp)-TrigPoint+1;
		end
		MaxBaseVec(Domain)=MaxBaseTmp;
		set(hList(59),'Value',MaxBaseTmp,'Userdata',MaxBaseVec,'String',sprintf('%g',MsHzMaxBaseTmp));
	end
	MinBaseVec(Domain)=MinBaseTmp;
	set(hList(58),'Value',MinBaseTmp,'Userdata',MinBaseVec,'String',sprintf('%g',MsHzMinBaseTmp));
	if ~strcmp(action,'setMinBaseNoCall') & ~strcmp(action,'setMinBaseNoCompNoCall')
		if (MaxBaseTmp~=MaxBase | MinBaseTmp~=MinBase) & CalcBaseStatus
			emegs2d('CalcBase')
		end
	end
	%=============================================================================
	%============ setMaxBase
	%=============================================================================	
elseif strcmp(action,'setMaxBase') | ...
	strcmp(action,'setMaxBaseNoComp') | ...
	strcmp(action,'setMaxBaseNoCall') | ...
	strcmp(action,'setMaxBaseNoCompNoCall'),

	hList=get(hPlot2dMenuFig,'Userdata');
	Domain=get(hList(20),'Value');
	NListHdr=get(hList(51),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	
	NPoints=get(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata');
	MinBase=get(hList(58),'Value');
	MinBaseVec=get(hList(58),'Userdata');

	TrigPoint=get(hList(22),'Value');
	MinPoint = get(hList(54),'Value');
	MaxPoint=get(hList(55),'Value');
	SampRate = get(hList(60),'Userdata');
	
	CalcBaseStatus=get(hList(57),'Value');	
% 	if ~strcmp(action,'setMaxBaseNoCall') & ~strcmp(action,'setMaxBaseNoCompNoCall') & CalcBaseStatus==0
% 		set(hList(57),'Value',1);	%CalcBaseStatus
% 	end
	MaxBase = get(hList(59),'Value');
	MaxBaseVec=get(hList(59),'Userdata');
    	MsHzMaxBaseString = get(hList(59),'String');
    	ind = find(abs(MsHzMaxBaseString)<32);
    	MsHzMaxBaseString(ind) = 32*ones(size(ind));
    	MsHzMaxBaseString = MsHzMaxBaseString';	
    	MsHzMaxBaseTmp = eval(['[' MsHzMaxBaseString(:)' ']'],'-1')';
	if Domain<3 | Domain==6 | Domain==7 %Time, Std
		MaxBaseTmp=round(MsHzMaxBaseTmp.*SampRate./1000+TrigPoint);
	elseif Domain>2 & Domain<5
		MaxBaseTmp=round(MsHzMaxBaseTmp.*NPoints.*2./SampRate);
	elseif Domain==5 %PCA
		MaxBaseTmp=round(MsHzMaxBaseTmp)+TrigPoint-1;
	end
	if ~strcmp(action,'setMaxBaseNoComp') & ~strcmp(action,'setMaxBaseNoCompNoCall')
  		if length(MaxBaseTmp)~=1; MaxBaseTmp=MaxBase; end
		if MaxBaseTmp>=NPoints; MaxBaseTmp=NPoints; end
		if MaxBaseTmp<1; MaxBaseTmp=1; end
		if MinBase==0; 
			MinBaseTmp=1;
		else
			MinBaseTmp=MinBase;
		end
		if MaxBaseTmp<MinBaseTmp
			MaxBaseTmp=MinBase;
		end
		if Domain<3 | Domain==6 | Domain==7 %Time, Std
			MsHzMinBaseTmp=round((MinBaseTmp-TrigPoint).*1000./SampRate);
			MsHzMaxBaseTmp=round((MaxBaseTmp-TrigPoint).*1000./SampRate);
		elseif Domain>2 & Domain<5
			MsHzMinBaseTmp=round(MinBaseTmp.*SampRate./(2.*NPoints));
			MsHzMaxBaseTmp=round(MaxBaseTmp.*SampRate./(2.*NPoints));
		elseif Domain==5 %PCA
			MsHzMinBaseTmp=round(MinBaseTmp)-TrigPoint+1;
			MsHzMaxBaseTmp=round(MaxBaseTmp)-TrigPoint+1;
		end
		MinBaseVec(Domain)=MinBaseTmp;
		set(hList(58),'Value',MinBaseTmp,'Userdata',MinBaseVec,'String',sprintf('%g',MsHzMinBaseTmp));
	end
	MaxBaseVec(Domain)=MaxBaseTmp;
	set(hList(59),'Value',MaxBaseTmp,'Userdata',MaxBaseVec,'String',sprintf('%g',MsHzMaxBaseTmp));
	if ~strcmp(action,'setMaxBaseNoCall') & ~strcmp(action,'setMaxBaseNoCompNoCall')
		if (MaxBaseTmp~=MaxBase | MinBaseTmp~=MinBase) & CalcBaseStatus
			emegs2d('CalcBase')
		end
	end
	
elseif strcmp(action,'setCalcBaseStatus') | ...
	 strcmp(action,'setCalcTotalBaseStatus'),

	hList=get(hPlot2dMenuFig,'Userdata');
	Domain=get(hList(20),'Value');
	if strcmp(action,'setCalcTotalBaseStatus')
		ActFileNo=get(hList(1),'Userdata');
		NListHdr=get(hList(51),'Userdata');
		FileNoVec=get(hList(56),'Userdata');
		NPoints=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+3),'Userdata');
		SampRate=get(hList(60),'Userdata');
		TrigPoint=get(hList(22),'Value');
		
		CalcBaseStatus=1;
		MinBaseVec=get(hList(58),'Userdata');
		MinBaseVec(Domain)=1;
		set(hList(58),'Userdata',MinBaseVec);
		[MinBaseStr]=Point2Ms(1,Domain,SampRate,TrigPoint,NPoints);
		set(hList(58),'Value',1,'String',MinBaseStr);	%MinBase
		emegs2d('setMinBaseNoCall')
		MaxBaseVec=get(hList(59),'Userdata');
		MaxBaseVec(Domain)=NPoints;
		set(hList(59),'Userdata',MaxBaseVec);
		[MaxBaseStr]=Point2Ms(NPoints,Domain,SampRate,TrigPoint,NPoints);
		set(hList(59),'Value',NPoints,'String',MaxBaseStr);	%MinBase
		emegs2d('setMaxBaseNoCall')
		set(hList(57),'Value',1);	%CalcBaseStatus
	else
		CalcBaseStatus=get(hList(57),'Value');
	end
	CalcBaseStatusVec=get(hList(57),'Userdata'); 
	CalcBaseStatusVec(Domain)=CalcBaseStatus;
	set(hList(57),'Userdata',CalcBaseStatusVec); 
	emegs2d('CalcBase')
	if strcmp(action,'setCalcTotalBaseStatus')
		emegs2d('AdjustAmp')
	end
	%=============================================================================
	%============ CalcBase: baseline calculation
	%============ call: PlotData
	%=============================================================================	

elseif strcmp(action,'CalcBase') | strcmp(action,'CalcBaseNoCall'),

	hList=get(hPlot2dMenuFig,'Userdata');
	Domain=get(hList(20),'Value');
	DomainLabelStr=get(hList(20),'String');
	NDomain=size(DomainLabelStr,1);
	CalcBaseStatus=get(hList(57),'Value'); 
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	ActFileNo=get(hList(1),'Userdata');
	NPoints=get(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata');
	OpenAvgFileStatus=get(hList(108),'Value');
	BaseMat=get(hList(115),'Userdata');

	if ~CalcBaseStatus
		for FileIndex=1:NUsedFiles
			BaseVec=BaseMat(:,(FileIndex-1).*NDomain+Domain);
			CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
			[CalcAvgMat]=CalcValOfVecToMat(CalcAvgMat',BaseVec,['+']);
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat');
			emegs2d('CalcFirst')
			BaseMat(:,(FileIndex-1).*NDomain+Domain)=zeros(size(BaseVec));
		end
	else
		MinBase=get(hList(58),'Value');
		MaxBase=get(hList(59),'Value');
		for FileIndex=1:NUsedFiles
			CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
			[CalcAvgMat,BaseStartPoint,BaseEndPoint,NonUse,BaseVec] = CalcBaseline(CalcAvgMat,MinBase,MaxBase,1,1);
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat);
			BaseMat(:,(FileIndex-1).*NDomain+Domain)=BaseVec; 
		end
	end
	set(hList(115),'Userdata',BaseMat); 
	if ~OpenAvgFileStatus & ~strcmp(action,'CalcBaseNoCall'); 
		emegs2d('PlotData'); 
	end
	
	%=============================================================================
	%============ setMinAmp; setMaxAmp, setMinAmpNoCall, setMaxAmpNoCall
	%============ call: setMinMaxAmpPoint
	%=============================================================================	
elseif strcmp(action,'setMinAmp') | ...
	strcmp(action,'setMinAmpNoCall') | ...
	strcmp(action,'setMaxAmp') | ...
	strcmp(action,'setMaxAmpNoCall'),
	 
	hList=get(hPlot2dMenuFig,'Userdata');
	Domain=get(hList(20),'Value');
	DecInc=get(hList(124),'Userdata'); 
	DecIncAmp=DecInc(2);
	Tmp=max([1./DecIncAmp 1000]);
	MinAmpVal=get(hList(52),'Value');
	MinAmpVec=get(hList(52),'Userdata');
	MinAmpStr = get(hList(52),'String');
	MaxAmpVal=get(hList(53),'Value');
	MaxAmpVec=get(hList(53),'Userdata');
	MaxAmpStr = get(hList(53),'String');
	if strcmp(action,'setMinAmp') | strcmp(action,'setMinAmpNoCall') 
		[MinAmpVal,MinAmpStr]=String2Value(MinAmpStr,MinAmpVal,[],MaxAmpVal);
		MinAmpVec(Domain)=MinAmpVal;
		set(hList(52),'Value',MinAmpVal,'Userdata',MinAmpVec,'String',sprintf('%g',round(MinAmpVal*Tmp)/Tmp));  
	else
		[MaxAmpVal,MaxAmpStr]=String2Value(MaxAmpStr,MaxAmpVal,MinAmpVal,[]);
		MaxAmpVec(Domain)=MaxAmpVal;
		set(hList(53),'Value',MaxAmpVal,'Userdata',MaxAmpVec,'String',sprintf('%g',round(MaxAmpVal*Tmp)/Tmp));  
	end
	if strcmp(action,'setMinAmp') | strcmp(action,'setMaxAmp')
		emegs2d('setMinMaxAmpPoint')
	end
	%=============================================================================
	%============ DecIncStatus | DecDecIncAmp | IncDecIncAmp; 
	%=============================================================================	
elseif strcmp(action,'DecIncStatus') | strcmp(action,'DecDecIncAmp') | strcmp(action,'IncDecIncAmp')

	hList=get(hPlot2dMenuFig,'Userdata');
	DecInc=get(hList(124),'Userdata');
	DecIncStatus=DecInc(1);
	DecIncAmp=DecInc(2);
	if strcmp(action,'DecIncStatus')
		DecIncStatus=DecIncStatus+1;
		if DecIncStatus==2; DecIncStatus=-1; end
	elseif strcmp(action,'DecDecIncAmp')
		DecIncAmp=DecIncAmp./10; 
	elseif strcmp(action,'IncDecIncAmp'); 
		DecIncAmp=DecIncAmp.*10;
	end
	if DecIncStatus==-1
		DecIncString=['- ' num2str(DecIncAmp)];
	elseif DecIncStatus==0
		DecIncString=['+/- ' num2str(DecIncAmp)];
	elseif DecIncStatus==1
		DecIncString=['+ ' num2str(DecIncAmp)];
	end
	set(hList(124),'Userdata',[DecIncStatus DecIncAmp],'String',DecIncString);

	%=============================================================================
	%============ AdjustAmp | CenterAmp | DecAmp | IncAmp; 
	%=============================================================================	
elseif strcmp(action,'AdjustAmp') | ...
	strcmp(action,'CenterAmp') | ...
	strcmp(action,'DecAmp') | ...
	strcmp(action,'IncAmp'),
	
	hList=get(hPlot2dMenuFig,'Userdata'); 
	Domain=get(hList(20),'Value');
		
	MinAmp=get(hList(52),'Value'); 
	MinAmpNew=MinAmp;
	MinAmpVec=get(hList(52),'Userdata');
	MaxAmp=get(hList(53),'Value');
	MaxAmpVec=get(hList(53),'Userdata');
	MaxAmpNew=MaxAmp;
	DecInc=get(hList(124),'Userdata');  
	DecIncStatus=DecInc(1);
	DecIncAmp=DecInc(2);
	
    if Domain==8
        MinPoint=get(hList(54),'Value');
		MaxPoint=get(hList(55),'Value');
        if any(strcmp(who('global'),'hGetFrequIntervalMenuFig'))
			global hGetFrequIntervalMenuFig
		end
		GetFrequIntervalMenuList=get(hGetFrequIntervalMenuFig,'Userdata'); 
		MinF0Point=get(GetFrequIntervalMenuList(4),'Value');
		MaxF0Point=get(GetFrequIntervalMenuList(7),'Value');
    end
        
        
	if strcmp(action,'CenterAmp')
		AbsAmp=max(abs([MinAmp,MaxAmp]));
		MaxAmp=AbsAmp; MinAmp=-1.*AbsAmp;
	elseif strcmp(action,'AdjustAmp')
		FileNoVec=get(hList(56),'Userdata');
		NUsedFiles=length(FileNoVec);
		ActFileNo=get(hList(1),'Userdata');
		NListHdr=get(hList(51),'Userdata');
		VisibleStatusVec=get(hList(109),'Userdata');
		MinAmp=10^10; MaxAmp=-10^10;
		for FileIndex=1:NUsedFiles
			if VisibleStatusVec(FileIndex)==1;
                if Domain==8
                    CalcAvgMat=get(hList(NListHdr+(ActFileNo-1).*50+36),'Userdata');
                    CalcAvgMat=CalcAvgMat(:,MinPoint:MaxPoint,MinF0Point:MaxF0Point);
                else
				    CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
                end
				hDataVec=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+25),'Userdata');
				Tmp=get(hList(16),'Userdata');
				SensorNChan=Tmp(2);
				ChanVisInd=0;
				VisIndVec=[];
                if Domain==8
                    for ChanInd=1:SensorNChan
						ChanVisInd=ChanVisInd+1;
                        VisIndVec(ChanVisInd) = ChanInd;
					end
                else
					for ChanInd=1:SensorNChan
						VisibleStatus=get(hDataVec(ChanInd),'Visible');
						if strcmp(VisibleStatus,'on')
							ChanVisInd=ChanVisInd+1;
							VisIndVec(ChanVisInd)=ChanInd;
						end
					end
                end
				if isempty(VisIndVec)
					MaxAmp=MaxAmpOld;
					MinAmp=MinAmpOld;
				else
                    if Domain==8
						CalcAvgMat=CalcAvgMat(VisIndVec,:,:);
						MinAmpOld=min(min(min(CalcAvgMat)));
						MaxAmpOld=max(max(max(CalcAvgMat)));
						MaxAmp=max([MaxAmpOld MaxAmp]);
						MinAmp=min([MinAmpOld MinAmp]);
                    else
                        CalcAvgMat=CalcAvgMat(VisIndVec,:);
						MinAmpOld=min(min(CalcAvgMat));
						MaxAmpOld=max(max(CalcAvgMat));
						MaxAmp=max([MaxAmpOld MaxAmp]);
						MinAmp=min([MinAmpOld MinAmp]);
                    end
				end
			end
		end
	elseif strcmp(action,'DecAmp')
		if DecIncStatus==-1 |  DecIncStatus==0
			MinAmpNew=MinAmp+DecIncAmp;
		end
		if DecIncStatus==1 |  DecIncStatus==0
			MaxAmpNew=MaxAmp-DecIncAmp;
		end
	elseif strcmp(action,'IncAmp')
		if DecIncStatus==-1 |  DecIncStatus==0
			MinAmpNew=MinAmp-DecIncAmp;
		end
		if DecIncStatus==1 |  DecIncStatus==0
			MaxAmpNew=MaxAmp+DecIncAmp;
		end
	end
	if strcmp(action,'DecAmp') | strcmp(action,'IncAmp'),
		if MinAmpNew<MaxAmpNew
			MinAmp=round(MinAmpNew./DecIncAmp).*DecIncAmp;
			MaxAmp=round(MaxAmpNew./DecIncAmp).*DecIncAmp;
		end
	end
	MinAmpVec(Domain)=MinAmp;
	MaxAmpVec(Domain)=MaxAmp;
	set(hList(52),'Value',MinAmp,'Userdata',MinAmpVec,'String',sprintf('%g',round(MinAmp*1000)/1000));  
	set(hList(53),'Value',MaxAmp,'Userdata',MaxAmpVec,'String',sprintf('%g',round(MaxAmp*1000)/1000));  
	emegs2d('setMinMaxAmpPoint')

elseif strcmp(action,'InvertGlobPowView')  | ...
	strcmp(action,'InvertSpecChanView')  | ...
	 strcmp(action,'InvertButView') 

	hList=get(hPlot2dMenuFig,'Userdata'); 
	if strcmp(action,'InvertButView')
		ListNo=63;
	elseif strcmp(action,'InvertSpecChanView')
		ListNo=64;
	elseif strcmp(action,'InvertGlobPowView')
		ListNo=66;
	end
	hhVec=get(hList(ListNo),'Userdata');
	Tmp=get(hhVec(19),'Userdata');
	if Tmp==1
		Tmp=-1;
		set(hhVec(17),'YDir','Reverse');
	elseif Tmp==-1
		Tmp=1;
		set(hhVec(17),'YDir','Normal');
	end
	set(hhVec(19),'Userdata',Tmp);
	
elseif strcmp(action,'SpecChanChan') | ...
	strcmp(action,'DecSpecChanChan') | ...
	strcmp(action,'IncSpecChanChan'),

    if isempty(varargin)
        chnr = [];
    else
        chnr = varargin{1};
    end
    
	hList=get(hPlot2dMenuFig,'Userdata'); 
	Domain=get(hList(20),'Value');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	hhVec=get(hList(64),'Userdata');
	AutoAdjustStatus=get(hhVec(21),'Value');
	MinPoint=get(hhVec(3),'Value');
	MaxPoint=get(hhVec(4),'Value');
	NPoints=MaxPoint-MinPoint+1;
    if isempty(chnr)
	    SpecChan=get(hhVec(33),'Value');
    else
        SpecChan = chnr;
        set(hhVec(33),'Value',chnr);
    end
	Tmp=get(hList(16),'Userdata');
	SensorNChan=Tmp(2);
	if strcmp(action,'DecSpecChanChan')
		if SpecChan==1;
			SpecChan=SensorNChan;
		else
			SpecChan=SpecChan-1;
		end
	elseif strcmp(action,'IncSpecChanChan')
		if SpecChan==SensorNChan;
			SpecChan=1;
		else
			SpecChan=SpecChan+1;
		end
	end
	set(hhVec(33),'Value',SpecChan);
	SensorNames=get(hList(4),'Userdata');
	SensorName=SensorNames(SpecChan,:);
	hSpecDataVec=get(hhVec(34),'Userdata');
	hTopMenu=get(hList(65),'Userdata');
	hExportMenu=get(hTopMenu(3),'children');	
	hExportUserData=get(hExportMenu(1),'children'); 
	hUserDataInfo=get(hExportUserData(1),'children');
	UserDataMat=zeros(length(hSpecDataVec),NPoints);
	for FileIndex=1:length(hSpecDataVec)
		if Domain==6 | Domain==7	
			CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+36),'Userdata');
			CalcAvgMat=squeeze(CalcAvgMat(SpecChan,MinPoint:MaxPoint,:))';
			UserDataMat=CalcAvgMat;
			set(hSpecDataVec(FileIndex),'CData',CalcAvgMat);
		else
			CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
			UserDataMat(FileIndex,:)=CalcAvgMat(SpecChan,MinPoint:MaxPoint);
			set(hSpecDataVec(FileIndex),'YData',CalcAvgMat(SpecChan,:));
		end
	end;
	set(hList(94),'Userdata',UserDataMat);
	set(hUserDataInfo,'Label',['Special Sensor ',int2str(SpecChan),':  ', SensorName]);
	set(hhVec(35),'Name',['Zoom Sensor ',int2str(SpecChan),':  ', SensorName]);	%hZoomFig;	
	set(hhVec(36),'Name',['Menu Sensor ',int2str(SpecChan),':  ', SensorName]);	%hZoomMenu;	
	set(hList(64),'Userdata',hhVec);
	set(hPlot2dMenuFig,'Userdata',hList);
	if AutoAdjustStatus
		emegs2d('AdjustSpecChanAmp');
	end
	%=============================================================================
	%============ DecIncButSta | DecDecIncButAmp | IncDecIncButAmp; 
	%============ DecIncSpecChanSta | DecDecIncSpecChanAmp | IncDecIncSpecChanAmp; 
	%============ DecIncGlobPowSta | DecDecIncGlobPowAmp | IncDecIncGlobPowAmp; 
	%=============================================================================	
elseif strcmp(action,'DecIncButSta') | strcmp(action,'DecDecIncButAmp') | strcmp(action,'IncDecIncButAmp') | ...
	 strcmp(action,'DecIncSpecChanSta') | strcmp(action,'DecDecIncSpecChanAmp') | strcmp(action,'IncDecIncSpecChanAmp') | ...
	 strcmp(action,'DecIncGlobPowSta') | strcmp(action,'DecDecIncGlobPowAmp') | strcmp(action,'IncDecIncGlobPowAmp'),

	hList=get(hPlot2dMenuFig,'Userdata'); 
	if strcmp(action(length(action)-5:length(action)-3),'But')
		ListNo=63;
	elseif strcmp(action(length(action)-6:length(action)-3),'Chan')
		ListNo=64;
	elseif strcmp(action(length(action)-5:length(action)-3),'Pow')
		ListNo=66;
	end
	hhVec=get(hList(ListNo),'Userdata');
	DecInc=get(hhVec(18),'Userdata');
	DecIncStatus=DecInc(1);
	DecIncAmp=DecInc(2);
	if strcmp(action,'DecIncButSta') | strcmp(action,'DecIncSpecChanSta') | strcmp(action,'DecIncGlobPowSta')
		DecIncStatus=DecIncStatus+1;
		if DecIncStatus==2; DecIncStatus=-1; end
	elseif strcmp(action,'DecDecIncButAmp') | strcmp(action,'DecDecIncSpecChanAmp') | strcmp(action,'DecDecIncGlobPowAmp')
		DecIncAmp=DecIncAmp./10; 
	elseif strcmp(action,'IncDecIncButAmp') | strcmp(action,'IncDecIncSpecChanAmp') | strcmp(action,'IncDecIncGlobPowAmp')
		DecIncAmp=DecIncAmp.*10;
	end
	if DecIncStatus==-1
		DecIncString=['- ' num2str(DecIncAmp)];
	elseif DecIncStatus==0
		DecIncString=['+/- ' num2str(DecIncAmp)];
	elseif DecIncStatus==1
		DecIncString=['+ ' num2str(DecIncAmp)];
	end
	set(hhVec(18),'Userdata',[DecIncStatus DecIncAmp],'String',DecIncString);

elseif strcmp(action,'AdjustButAmp') | ...
	strcmp(action,'CenterButAmp') | ...
	strcmp(action,'DecButAmp') | ...
	strcmp(action,'IncButAmp') | ...
	strcmp(action,'AdjustSpecChanAmp') | ...
	strcmp(action,'CenterSpecChanAmp') | ...
	strcmp(action,'DecSpecChanAmp') | ...
	strcmp(action,'IncSpecChanAmp') | ...
	strcmp(action,'AdjustGlobPowAmp') | ...
	strcmp(action,'CenterGlobPowAmp') | ...
	strcmp(action,'DecGlobPowAmp') | ...
	strcmp(action,'IncGlobPowAmp'),
	
	hList=get(hPlot2dMenuFig,'Userdata'); 
	if strcmp(action(length(action)-5:length(action)-3),'But')
		ListNo=63;
		hhVec=get(hList(ListNo),'Userdata');
		NListHdr=get(hList(51),'Userdata');
		FileNoVec=get(hList(56),'Userdata');
		Tmp=get(hList(16),'Userdata');
		SensorNChan=Tmp(2);
		VisibleStatusVec=get(hList(109),'Userdata');
	elseif strcmp(action(length(action)-6:length(action)-3),'Chan')
		ListNo=64;
		hhVec=get(hList(ListNo),'Userdata');
        GlobDissimStatus = 0;
        if strcmp(get(hhVec(35),'Name'),'Global Dissimilarity')
            GlobDissimStatus = 1;
        end
		SpecChan=get(hhVec(33),'Value');
	elseif strcmp(action(length(action)-5:length(action)-3),'Pow')
		ListNo=66;
		hhVec=get(hList(ListNo),'Userdata');
	end
	
            
	MinAmp=get(hhVec(1),'Value'); MinAmpNew=MinAmp;
	MaxAmp=get(hhVec(2),'Value');MaxAmpNew=MaxAmp;
    
	MinPoint=get(hhVec(3),'Value');
	MaxPoint=get(hhVec(4),'Value');
	DecInc=get(hhVec(18),'Userdata');
	Domain=get(hList(20),'Value');
    if Domain == 7 | Domain == 8
        MinFreq = num2str(get(hhVec(24),'String'));
        MinFreqPoint = get(hhVec(25),'Value');
        MaxFreq = num2str(get(hhVec(26),'String'));
        MaxFreqPoint = get(hhVec(27),'Value');
    end
    
	DecIncStatus=DecInc(1);
	DecIncAmp=DecInc(2);
	if strcmp(action(1:6),'DecDec') | strcmp(action(1:6),'IncDec')
		if strcmp(action(1:6),'DecDec')
			DecIncAmp=DecIncAmp./10; 
		elseif strcmp(action(1:6),'IncDec'); 
			DecIncAmp=DecIncAmp.*10;
		end
		set(hhVec(18),'Userdata',DecIncAmp,'String',num2str(DecIncAmp));
		return;
	end
	if strcmp(action(1:6),'Center')
		AbsAmp=max(abs([MinAmp,MaxAmp]));
		MaxAmp=AbsAmp; MinAmp=-1.*AbsAmp;
	elseif strcmp(action(1:6),'Adjust')
		FileNoVec=get(hList(56),'Userdata');
		NUsedFiles=length(FileNoVec);
		ActFileNo=get(hList(1),'Userdata');
		NListHdr=get(hList(51),'Userdata');
		MinAmp=10^10; MaxAmp=-10^10;
		for FileIndex=1:NUsedFiles
			if strcmp(action(length(action)-5:length(action)-3),'But')
				hhButVec=get(hList(63),'Userdata');
				hButChanLineVec=get(hhButVec(25),'Userdata');
				for ChanInd=1:length(hButChanLineVec)
					YData=get(hButChanLineVec(ChanInd),'YData');
					MinAmp=min([MinAmp,min(YData)]);
					MaxAmp=max([MaxAmp,max(YData)]);
				end
				CalcAvgMat=[MinAmp MaxAmp];
			elseif strcmp(action(length(action)-6:length(action)-3),'Chan')
				if Domain==6 | Domain==7 
					CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+36),'Userdata');
					CalcAvgMat=squeeze(CalcAvgMat(SpecChan,MinPoint:MaxPoint,:))';
                elseif Domain == 8
					CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+36),'Userdata');
					CalcAvgMat=squeeze(CalcAvgMat(SpecChan,MinPoint:MaxPoint,MinFreqPoint:MaxFreqPoint))';
                elseif GlobDissimStatus
                    hDissimLine = get(hList(144),'userdata');
                    DissimData = get(hDissimLine,'YData');
                    CalcAvgMat = DissimData(MinPoint:MaxPoint);
				else
					CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
					CalcAvgMat=CalcAvgMat(SpecChan,MinPoint:MaxPoint);	
				end
			elseif strcmp(action(length(action)-5:length(action)-3),'Pow')
                if Domain==6 | Domain==7 | Domain == 8
					CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+26),'Userdata');
					CalcAvgMat=squeeze(CalcAvgMat(MinPoint:MaxPoint,MinFreqPoint:MaxFreqPoint))';
				else
					CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+26),'Userdata');
					CalcAvgMat=CalcAvgMat(MinPoint:MaxPoint);
                end
			end
			MinAmpOld=min(min(CalcAvgMat));
			MaxAmpOld=max(max(CalcAvgMat));
			MaxAmp=max([MaxAmpOld MaxAmp]);
			MinAmp=min([MinAmpOld MinAmp]);
            if Domain==7  | Domain==8
                break;
            end
		end
	elseif strcmp(action(1:3),'Dec')
		if DecIncStatus==-1 |  DecIncStatus==0
			MinAmpNew=MinAmp+DecIncAmp;
		end
		if DecIncStatus==1 |  DecIncStatus==0
			MaxAmpNew=MaxAmp-DecIncAmp;
		end
	elseif strcmp(action(1:3),'Inc')
		if DecIncStatus==-1 |  DecIncStatus==0
			MinAmpNew=MinAmp-DecIncAmp;
		end
		if DecIncStatus==1 |  DecIncStatus==0
			MaxAmpNew=MaxAmp+DecIncAmp;
		end
	end
	if strcmp(action(1:3),'Dec') | ...
		strcmp(action(1:3),'Inc'),
		if MinAmpNew<MaxAmpNew
			MinAmp=round(MinAmpNew./DecIncAmp).*DecIncAmp;
			MaxAmp=round(MaxAmpNew./DecIncAmp).*DecIncAmp;
		end
	end
	set(hhVec(1),'Value',MinAmp,'String',num2str(MinAmp));
	set(hhVec(2),'Value',MaxAmp,'String',num2str(MaxAmp));
	if Domain==6 | Domain==7 
		hSpecDataVec=get(hhVec(14),'Userdata');
		SpecDataParent=get(hSpecDataVec(1),'Parent');
		set(SpecDataParent,'Clim',[MinAmp MaxAmp]);
    elseif Domain == 8
        axes(hhVec(17));
        set(hhVec(17),'CLimMode','manual','CLim',[MinAmp,MaxAmp]);
		
	else
		set(hhVec(17),'YLim',[MinAmp MaxAmp]);
	end
	
	%=============================================================================
	%============ setMinPoint
	%============ call: setMinMaxAmpPoint
	%=============================================================================			
elseif strcmp(action,'setMinPoint') | ...
	strcmp(action,'setMinPointSlider') | ...
	strcmp(action,'setMinPointNoComp') | ...
	strcmp(action,'setMinPointNoCall') | ...
	strcmp(action,'setMinPointNoCompNoCall'),
	  
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	Domain=get(hList(20),'Value');
	DomainLabelStr=get(hList(20),'String');
	NDomain=size(DomainLabelStr,1);
	TrigPoint=get(hList(22),'Value');
	NListHdr=get(hList(51),'Userdata');
	ActAvgMat=get(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata');
	NPoints=get(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata');
	NPointsString=get(hList(NListHdr+(ActFileNo-1).*50+3),'String');
	SampRate=get(hList(60),'Userdata');
    MaxPoint=get(hList(55),'Value');
	%==========    
	MinPointSlider=get(hList(122),'Value'); %MinPointSlider
	if ~strcmp(action,'setMinPointSlider')
		MsHzMinPointString = get(hList(54),'String');
		ind = find(abs(MsHzMinPointString)<32);
		MsHzMinPointString(ind) = 32*ones(size(ind));
		MsHzMinPointString = MsHzMinPointString';	
		MsHzMinPointTmp = eval(['[' MsHzMinPointString(:)' ']'],'-1')';
		if Domain<3 | Domain==6 | Domain==7  %Time, Std, Wavelet
			MinPointTmp=round(MsHzMinPointTmp.*SampRate./1000+TrigPoint);
		elseif Domain>2 & Domain<5		     %FFT
			MinPointTmp=round(MsHzMinPointTmp.*NPoints.*2./SampRate);
		elseif Domain==5				     %PCA
			MinPointTmp=MsHzMinPointTmp;
		end
	else
		MinPointTmp=round(MinPointSlider);
	end
	if ~strcmp(action,'setMinPointNoComp') & ~strcmp(action,'setMinPointNoCompNoCall')
		if length(MinPointTmp)~=1; MinPointTmp = MinPoint; end
        if MinPointTmp>NPoints; MinPointTmp=NPoints; end
		if MinPointTmp>MaxPoint; 
            set(hList(123),'Value',NPoints); %MaxPointSlider
            emegs2d('setMaxPointSlider')
        end
		if MinPointTmp<=0; MinPointTmp=1; end
	end
	MinPointVec(Domain)=MinPointTmp;
	set(hList(54),'Value',MinPointTmp,'String',MinPointVec);	
	set(hList(122),'Value',MinPointTmp); %MinPointSlider
	hMinMaxText=get(hList(21),'Userdata');
	MinPointText=get(hMinMaxText(3),'String');
	Ind=findstr(MinPointText,'#');
	if ~isempty(Ind)
		MinPointText=[MinPointText(1:Ind),' ',int2str(MinPointTmp)];
	else
		MinPointText=[MinPointText,'; # ',int2str(MinPointTmp)];
	end
	set(hMinMaxText(3),'String',MinPointText);
	if ~strcmp(action,'setMinPointNoCall') & ~strcmp(action,'setMinPointNoCompNoCall')
		emegs2d('setMinMaxAmpPoint')
	end
	%=============================================================================
	%============ setMaxPoint
	%============ call: setMinMaxAmpPoint
	%=============================================================================	
elseif strcmp(action,'setMaxPoint') | ...
	strcmp(action,'setMaxPointSlider') | ...
	strcmp(action,'setMaxPointNoComp') | ...
	strcmp(action,'setMaxPointNoCall') | ...
	strcmp(action,'setMaxPointNoCompNoCall'),
	
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	Domain=get(hList(20),'Value');
	DomainLabelStr=get(hList(20),'String');
	NDomain=size(DomainLabelStr,1);
	TrigPoint=get(hList(22),'Value');
	NListHdr=get(hList(51),'Userdata');
	ActAvgMat=get(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata');
	NPoints=get(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata');
	NPointsString=get(hList(NListHdr+(ActFileNo-1).*50+3),'String');
	SampRate=get(hList(60),'Userdata');
    MinPoint=get(hList(54),'Value');
    %-----
	MaxPointSlider=get(hList(123),'Value'); %MaxPointSlider
	if ~strcmp(action,'setMaxPointSlider')
		MsHzMaxPointString = get(hList(55),'String');
		ind=find(abs(MsHzMaxPointString)<32);
		MsHzMaxPointString(ind) = 32*ones(size(ind));
		MsHzMaxPointString = MsHzMaxPointString';	
		MsHzMaxPointTmp = eval(['[' MsHzMaxPointString(:)' ']'],'-1')';
		if Domain<3 | Domain==6 | Domain==7 | Domain==8%Time, Std
			MaxPointTmp=round(MsHzMaxPointTmp.*SampRate./1000+TrigPoint);
		elseif Domain>2 & Domain<5		%FFT
			MaxPointTmp=round(MsHzMaxPointTmp.*NPoints.*2./SampRate);
		elseif Domain==5				%PCA
			MaxPointTmp=MsHzMaxPointTmp;
		end
	else
		MaxPointTmp=round(MaxPointSlider);
	end
	if length(MaxPointTmp)~=1; MaxPointTmp=MaxPoint; end
	if ~strcmp(action,'setMaxPointNoComp') & ~strcmp(action,'setMaxPointNoCompNoCall')
		if MaxPointTmp<MinPoint; 
            set(hList(122),'Value',1); %MinPointSlider
            emegs2d('setMinPointSlider')
        end
		if MaxPointTmp>NPoints ; MaxPointTmp=NPoints; end
	end
	MaxPointVec(Domain)=MaxPointTmp;
	set(hList(55),'Value',MaxPointTmp,'Userdata',MaxPointVec);		
	set(hList(123),'Value',MaxPointTmp); %MaxPointSlider
    hMinMaxText=get(hList(21),'Userdata');
	MaxPointText=get(hMinMaxText(4),'String');
	Ind=findstr(MaxPointText,'#');
	if ~isempty(Ind)
		MaxPointText=[MaxPointText(1:Ind),' ',int2str(MaxPointTmp)];
	else
		MaxPointText=[MaxPointText,'; # ',int2str(MaxPointTmp)];
	end
	set(hMinMaxText(4),'String',MaxPointText);
	if ~strcmp(action,'setMinPointNoCall') & ~strcmp(action,'setMaxPointNoCompNoCall')
		emegs2d('setMinMaxAmpPoint')
	end
	%=============================================================================
	%============ setMinMaxAmpPoint
	%=============================================================================	
elseif strcmp(action,'setMinMaxAmpPoint'),

	hList=get(hPlot2dMenuFig,'Userdata'); 
	Domain=get(hList(20),'Value');
	hAxesVec=get(hList(6),'Userdata');
	TrigPoint=get(hList(22),'Value');
	MinAmp=get(hList(52),'Value');
	MaxAmp=get(hList(53),'Value');
	SampRate = get(hList(60),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	%==================================
	MinPoint=get(hList(54),'Value');
	if Domain<3 | Domain==6 | Domain==7 | Domain ==8%Time, Std
		MsHzMinPoint=round((MinPoint-TrigPoint).*1000./SampRate);
	elseif Domain>2 & Domain<5	%FFT
		MsHzMinPoint=(MinPoint-TrigPoint).*(NPoints+1).*(SampRate./2)./NPoints.^2
	elseif Domain==5 			%PCA
		MsHzMinPoint=MinPoint;
	end
   	MsHzMinPointString = sprintf('%g',round(MsHzMinPoint.*1000)./1000);
	set(hList(54),'String',MsHzMinPointString);
	%==================================
	MaxPoint=get(hList(55),'Value');
	if Domain<3 | Domain==6 | Domain==7 | Domain==8%Time, Std
		MsHzMaxPoint=round((MaxPoint-TrigPoint).*1000./SampRate);
	elseif Domain>2 & Domain<5	%FFT
		MsHzMaxPoint=(MaxPoint-TrigPoint).*(NPoints+1).*(SampRate./2)./NPoints.^2;	
	elseif Domain==5 			%PCA
		MsHzMaxPoint=MaxPoint;
	end
    MsHzMaxPointString = sprintf('%g',round(MsHzMaxPoint.*1000)./1000);
	set(hList(55),'String',MsHzMaxPointString);
	%==================================
	SampRate = get(hList(60),'Userdata');
	hSpec1Axes=get(hList(76),'Userdata');
	hSpec1ZeroLine=get(hList(77),'Userdata');
	MainMatlabVersion=get(hList(100),'Userdata');
	NActChan=length(hAxesVec);
	
	if MaxPoint<=MinPoint; return; end
	for ChanInd=1:NActChan
		if Domain==6 | Domain==7 | Domain == 8	
			set(hAxesVec(ChanInd),'XLim',[MinPoint MaxPoint],'Clim',[MinAmp MaxAmp]);
%         elseif Domain == 8
%             delete(get(hAxesVec(ChanInd),'children'));
% 			NListHdr=get(hList(51),'Userdata');
% 			FileNoVec=get(hList(56),'Userdata');
% 			NUsedFiles=length(FileNoVec);
% 			ActFileNo=get(hList(1),'Userdata');
% 			Spec1Axes=get(hList(76),'Userdata');
% 			set(Spec1Axes,'Visible','on');
% 			Spec1ZeroLine=get(hList(77),'Userdata');
% 			set(Spec1ZeroLine,'Visible','on');
% 			hAxesVec=get(hList(6),'Userdata');
% 			kActAxes=get(hList(27),'Userdata');
% 			hDataVec=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+25),'Userdata');
% 			NActChan=length(hDataVec);
% 			WaveVec=get(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata');
%             WaveMat=get(hList(NListHdr+(ActFileNo-1).*50+36),'Userdata');
% 			CalcAvgMat=WaveMat;
%             if any(strcmp(who('global'),'hGetFrequIntervalMenuFig'))
% 				global hGetFrequIntervalMenuFig
% 			end
% 			GetFrequIntervalMenuList=get(hGetFrequIntervalMenuFig,'Userdata'); 
% 			MinF0Point=get(GetFrequIntervalMenuList(4),'Value');
% 			MaxF0Point=get(GetFrequIntervalMenuList(7),'Value');   
%             TmpMat=squeeze(CalcAvgMat(ChanInd,MinPoint:MaxPoint,MinF0Point:MaxF0Point));
%             axes(hAxesVec(ChanInd));
%             hDataVec(ChanInd)=image(flipud(TmpMat'),'CDataMapping','scaled');
%             set(hAxesVec(ChanInd),'Clim',[MinAmp MaxAmp]);
%             axis off;
		else
			set(hAxesVec(ChanInd),'XLim',[MinPoint MaxPoint],'YLim',[MinAmp MaxAmp]);
		end
	end
	if Domain==6 | Domain==7	
		set(hSpec1Axes,'XLim',[MinPoint MaxPoint]);
	else
		set(hSpec1Axes,'XLim',[MinPoint MaxPoint],'YLim',[MinAmp MaxAmp],'ytick',[MinAmp MaxAmp],'YTickLabel',[round(10.*MinAmp)./10 round(10.*MaxAmp)./10]);
	end
	if TrigPoint>MinPoint & TrigPoint<MaxPoint & Domain<3
		set(hSpec1Axes,'xtick',[TrigPoint MaxPoint],'XTickLabel',[0 MsHzMaxPoint]);	
	else
		set(hSpec1Axes,'xtick',[MinPoint MaxPoint],'XTickLabel',[MsHzMinPoint MsHzMaxPoint]);	
	end
	set(hSpec1ZeroLine,'XData',[MinPoint MaxPoint],'YData',[0 0]);
	if Domain==6 | Domain==7	
		hSpec2Axes=get(hList(104),'Userdata');
		set(hSpec2Axes,'XTick',[0 1],'XTickLabel',[round(MinAmp.*100)./100 round(MaxAmp.*100)./100]);
	end
	%=============================================================================
	%============ setTrigPoint
	%============ call: setMinPoint, setMaxPoint, setMinBase, setMaxBase
	%=============================================================================	
elseif strcmp(action,'setTrigPoint') | ...
	strcmp(action,'setTrigPointNoCall'),
	  
	hList=get(hPlot2dMenuFig,'Userdata');
	Domain=get(hList(20),'Value');
	TrigPoint = get(hList(22),'Value');
	TrigPointVec = get(hList(22),'Userdata');
	hTrigLine=get(hList(9),'Userdata');
	TrigVisible=get(hTrigLine(1),'Visible');
	NListHdr=get(hList(51),'Userdata');
	MinPoint=get(hList(54),'Value');
	MsHzMinPoint=get(hList(54),'String');
	MaxPoint=get(hList(55),'Value');
	MsHzMaxPointString=get(hList(54),'String');
	NPoints=get(hList(NListHdr+3),'Userdata');
	SampRate = get(hList(60),'Userdata');
	hSpec1Axes=get(hList(76),'Userdata');
	hSpec1TrigLine=get(hList(78),'Userdata');
	MainMatlabVersion=get(hList(100),'Userdata');
	TrigPointStr = get(hList(22),'String');
	
	[TrigPoint,TrigPointStr]=String2Value(TrigPointStr,TrigPoint,1,NPoints,1,1);
	
	TrigPointVec(Domain)=TrigPoint;
	set(hList(22),'Value',TrigPoint,'Userdata',TrigPointVec,'String',sprintf('%g',TrigPoint));	
	NActChan=length(hTrigLine);
	for ChanInd=1:NActChan
		set(hTrigLine(ChanInd),'XData',[TrigPoint TrigPoint],'Visible','on');
	end
	set(hSpec1TrigLine,'XData',[TrigPoint TrigPoint],'Visible','on');
	if TrigPoint>MinPoint & TrigPoint<MaxPoint
		if Domain<3 | Domain==6 | Domain==7
			XTickLabelVec=[0 (MaxPoint-TrigPoint).*1000./SampRate];
		elseif Domain>2 & Domain<5
			XTickLabelVec=[0 (MaxPoint-TrigPoint).*1000./SampRate];
		elseif Domain==5
			XTickLabelVec=[0 MaxPoint-TrigPoint+1];
		end	
		set(hSpec1Axes,'xtick',[TrigPoint MaxPoint],'XTickLabel',XTickLabelVec);	
	else
		if Domain<3 | Domain==6 | Domain==7
			XTickLabelVec=[round((MinPoint-TrigPoint).*1000./SampRate) round((MaxPoint-TrigPoint).*1000./SampRate)];
		elseif Domain>2 & Domain<5
			XTickLabelVec=[round((MinPoint-TrigPoint).*1000./SampRate) round((MaxPoint-TrigPoint).*1000./SampRate)];
		elseif Domain==5
			XTickLabelVec=[MinPoint-round(TrigPoint)+1 MaxPoint-round(TrigPoint)+1];
		end	
		set(hSpec1Axes,'xtick',[MinPoint MaxPoint],'XTickLabel',XTickLabelVec);	
	end
	if ~strcmp(action,'setTrigPointNoCall')
		emegs2d('setMinPoint');
		emegs2d('setMaxPoint');
		emegs2d('setMinBase');
		emegs2d('setMaxBaseTrig');
		emegs2d('setCursorPoint');
	end
	if strcmp(TrigVisible,'off')
		hTopMenu=get(hList(65),'Userdata');
		hStyleMenu=get(hTopMenu(2),'children');
		hLineMenu=get(hStyleMenu(4),'children');
		LineVisibleLabel=get(hLineMenu(3),'Label');
		PointPos=get(hLineMenu(3),'Userdata');
		LineVisibleLabel((PointPos-2):PointPos)='on ';
		set((hLineMenu(3)),'Label',LineVisibleLabel);
	end
	%=============================================================================
	%============ setCursorPoint setCursorPointSlider
	%============ call: setCursorTextPos
	%=============================================================================	
elseif strcmp(action,'setCursorPoint') | strcmp(action,'setCursorPointSlider'),
	  
	hList=get(hPlot2dMenuFig,'Userdata'); 
	Domain=get(hList(20),'Value');
	CursPoint = get(hList(23),'Value');
	CursPointVec = get(hList(23),'Userdata');
	hMinMaxText=get(hList(21),'Userdata');		%	hMinMaxText=[hMinAmpText hMaxAmpText hMinPointText hMaxPointText hTrigPointText hCursorPointText hMinBaseText hMaxBaseText];
	CursorPointText=get(hMinMaxText(6),'String'); 
	MsHzCursPointString = get(hList(23),'String');
    hCursLine=get(hList(10),'Userdata');
  	CursorVisible=get(hCursLine(1),'Visible');
        
    if Domain == 7 | Domain == 8
        if any(strcmp(who('global'),'hGetFrequIntervalMenuFig'))
			global hGetFrequIntervalMenuFig
		end
		GetFrequIntervalMenuList=get(hGetFrequIntervalMenuFig,'Userdata'); 
		MinF0Point=get(GetFrequIntervalMenuList(4),'Value');
		MaxF0Point=get(GetFrequIntervalMenuList(7),'Value');
		MinF0Val=str2num(get(GetFrequIntervalMenuList(3),'String'));
		MaxF0Val=str2num(get(GetFrequIntervalMenuList(6),'String'));
    end

	TrigPoint=get(hList(22),'Value');
	SampRate = get(hList(60),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	MinPoint=get(hList(54),'Value');
	MaxPoint=get(hList(55),'Value');
	hSpec1CursLine=get(hList(79),'Userdata');
	hSpec1CursText=get(hList(80),'Userdata');
	MinAmp=get(hList(52),'Value');
	if strcmp(action,'setCursorPoint')
		ind = find(abs(MsHzCursPointString)<32);
		MsHzCursPointString(ind) = 32*ones(size(ind));
		MsHzCursPointString = MsHzCursPointString';	
		MsHzCursPointTmp = eval(['[' MsHzCursPointString(:)' ']'],'-1')';
		if Domain<3 | Domain==6 | Domain==7%Time, Std, Wavelet
			CursPointTmp=round(MsHzCursPointTmp.*SampRate./1000+TrigPoint);
		elseif Domain>2 & Domain<5	%FFT
			CursPointTmp=round(MsHzCursPointTmp.*NPoints.*2./SampRate);
		elseif Domain==5			%PCA
			CursPointTmp=round(MsHzCursPointTmp)+TrigPoint-1;
		end	
		set(hList(132),'Value',CursPointTmp);
	elseif strcmp(action,'setCursorPointSlider')
		CursPointTmp=round(get(hList(132),'Value'));
	end
	if length(CursPointTmp)~=1; CursPointTmp = CursPoint; end
	if CursPointTmp>NPoints 
	   	CursPointTmp = NPoints;
	elseif CursPointTmp<1 
		CursPointTmp = 1;
	end
   %set(hList(132),'Value',CursPointTmp); %CursorPointSlider
	if Domain<3 | Domain==6 | Domain==7 | Domain==8%Time, Std, Wavelet
		MsHzCursPointTmp=round((CursPointTmp-TrigPoint).*1000./SampRate);
	elseif Domain>2 & Domain<5	%FFT
		MsHzCursPointTmp=CursPointTmp.*SampRate./(2.*NPoints);
	elseif Domain==5			%PCA
		MsHzCursPointTmp=CursPointTmp-TrigPoint+1;
	end
	MsHzCursPointTmpString = sprintf('%g',round(MsHzCursPointTmp.*1000)./1000);
	CursPointVec(Domain)=CursPointTmp;
	set(hList(23),'Value',CursPointTmp,'Userdata',CursPointVec,'String',MsHzCursPointTmpString);
	Ind=findstr(CursorPointText,'#');
	if ~isempty(Ind)
		CursorPointText=[CursorPointText(1:Ind),' ',int2str(CursPointTmp)];
	else
		CursorPointText=[CursorPointText,'; # ',int2str(CursPointTmp)];
	end
	set(hMinMaxText(6),'String',CursorPointText);
	NActChan=length(hCursLine);
	for ChanInd=1:NActChan
        if Domain == 7 | Domain == 8
		    set(hCursLine(ChanInd),'XData',[CursPointTmp CursPointTmp],'YData',[MinF0Val MaxF0Val],'Visible','on');
        else
		    set(hCursLine(ChanInd),'XData',[CursPointTmp CursPointTmp],'Visible','on');
        end
	end
	set(hSpec1CursLine,'XData',[CursPointTmp CursPointTmp],'Visible','on');	
	set(hSpec1CursText,'Position',[CursPointTmp .8.*MinAmp],'String',MsHzCursPointTmpString,'Visible','on');	
	if Domain==5
      	ActFileNo=get(hList(1),'Userdata');
		FileNoVec=get(hList(56),'Userdata');
      	NListHdr=get(hList(51),'Userdata');
      	VarVecMat=get(hList(113),'Userdata');
        if size(VarVecMat,2)==1
            FileNoVecTmp=ActFileNo;
        else
            FileNoVecTmp=FileNoVec;
        end
		SigValVec=get(hList(114),'Userdata');
      	for	FileIndex=1:length(FileNoVecTmp)
   			hSigVec=get(hList(NListHdr+(FileNoVecTmp(FileIndex)-1).*50+30),'Userdata');
   			set(hSigVec,'Visible','off','String',[]);
         	ActTmpMat=get(hList(NListHdr+(FileNoVecTmp(FileIndex)-1).*50+1),'Userdata');
        	ColorVal=get(hList(NListHdr+(FileNoVecTmp(FileIndex)-1).*50+16),'Value');
			if 		ColorVal==1; 		ColorStr='k'; 	
			elseif 	ColorVal==2; 	ColorStr='w'; 	
         	elseif 	ColorVal==3;	ColorStr='y'; 	
        	elseif 	ColorVal==4; 	ColorStr='r'; 	
			elseif 	ColorVal==5; 	ColorStr='g'; 	
			elseif 	ColorVal==6; 	ColorStr='b'; 	
			elseif 	ColorVal==7; 	ColorStr='m'; 	
			elseif 	ColorVal==8; 	ColorStr='c'; 	
			else	ColorStr='b'; 	
			end
       		SigValVecTmp=SigValVec.*VarVecMat(CursPointTmp,FileIndex);
   			SigVec5=find(abs(ActTmpMat(:,CursPointTmp))>SigValVecTmp(1));
   			if ~isempty(SigVec5)
      			set(hSigVec(SigVec5),'Visible','on','Color',ColorStr,'String','*');
   			end
   			SigVec1=find(abs(ActTmpMat(:,CursPointTmp))>SigValVecTmp(2));
   			if ~isempty(SigVec1)
      			set(hSigVec(SigVec1),'Visible','on','Color',ColorStr,'String','**');
   			end
		end
	end
	if strcmp(CursorVisible,'off')
		hTopMenu=get(hList(65),'Userdata');
		hStyleMenu=get(hTopMenu(2),'children');
		hLineMenu=get(hStyleMenu(3),'children');
		LineVisibleLabel=get(hLineMenu(3),'Label');
		PointPos=get(hLineMenu(3),'Userdata');
		LineVisibleLabel((PointPos-2):PointPos)='on ';
		set((hLineMenu(3)),'Label',LineVisibleLabel);
	end
	emegs2d('setCursorTextPos')	
	%=============================================================================
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	hTextMenu=get(hStyleMenu(6),'children');
	pointer=get(hList(83),'Userdata');
	DisplayTextLabel=get(hTextMenu(5),'Label');
	PointPos=get(hTextMenu(5),'Userdata');
	if strcmp(DisplayTextLabel(PointPos),setstr(pointer))
		emegs2d('DispCursorAmpActFileNo')
	end

	%=============================================================================
	%============ SetFrequInterval
	%=============================================================================	
elseif strcmp(action,'SetFrequInterval'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
    FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	NListHdr=get(hList(51),'Userdata');
	Domain=get(hList(20),'Value');

	if any(strcmp(who('global'),'hGetFrequIntervalMenuFig'))
		global hGetFrequIntervalMenuFig
	end
	GetFrequIntervalMenuList=get(hGetFrequIntervalMenuFig,'Userdata'); 
	MinF0Point=get(GetFrequIntervalMenuList(4),'Value');
	MaxF0Point=get(GetFrequIntervalMenuList(7),'Value');
	if MinF0Point==MaxF0Point & Domain~=1
		set(hList(20),'Value',1);
		emegs2d('setDomain')
		Domain=1;
	end
    for FileInd=1:NUsedFiles
        ActFileNo=FileNoVec(FileInd);
        WaveVec=get(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata');
	    WaveMat=get(hList(NListHdr+(ActFileNo-1).*50+36),'Userdata');
	    WaveVec(12)=MinF0Point;
	    WaveVec(13)=MaxF0Point;
        MinPoint=get(hList(54),'Value');
		MaxPoint=get(hList(55),'Value');
	    if Domain==1 %Time
		    ActAvgMat=squeeze(mean(WaveMat(:,:,MinF0Point:MaxF0Point),3));
        elseif Domain==8 %Amp Wave II
            %ActAvgMat=WaveMat(:,MinPoint:MaxPoint,MinF0Point:MaxF0Point); %%
            ActAvgMat=WaveMat; 
        else
		    ActAvgMat=WaveMat;
	    end
	    set(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata',WaveVec);
	    set(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata',ActAvgMat);
    end
	emegs2d('PlotData')
    
    
	%=============================================================================
	%============ InfoFile
	%=============================================================================	
	
elseif strcmp(action,'InfoFile'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	ActAvgMat=get(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata');
	hAvgMatFig=figure('Units','normal','NumberTitle','off','Position',[0,0,.5,1],'Name','AvgMat');
	surf(ActAvgMat)

	
	%=============================================================================
	%============ PlotMedMedVec
	%=============================================================================	
elseif strcmp(action,'PlotMedMedVec'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	Plot2dVersion=get(hList(97),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	ActFilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
	[ActFile,ActPath]=SepFilePath(ActFilePath);
	MedMedRawVec=get(hList(NListHdr+(ActFileNo-1).*50+9),'Userdata')
	MedMedAvgVec=get(hList(NListHdr+(ActFileNo-1).*50+10),'Userdata')
	hMedMedFig=figure('Units','normal','NumberTitle','off','Position',[0,0,.5,1],'Name','MedMedVec');
			
	subplot(4,1,1)	
	plot(MedMedRawVec)
	title(['MedMedRawVec of file: ' setstr(ActFile)])
			
	subplot(4,1,2)	
	NoZeroInd=find(MedMedRawVec~=0);
	plot(NoZeroInd,MedMedRawVec(NoZeroInd))
	title(['MedMedRawVec of file: ' setstr(ActFile)])
			
	subplot(4,1,3)	
	plot(MedMedAvgVec)
	title(['MedMedAvgVec of file: ' setstr(ActFile)])	
			
	subplot(4,1,4)	
	NoZeroInd=find(MedMedAvgVec~=0);
	plot(NoZeroInd,MedMedAvgVec(NoZeroInd));			
	title(['MedMedAvgVec of file: ' setstr(ActFile)]);	
	xlabel('Trial');
	ylabel('Amplitude');

elseif strcmp(action,'PlotSpecChanXCorr') | strcmp(action,'PlotAllChanXCorr'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	
% 	FileMat=char('Rudi:Data:EEG:AlterPix:AP1:AP1Hz.fl40.E1');
% 	FileMat=char(FileMat,'Rudi:Data:EEG:AlterPix:AP2:AP2Hz.fl40.E1');
% 	FileMat=char(FileMat,'Rudi:Data:EEG:AlterPix:AP3:AP3Hz.fl40.E1');
% 	FileMat=char(FileMat,'Rudi:Data:EEG:AlterPix:AP4:AP4Hz.fl40.E1');
% 	FileMat=char(FileMat,'Rudi:Data:EEG:AlterPix:AP5:AP5Hz.fl40.E1');
% 	FileMat=char(FileMat,'Rudi:Data:EEG:AlterPix:AP6:AP6Hz.fl40.E1');
% 	FileMat=char(FileMat,'Rudi:Data:EEG:AlterPix:AP7:AP7Hz.fl40.E1');
% 	FileMat=char(FileMat,'Rudi:Data:EEG:AlterPix:AP8:AP8Hz.fl40.E1');
% 	FileMat=char(FileMat,'Rudi:Data:EEG:AlterPix:AP9:AP9Hz.fl40.E1');
%  	FileMat=char(FileMat,'Rudi:Data:EEG:AlterPix:AP10:AP10Hz.fl40.E1');
% 	FileMat=char(FileMat,'Rudi:Data:EEG:AlterPix:AP11:AP11Hz.fl40.E1');
%  	FileMat=char(FileMat,'Rudi:Data:EEG:AlterPix:AP12:AP12Hz.fl40.E1');

% 	FileMat=char('Paul:Data:EEG:AlterPix:01:AP1:AP1Hz.fl40.E1');
% 	FileMat=char(FileMat,'Paul:Data:EEG:AlterPix:01:AP2:AP2Hz.fl40.E1');
% 	FileMat=char(FileMat,'Paul:Data:EEG:AlterPix:01:AP3:AP3Hz.fl40.E1');
% 	FileMat=char(FileMat,'Paul:Data:EEG:AlterPix:01:AP4:AP4Hz.fl40.E1');
% 	FileMat=char(FileMat,'Paul:Data:EEG:AlterPix:01:AP5:AP5Hz.fl40.E1');
% 	FileMat=char(FileMat,'Paul:Data:EEG:AlterPix:01:AP6:AP6Hz.fl40.E1');
% 	FileMat=char(FileMat,'Paul:Data:EEG:AlterPix:01:AP7:AP7Hz.fl40.E1');
% 	FileMat=char(FileMat,'Paul:Data:EEG:AlterPix:01:AP8:AP8Hz.fl40.E1');
% 	FileMat=char(FileMat,'Paul:Data:EEG:AlterPix:02:AP09:AP09Hz.fl40.E1');
% 	FileMat=char(FileMat,'Paul:Data:EEG:AlterPix:02:AP10:AP10Hz.fl40.E1');
% 	FileMat=char(FileMat,'Paul:Data:EEG:AlterPix:02:AP11:AP11Hz.fl40.E1');
% 	FileMat=char(FileMat,'Paul:Data:EEG:AlterPix:02:AP12:AP12Hz.fl40.E1');
	
	FileMat=char('C:\Data\EEGData\AlterPics\Ap01\AP1Hz.fl40.E1');
	FileMat=char(FileMat,'C:\Data\EEGData\AlterPics\Ap02\AP2Hz.fl40.E1');
	FileMat=char(FileMat,'C:\Data\EEGData\AlterPics\Ap03\AP3Hz.fl40.E1');
	FileMat=char(FileMat,'C:\Data\EEGData\AlterPics\Ap04\AP4Hz.fl40.E1');
	FileMat=char(FileMat,'C:\Data\EEGData\AlterPics\Ap05\AP5Hz.fl40.E1');
	FileMat=char(FileMat,'C:\Data\EEGData\AlterPics\Ap06\AP6Hz.fl40.E1');
	FileMat=char(FileMat,'C:\Data\EEGData\AlterPics\Ap07\AP7Hz.fl40.E1');
	FileMat=char(FileMat,'C:\Data\EEGData\AlterPics\Ap08\AP8Hz.fl40.E1');
	FileMat=char(FileMat,'C:\Data\EEGData\AlterPics\Ap09\AP09Hz.fl40.E1');
	FileMat=char(FileMat,'C:\Data\EEGData\AlterPics\Ap10\AP10Hz.fl40.E1');
	FileMat=char(FileMat,'C:\Data\EEGData\AlterPics\Ap11\AP11Hz.fl40.E1');
	FileMat=char(FileMat,'C:\Data\EEGData\AlterPics\Ap12\AP12Hz.fl40.E1');
    
    if strcmp(action,'PlotAllChanXCorr')
	    global hPlot3dMenuFig
	    hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
    end
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	SampRate=get(hList(60),'Userdata');	
	
	FileIndex=1
	OrigAvgMat1=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+24),'Userdata'); %Orig
	[NChan,NPoints]=size(OrigAvgMat1);
	CalcAvgMat1=OrigAvgMat1;
	OrigChanVec1=CalcAvgMat1(85,:);
	FileIndex=2;
	OrigAvgMat2=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+24),'Userdata'); %Orig
	CalcAvgMat2=OrigAvgMat2;
	OrigChanVec2=CalcAvgMat2(85,:);

	OrigDiffVec=OrigChanVec1-OrigChanVec2;
	OrigGP1=mean(CalcAvgMat1.^2,1);
	OrigGP2=mean(CalcAvgMat2.^2,1);
	DiffOrigGP=mean((CalcAvgMat1-CalcAvgMat2).^2,1);
	
	MaxOrigDiffVec=max(OrigDiffVec);
	MinOrigDiffVec=min(OrigDiffVec);
	h1=figure('Units','normal','Position',[0 .4 .5 .55],'NumberTitle','off');
	h2=figure('Units','normal','Position',[.5 .4 .5 .55],'NumberTitle','off');
	if strcmp(action,'PlotAllChanXCorr')
		h3=figure('Units','normal','Position',[0 0 .3 .3],'NumberTitle','off');
	end
	axes('Units','normal','Position',[0 0 1 1])
	axis off
	h2Text1=text('Units','normal','Position',[.05 .95],'String','Original   Difference: 1 Hz;','Color','k','FontSize',10);
	h2Text2=text('Units','normal','Position',[.35 .95],'String','Measured   Difference: 1 Hz;','Color','b','FontSize',10);
	h2Text3=text('Units','normal','Position',[.65 .95],'String','Calculated Difference: 1 Hz;','Color','r','FontSize',10);
	ChanVec1=OrigChanVec1;
	ChanVec2=OrigChanVec2;

	MsPerPoint=1000./SampRate;
	x=[1:NPoints].*MsPerPoint;
	fVec=[1:13];
	iVec=[1 125 167 187 200 208 214 219 222 225 227 229 231]
	%iVec=[1:250]
	for Ind=1:length(iVec)
			Ind=Ind
			[File,Path,FilePath]=GetFileNameOfMat(FileMat,Ind);
			DiffFilePath=[FilePath,'.at1-0.ar.db']
			DiffMat=ReadAvgFile(DiffFilePath);
			Tmp=DiffMat(85,:);
			ExtDiffChan=zeros(NPoints,1);
			ExtDiffChan(NPoints./2+1:NPoints./2+length(Tmp))=Tmp;
			i=iVec(Ind)
			figure(h1);
			ms=floor((1000-i.*4).*100)./100;
			f=floor((1000./(1000-i.*4)).*100)./100;
			set(h1,'Name',['Data; ms=',num2str(ms),'; f=',num2str(f)]);
			set(h2,'Name',['Difference; ms=',num2str(ms),'; f=',num2str(f)]);
			set(h2Text2,'String',['Measured   Difference: ',int2str(fVec(Ind)), ' Hz;'])
			set(h2Text3,'String',['Calculated Difference: ',int2str(fVec(Ind)), ' Hz;'])
			if strcmp(action,'PlotAllChanXCorr'),
				set(h3,'Name',['Global Power; ms=',num2str(ms),'; f=',num2str(f)]);
			end
			ChanVec1=OrigChanVec1;
			ChanVec2=OrigChanVec2;
			CalcAvgMat1=OrigAvgMat1;
			CalcAvgMat2=OrigAvgMat2;
			for j=1:23 %15 bei x8
				ChanVec1(j.*250+1:j.*250+i)=ChanVec1(j.*250+1:j.*250+i)+ChanVec1(j.*250+1-i:j.*250);
				ChanVec1(i+j:j.*250)=ChanVec1(j:j.*250-i);
				ChanVec1(1:i+j)=zeros(i+j,1);
			 
				ChanVec2(j.*250+1:j.*250+i)=ChanVec2(j.*250+1:j.*250+i)+ChanVec2(j.*250+1-i:j.*250);
				ChanVec2(i+j:j.*250)=ChanVec2(j:j.*250-i);
				ChanVec2(1:i+j)=zeros(i+j,1);
				if strcmp(action,'PlotAllChanXCorr'),
					for ChanInd=1:NChan
						CalcAvgMat1(ChanInd,j.*250+1:j.*250+i)=CalcAvgMat1(ChanInd,j.*250+1:j.*250+i)+CalcAvgMat1(ChanInd,j.*250+1-i:j.*250);
						CalcAvgMat1(ChanInd,i+j:j.*250)=CalcAvgMat1(ChanInd,j:j.*250-i);
						CalcAvgMat1(ChanInd,1:i+j)=zeros(1,i+j);
						CalcAvgMat2(ChanInd,j.*250+1:j.*250+i)=CalcAvgMat2(ChanInd,j.*250+1:j.*250+i)+CalcAvgMat2(ChanInd,j.*250+1-i:j.*250);
						CalcAvgMat2(ChanInd,i+j:j.*250)=CalcAvgMat2(ChanInd,j:j.*250-i);
						CalcAvgMat2(ChanInd,1:i+j)=zeros(1,i+j);
					end
				end
			end
			if strcmp(action,'PlotAllChanXCorr'),
				CalcAvgMat1=CalcBaseline(CalcAvgMat1,1,NPoints);
				CalcAvgMat2=CalcBaseline(CalcAvgMat2,1,NPoints);
				DiffMat=CalcAvgMat1-CalcAvgMat2;
				FileIndex=1
				set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat1);
				FileIndex=2
				set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',CalcAvgMat2);
				FileIndex=3
				set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',DiffMat);
			end
			ChanVec1=CalcBaseline(ChanVec1,1,NPoints);
			ChanVec2=CalcBaseline(ChanVec2,1,NPoints);

			MaxChanVec1=max(ChanVec1);
			MinChanVec1=min(ChanVec1);
			
			subplot(3,1,1)
			plot(x,OrigChanVec1,'k');
			hold on
			plot(x,ChanVec1,'b');
			hold off
			axis([x(i.*j),x(NPoints)-i.*MsPerPoint,1.1.*MinChanVec1,1.1.*MaxChanVec1])
			title('High Arousing - Low Arousing - High Arousing ...')
			subplot(3,1,2)
			plot(x,OrigChanVec2,'k');
			hold on
			plot(x,ChanVec2,'g');
			hold off
			axis([x(i.*j),x(NPoints)-i.*MsPerPoint,1.1.*MinChanVec1,1.1.*MaxChanVec1])
			title('Low Arousing - High Arousing - Low Arousing ...')
            
			DiffVec=ChanVec1-ChanVec2;
			MaxDiffVec=max(DiffVec);
			MinDiffVec=min(DiffVec);
			subplot(3,1,3)
			plot(x,OrigDiffVec,'k');
			hold on
			plot(x,DiffVec,'r');
			hold off
			axis([x(i.*j),x(NPoints),1.1.*min([MinOrigDiffVec,MinDiffVec]),1.1.*max([MaxOrigDiffVec,MaxDiffVec])])
			 title('Difference: High Arousing - Low Arousing')
            
			figure(h2)
			axes('Units','normal','Position',[.1 .1 .8 .8])
			y=[0:4:996];
			DiffMin=1.1.*min([MinOrigDiffVec,MinDiffVec]);
			DiffMax=1.1.*max([MaxOrigDiffVec,MaxDiffVec]);
			plot(y,OrigDiffVec(NPoints./2+1:NPoints./2+250),'k');
			hold on
			plot(y,ExtDiffChan(NPoints./2+1:NPoints./2+250),'b');
			plot(y,DiffVec(NPoints./2+1+11.*i:NPoints./2+250+11.*i),'r');
			for k=1:9
				Trig=k.*10.*MsPerPoint;	
				plot([Trig,Trig],[-4,4],'k');
			end
			for k=1:5
				Trig=k.*1000-k.*i.*MsPerPoint;
				plot([Trig,Trig],[-4,4],'--k');
			end
			hold off
			axis([0,min(360,Trig),-4,4])
           
			ylabel('Difference Amplitude [µV]')
			xlabel('Time [ms]')
			if strcmp(action,'PlotAllChanXCorr'),			
				figure(h3)
				GP1=mean(CalcAvgMat1.^2,1);
				GP2=mean(CalcAvgMat2.^2,1);
				DiffGP=mean(DiffMat.^2,1);
% 				plot(y,OrigGP1(2001:2250),'--b');
% 				hold on
% 				plot(y,OrigGP2(2001:2250),'--g');
% 				plot(y,DiffOrigGP(2001:2250),'--r');
				plot(y,GP1(NPoints./2+1+7.*i:NPoints./2+250+7.*i),'b');
				hold on;
				plot(y,GP2(NPoints./2+1+7.*i:NPoints./2+250+7.*i),'g');
				plot(y,DiffGP(NPoints./2+1+7.*i:NPoints./2+250+7.*i),'r');
				for k=1:5
					Trig=[k.*1000-k.*i.*MsPerPoint];
					if Trig<1000
						plot([Trig,Trig],[0,16],'--k');
					end
				end
				hold off
				axis([0,min(996,Trig),0,16])
				set(hList(122),'Value',NPoints./2+1+7.*i); 
				emegs2d('setMinPointSlider');
				set(hList(123),'Value',NPoints./2+1+7.*i);
				emegs2d('setMaxPointSlider');
				
				emegs2d('PlotData')
				set(hPlot3dList(47),'Value',NPoints./2+1+7.*i);	%MinPoint
				emegs3d('setMinPointString');
				set(hPlot3dList(49),'Value',NPoints./2+1+7.*i); %MaxPoint 
				emegs3d('setMaxPointString');
				set(hPlot3dList(87),'Value',3);
				emegs3d('setActFileNo');
				emegs3d('CalcCortMap');
			end
			pause
		end
	%=============================================================================
	%============ ToggleMouseZoom: 
	%=============================================================================	

elseif strcmp(action,'ToggleMouseZoom'),
    hList=get(hPlot2dMenuFig,'Userdata');
    ZoomModeStatus = get(hList(116),'Userdata');
    if isempty(ZoomModeStatus), ZoomModeStatus = 0;end
	NListHdr=get(hList(51),'Userdata');
	Domain=get(hList(20),'Value');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	ActFileNo=get(hList(1),'Userdata');
	Spec1Axes=get(hList(76),'Userdata');
	set(Spec1Axes,'Visible','on');
	Spec1ZeroLine=get(hList(77),'Userdata');
	set(Spec1ZeroLine,'Visible','on');
	hAxesVec=get(hList(6),'Userdata');
    for r=1:length(hAxesVec)
        if ZoomModeStatus == 0
            axes(hAxesVec(r));
            axis('on');
            set(hAxesVec(r),'XTickLabelMode','manual','YTickLabelMode','manual','ZTickLabelMode','manual','XColor',[1 1 1],...
                'YColor',[1 1 1],'Color','none','XTickLabel',[],'YTickLabel',[],'ZTickLabel','');
        else
            axes(hAxesVec(r));
            axis('off');
        end
    end
    if ZoomModeStatus == 0
        ZoomModeStatus = 1;
    else
        ZoomModeStatus = 0;
    end
    set(hList(116),'Userdata',ZoomModeStatus);
    
    
	%=============================================================================
	%============ ZoomSpecChan: figure and menue for selected channel
	%       
	%============	(selection by mouse only matlab 4)
	%============ call: setSpecChanCursorText
	%=============================================================================	

elseif strcmp(action,'ZoomSpecChan'),

    GPDissimStatus = 0;
    if ~isempty(varargin)
        SelChan = varargin;
        if strcmp(varargin{1},'GPDissim')
            GPDissimData = varargin{2};
            GPDissimStatus = 1;
            SelChan = 1;
        end
    else
        SelChan = [];
    end
	hList=get(hPlot2dMenuFig,'Userdata');
	hZoomSpecChan=hList(46);	
	ZoomSpecChanVal=get(hZoomSpecChan,'Value');
	ActFileNo=get(hList(1),'Userdata');
	Tmp=get(hList(16),'Userdata');
	DataNChan=Tmp(1);
	SensorNChan=Tmp(2);
	SensorNames=get(hList(4),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);

	AxesPosMat=get(hList(5),'Userdata');
	hhSpecChanVec=get(hList(64),'Userdata');

	MinAmp=get(hList(52),'Value');
	MinAmpString=get(hList(52),'String');
	MaxAmp=get(hList(53),'Value');
	MaxAmpString=get(hList(53),'String');
	MinPoint=get(hList(54),'Value');
	MSMinPointString=get(hList(54),'String');
	MaxPoint=get(hList(55),'Value');
	MSMaxPointString=get(hList(55),'String');
	NChan=get(hList(NListHdr+(1-1)*50+2),'Userdata');
	NPoints=get(hList(NListHdr+(1-1)*50+3),'Userdata');
	Domain=get(hList(20),'Value');
	TrigPoint=get(hList(22),'Value');
	CursorPoint=get(hList(23),'Value');
	CursorPointString=get(hList(23),'String');
	if CursorPoint<MinPoint
		CursorPoint=MinPoint;
		CursorPointString=MSMinPointString;
	elseif CursorPoint>MaxPoint
		CursorPoint=MaxPoint;
		CursorPointString=MSMaxPointString;
	end
	BGColor=get(hList(93),'Color');
	SampRate=get(hList(60),'Userdata');	

	kActAxes=get(hList(27),'Userdata');
	ActAxes=get(hList(28),'Userdata');
	TrigLength=1;		%TrigLength=get(hList(29),'Userdata');
	CursorLength=1;		%CursorLength=get(hList(30),'Userdata'); 
	
	hTopMenu=get(hList(65),'Userdata');
	hExportMenu=get(hTopMenu(3),'children');	
	hExportUserData=get(hExportMenu(1),'children'); 
	hUserDataInfo=get(hExportUserData(1),'children');
	
	MainMatlabVersion=get(hList(100),'Userdata');
	EegMegStatusString=get(hList(110),'String');
	if strcmp(EegMegStatusString,'EEG'); EegMegString='µV'; else; EegMegString='fT'; end

	%========== graphical zoom (by mouse) =======================

    if isempty(SelChan)
		if ZoomSpecChanVal==1	
            return;
		else
			SpecChan=ZoomSpecChanVal-1;
		end
    else
        if iscell(SelChan)
            if ischar(SelChan{1})
                SpecChan = str2num(SelChan{1});
            else
                SpecChan = SelChan{1};
            end
        elseif ischar(SelChan)
            SpecChan = str2num(SelChan);
        else
            SpecChan = SelChan;
        end
    end
    emegs2d('PlotData');
	
	%======== figure =========================================
  	if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
		if Domain==6 | Domain==7	
	   		ChanFigPosVec=[.01,.01,.4,.6];	
			MenuFigPosVec=[.4225,.01,.175,.5];
		else
			ChanFigPosVec=[.66,.5,.33,.45];	
		end
		if Domain<3
      		MenuFigPosVec=[.66 .01 .175 .42];
		elseif Domain~=6 & Domain~=7 & Domain~=8
		    MenuFigPosVec=[.65,.155,.25,.25];
		end
    elseif strcmp(computer,'PCWIN') 
		if Domain==6 | Domain==7 | Domain==8
	   		ChanFigPosVec=[.66,.45,.33,.5];	
			MenuFigPosVec=[.66,.08,.175,.45];
		else
			ChanFigPosVec=[.66,.45,.33,.5];	
		end
		if Domain<3
      		MenuFigPosVec=[.66 .01 .2 .42];
		elseif Domain~=6 & Domain~=7 & Domain~=8
		    MenuFigPosVec=[.66,.155,.25,.25];
		end
   	elseif strcmp(computer,'SOL2') | strcmp(computer,'LNX86') | strcmp(computer,'GLNX86')
		if Domain==6 | Domain==7	
      		ChanFigPosVec=[.01,.01,.4,.6];	
			MenuFigPosVec=[.42225,.01,.175,.25];
		else
			ChanFigPosVec=[.66,.42,.33,.5];
		end
		if Domain<3
      		MenuFigPosVec=[.65,.055,.175,.275];
		elseif Domain~=6 & Domain~=7 & Domain~=8
      		MenuFigPosVec=[.65,.055,.25,.275];
		end
   	end;
    
    hhSpecChanVec(34)=uicontrol('Visible','off');
  
    if ~isempty(findobj('tag','ZoomChanPlot')) & ~isempty(findobj('tag','ZoomChanMenu'))
        
         emegs2d('SpecChanChan',SpecChan);
         figure(findobj('tag','ZoomChanPlot'));
         figure(findobj('tag','ZoomChanMenu'));
         return
        
    else
        
        if GPDissimStatus
            CloseRequestFcnStr='emegs2d(''CloseZoomChanPlot'')';
         	hZoomFig=figure('Units','normal','NumberTitle','off','Position',ChanFigPosVec,'Name',['Global Dissimilarity'],'tag','ZoomChanPlot','CloseRequestFcn',CloseRequestFcnStr);	
			hhSpecChanVec(35)=hZoomFig;	
			hZoomMenu=figure('Units','normal','NumberTitle','off','Position',MenuFigPosVec,'Name',['Menu Global Dissimilarity'],'tag','ZoomChanMenu');
			hhSpecChanVec(36)=hZoomMenu;	
        else
            CloseRequestFcnStr='emegs2d(''CloseZoomChanPlot'')';
         	hZoomFig=figure('Units','normal','NumberTitle','off','Position',ChanFigPosVec,'Name',['Zoom Sensor ',int2str(SpecChan),': ',SensorNames(SpecChan,:)],'tag','ZoomChanPlot','CloseRequestFcn',CloseRequestFcnStr);	
			hhSpecChanVec(35)=hZoomFig;	
			hZoomMenu=figure('Units','normal','NumberTitle','off','Position',MenuFigPosVec,'Name',['Menu Sensor ',int2str(SpecChan),': ',SensorNames(SpecChan,:)],'tag','ZoomChanMenu');
			hhSpecChanVec(36)=hZoomMenu;
        end
		%============================== console frame with buttons 
		%========Information for all SpecChan buttons
		labelColor=[0.8 0.8 0.8];
		yInitPos=0.90;
		menutop=0.95;
		btnTop = 0.6;
		top=0.75;
		left=0.125;		
       	btnWid=0.8;		
		btnHt=0.105;
		textHeight = 0.05;
		textWidth = 0.06;
		spacing=0.01;	% Spacing between the button and the next command's label
		% ========= CONSOLE frame =================================
		frmBorder=0.019; frmBottom=0.04; 
		frmHeight = 0.92; frmWidth = btnWid;
		yPos=frmBottom-frmBorder;
		frmPos=[left-frmBorder yPos frmWidth+2*frmBorder frmHeight+2*frmBorder];
		h=uicontrol( ...
            'Style','frame', ...
            'Units','normalized', ...
            'Position',frmPos, ...
		    'BackgroundColor',[0 0 0.3]);
		%===== Time <-> Frequency =========
		if Domain==1 | Domain==2 | Domain==5 |  Domain==6  |  Domain==7
			if Domain==6 | Domain ==8
				MenuTextString1=['Min. amp [',EegMegString,'/Hz]'];
				MenuTextString2=['Max. amp [',EegMegString,'/Hz]'];
			elseif  Domain==7	
				MenuTextString1=['Min. Phaselock'];
				MenuTextString2=['Max. Phaselock'];
            elseif GPDissimStatus==1
				MenuTextString1=['Min. Dissimilarity'];
				MenuTextString2=['Max. Dissimilarity'];
			else
				MenuTextString1=['Min. amp [',EegMegString,']'];
				MenuTextString2=['Max. amp [',EegMegString,']'];
			end
			MenuTextString3=['Min. time [ms]; #',int2str(MinPoint)];
			MenuTextString4=['Max. time [ms]; #',int2str(MaxPoint)];
			MenuTextString5=['Cursor [ms]; #',int2str(CursorPoint)];
		elseif  Domain==3 | Domain==4
			MenuTextString1=['Min. amp [',EegMegString,'/sqrt(Hz)]'];
			MenuTextString2=['Max. amp [',EegMegString,'/sqrt(Hz)]'];
            MenuTextString3=['Min. frquz. [Hz]; #',int2str(MinPoint)];
			MenuTextString4=['Max. frquz. [Hz]; #',int2str(MaxPoint)];
			MenuTextString5=['Cursor [Hz]; #',int2str(CursorPoint)];
		end
	
		%============MinAmpHandle ================================= 
		btnNumber=1;     
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
        
		hSpecChanMinAmpText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String',MenuTextString1);
		hhSpecChanVec(11)=hSpecChanMinAmpText;
		
		btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
		callbackStr = 'emegs2d(''setSpecChanMinAmp'')';
        
		hSpecChanMinAmp = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String',MinAmpString,...
		'Value',MinAmp, ...
		'callback',callbackStr);
		hhSpecChanVec(1)=hSpecChanMinAmp;
		
      	%============MaxAmpHandle ============================== 
		btnPos=[left yPos-btnHt 2.*btnWid./3 btnHt./2];
        
		hSpecChanMaxAmpText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String',MenuTextString2);
		hhSpecChanVec(12)=hSpecChanMaxAmpText;
		
        btnPos=[left+2.*btnWid./3 yPos-btnHt btnWid./3 1.*btnHt./2];
		callbackStr = 'emegs2d(''setSpecChanMaxAmp'')';
        
		hSpecChanMaxAmp = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String',MaxAmpString,...
		'Value',MaxAmp, ...
		'callback',callbackStr);
		hhSpecChanVec(2)=hSpecChanMaxAmp;
		
		%===================================
		btnNumber=2;     	
		% Adjust SpecChan Amplitude
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left yPos-btnHt./2 2*btnWid./8 btnHt./2];
		callbackStr = 'emegs2d(''AdjustSpecChanAmp'')';
		hAdjustSpecChanAmp=uicontrol( ...
		'Style','pushbutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','Adjust', ...
		'HorizontalAlignment','center',...
		'Callback',callbackStr,...
		'Enable','on');
		
		% Center SpecChan Amplitude
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left yPos-btnHt 2*btnWid./8 btnHt./2];
		callbackStr = 'emegs2d(''CenterSpecChanAmp'')';
		hCenterSpecChanAmp=uicontrol( ...
		'Style','pushbutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','Center', ...
		'HorizontalAlignment','center',...
		'Callback',callbackStr,...
		'Enable','on');
		
		% Decrease/Increase  SpecChan Status
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left+2.*btnWid./8 yPos-btnHt./2 2.*btnWid./8 btnHt./2];
		callbackStr = 'emegs2d(''DecIncSpecChanSta'')';
		hDecIncSpecChanStaAmp = uicontrol( ...
		'Style','pushbutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Userdata',[0 1],...
		'String','+/- 1',...
		'Callback',callbackStr,...
		'Enable','on');
		hhSpecChanVec(18)=hDecIncSpecChanStaAmp;
		
		% Invert View
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left+2.*btnWid./8 yPos-btnHt 2*btnWid./8 btnHt./2];
		callbackStr = 'emegs2d(''InvertSpecChanView'')';
		hInvertSpecChanView=uicontrol( ...
		'Style','pushbutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','View', ...
		'Userdata',1,...
		'HorizontalAlignment','center',...
		'Callback',callbackStr,...
		'Enable','on');
		hhSpecChanVec(19)=hInvertSpecChanView;
		%==================================================
		
		%Decrease  of SpecChan Amplitude
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left+4.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
		callbackStr = 'emegs2d(''DecSpecChanAmp'')';
		hDecSpecChanAmp=uicontrol( ...
		'Style','pushbutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','<', ...
		'HorizontalAlignment','center',...
		'Callback',callbackStr,...
		'Enable','on');
		
		% Decrease Decrease/Increase  Amplitude of SpecChan 
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left+5.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
		callbackStr = 'emegs2d(''DecDecIncSpecChanAmp'')';
		hDecDecIncAmp=uicontrol( ...
		'Style','pushbutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','<<', ...
		'HorizontalAlignment','center',...
		'Callback',callbackStr,...
		'Enable','on');
		
		% Increase Decrease/Increase Amplitude
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left+6.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
		callbackStr = 'emegs2d(''IncDecIncSpecChanAmp'')';
		hIncDecIncSpecChanAmp=uicontrol( ...
		'Style','pushbutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','>>', ...
		'HorizontalAlignment','center',...
		'Callback',callbackStr,...
		'Enable','on');
		
		% Slow Increase of SpecChan Amplitude
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left+7.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
		callbackStr = 'emegs2d(''IncSpecChanAmp'')';
		hIncSpecChanAmp=uicontrol( ...
		'Style','pushbutton', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','>', ...
		'HorizontalAlignment','center',...
		'Callback',callbackStr,...
		'Enable','on');
	
     	%============MinPointHandle ================================= 
		btnNumber=3;    
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
        
		hSpecChanMinPointText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String',MenuTextString3);
		hhSpecChanVec(13)=hSpecChanMinPointText;
        
		btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
		callbackStr = 'emegs2d(''setSpecChanMinPoint'')';
        
		hSpecChanMinPoint = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String',MSMinPointString,...
		'Value',MinPoint, ...
		'callback',callbackStr);
		hhSpecChanVec(3)=hSpecChanMinPoint;
	
		NPointsTmp=MaxPoint-MinPoint+1;
		if NPointsTmp>=10
			SliderStep=[1./NPointsTmp 10./NPointsTmp];
		else
			SliderStep=[.1 1];
		end
     	btnPos=[left yPos-btnHt btnWid btnHt./2];
		callbackStr = 'emegs2d(''setSpecChanMinPointSlider'')';
		hSpecChanMinPointSlider=uicontrol( ...
		'Style','slider', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','Cursor', ...
		'HorizontalAlignment','center',...
		'Userdata',[], ...
		'Min',1, ...
		'Max',NPoints, ...
		'SliderStep',SliderStep, ...
		'Value',MinPoint, ...
		'Callback',callbackStr,...
		'Enable','on');
		hhSpecChanVec(22)=hSpecChanMinPointSlider;
		
       	%============MaxPointHandle ============================== 
		btnNumber=4;     
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
        
		hSpecChanMaxPointText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String',MenuTextString4);
		hhSpecChanVec(14)=hSpecChanMaxPointText;
	
		btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
		callbackStr = 'emegs2d(''setSpecChanMaxPoint'')';
		
		hSpecChanMaxPoint = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String',MSMaxPointString,...
		'Value',MaxPoint, ...
		'callback',callbackStr);
		hhSpecChanVec(4)=hSpecChanMaxPoint;
		
		btnPos=[left yPos-btnHt btnWid btnHt./2];
		callbackStr = 'emegs2d(''setSpecChanMaxPointSlider'')';
		hSpecChanMaxPointSlider=uicontrol( ...
		'Style','slider', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','Cursor', ...
		'HorizontalAlignment','center',...
		'Userdata',[], ...
		'Min',1, ...
		'Max',NPoints, ...
		'SliderStep',SliderStep, ...
		'Value',MaxPoint, ...
		'Callback',callbackStr,...
		'Enable','on');
		hhSpecChanVec(23)=hSpecChanMaxPointSlider;
		
		if Domain ==6 | Domain==7 | Domain == 8
			
			WaveVec=get(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata');
			NFrequ=WaveVec(4);
			StartF0=WaveVec(7);
			EndF0=WaveVec(8);
			DeltaF0=WaveVec(9);
			F0Vec=[StartF0:DeltaF0:EndF0];
			StartF0IndPlot=WaveVec(12);
			EndF0IndPlot=WaveVec(13);
		
			if NFrequ>=10
				SliderStep=[1./NFrequ 10./NFrequ];
			else
				SliderStep=[.1 1];
			end
			%============MinFrequHandle ================================= 
			btnNumber=5;    
			yPos=menutop-(btnNumber-1)*(btnHt+spacing);
			btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
			
			hSpecChanMinFrequText = uicontrol( ...
			'Style','text', ...
			'Units','normalized', ...
			'Position',btnPos, ...
			'Horiz','left', ...
			'Foreground','black', ...
			'String','Min. frequency [Hz]');
			
			btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
			callbackStr = 'emegs2d(''setSpecChanMinFrequPoint'')';
			
			hSpecChanMinFrequPoint = uicontrol( ...
			'Style','edit', ...
			'Units','normalized', ...
			'Position',btnPos, ...
			'Horiz','center', ...
			'Background','white', ...
			'Foreground','black', ...
			'String',num2str(round(F0Vec(StartF0IndPlot).*100)./100),...
			'Value',StartF0IndPlot, ...
			'callback',callbackStr);
			
			hhSpecChanVec(24)=hSpecChanMinFrequPoint;
			
			btnPos=[left yPos-btnHt btnWid btnHt./2];
			callbackStr = 'emegs2d(''setSpecChanMinFrequPointSlider'')';
			hSpecChanMinFrequPointSlider=uicontrol( ...
			'Style','slider', ...
			'Units','normalized', ...
			'Position',btnPos, ...
			'String','Cursor', ...
			'HorizontalAlignment','center',...
			'Userdata',[], ...
			'Min',1, ...
			'Max',NFrequ, ...
			'SliderStep',SliderStep, ...
			'Value',StartF0IndPlot, ...
			'Callback',callbackStr);
			hhSpecChanVec(25)=hSpecChanMinFrequPointSlider;
			
			%============MaxFrequHandle ================================= 
			btnNumber=6;    
			yPos=menutop-(btnNumber-1)*(btnHt+spacing);
			btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
			
			hSpecChanMaxFrequText = uicontrol( ...
			'Style','text', ...
			'Units','normalized', ...
			'Position',btnPos, ...
			'Horiz','left', ...
			'Foreground','black', ...
			'String','Max. frequency [Hz]');
			
			btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
			callbackStr = 'emegs2d(''setSpecChanMaxFrequPoint'')';
			
			hSpecChanMaxFrequPoint = uicontrol( ...
			'Style','edit', ...
			'Units','normalized', ...
			'Position',btnPos, ...
			'Horiz','center', ...
			'Background','white', ...
			'Foreground','black', ...
			'String',num2str(round(F0Vec(EndF0IndPlot).*100)./100),...
			'Value',EndF0IndPlot, ...
			'callback',callbackStr);
			
			hhSpecChanVec(26)=hSpecChanMaxFrequPoint;
			
			btnPos=[left yPos-btnHt btnWid btnHt./2];
			callbackStr = 'emegs2d(''setSpecChanMaxFrequPointSlider'')';
			
			hSpecChanMaxFrequPointSlider=uicontrol( ...
			'Style','slider', ...
			'Units','normalized', ...
			'Position',btnPos, ...
			'String','Cursor', ...
			'HorizontalAlignment','center',...
			'Userdata',[], ...
			'Min',1, ...
			'Max',NFrequ, ...
			'SliderStep',SliderStep, ...
			'Value',EndF0IndPlot, ...
			'Callback',callbackStr);
			hhSpecChanVec(27)=hSpecChanMaxFrequPointSlider;
			
		end
		%============CursorPointHandle============================== 
		if Domain ==6 | Domain==7 | Domain==8
			btnNumber=7;
		else
			btnNumber=5;
		end
		yPos=menutop-(btnNumber-1)*(btnHt+spacing);
		btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
        
		hSpecChanCursorPointText = uicontrol( ...
		'Style','text', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','left', ...
		'Foreground','black', ...
		'String',MenuTextString5);
        hhSpecChanVec(15)=hSpecChanCursorPointText;
	
		btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 btnHt./2];
		callbackStr = 'emegs2d(''setSpecChanCursorPoint'')';
        
		hSpecChanCursorPoint = uicontrol( ...
		'Style','edit', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'Horiz','center', ...
		'Background','white', ...
		'Foreground','black', ...
		'String',CursorPointString,...
		'Value',CursorPoint, ...
		'callback',callbackStr);
		hhSpecChanVec(5)=hSpecChanCursorPoint;	
		
		NPointsTmp=MaxPoint-MinPoint+1;
		if NPointsTmp>=10
			SliderStep=[1./NPointsTmp 10./NPointsTmp];
		else
			SliderStep=[.1 1];
		end
     	btnPos=[left yPos-btnHt btnWid btnHt./2];
		callbackStr = 'emegs2d(''setSpecChanCursorPointSlider'')';
		hSpecChanCursorPointSlider=uicontrol( ...
		'Style','slider', ...
		'Units','normalized', ...
		'Position',btnPos, ...
		'String','Cursor', ...
		'HorizontalAlignment','center',...
		'Userdata',[], ...
		'Min',MinPoint, ...
        'Max',MaxPoint, ...
        'SliderStep',SliderStep, ...
        'Value',CursorPoint, ...
        'Callback',callbackStr,...
        'Enable','on');
        hhSpecChanVec(20)=hSpecChanCursorPointSlider;
    
        %============ChannelHandle============================== 
        labelStr=['1:',SensorNames(1,:)];
        for ChanInd=2:SensorNChan; 
            labelStr=[labelStr ' | ',int2str(ChanInd),': ' SensorNames(ChanInd,:)];
        end
        if Domain ==6 | Domain==7 | Domain==8
            btnNumber=8;
        else
            btnNumber=6;
        end     
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left yPos-btnHt./2 btnWid./2 btnHt./2];
        callbackStr = 'emegs2d(''SpecChanChan'')';
    
        hSpecChanChan = uicontrol( ...
            'Style','popupmenu', ...
            'Units','normalized', ...
            'Position',btnPos, ...
            'Horiz','center', ...
            'Background','white', ...
            'Foreground','black', ...
            'String',labelStr,...
            'Value',SpecChan, ...
            'callback',callbackStr);
        hhSpecChanVec(33)=hSpecChanChan;	
    
        %Decrease  of SpecChan Channel
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left+btnWid./2 yPos-btnHt./2 btnWid./4 btnHt./2];
        callbackStr = 'emegs2d(''DecSpecChanChan'')';
        hDecSpecChanChan=uicontrol( ...
            'Style','pushbutton', ...
            'Units','normalized', ...
            'Position',btnPos, ...
            'String','<', ...
            'HorizontalAlignment','center',...
            'Callback',callbackStr,...
            'Enable','on');
    
        %Increase  of SpecChan Channel
        btnPos=[left+3.*btnWid./4 yPos-btnHt./2 btnWid./4 btnHt./2];
        callbackStr = 'emegs2d(''IncSpecChanChan'')';
        hIncSpecChanChan=uicontrol( ...
            'Style','pushbutton', ...
            'Units','normalized', ...
            'Position',btnPos, ...
            'String','>', ...
            'HorizontalAlignment','center',...
            'Callback',callbackStr,...
            'Enable','on');
    
        %===================================	 	
        %Auto Adjust SpecChan Amplitude
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left yPos-btnHt btnWid btnHt./2];
        callbackStr = 'emegs2d(''AdjustSpecChanAmp'')';
        hAutoAdjustSpecChanAmp=uicontrol( ...
            'Style','radiobutton', ...
            'Units','normalized', ...
            'Position',btnPos, ...
            'String','Auto Adjust', ...
            'HorizontalAlignment','center',...
            'Value',0,...
            'Callback',callbackStr,...
            'Enable','on');
        hhSpecChanVec(21)=hAutoAdjustSpecChanAmp;
    
    
        %====================================
        %====================================
        % The setSpecChan2Emegs2dCursor / setSpecChan2Emegs3dCursor
        if Domain ==6 | Domain==7 | Domain==8
        btnNumber=8;
        else
            btnNumber=7;
        end      
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left yPos-btnHt/2 btnWid/2 btnHt./2];
        labelStr='Emegs2d Cursor';
        callbackStr='emegs2d(''setSpecChan2Emegs2dCursor'')';
    
        hsetSpecChan2Emegs2dCursor=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Callback',callbackStr);
    
        yPos=menutop-(btnNumber-1)*(btnHt+spacing);
        btnPos=[left+btnWid/2 yPos-btnHt/2 btnWid/2 btnHt./2];
        labelStr='Emegs3d Point';
        callbackStr='emegs2d(''setSpecChan2Emegs3dCursor'')';
    
        hsetSpecChan2Emegs3dCursor=uicontrol( ...
            'Style','pushbutton', ...
            'Units','normalized', ...
            'Position',btnPos, ...
            'String',labelStr, ...
            'Interruptible','on', ...
            'Callback',callbackStr);
    
        %======== axes   =========================================
        figure(hZoomFig);
        hSpecAxes=axes('Units','normal','Position',[.1 .15 .85 .7],'Box','on','XLim',[MinPoint MaxPoint],'YLim',[MinAmp MaxAmp],'Color',BGColor);
		hhSpecChanVec(17)=hSpecAxes;	
		SegmentMS=get(hList(101),'Userdata');
		if Domain<3 | Domain==6 | Domain==7 | Domain == 8
			Segment=(SegmentMS.*SampRate./1000);	
			if TrigPoint>MinPoint & TrigPoint<MaxPoint
				XTickVec1=TrigPoint:Segment:MaxPoint;
				XTickVec2=sort(TrigPoint:(-1)*Segment:MinPoint);
				XTickVec=[XTickVec2 XTickVec1(2:length(XTickVec1))];
				XTickLabelVec1=0:SegmentMS:(round((MaxPoint-TrigPoint).*1000./SampRate));
				XTickLabelVec2=sort(0:(-1)*SegmentMS:(round((MinPoint-TrigPoint).*1000./SampRate)));
				XTickLabelVec=[XTickLabelVec2 XTickLabelVec1(2:length(XTickLabelVec1))];
			else
				if TrigPoint<=MinPoint
					XTickVec1=TrigPoint:Segment:MaxPoint;
					ind=find(XTickVec1>=MinPoint);
					XTickVec=XTickVec1(ind(1):length(XTickVec1));
					XTickLabelVec1=0:SegmentMS:(round((MaxPoint-TrigPoint).*1000./SampRate));
					XTickLabelVec=XTickLabelVec1(ind(1):length(XTickLabelVec1));
				elseif TrigPoint>=MaxPoint;	
					XTickVec1=sort(TrigPoint:(-1)*Segment:MinPoint);
					ind=find(XTickVec1>MaxPoint);
					XTickVec=XTickVec1(1:(ind(1)-1));
					XTickLabelVec1=sort(0:(-1)*SegmentMS:round((MinPoint-TrigPoint).*1000./SampRate));
					XTickLabelVec=XTickLabelVec1(1:(ind(1)-1));
				end;
			end;
		else 	% frequency
			Segment=(SegmentMS.*(2.*NPoints)./SampRate);
			XTickVec=MinPoint:Segment:MaxPoint;
			XTickLabelVec=[round(MinPoint.*SampRate./(2.*NPoints)):SegmentMS:round(MaxPoint.*SampRate./(2.*NPoints))];	
		 end;
		
		set(hSpecAxes,'xtick',XTickVec,'XTickLabel',XTickLabelVec);	
		hhSpecChanVec(6)=hSpecAxes;
		%======== ZeroLine, CursorLine, TriggerLine ===============	
		if Domain~=6 & Domain~=7 
			hZeroLine=get(hList(8),'Userdata');
			ZeroLineColor=get(hZeroLine(SpecChan),'Color');
			ZeroLineStyle=get(hZeroLine(SpecChan),'LineStyle');
			hSpecZeroLine=line('XData',[MinPoint MaxPoint],'YData',[0 0],'Color',ZeroLineColor,'LineStyle',ZeroLineStyle);
			hhSpecChanVec(8)=hSpecZeroLine;
	
			hTriggerLine=get(hList(9),'Userdata');
			TriggerLineColor=get(hTriggerLine(SpecChan),'Color');
			TriggerLineStyle=get(hTriggerLine(SpecChan),'LineStyle');
			hSpecTrigLine=line('XData',[TrigPoint TrigPoint],'YData',[MinAmp.*TrigLength MaxAmp.*TrigLength],'Color',TriggerLineColor,'LineStyle',TriggerLineStyle);
		
			hCursorLine=get(hList(10),'Userdata');
			CursorLineColor=get(hCursorLine(SpecChan),'Color');
			CursorLineStyle=get(hCursorLine(SpecChan),'LineStyle');
			hSpecCursorLine=line('XData',[CursorPoint CursorPoint],'YData',[MinAmp.*CursorLength MaxAmp.*CursorLength],'Color',CursorLineColor,'LineStyle',CursorLineStyle);
			hhSpecChanVec(7)=hSpecCursorLine;
		
			hSpecChanCursorText=text('FontSize',[10],'Color',[0 0 0],'HorizontalAlignment','left','Visible','off');
			hhSpecChanVec(9)=hSpecChanCursorText;
		end
		hSpecChanAmpText1=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
		hList(NListHdr+29+(50*0))=hSpecChanAmpText1;
		hSpecChanAmpText2=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
		hList(NListHdr+29+(50*1))=hSpecChanAmpText2;
		hSpecChanAmpText3=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
		hList(NListHdr+29+(50*2))=hSpecChanAmpText3;
		hSpecChanAmpText4=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
		hList(NListHdr+29+(50*3))=hSpecChanAmpText4;
        hSpecChanAmpText5=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
		hList(NListHdr+29+(50*4))=hSpecChanAmpText5;
        hSpecChanAmpText6=text('FontSize',[10],'HorizontalAlignment','left','Visible','off');
		hList(NListHdr+29+(50*5))=hSpecChanAmpText6;
		UserDataMat=zeros(NUsedFiles,MaxPoint-MinPoint+1);
		LineWidthVec=get(hList(98),'Userdata');

        for FileIndex=1:NUsedFiles
			 if Domain==6 | Domain==7 
				WaveVec=get(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata');
				NFrequ=WaveVec(4);
				StartF0=WaveVec(7);
				EndF0=WaveVec(8);
				DeltaF0=WaveVec(9);
                StartF0IndPlot=WaveVec(12);
                EndF0IndPlot=WaveVec(13);
				CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+36),'Userdata');
				UserDataMat=squeeze(CalcAvgMat(SpecChan,MinPoint:MaxPoint,:));
				hSpecData(FileIndex)=surf(UserDataMat');
                axis([1,NPoints,StartF0IndPlot,EndF0IndPlot,MinAmp,MaxAmp])
				view(0,90)
				shading interp
				set(gca,'Clim',[MinAmp MaxAmp]);
				set(gca,'xtick',XTickVec,'XTickLabel',XTickLabelVec);
				YTickVec=get(gca,'ytick');
				Tmp=[StartF0:DeltaF0:EndF0];
				Tmp=round(Tmp.*100)./100;
     			YTickLabelVec=Tmp(YTickVec);
				set(gca,'ytick',YTickVec,'YTickLabel',YTickLabelVec);
				pause(0.01)
            elseif Domain == 8
                WaveVec=get(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata');
				NFrequ=WaveVec(4);
				StartF0=WaveVec(7);
				EndF0=WaveVec(8);
				DeltaF0=WaveVec(9);
                StartF0IndPlot=WaveVec(12);
                EndF0IndPlot=WaveVec(13);
				CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+36),'Userdata');
				UserDataMat=squeeze(CalcAvgMat(SpecChan,MinPoint:MaxPoint,:));
				hSpecData(FileIndex)=image('XData',[MinPoint MaxPoint],'YData',[StartF0 EndF0],'CData',UserDataMat','CDataMapping','scaled');
                set(gca,'XLim',[1 NPoints],'YLim',[StartF0IndPlot EndF0IndPlot],'CLim',[MinAmp,MaxAmp]);
				shading interp
				set(gca,'xtick',XTickVec,'XTickLabel',XTickLabelVec);
				YTickVec=get(gca,'ytick');
				Tmp=[StartF0:DeltaF0:EndF0];
				Tmp=round(Tmp.*100)./100;
     			YTickLabelVec=Tmp(YTickVec);
				set(gca,'ytick',YTickVec,'YTickLabel',YTickLabelVec);
				pause(0.01)
			else
				CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
				SpecChanVec=CalcAvgMat(SpecChan,:);	
				UserDataMat(FileIndex,:)=SpecChanVec(MinPoint:MaxPoint);
				ColorRGB=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+16),'Userdata');
				LineStyleStr=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+17),'Userdata');
                
                if ~isempty(varargin)
                    if strcmp(varargin{1},'GPDissim')
				        hSpecData(FileIndex)=line('XData',[1:NPoints],'YData',GPDissimData,...
				        'Color',ColorRGB,'LineStyle',LineStyleStr,'LineWidth',LineWidthVec(FileNoVec(FileIndex)));
                        set(hList(144),'userdata',hSpecData(FileIndex));
                    else
				        hSpecData(FileIndex)=line('XData',[1:NPoints],'YData',CalcAvgMat(SpecChan,:),...
				        'Color',ColorRGB,'LineStyle',LineStyleStr,'LineWidth',LineWidthVec(FileNoVec(FileIndex)));
                    end
				else
                    
				    hSpecData(FileIndex)=line('XData',[1:NPoints],'YData',CalcAvgMat(SpecChan,:),...
				    'Color',ColorRGB,'LineStyle',LineStyleStr,'LineWidth',LineWidthVec(FileNoVec(FileIndex)));
				end
    
            end
		end
        set(hhSpecChanVec(34),'Userdata',hSpecData);
     	set(hList(64),'Userdata',hhSpecChanVec);
		if Domain==1 | Domain==2 | Domain==5
			xlabel('Time [ms]')
            ylabel(['Amplitude [',EegMegString,']']);
		elseif Domain==3 | Domain==4
			xlabel('Frequency [Hz]')
            ylabel(['Amplitude [',EegMegString,'/sqrt(Hz)]']);
		elseif Domain==6 | Domain==7 | Domain==8
			xlabel('Time [ms]')
            ylabel(['Frequency [Hz]']);
		end;
		set(hList(94),'Userdata',UserDataMat);
		set(hUserDataInfo,'Label',['Special sensor # ',int2str(SpecChan),':', SensorNames(kActAxes(SpecChan),:)]);
		set(hExportUserData,'Enable','on');	%Export User data enable on
		hhSpecChanVec(10)=SpecChan;
		set(hList(64),'Userdata',hhSpecChanVec);
		set(hPlot2dMenuFig,'Userdata',hList);
		if Domain~=6 & Domain~=7 & Domain~=8
			emegs2d('setSpecChanCursorText');	
		end
	end



%=============================================================================
%============ InitializeButterfly: figure and menue for butterfly plot
%============ call: PlotButterfly
%=============================================================================	
	
elseif strcmp(action,'InitializeButterfly'),

	hList=get(hPlot2dMenuFig,'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	Domain=get(hList(20),'Value');
	MinAmp=get(hList(52),'Value');
	MinAmpString=get(hList(52),'String');
	MaxAmp=get(hList(53),'Value');
	MaxAmpString=get(hList(53),'String');
	MinPoint=get(hList(54),'Value');
	MSMinPointString=get(hList(54),'String');
	MaxPoint=get(hList(55),'Value');
	MSMaxPointString=get(hList(55),'String');
	NChan=get(hList(NListHdr+(ActFileNo-1)*50+2),'Userdata');
	NPoints=get(hList(NListHdr+(ActFileNo-1)*50+3),'Userdata');
	SampRate=get(hList(60),'Userdata');	
	TrigPoint=get(hList(22),'Value');
	CursorPoint=get(hList(23),'Value');
	CursorPointString=get(hList(23),'String');
	if CursorPoint<MinPoint
		CursorPoint=MinPoint;
		CursorPointString=MSMinPointString;
	elseif CursorPoint>MaxPoint
		CursorPoint=MaxPoint;
		CursorPointString=MSMaxPointString;
	end 
	kActAxes=get(hList(27),'Userdata');
	ActAxes=get(hList(28),'Userdata');
	CursorLength=get(hList(30),'Userdata');
	BGColor=get(hList(93),'Color');
	hhButVec=get(hList(63),'Userdata');
	MainMatlabVersion=get(hList(100),'Userdata');
	SegmentMS=get(hList(101),'Userdata');
	EegMegStatusString=get(hList(110),'String');
	if strcmp(EegMegStatusString,'EEG'); EegMegString='µV'; else; EegMegString='fT'; end
	%======== figure =========================================
  	if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
		if Domain==6 | Domain==7 | Domain==8
	   		ChanFigPosVec=[.01 .01 .4 .6];		
			MenuFigPosVec=[.4225 .01 .175 .5];
		else
			ChanFigPosVec=[.33 .5 .33 .45];	
		end
		if Domain<3
      		MenuFigPosVec=[.33 .01 .175 .42];
		elseif Domain~=6 & Domain~=7 & Domain~=8
		    MenuFigPosVec=[.33,.155,.25,.25];
		end
    elseif strcmp(computer,'PCWIN') 
		if Domain==6 | Domain==7 | Domain==8
	   		ChanFigPosVec=[.01 .01 .4 .6];	
			MenuFigPosVec=[.4225 .01 .175 .5];
		else
			ChanFigPosVec=[.33 .45 .33 .5];	
		end
		if Domain<3
      		MenuFigPosVec=[.33 .01 .2 .42];
		elseif Domain~=6 & Domain~=7 & Domain~=8
		    MenuFigPosVec=[.33 .155 .25 .25];
		end
   	elseif strcmp(computer,'SOL2') | strcmp(computer,'LNX86') | strcmp(computer,'GLNX86')
		if Domain==6 | Domain==7	
      		ChanFigPosVec=[.01 .01 .4 .6];	
			MenuFigPosVec=[.42225 .01 .175 .5];
		else
			ChanFigPosVec=[.33 .42 .33 .5];
		end
		if Domain<3
      		MenuFigPosVec=[.33 .055 .175 .275];
		elseif Domain~=6 & Domain~=7 & Domain~=8
      		MenuFigPosVec=[.33 .055 .25 .275];
		end
   	end;
  
	hhButChanLineVec=uicontrol('Visible','off');			
	hhButVec(25)=hhButChanLineVec;
    
    CloseRequestFcnStr='emegs2d(''CloseButterflyPlot'')';
  	hButPlot=figure('Units','normal','NumberTitle','off','Position',ChanFigPosVec,'Name','Butterfly Plot','tag','ButterflyPlot','CloseRequestFcn',CloseRequestFcnStr);
	hhButVec(15)=hButPlot;	
	hButMenu=figure('Units','normal','NumberTitle','off','Position',MenuFigPosVec,'Name','Butterfly Menu','tag','ButterflyMenu');
	hhButVec(16)=hButMenu;	
	
    %============================== console frame with buttons 
	%========Information for all SpecChan buttons
	labelColor=[0.8 0.8 0.8];
	yInitPos=0.90;
	menutop=0.95;
	btnTop = 0.6;
	top=0.75;
	left=0.125;		
   	btnWid=0.8;		
	btnHt=0.105;
	textHeight = 0.05;
	textWidth = 0.06;
	spacing=0.01;	% Spacing between the button and the next command's label
    
	% ========= CONSOLE frame =================================
	frmBorder=0.019; frmBottom=0.04; 
	frmHeight = 0.92; frmWidth = btnWid;
	yPos=frmBottom-frmBorder;
	frmPos=[left-frmBorder yPos frmWidth+2*frmBorder frmHeight+2*frmBorder];
	h=uicontrol( ...
	'Style','frame', ...
	'Units','normalized', ...
	'Position',frmPos, ...
	'BackgroundColor',[0 0 0.3]);
	
	%===== Time <-> Frequency =========
	if Domain<3 | Domain==6 | Domain==7	
		MenuTextString1=['Min.amp [',EegMegString,']'];
		MenuTextString2=['Max.amp [',EegMegString,']'];
		MenuTextString3=['Min. time [ms]; #',int2str(MinPoint)];
		MenuTextString4=['Max. time [ms]; #',int2str(MaxPoint)];
		MenuTextString5=['Cursor [ms]; #',int2str(CursorPoint)];
	else
		MenuTextString1=['Min.amp [',EegMegString,'/sqrt(Hz)]'];
		MenuTextString2=['Max.amp [',EegMegString,'/sqrt(Hz)]'];
        MenuTextString3=['Min. frquz. [Hz]; #',int2str(MinPoint)];
		MenuTextString4=['Max. frquz. [Hz]; #',int2str(MaxPoint)];
		MenuTextString5=['Cursor [Hz]; #',int2str(CursorPoint)];		
	end;

	%============MinAmpHandle ================================= 
	btnNumber=1;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
    
	hButMinAmpText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String',MenuTextString1);
	hhButVec(11)=hButMinAmpText;
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
	callbackStr = 'emegs2d(''setButMinAmp'')';
    
	hButMinAmp = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String',MinAmpString,...
	'Value',MinAmp, ...
	'callback',callbackStr);
	hhButVec(1)=hButMinAmp;
	
  	%============MaxAmpHandle ============================== 
	btnPos=[left yPos-btnHt 2.*btnWid./3 btnHt./2];
    
	hButMaxAmpText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String',	MenuTextString2);
	hhButVec(12)=hButMaxAmpText;
	
	btnPos=[left+2.*btnWid./3 yPos-btnHt btnWid./3 btnHt./2];
	callbackStr = 'emegs2d(''setButMaxAmp'')';
	
	hButMaxAmp = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String',MaxAmpString,...
	'Value',MaxAmp, ...
	'callback',callbackStr);
	hhButVec(2)=hButMaxAmp;
	
	%===================================
	btnNumber=2;     	
	% Adjust But Amplitude
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 2*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''AdjustButAmp'')';
	hAdjustButAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Adjust', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	
	% Center But Amplitude
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt 2*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''CenterButAmp'')';
	hCenterButAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Center', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	
	% Decrease/Increase  But Amplitude
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+2.*btnWid./8 yPos-btnHt./2 2.*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''DecIncButSta'')';
	hDecIncButStaAmp = uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'HorizontalAlignment','Center',...
	'Userdata',[0 1],...
	'String','+/- 1',...
	'Callback',callbackStr,...
	'Enable','on');
	hhButVec(18)=hDecIncButStaAmp;
	
	% Invert View
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+2.*btnWid./8 yPos-btnHt 2*btnWid./8 btnHt./2];
	callbackStr = 'emegs2d(''InvertButView'')';
	hInvertButView=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','View', ...
	'Userdata',1,...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	hhButVec(19)=hInvertButView;
	%==================================================
	
	%Decrease  of But Amplitude
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+4.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''DecButAmp'')';
	hDecButAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','<', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	
	% Decrease Decrease/Increase  Amplitude of But 
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+5.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''DecDecIncButAmp'')';
	hDecDecIncAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','<<', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	
	% Increase Decrease/Increase Amplitude
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+6.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''IncDecIncButAmp'')';
	hIncDecIncButAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','>>', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	
	% Slow Increase of But Amplitude
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+7.*btnWid./8 yPos-btnHt btnWid./8 btnHt];
	callbackStr = 'emegs2d(''IncButAmp'')';
	hIncButAmp=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','>', ...
	'HorizontalAlignment','center',...
	'Callback',callbackStr,...
	'Enable','on');
	
 	%============MinPointHandle ================================= 
   	btnNumber=3;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
    
	hButMinPointText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String',	MenuTextString3);
	hhButVec(13)=hButMinPointText;
    
	btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
	callbackStr = 'emegs2d(''setButMinPoint'')';
    
	hButMinPoint = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String',MSMinPointString,...
	'Value',MinPoint, ...
	'callback',callbackStr);
	hhButVec(3)=hButMinPoint;

    %============MinPointSliderHandle ================================= 
    NPointsTmp=MaxPoint-MinPoint+1;
	if NPointsTmp>=10
		SliderStep=[1./NPointsTmp 10./NPointsTmp];
	else
		SliderStep=[.1 1];
	end
 	btnPos=[left yPos-btnHt btnWid btnHt./2];
	callbackStr = 'emegs2d(''setButMinPointSlider'')';
	hButMinPointSlider=uicontrol( ...
	'Style','slider', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Cursor', ...
	'HorizontalAlignment','center',...
	'Userdata',[], ...
	'Min',1, ...
	'Max',NPoints, ...
	'SliderStep',SliderStep, ...
	'Value',MinPoint, ...
	'Callback',callbackStr,...
	'Enable','on');
	hhButVec(22)=hButMinPointSlider;
    
   	%============MaxPointHande ============================== 
    btnNumber=4; 
   	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
    
	hButMaxPointText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String',MenuTextString4);
    hhButVec(14)=hButMaxPointText;
    
	btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
	callbackStr = 'emegs2d(''setButMaxPoint'')';
    
	hButMaxPoint = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String',MSMaxPointString,...
	'Value',MaxPoint, ...
	'callback',callbackStr);
	hhButVec(4)=hButMaxPoint;
	
    %============MaxPointSliderHandle ================================= 
 	btnPos=[left yPos-btnHt btnWid btnHt./2];
	callbackStr = 'emegs2d(''setButMaxPointSlider'')';
	hButMaxPointSlider=uicontrol( ...
	'Style','slider', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Cursor', ...
	'HorizontalAlignment','center',...
	'Userdata',[], ...
	'Min',1, ...
	'Max',NPoints, ...
	'SliderStep',SliderStep, ...
	'Value',MaxPoint, ...
	'Callback',callbackStr,...
	'Enable','on');
	hhButVec(23)=hButMaxPointSlider;
    
	%============CursorPointHandle============================== 
	btnNumber=5;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 2.*btnWid./3 btnHt./2];
    
	hButCursorPointText = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','left', ...
	'Foreground','black', ...
	'String',MenuTextString5);
    hhButVec(15)=hButCursorPointText;
    
	btnPos=[left+2.*btnWid./3 yPos-btnHt./2 btnWid./3 1.*btnHt./2];
	callbackStr='emegs2d(''setButCursorPoint'')';
    
	hButCursorPoint = uicontrol( ...
	'Style','edit', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'Horiz','center', ...
	'Background','white', ...
	'Foreground','black', ...
	'String',CursorPointString,...
	'Value',CursorPoint, ...
	'callback',callbackStr);
	hhButVec(5)=hButCursorPoint;
	
	NPointsTmp=MaxPoint-MinPoint+1;
	if NPointsTmp>=10
		SliderStep=[1./NPointsTmp 10./NPointsTmp];
	else
		SliderStep=[.1 1];
	end
 	btnPos=[left yPos-btnHt btnWid btnHt./2];
	callbackStr = 'emegs2d(''setButCursorPointSlider'')';
	hButCursorPointSlider=uicontrol( ...
	'Style','slider', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Cursor', ...
	'HorizontalAlignment','center',...
	'Min',MinPoint, ...
	'Max',MaxPoint, ...
	'SliderStep',SliderStep, ...
	'Value',CursorPoint, ...
	'Callback',callbackStr,...
	'Enable','on');
	hhButVec(20)=hButCursorPointSlider;
	
	%============LineColorHandle============================== 
	btnNumber=6;
	ColorChanInd=0;
	for FileIndex=1:NUsedFiles
		hDataVec=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+25),'Userdata');
		NChan=get(hList(NListHdr+(FileIndex-1)*50+2),'Userdata');
		for ChanInd=1:NChan
			VisStatusStr=get(hDataVec(ChanInd),'Visible');
			if strcmp(VisStatusStr,'on')
				ColorChanInd=ColorChanInd+1;
			end
		end
	end
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt./2 btnWid./2 btnHt./2];
	callbackStr='emegs2d(''PlotButterfly'')';
	if ColorChanInd>10; Value=0; else; Value=1; end
	hSetButLineColor=uicontrol( ...
	'Style','radiobutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Line Color', ...
	'Userdata',[1 1 1 1],...
	'Value',Value,...
	'Callback',callbackStr,...
	'Enable','on');
	hhButVec(21)=hSetButLineColor;
	
	%============ButUpdate============================== 
	btnNumber=6;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./2 yPos-btnHt./2 btnWid./2 btnHt./2];
	callbackStr = 'emegs2d(''PlotButterfly'')';
	ButUpdateChan=uicontrol( ...
	'Style','pushbutton', ...
	'Units','normalized', ...
	'Position',btnPos, ...
	'String','Update Sensor', ...
	'Userdata','0', ...
	'Value',0, ...
	'Callback',callbackStr,...
	'Enable','on');
	hhButVec(24)=ButUpdateChan;

    %====================================
    %====================================
    % The setBut2Emegs2dCursor / setBut2Emegs3dCursor
    btnNumber=7;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt/2 btnWid/2 btnHt./2];
    labelStr='Emegs2d Cursor';
    callbackStr='emegs2d(''setBut2Emegs2dCursor'')';
    
    hsetBut2Emegs2dCursor=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Callback',callbackStr);
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid/2 yPos-btnHt/2 btnWid/2 btnHt./2];
    labelStr='Emegs3d Point';
    callbackStr='emegs2d(''setBut2Emegs3dCursor'')';
    
    hsetBut2Emegs3dCursor=uicontrol( ...
         'Style','pushbutton', ...
         'Units','normalized', ...
         'Position',btnPos, ...
         'String',labelStr, ...
         'Interruptible','on', ...
         'Callback',callbackStr);
        
	%======================= axes 
	figure(hButPlot);
	hButAxes=axes('Units','normal','Position',[.1 .15 .85 .7],'Box','on','XLim',[MinPoint MaxPoint],'YLim',[MinAmp MaxAmp],'Color',BGColor);
	hhButVec(17)=hButAxes;	
	if Domain<3 | Domain==6 | Domain==7	
		Segment=(SegmentMS.*SampRate./1000);	
		if TrigPoint>MinPoint & TrigPoint<MaxPoint
			XTickVec1=TrigPoint:Segment:MaxPoint;
			XTickVec2=sort(TrigPoint:(-1)*Segment:MinPoint);
			XTickVec=[XTickVec2 XTickVec1(2:length(XTickVec1))];
			XTickLabelVec1=0:SegmentMS:(round((MaxPoint-TrigPoint).*1000./SampRate));
			XTickLabelVec2=sort(0:(-1)*SegmentMS:(round((MinPoint-TrigPoint).*1000./SampRate)));
			XTickLabelVec=[XTickLabelVec2 XTickLabelVec1(2:length(XTickLabelVec1))];
		else
			if TrigPoint<=MinPoint
				XTickVec1=TrigPoint:Segment:MaxPoint;
				ind=find(XTickVec1>=MinPoint);
				XTickVec=XTickVec1(ind(1):length(XTickVec1));
				XTickLabelVec1=0:SegmentMS:(round((MaxPoint-TrigPoint).*1000./SampRate));
				XTickLabelVec=XTickLabelVec1(ind(1):length(XTickLabelVec1));
			elseif TrigPoint>=MaxPoint;	
				XTickVec1=sort(TrigPoint:(-1)*Segment:MinPoint);
				ind=find(XTickVec1>MaxPoint);
				XTickVec=XTickVec1(1:(ind(1)-1));
				XTickLabelVec1=sort(0:(-1)*SegmentMS:round((MinPoint-TrigPoint).*1000./SampRate));
				XTickLabelVec=XTickLabelVec1(1:(ind(1)-1));
			end;
		end;
	else	% frequency
		Segment=(SegmentMS.*(2.*NPoints)./SampRate);
		XTickVec=MinPoint:Segment:MaxPoint;
		XTickLabelVec=[round(MinPoint.*SampRate./(2.*NPoints)):SegmentMS:round(MaxPoint.*SampRate./(2.*NPoints))];	
	 end;
	
	if MainMatlabVersion<5
		set(hButAxes,'xtick',XTickVec,'XTickLabel',[0 XTickLabelVec]);	
	else	
		set(hButAxes,'xtick',XTickVec,'XTickLabel',XTickLabelVec);	
	end
	
	if Domain<3 | Domain==6 | Domain==7	
		xlabel('Time [ms]');ylabel(['Amplitude [',EegMegString,']']);
	else
		xlabel('Frequency [Hz]');ylabel(['Pot. [',EegMegString,'/sqrt(Hz)]']);
	end;
	title('Butterfly Plot');
	hhButVec(6) = hButAxes;

    %=========== Zero/Cursor/Triggger-Line Style and Color		
	hZeroLine=get(hList(8),'Userdata');
	ZeroLineColor=get(hZeroLine(1),'Color');
	ZeroLineStyle=get(hZeroLine(1),'LineStyle');
	hButZeroLine=line('XData',[MinPoint MaxPoint],'YData',[0 0],'Color',ZeroLineColor,'LineStyle',ZeroLineStyle);
	hhButVec(8)=hButZeroLine;

	hTriggerLine=get(hList(9),'Userdata');
	TriggerLineColor=get(hTriggerLine(1),'Color');
	TriggerLineStyle=get(hTriggerLine(1),'LineStyle');	
	hSpecTrigLine=line('XData',[TrigPoint TrigPoint],'YData',[MinAmp MaxAmp],'Color',TriggerLineColor,'LineStyle',TriggerLineStyle);
	
	hCursorLine=get(hList(10),'Userdata');
	CursorLineColor=get(hCursorLine(1),'Color');
	CursorLineStyle=get(hCursorLine(1),'LineStyle');
	hButCursorLine=line('XData',[CursorPoint CursorPoint],'YData',[MinAmp MaxAmp],'Color',CursorLineColor,'LineStyle',CursorLineStyle,'Visible','on');
	hhButVec(7)=hButCursorLine;
	
	hButCursorText=text('FontSize',[10],'Color',[0 0 0],'HorizontalAlignment','left','Visible','off');
	hhButVec(9)=hButCursorText;
	
	set(hList(63),'Userdata',hhButVec);	
	set(hPlot2dMenuFig,'Userdata',hList);

    emegs2d('PlotButterfly');
    figure(hButPlot);
	clear;

	%=============================================================================
	%============ PlotButterfly
	%============ call: setButCursorText
	%=============================================================================	
	
elseif strcmp(action,'PlotButterfly'),	

	hList=get(hPlot2dMenuFig,'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	NPoints=get(hList(NListHdr+(ActFileNo-1)*50+3),'Userdata');
	SampRate=get(hList(60),'Userdata');	
	hhButVec=get(hList(63),'Userdata');
	ButAxes=hhButVec(6);
	LineWidthVec=get(hList(98),'Userdata');

	axes(ButAxes); 
	ButLineColorStatus=get(hhButVec(21),'Value');
	if ButLineColorStatus
		RGBColorMat=get(hList(128),'Userdata');
		NColor=size(RGBColorMat,1);
		RGBColorMat=RGBColorMat(3:NColor,:);
		NColor=NColor-2;
	end
	ColorInd=0;
	UsedChanInd=0;
	hButChanLineVec=get(hhButVec(25),'Userdata');
	NUsedChanLine=length(hButChanLineVec);
	for FileIndex=1:NUsedFiles
		NChan=get(hList(NListHdr+(FileIndex-1)*50+2),'Userdata');
		hDataVec=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+25),'Userdata');
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		RGBColor =get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+16),'Userdata');
		LineStyleStr=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+17),'Userdata');
		if ButLineColorStatus 
			text('Units','normal','Position',[0 -.175], 'FontSize',10 ,'Color',[0 0 0],'String',['File: ',int2str(FileIndex)]);
		end
		for ChanInd=1:NChan
			VisStatusStr=get(hDataVec(ChanInd),'Visible');
			if strcmp(VisStatusStr,'on')
				if ButLineColorStatus 
					ColorInd=ColorInd+1;
					if ColorInd<=NColor
						RGBColor=RGBColorMat(ColorInd,:);
					end	
					htext=text('Units','normal','Position',[.1+UsedChanInd.*.13 -.175], 'FontSize',10 ,'Color',RGBColor,'String',[' ; Chan.: ',int2str(ChanInd)]);
				end
				UsedChanInd=UsedChanInd+1;
				if UsedChanInd>NUsedChanLine
					hButChanLineVec(UsedChanInd)=line('XData',[1:NPoints],'YData',CalcAvgMat(ChanInd,:),...
					'Color',RGBColor,'LineStyle',LineStyleStr,'LineWidth',LineWidthVec(FileNoVec(FileIndex)));		
				else
					set(hButChanLineVec(UsedChanInd),'XData',[1:NPoints],'YData',CalcAvgMat(ChanInd,:),...
					'Color',RGBColor,'LineStyle',LineStyleStr,'LineWidth',LineWidthVec(FileNoVec(FileIndex)));			
				end
			end
		end
	end
	set(hhButVec(25),'Userdata',hButChanLineVec);
	emegs2d('setButCursorText');
	figure(hhButVec(16));	%hButMenu;	
	
	%=============================================================================
	%============ setButMinAmp | setSpecChanMinAmp: minimum amplitude
	%============ call: setButMinMaxAmpPoint | setSpecChanMinMaxAmpPoint
	%=============================================================================	
	%=============================================================================
	%============ setButMaxAmp | setSpecChanMaxAmp: maximum amplitude
	%============ call: setButMinMaxAmpPoint | setSpecChanMinMaxAmpPoint
	%=============================================================================	
elseif strcmp(action,'setGlobPowMinAmp') | ...
	strcmp(action,'setGlobPowMaxAmp') | ...
	strcmp(action,'setButMinAmp') | ...
	strcmp(action,'setButMaxAmp') | ...
	strcmp(action,'setSpecChanMinAmp') | ...
	strcmp(action,'setSpecChanMaxAmp'),

	hList=get(hPlot2dMenuFig,'Userdata');
	Domain=get(hList(20),'Value');
	DecInc=get(hList(124),'Userdata'); 
	DecIncAmp=DecInc(2);
	Tmp=max([1./DecIncAmp 1000]);
	if strcmp(action,'setGlobPowMinAmp') | strcmp(action,'setGlobPowMaxAmp')	
		hhVec=get(hList(66),'Userdata');
	elseif strcmp(action,'setButMinAmp') | strcmp(action,'setButMaxAmp')	
		hhVec=get(hList(63),'Userdata');
	elseif strcmp(action,'setSpecChanMinAmp') | strcmp(action,'setSpecChanMaxAmp'),
		hhVec = get(hList(64),'Userdata'); 
	end;	
	MinAmpVal=get(hhVec(1),'Value');
	MinAmpVec=get(hhVec(1),'Userdata');
	MinAmpStr=get(hhVec(1),'String');
	MaxAmpVal=get(hhVec(2),'Value');
	MaxAmpVec=get(hhVec(2),'Userdata');
	MaxAmpStr = get(hhVec(2),'String');
	if strcmp(action,'setGlobPowMinAmp') | strcmp(action,'setButMinAmp') | strcmp(action,'setSpecChanMinAmp')
		[MinAmpVal,MinAmpStr]=String2Value(MinAmpStr,MinAmpVal,[],MaxAmpVal);
		MinAmpVec(Domain)=MinAmpVal;
		set(hhVec(1),'Value',MinAmpVal,'Userdata',MinAmpVec,'String',sprintf('%g',round(MinAmpVal*Tmp)/Tmp));  
	else
		[MaxAmpVal,MaxAmpStr]=String2Value(MaxAmpStr,MaxAmpVal,MinAmpVal);
		MaxAmpVec(Domain)=MaxAmpVal;
		set(hhVec(2),'Value',MaxAmpVal,'Userdata',MaxAmpVec,'String',sprintf('%g',round(MaxAmpVal*Tmp)/Tmp));  
    end
    if strcmp(action,'setGlobPowMinAmp') | strcmp(action,'setGlobPowMaxAmp')	
		emegs2d('setGPMinMaxAmpPoint');
	elseif strcmp(action,'setButMinAmp') | strcmp(action,'setButMaxAmp')	
		emegs2d('setButMinMaxAmpPoint');	
	elseif strcmp(action,'setSpecChanMinAmp') | strcmp(action,'setSpecChanMaxAmp'),
		emegs2d('setSpecChanMinMaxAmpPoint');
	end;	
	
	%=============================================================================
	%============ setButMinMaxAmpPoint | setSpecChanMinMaxAmpPoint
	%=============================================================================	
elseif strcmp(action,'setButMinMaxAmpPoint') | strcmp(action,'setSpecChanMinMaxAmpPoint')

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	Domain=get(hList(20),'Value');
	SampRate=get(hList(60),'Userdata');	
	TrigPoint=get(hList(22),'Value');
	MainMatlabVersion=get(hList(100),'Userdata');
	
	if strcmp(action,'setButMinMaxAmpPoint')			
		hhVec=get(hList(63),'Userdata') ;
	elseif strcmp(action,'setSpecChanMinMaxAmpPoint')	
		hhVec=get(hList(64),'Userdata'); 
	end;
	hAxes=hhVec(6);
	hCursorLine=hhVec(7);
	hZeroLine=hhVec(8);
	
	MinAmp=get(hhVec(1),'Value');
	MaxAmp=get(hhVec(2),'Value');
	MinPoint=get(hhVec(3),'Value');
	MaxPoint=get(hhVec(4),'Value');
	
	set(hAxes,'XLim',[MinPoint MaxPoint]);
	if Domain==6 | Domain==7 | Domain==8
		StartF0IndPlot=round(get(hhVec(25),'Value'));
		EndF0IndPlot=round(get(hhVec(27),'Value'));
		set(hAxes,'YLim',[StartF0IndPlot EndF0IndPlot]);
		set(hAxes,'CLim',[MinAmp MaxAmp]);
	else
		set(hAxes,'YLim',[MinAmp MaxAmp]);
		set(hCursorLine,'YData',[MinAmp MaxAmp]);
		set(hZeroLine,'XData',[MinPoint MaxPoint]);		
	end
	SegmentMS=get(hList(101),'Userdata');
	if Domain<3 | Domain==6 | Domain==7	| Domain==8
		Segment=(SegmentMS.*SampRate./1000);
		if TrigPoint>MinPoint & TrigPoint<MaxPoint
			XTickVec1=TrigPoint:Segment:MaxPoint;
			XTickVec2=sort(TrigPoint:(-1)*Segment:MinPoint);
			XTickVec=[XTickVec2 XTickVec1(2:length(XTickVec1))];
			XTickLabelVec1=0:SegmentMS:(round((MaxPoint-TrigPoint).*1000./SampRate));
			XTickLabelVec2=sort(0:(-1)*SegmentMS:(round((MinPoint-TrigPoint).*1000./SampRate)));
			XTickLabelVec=[XTickLabelVec2 XTickLabelVec1(2:length(XTickLabelVec1))];
		else
			if TrigPoint<=MinPoint
				XTickVec1=TrigPoint:Segment:MaxPoint;
				ind=find(XTickVec1>=MinPoint);
				if ~isempty(ind)
					XTickVec=XTickVec1(ind(1):length(XTickVec1));
					XTickLabelVec1=0:SegmentMS:(round((MaxPoint-TrigPoint).*1000./SampRate));
					XTickLabelVec=XTickLabelVec1(ind(1):length(XTickLabelVec1));
				else
					XTickVec=[];
				end
			elseif TrigPoint>=MaxPoint;	
				XTickVec1=sort(TrigPoint:(-1)*Segment:MinPoint);
				ind=find(XTickVec1>MaxPoint);
				if ~isempty(ind)
					XTickVec=XTickVec1(1:(ind(1)-1));
					XTickLabelVec1=sort(0:(-1)*SegmentMS:round((MinPoint-TrigPoint).*1000./SampRate));
					XTickLabelVec=XTickLabelVec1(1:(ind(1)-1));
				else
					XTickVec=[];
				end
			end;
		end;
	else    % frequency
		Segment=(SegmentMS.*(2.*NPoints)./SampRate);
		XTickVec=MinPoint:Segment:MaxPoint;
		XTickLabelVec=[round(MinPoint.*SampRate./(2.*NPoints)):SegmentMS:round(MaxPoint.*SampRate./(2.*NPoints))];		
	end;
	if ~isempty(XTickVec)
		set(hAxes,'xtick',XTickVec,'XTickLabel',XTickLabelVec);	
	end

	%=============================================================================
	%============ setButMinPoint | setSpecChanMinPoint
	%============ setButMaxPoint | setSpecChanMaxPoint
	%=============================================================================	
elseif  strcmp(action,'setGPMinPoint') | ...
	 	strcmp(action,'setGPMinPointSlider') | ...
		strcmp(action,'setGPMinFrequPoint') | ...
		strcmp(action,'setGPMinFrequPointSlider') | ...
		strcmp(action,'setGPMaxPoint') | ...
		strcmp(action,'setGPMaxPointSlider') | ...
		strcmp(action,'setGPMaxFrequPoint') | ...
		strcmp(action,'setGPMaxFrequPointSlider') | ...
		strcmp(action,'setButMinPoint') | ....
        strcmp(action,'setButMinPointSlider') | ....
		strcmp(action,'setButMaxPoint') | ...
        strcmp(action,'setButMaxPointSlider') | ....
		strcmp(action,'setSpecChanMinPoint') | ...
		strcmp(action,'setSpecChanMinPointSlider') | ...
		strcmp(action,'setSpecChanMaxPoint') | ...
		strcmp(action,'setSpecChanMaxPointSlider') | ...
		strcmp(action,'setSpecChanMinFrequPoint') | ...
		strcmp(action,'setSpecChanMinFrequPointSlider')  | ...
		strcmp(action,'setSpecChanMaxFrequPoint') | ...
		strcmp(action,'setSpecChanMaxFrequPointSlider') ,
	  
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	TrigPoint=get(hList(22),'Value');
	NPoints=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+3),'Userdata');
	Domain=get(hList(20),'Value');
	AllMinPointVal=get(hList(54),'Value');
	AllMaxPointVal=get(hList(55),'Value');
	TrigPoint=get(hList(22),'Value');
	SampRate=get(hList(60),'Userdata');

	if  ~isempty(findstr(action,'setBut')),
		hhVec=get(hList(63),'Userdata');
	elseif ~isempty(findstr(action,'setSpecChan')),
		hhVec=get(hList(64),'Userdata'); 
	elseif ~isempty(findstr(action,'setGP')),
		hhVec=get(hList(66),'Userdata'); 
	end

	if (Domain==6 | Domain==7 | Domain==8) & ~isempty(findstr(action,'Freq')),
		WaveVec=get(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata');
		NFrequ=WaveVec(4);
		StartF0=WaveVec(7);
		EndF0=WaveVec(8);
		DeltaF0=WaveVec(9);
		F0Vec=[StartF0:DeltaF0:EndF0];
		StartF0IndPlot=WaveVec(12);
		EndF0IndPlot=WaveVec(13);
		MinPointInd=24;
		MinPointSliderInd=25;
		MaxPointInd=26;
		MaxPointSliderInd=27;
		CursPointInd=5;
		CursPointSliderInd=20;
	else
		MinPointInd=3;
		MinPointSliderInd=22;
		MaxPointInd=4;
		MaxPointSliderInd=23;
		CursPointInd=5;
		CursPointSliderInd=20;
	end
	MinPointVal=get(hhVec(MinPointInd),'Value');
	MinPointStr=get(hhVec(MinPointInd),'String');
    MinPointText=get(hhVec(13),'String');
	MinPointSliderVal=round(get(hhVec(MinPointSliderInd),'Value'));
	MaxPointVal=get(hhVec(MaxPointInd),'Value');
	MaxPointStr=get(hhVec(MaxPointInd),'String');
    MaxPointText=get(hhVec(14),'String');
	MaxPointSliderVal=round(get(hhVec(MaxPointSliderInd),'Value'));
	CursPointVal=get(hhVec(CursPointInd),'Value');
	CursPointStr=get(hhVec(CursPointInd),'String');
    CursPointText=get(hhVec(15),'String');
    
	if ~isempty(findstr(action,'Min')) &  isempty(findstr(action,'Slider'))
    	[MSPointTmp]=String2Value(MinPointStr);
		if isempty(findstr(action,'Freq')),
			[PointTmp]=Ms2Point(MSPointTmp,Domain,SampRate,TrigPoint,NPoints);
		else
			[NonUse,PointTmp]=min(abs(F0Vec-MSPointTmp));
		end
	elseif ~isempty(findstr(action,'Max')) &  isempty(findstr(action,'Slider'))
    	[MSPointTmp]=String2Value(MaxPointStr);
		if isempty(findstr(action,'Freq')),
			[PointTmp]=Ms2Point(MSPointTmp,Domain,SampRate,TrigPoint,NPoints);
		else
			[NonUse,PointTmp]=min(abs(F0Vec-MSPointTmp));
		end
	elseif ~isempty(findstr(action,'Min')) &  ~isempty(findstr(action,'Slider'))
    	PointTmp=MinPointSliderVal;
		MinPointVal=PointTmp;
	elseif ~isempty(findstr(action,'Max')) &  ~isempty(findstr(action,'Slider'))
    	PointTmp=MaxPointSliderVal;
		MaxPointVal=PointTmp;
	end
	if ~isempty(findstr(action,'Min'))
		if PointTmp>=MaxPointVal | PointTmp>=AllMaxPointVal
			PointTmp=MaxPointVal-1;
		end
		if PointTmp<=0
			PointTmp=1;
		end
	else
		if PointTmp<=MinPointVal | PointTmp<=AllMinPointVal
			PointTmp=MinPointVal+1;
		end
		if PointTmp>NPoints
			PointTmp=NPoints;
		end
	end
	if isempty(findstr(action,'Freq')),
		[MSPointTmp]=Point2Ms(PointTmp,Domain,SampRate,TrigPoint,NPoints);
	else
		MSPointTmp=F0Vec(PointTmp);
	end
	MSPointString=sprintf('%g',round(MSPointTmp.*1000)./1000);
	if ~isempty(findstr(action,'Min'))
		NPointsTmp=MaxPointVal-PointTmp+1;
    	set(hhVec(MinPointInd),'Value',PointTmp,'String',MSPointString);
		set(hhVec(MinPointSliderInd),'Value',PointTmp); 
		if isempty(findstr(action,'Freq')),
			set(hhVec(CursPointSliderInd),'Min',PointTmp);					
			if CursPointVal<PointTmp
				set(hhVec(CursPointSliderInd),'Value',PointTmp);
				set(hhVec(CursPointInd),'Value',PointTmp,'String',MSPointString);
                Ind=findstr(CursPointText,'#');
	            if ~isempty(Ind)
		            CursPointText=[CursPointText(1:Ind),' ',int2str(PointTmp)];
	            else
		            CursPointText=[CursPointText,'; # ',int2str(PointTmp)];
	            end
                set(hhVec(15),'String',CursPointText);
			end
		end
        Ind=findstr(MinPointText,'#');
	    if ~isempty(Ind)
		    MinPointText=[MinPointText(1:Ind),' ',int2str(PointTmp)];
	    else
		    MinPointText=[MinPointText,'; # ',int2str(PointTmp)];
	    end
        set(hhVec(13),'String',MinPointText);
	elseif ~isempty(findstr(action,'Max'))
		NPointsTmp=PointTmp-MinPointVal+1;
    	set(hhVec(MaxPointInd),'Value',PointTmp,'String',MSPointString);
		set(hhVec(MaxPointSliderInd),'Value',PointTmp);
		if isempty(findstr(action,'Freq')),
			set(hhVec(CursPointSliderInd),'Max',PointTmp);
			if CursPointVal>PointTmp
				set(hhVec(CursPointSliderInd),'Value',PointTmp);
				set(hhVec(CursPointInd),'Value',PointTmp,'String',MSPointString);
                Ind=findstr(CursPointText,'#');
	            if ~isempty(Ind)
		            CursPointText=[CursPointText(1:Ind),' ',int2str(PointTmp)];
	            else
		            CursPointText=[CursPointText,'; # ',int2str(PointTmp)];
	            end
                set(hhVec(15),'String',CursPointText);
			end
		end
        Ind=findstr(MaxPointText,'#');
	    if ~isempty(Ind)
		    MaxPointText=[MaxPointText(1:Ind),' ',int2str(PointTmp)];
	    else
		    MaxPointText=[MaxPointText,'; # ',int2str(PointTmp)];
	    end
        set(hhVec(14),'String',MaxPointText);
	end	
	if isempty(findstr(action,'Freq')),
		if NPointsTmp>=10
			SliderStep=[1./NPointsTmp 10./NPointsTmp];
		else
			SliderStep=[.1 1];
		end
		set(hhVec(CursPointSliderInd),'SliderStep',SliderStep);
	end
	if ~isempty(findstr(action,'setGP')),
		emegs2d('setGPMinMaxAmpPoint');
	elseif ~isempty(findstr(action,'setBut')),
		emegs2d('setButMinMaxAmpPoint');	
	elseif ~isempty(findstr(action,'setSpecChan')),
		emegs2d('setSpecChanMinMaxAmpPoint'); 
	end;

	%=============================================================================
	%============ setButCursorPoint | setSpecChanCursorPoint | setSpecChanCursorPoint
	%============ call: setButCursorText | setSpecChanCursorText
	%=============================================================================	
elseif  strcmp(action,'setGPCursorPoint') | ...
		strcmp(action,'setGPCursorPointSlider') | ...
		strcmp(action,'setButCursorPoint') | ...
		strcmp(action,'setButCursorPointSlider') | ...
		strcmp(action,'setSpecChanCursorPoint') | ...
		strcmp(action,'setSpecChanCursorPointSlider')
	 
	hList=get(hPlot2dMenuFig,'Userdata');
    if  strcmp(action,'setGPCursorPoint') | ...
		strcmp(action,'setGPCursorPointSlider') 
		hhVec=get(hList(66),'Userdata');
        hhGPVec=get(hList(66),'Userdata');
        GPMinAmp=get(hhGPVec(1),'Value');
        GPMaxAmp=get(hhGPVec(2),'Value');
		GPMinPoint=get(hhGPVec(3),'Value');
		GPMaxPoint=get(hhGPVec(4),'Value');
	elseif  strcmp(action,'setButCursorPoint') | ...
	 	strcmp(action,'setButCursorPointSlider') 
		hhVec=get(hList(63),'Userdata');
	elseif strcmp(action,'setSpecChanCursorPoint') | ...
		strcmp(action,'setSpecChanCursorPointSlider') 
		hhVec=get(hList(64),'Userdata'); 
	end;
	MinPoint=get(hhVec(3),'Value');
	MaxPoint=get(hhVec(4),'Value');
    CursPointText=get(hhVec(15),'String');
	TrigPoint=get(hList(22),'Value');
	SampRate = get(hList(60),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	Domain=get(hList(20),'value');	
    Toggle3dMovie = findobj('tag','Toggle3dMovie');
    
    
    if Domain == 7 | Domain == 8
        if strcmp(action,'setGPCursorPoint') | strcmp(action,'setGPCursorPointSlider')
			GPMinFreqVal = str2num(get(hhGPVec(24),'String'));
			GPMaxFreqVal = str2num(get(hhGPVec(26),'String'));
        elseif strcmp(action,'setSpecChanCursorPoint') | strcmp(action,'setSpecChanCursorPointSlider')
            MinFreqVal = str2num(get(hhVec(24),'String'));
			MaxFreqVal = str2num(get(hhVec(26),'String'));
        end
    end
	
	if ~(strcmp(action,'setGPCursorPointSlider') | strcmp(action,'setButCursorPointSlider') | strcmp(action,'setSpecChanCursorPointSlider'))
    	CursPoint=get(hhVec(5),'Value');
		CursPointString=get(hhVec(5),'String');
		[CursPointTmp]=String2Value(CursPointString);
		[CursPointTmp]=Ms2Point(CursPointTmp,Domain,SampRate,TrigPoint,NPoints)		
    	if  CursPointTmp>NPoints 
			CursPointTmp=NPoints;
		elseif CursPointTmp<1 
			CursPointTmp=1;
		elseif length(CursPointTmp)~=1  
        	CursPointTmp = CursPoint;	
		elseif CursPointTmp>MaxPoint 
			CursPointTmp = MaxPoint;
		elseif CursPointTmp<MinPoint
			CursPointTmp=MinPoint;
		end
		set(hhVec(20),'Value',CursPointTmp);
	else
		CursorPointSlider = get(hhVec(20),'Value');
		CursPointTmp = round(CursorPointSlider);
	end
	if strcmp(action,'setGPCursorPoint') | strcmp(action,'setGPCursorPointSlider')
        if Domain == 8
            axes(hhGPVec(17));
            holdstatus = ishold;
            if holdstatus==0
                hold on
            end
			set(hList(74),'XData',[CursPointTmp CursPointTmp],'YData',[GPMinFreqVal GPMaxFreqVal],'ZData',[1 1]);			%hGlobPowCursorLine
			set(hList(68),'Userdata',CursPointTmp);
            if holdstatus==0
                hold off
            end
        else
			set(hList(74),'XData',[CursPointTmp CursPointTmp],'YData',[GPMinAmp GPMaxAmp],'ButtonDownFcn','emegs2d(''ScrollGPCursPlot'')');			%hGlobPowCursorLine
			set(hList(68),'Userdata',CursPointTmp);
        end
	else
        if Domain == 8
            set(hhVec(7),'XData',[CursPointTmp CursPointTmp],'YData',[MinFreqVal MaxFreqVal],'ZData',[1 1]);
        else
		    set(hhVec(7),'XData',[CursPointTmp CursPointTmp]);
        end
	end
	[CursPointStr]=Point2Ms(CursPointTmp,Domain,SampRate,TrigPoint,NPoints);
	CursPointStr = sprintf('%g',round(CursPointStr.*1000)./1000);
	set(hhVec(5),'Value',CursPointTmp,'String',CursPointStr);	
    Ind=findstr(CursPointText,'#');
	if ~isempty(Ind)
		CursPointText=[CursPointText(1:Ind),' ',int2str(CursPointTmp)];
	else
		CursPointText=[CursPointText,'; # ',int2str(CursPointTmp)];
	end
    set(hhVec(15),'String',CursPointText);
	if  strcmp(action,'setGPCursorPoint') | strcmp(action,'setGPCursorPointSlider') 
		emegs2d('setGlobPowCursorText')	
        if get(Toggle3dMovie,'Value')==1
            emegs2d('MovieUpdateGPCursor','norepeat')
        end
	elseif  strcmp(action,'setButCursorPoint') | strcmp(action,'setButCursorPointSlider') 
		emegs2d('setButCursorText');
	elseif strcmp(action,'setSpecChanCursorPoint') | strcmp(action,'setSpecChanCursorPointSlider') 
		emegs2d('setSpecChanCursorText');	 
	end
	%=============================================================================
	%============ ScrollGPCursPlot
	%=============================================================================	
elseif strcmp(action,'ScrollGPCursPlot')
    
    hList=get(hPlot2dMenuFig,'Userdata');
    hhVec=get(hList(66),'Userdata');
    hhGPVec=get(hList(66),'Userdata');
    pos = get(hhGPVec(17),'position'); 
    startpt = get(hList(71),'CurrentPoint');
    startpt = startpt - [pos(1), pos(2)];
    set(gcf,'Pointer','right')
    set(hList(71),'WindowButtonMotionFcn','emegs2d(''DragGPCursor'')','WindowButtonUpFcn','emegs2d(''StopDragGPCursor'')','userdata',startpt);
    
    
	%=============================================================================
	%============ StopDragGPCursor
	%=============================================================================	
elseif strcmp(action,'StopDragGPCursor')
      
    hList=get(hPlot2dMenuFig,'Userdata');
    hhVec=get(hList(66),'Userdata');
    hList=get(hPlot2dMenuFig,'Userdata');
    hhVec=get(hList(66),'Userdata');
    hhGPVec=get(hList(66),'Userdata');
    GPMinAmp=get(hhGPVec(1),'Value');
    GPMaxAmp=get(hhGPVec(2),'Value');
    GPMinPoint=get(hhGPVec(3),'Value');
    GPMaxPoint=get(hhGPVec(4),'Value');
	MinPoint=get(hhVec(3),'Value');
	MaxPoint=get(hhVec(4),'Value');
    CursPointText=get(hhVec(15),'String');
	TrigPoint=get(hList(22),'Value');
	SampRate = get(hList(60),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	Domain=get(hList(20),'value');	
    
    set(hList(71),'WindowButtonMotionFcn','','WindowButtonUpFcn','','userdata',[]);
    set(gcf,'Pointer','arrow')
    xdat = get(hList(74),'XData');
    set(hhGPVec(5),'String',Point2Ms(xdat(1),Domain,SampRate,TrigPoint,NPoints));
    emegs2d('setGPCursorPoint');
    Toggle3dMovie = findobj('tag','Toggle3dMovie');
    if get(Toggle3dMovie,'Value')==1
        emegs2d('setGP2Emegs3dCursor');
    end
    
 	%=============================================================================
	%============ MovieUpdateGPCursor
	%=============================================================================	
elseif strcmp(action,'MovieUpdateGPCursor')
      
    hList=get(hPlot2dMenuFig,'Userdata');
    hhVec=get(hList(66),'Userdata');
    hList=get(hPlot2dMenuFig,'Userdata');
    hhVec=get(hList(66),'Userdata');
    hhGPVec=get(hList(66),'Userdata');
    GPMinAmp=get(hhGPVec(1),'Value');
    GPMaxAmp=get(hhGPVec(2),'Value');
    GPMinPoint=get(hhGPVec(3),'Value');
    GPMaxPoint=get(hhGPVec(4),'Value');
	MinPoint=get(hhVec(3),'Value');
	MaxPoint=get(hhVec(4),'Value');
    CursPointText=get(hhVec(15),'String');
	TrigPoint=get(hList(22),'Value');
	SampRate = get(hList(60),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	Domain=get(hList(20),'value');	
    xdat = get(hList(74),'XData');
    set(hhGPVec(5),'String',Point2Ms(xdat(1),Domain,SampRate,TrigPoint,NPoints));
    if isempty(varargin)
        emegs2d('setGPCursorPoint');
    end
    emegs2d('setGP2Emegs3dCursor');   
    
	%=============================================================================
	%============ DragGPCursor
	%=============================================================================	
elseif strcmp(action,'DragGPCursor')
     
    hList=get(hPlot2dMenuFig,'Userdata');
    hhVec=get(hList(66),'Userdata');
    hhGPVec=get(hList(66),'Userdata');
    
    xl = get(hhGPVec(17),'xlim');
    pos = get(hhGPVec(17),'position'); 
    units_per_width =  diff(xl)/pos(3);
    startpt = get(hList(71),'UserData');
    endpt = get(hList(71),'CurrentPoint');
    endpt = endpt - [pos(1), pos(2)];
    diffpt = endpt(1) - startpt(1);
    xdat = get(hList(74),'XData');
    set(hList(74),'XData',xdat + diffpt*units_per_width);
    set(hList(71),'userdata',endpt);
    
    Toggle3dMovie = findobj('tag','Toggle3dMovie');
    if get(Toggle3dMovie,'Value')==1
        emegs2d('MovieUpdateGPCursor');
    end
        
    
    
	%=============================================================================
	%============ setButCursorText | setSpecChanCursorText
	%=============================================================================	
elseif strcmp(action,'setButCursorText') | strcmp(action,'setSpecChanCursorText')

	hList=get(hPlot2dMenuFig,'Userdata');
	TrigPoint=get(hList(22),'Value');
	SampRate = get(hList(60),'Userdata');
	Domain=get(hList(20),'value');
	NListHdr=get(hList(51),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');

	if  strcmp(action,'setButCursorText') 
		hhVec=get(hList(63),'Userdata');
	elseif strcmp(action,'setSpecChanCursorText') 
		hhVec=get(hList(64),'Userdata'); 
	end;
	MaxAmp=get(hhVec(2),'Value');
	MinAmp=get(hhVec(1),'Value');
	MaxPoint=get(hhVec(4),'Value');
	MinPoint=get(hhVec(3),'Value');
	CursorPoint=get(hhVec(5),'Value');
	if Domain<3 | Domain==6 | Domain==7	
		CursorString=num2str((CursorPoint-TrigPoint).*1000./SampRate);
	else
		CursorString=num2str(round(CursorPoint.*SampRate./(2.*NPoints)));
	end;
	set(hhVec(9),'Position',[CursorPoint+(MaxPoint-MinPoint)/100 MinAmp+(MaxAmp-MinAmp)/20],'Visible','on','String',CursorString);
	if strcmp(action,'setSpecChanCursorText')
		SpecChan=hhVec(10);
		NListHdr=get(hList(51),'Userdata');
		FileNoVec=get(hList(56),'Userdata');
		NUsedFiles=length(FileNoVec);
		for FileIndex=1:NUsedFiles
			ActColor=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+16),'Userdata');
			CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
			SpecChanVec=CalcAvgMat(SpecChan,:);	
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+29), ...
			'Position',[CursorPoint (0.95-(FileNoVec(FileIndex)-1).*0.075).*MaxAmp], ...
			'Visible','on', ...
			'String',num2str(round(SpecChanVec(CursorPoint).*100)./100), ...
			'Color',ActColor);
		end;
	end;
	%=============================================================================
	%============ SurfDataMatrix
	%=============================================================================	
elseif strcmp(action,'SurfDataMatrix'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
		
	MinAmp=get(hList(52),'Value');
	MaxAmp=get(hList(53),'Value');
	MinPoint=get(hList(54),'Value');
	MaxPoint=get(hList(55),'Value');
	NChan=get(hList(NListHdr+(ActFileNo-1)*50+2),'Userdata');
	NPoints=get(hList(NListHdr+(ActFileNo-1)*50+3),'Userdata');

	TrigPoint=get(hList(22),'Value');
	CursorPoint=get(hList(23),'Value');
	
	kActAxes=get(hList(27),'Userdata');
	ActAxes=get(hList(28),'Userdata');
	TrigLength=1;	%TrigLength=get(hList(29),'Userdata');
	CursorLength=1;	%CursorLength=get(hList(30),'Userdata'); 
	
	MainMatlabVersion=get(hList(100),'Userdata');
	EegMegStatusString=get(hList(110),'String');
	if strcmp(EegMegStatusString,'EEG'); EegMegString='Potential [µV]'; else; EegMegString='Field [fT]'; end
	
	if NUsedFiles<3
      		if strcmp(computer,'PCWIN') | strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
       			FigPos=[0.01 0.66 0.66 0.33];
       		elseif strcmp(computer,'SOL2') | strcmp(computer,'LNX86') | strcmp(computer,'GLNX86')
          		FigPos=[0.01 0.60 0.66 0.33];
       		end;   
  	else
       		if strcmp(computer,'PCWIN') | strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
       			FigPos=[0 0.33 0.66 0.66];
       		elseif strcmp(computer,'SOL2') | strcmp(computer,'LNX86')  | strcmp(computer,'GLNX86')
          		FigPos=[0.01 0.27 0.66 0.66];
       		end; 
	end;	
	hSurfFig=figure('Units','normal','NumberTitle','off','Position',FigPos,'Name','Surf Data Matrix');	
	
	for FileIndex=1:NUsedFiles
		if NUsedFiles<3
			subplot(1,NUsedFiles,FileIndex)	
		else
			subplot(2,ceil(NUsedFiles./2),FileIndex)
		end	
		CalcAvgMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		surf(CalcAvgMat','EdgeColor','none')
        shading interp;
		axis([1 NChan MinPoint MaxPoint MinAmp MaxAmp])
		xlabel('Channel')
		ylabel('Time')
		zlabel(EegMegString)
		title(['File:',int2str(FileNoVec(FileIndex))]);
	end
	
	%=============================================================================
	%============ setActSpecVisible | setAllSpecVisible:
	%============		visibility of special channel
	%=============================================================================	
elseif (strcmp(action,'setActSpecVisible') | strcmp(action,'setAllSpecVisible')),

	hList=get(hPlot2dMenuFig,'Userdata');

	hActSpecVisible=hList(45);
	ActSpecVisChanVal=get(hActSpecVisible,'Value');
	hAllSpecVisible=hList(47);
	AllSpecVisChanVal=get(hAllSpecVisible,'Value');
    
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
    
	if (strcmp(action,'setActSpecVisible') & ActSpecVisChanVal==1)
        hDataVec=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+25),'Userdata');
        for ChanInd=1:length(hDataVec)
            set(hDataVec(ChanInd),'Visible','on');
        end
    elseif  (strcmp(action,'setAllSpecVisible') & AllSpecVisChanVal==1)
        for FileInd=1:NUsedFiles
            hDataVec=get(hList(NListHdr+(FileNoVec(FileInd)-1).*50+25),'Userdata');
            for ChanInd=1:length(hDataVec)
                set(hDataVec(ChanInd),'Visible','on');
            end
        end
	else
		if strcmp(action,'setActSpecVisible')
			SpecChan=ActSpecVisChanVal-1;
		else
			SpecChan=AllSpecVisChanVal-1;
		end					
		hDataVec=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+25),'Userdata');
		VisibleStatus=get(hDataVec(SpecChan),'Visible');
		if strcmp(action,'setActSpecVisible');
			if strcmp(VisibleStatus,'off');
				set(hDataVec(SpecChan),'Visible','on');
			elseif strcmp(VisibleStatus,'on');
				set(hDataVec(SpecChan),'Visible','off');
			end
		elseif strcmp(action,'setAllSpecVisible');
			for FileInd=1:NUsedFiles
				hDataVec=get(hList(NListHdr+(FileNoVec(FileInd)-1).*50+25),'Userdata');
				if strcmp(VisibleStatus,'off');
					set(hDataVec(SpecChan),'Visible','on');
				elseif strcmp(VisibleStatus,'on');
					set(hDataVec(SpecChan),'Visible','off');
				end
			end
		end
	end
      
	%=============================================================================
	%============ setActAllVisible
	%============ Visibility of all channels
	%=============================================================================	
elseif strcmp(action,'setActAllVisible'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	hActAllVisible=hList(109);
	VisibleStatus=get(hActAllVisible,'Value');
	VisibleStatusVec=get(hActAllVisible,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NActChan=length(kActAxes);
	hDataVec=get(hList(NListHdr+(ActFileNo-1).*50+25),'Userdata');
	set(hList(NListHdr+(ActFileNo-1).*50+18),'Userdata',VisibleStatus);

	if VisibleStatus==1
		for ChanInd=1:NActChan
			set(hDataVec(ChanInd),'Visible','on');
		end
		VisibleStatusVec(ActFileNo)=1;
	elseif VisibleStatus==0
		for ChanInd=1:NActChan
			set(hDataVec(ChanInd),'Visible','off');
		end
		VisibleStatusVec(ActFileNo)=0;
	end
	set(hActAllVisible,'Userdata',VisibleStatusVec);
    
    
   %=============================================================================
	%============ HelpBrowser
	%=============================================================================	
elseif strcmp(action,'HelpBrowser')
    
    helpwin;
    [nouse,emegspath] = sepfilepath(which('emegs2d.m'));
    web(['file:',[emegspath,'emegsHelp','\','index.html']])
    
   %=============================================================================
	%============ MFileHelp
	%=============================================================================	
elseif strcmp(action,'MFileHelp')
    
    helpwin;
    [nouse,emegspath] = sepfilepath(which('emegs2d.m'));
    helpwin( emegspath);
      
   %=============================================================================
	%============ LastOpenFile
	%=============================================================================	
elseif strcmp(action,'LastOpenFile1') | ...
        strcmp(action,'LastOpenFile2') | ...
        strcmp(action,'LastOpenFile3') | ...
        strcmp(action,'LastOpenFile4') | ...
        strcmp(action,'LastOpenFile5') | ...
        strcmp(action,'LastOpenFile6') 
    
        
    
	%=============================================================================
	%============ DispENames: display number of sensors
	%=============================================================================
elseif strcmp(action,'DispENames'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	hhText1=get(hList(11),'Userdata');
	hAxesVec=get(hList(6),'Userdata');
	kActAxes=get(hList(27),'Userdata');
   	FontSizeVec=get(hList(112),'Userdata');

	NActChan=length(kActAxes);
	for ChanInd=1:NActChan
		VisibleStatus=get(hhText1(kActAxes(ChanInd)),'Visible');
		if strcmp(VisibleStatus,'on')
			set(hhText1(kActAxes(ChanInd)),'Visible','off');		
		else
      		set(hhText1(kActAxes(ChanInd)),'FontSize',FontSizeVec(2),'Visible','on');	
      	end
	end

	%------------------ change index position in menu ----------------
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	hTextMenu=get(hStyleMenu(6),'children');
	DisplayTextLabel=get(hTextMenu(7),'Label');
	pointer=get(hList(83),'Userdata');
	PointPos=get(hTextMenu(7),'Userdata');
	
	if strcmp(VisibleStatus,'on')
		DisplayTextLabel(PointPos)=' ';
	else	
		DisplayTextLabel(PointPos)=setstr(pointer);
	end;	
	set(hTextMenu(7),'Label',DisplayTextLabel);
	%set(hList(65),'Userdata',hTopMenu);
	
	%=============================================================================
	%============ DispCursorAmp: display cursoramplitudes
	%=============================================================================		
elseif strcmp(action,'DispCursorAmp') | strcmp(action,'DispCursorAmpActFileNo'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	CursorPoint=get(hList(23),'Value');
	if CursorPoint==0; return; end
	CursorDec=get(hList(24),'Userdata');
	
	hhText2=get(hList(12),'Userdata');
	hAxesVec=get(hList(6),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NActChan=length(kActAxes);
	
	MaxAmp=get(hList(53),'Value');
	
	ColorRGB =get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+16),'Userdata');
	CalcAvgMat=get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+1),'Userdata');
	CalcAvgCursorVec=round(CalcAvgMat(:,CursorPoint).*10.^CursorDec)./10.^CursorDec;
	
	if strcmp(action,'DispCursorAmp')
		for ChanInd=1:NActChan
			VisibleStatus=get(hhText2(kActAxes(ChanInd)),'Visible');
			if strcmp(VisibleStatus,'on')
				set(hhText2(kActAxes(ChanInd)),'Visible','off');
			else
				set(hhText2(kActAxes(ChanInd)),'Visible','on','String',[num2str(CalcAvgCursorVec(ChanInd))],'Position',[CursorPoint .8.*MaxAmp],'Color',ColorRGB);
			end
		end
		%------------------ change index position in menu ----------------
		hTopMenu=get(hList(65),'Userdata');
		hStyleMenu=get(hTopMenu(2),'children');
		pointer=get(hList(83),'Userdata');
		hTextMenu=get(hStyleMenu(6),'children');
		DisplayTextLabel=get(hTextMenu(5),'Label');
		PointPos=get(hTextMenu(5),'Userdata');
		if strcmp(VisibleStatus,'on') 
			DisplayTextLabel(PointPos)=' ';
		else	
			DisplayTextLabel(PointPos)=setstr(pointer);
		end;	
		set(hTextMenu(5),'Label',DisplayTextLabel);
	elseif strcmp(action,'DispCursorAmpActFileNo'),
		for ChanInd=1:NActChan
			set(hhText2(kActAxes(ChanInd)),'Visible','on','String',[num2str(CalcAvgCursorVec(ChanInd))],'Position',[CursorPoint .8.*MaxAmp],'Color',ColorRGB);
		end
	end;
	%=============================================================================
	%============ DispNTrials: display number of trials
	%=============================================================================		
elseif strcmp(action,'DispNTrials') | strcmp(action,'DispNTrialsActFileNo'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');

	hhText3=get(hList(13),'Userdata');
	hAxesVec=get(hList(6),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NActChan=length(kActAxes);
	
	ColorRGB =get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+16),'Userdata');
	NTrialAvgVec=get(hList(NListHdr+(ActFileNo-1).*50+5),'Userdata');
	if strcmp(action,'DispNTrials')
		for ChanInd=1:NActChan
			VisibleStatus=get(hhText3(kActAxes(ChanInd)),'Visible');
			if strcmp(VisibleStatus,'on')
				set(hhText3(kActAxes(ChanInd)),'Visible','off');
			else
				set(hhText3(kActAxes(ChanInd)),'Visible','on','String',[num2str(NTrialAvgVec(kActAxes(ChanInd)))],'Color',ColorRGB);
			end
		end
		%------------------ change index position in menu ----------------
		hTopMenu=get(hList(65),'Userdata');
		hStyleMenu=get(hTopMenu(2),'children');
		hTextMenu=get(hStyleMenu(6),'children');
		DisplayTextLabel=get(hTextMenu(4),'Label');
		pointer=get(hList(83),'Userdata');
		PointPos=get(hTextMenu(4),'Userdata');
	
		if strcmp(VisibleStatus,'on')
			DisplayTextLabel(PointPos)=' ';
		else	
			DisplayTextLabel(PointPos)=setstr(pointer);
		end
		set(hTextMenu(4),'Label',DisplayTextLabel);
	elseif strcmp(action,'DispNTrialsActFileNo')
		for ChanInd=1:NActChan
			set(hhText3(kActAxes(ChanInd)),'Visible','on','String',[num2str(NTrialAvgVec(kActAxes(ChanInd)))],'Color',ColorRGB);
		end
	end

	%=============================================================================
	%============ DispMeanStd
	%=============================================================================		
elseif strcmp(action,'DispMeanStd') | strcmp(action,'DispMeanStdActFileNo'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	CursorPoint=get(hList(23),'Value');

	hhText4=get(hList(14),'Userdata');
	hAxesVec=get(hList(6),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NActChan=length(kActAxes);
	
	ColorRGB =get(hList(NListHdr+(FileNoVec(ActFileNo)-1).*50+16),'Userdata');
	StdChanTimeMat=get(hList(NListHdr+(ActFileNo-1).*50+6),'Userdata');
	MeanStdChanTimeVec=(round(mean(StdChanTimeMat).*100))./100;
	if strcmp(action,'DispMeanStd')
		for ChanInd=1:NActChan
			if CursorPoint==0;
				set(hhText4(kActAxes(ChanInd)),'Visible','off');
			else
				VisibleStatus=get(hhText4(kActAxes(ChanInd)),'Visible');
				if strcmp(VisibleStatus,'on')
					set(hhText4(kActAxes(ChanInd)),'Visible','off');
				else
					set(hhText4(kActAxes(ChanInd)),'Visible','on','String',[num2str(MeanStdChanTimeVec(kActAxes(ChanInd)))],'Color',ColorRGB);
				end
			end
		end
		%------------------ change index position in menu ----------------
		hTopMenu=get(hList(65),'Userdata');
		hStyleMenu=get(hTopMenu(2),'children');
		hTextMenu=get(hStyleMenu(6),'children');
		DisplayTextLabel=get(hTextMenu(3),'Label');
		pointer=get(hList(83),'Userdata');
		PointPos=get(hTextMenu(3),'Userdata');
		if strcmp(VisibleStatus,'on')
			DisplayTextLabel(PointPos)=' ';
		else	
			DisplayTextLabel(PointPos)=setstr(pointer);
		end;	
		set(hTextMenu(3),'Label',DisplayTextLabel);
	elseif strcmp(action,'DispMeanStdActFileNo')
		for ChanInd=1:NActChan
			if CursorPoint==0;
				set(hhText4(kActAxes(ChanInd)),'Visible','off');
			else
				set(hhText4(kActAxes(ChanInd)),'Visible','on','String',[num2str(MeanStdChanTimeVec(kActAxes(ChanInd)))],'Color',ColorRGB);
			end
		end
	end

	
	%=============================================================================
	%============ DispLREarNoseText
	%=============================================================================		
elseif strcmp(action,'DispLREarNoseText'),

	hList=get(hPlot2dMenuFig,'Userdata');
	hhText5=get(hList(15),'Userdata');
	hhText5VisVal=get(hList(15),'value');
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	hTextMenu=get(hStyleMenu(6),'children');

	DisplayTextLabel=get(hTextMenu(2),'Label');
	pointer=get(hList(83),'Userdata');
	PointPos=get(hTextMenu(2),'Userdata');
	
	if hhText5VisVal					
		hhText5VisVal=0;				
		set(hhText5,'Visible','off');	
		DisplayTextLabel(PointPos)=' ';			    % change index position in menu 
	else								
		hhText5VisVal=1;				
		set(hhText5,'Visible','on');	
		DisplayTextLabel(PointPos)=setstr(pointer);	% change index position in menu 
	end;								
	
	set(hList(15),'Value',hhText5VisVal);
	set(hTextMenu(2),'Label',DisplayTextLabel);
	%set(hList(65),'Userdata',hTopMenu);

	%=============================================================================
	%============ ChangeLREarNoseTextPosition
	%=============================================================================	
elseif strcmp(action,'ChangeLREarNoseTextPosition'),

	hList=get(hPlot2dMenuFig,'Userdata');
	hhText5=get(hList(15),'Userdata');

	hhText5VisVal = get(hList(15),'value');	
	LeftLeftEarPosMat=get(hhText5(1),'Userdata');
	EarLeftEarPosMat=get(hhText5(2),'Userdata');
	RightRightEarPosMat=get(hhText5(3),'Userdata');
	EarRightEarPosMat=get(hhText5(4),'Userdata');
	NosePosMat=get(hhText5(5),'Userdata');
	hPlot2dChanAxes=get(hList(25),'Userdata');
	ViewVal=get(hList(26),'value');
	MainMatlabVersion=get(hList(100),'Userdata');	
	
	if MainMatlabVersion > 4					
		set(hhText5,'Parent',hPlot2dChanAxes);		
	end;										
	
	set(hhText5(1),'Position',LeftLeftEarPosMat(ViewVal,:));		
	set(hhText5(2),'Position',EarLeftEarPosMat(ViewVal,:));		
	set(hhText5(3),'Position',RightRightEarPosMat(ViewVal,:));		
	set(hhText5(4),'Position',EarRightEarPosMat(ViewVal,:));		
	set(hhText5(5),'Position',NosePosMat(ViewVal,:));	
	if hhText5VisVal	
		set(hhText5,'Visible','on');
		if 	ViewVal==1;		%Top
			set(hhText5(5),'Visible','off');	
		elseif 	ViewVal==2; %Front
			set(hhText5(5),'Visible','off');
		elseif 	ViewVal==3; %Back
			set(hhText5(5),'Visible','off');	
		elseif 	ViewVal==3; %Left
			set(hhText5(3:4),'Visible','off');	
		elseif 	ViewVal==3; %Right
			set(hhText5(1:2),'Visible','off');	
		end
	end;
	
	%=============================================================================
	%============ ChangeBlackWhiteTextLineColor
	%=============================================================================		
elseif strcmp(action,'ChangeBlackWhiteTextLineColor'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ChanFigBGColor=get(hList(93),'Color');	%hChanFig
	
	for TextInd=1:5
		hhText=get(hList(10+TextInd),'Userdata');
		hhTextColor=get(hhText(1),'Color');
		if ChanFigBGColor==[1 1 1] & hhTextColor==[1 1 1]
			for ChanInd=1:length(hhText)
				set(hhText(ChanInd),'Color',[0 0 0]);
			end
		end
		if ChanFigBGColor==[0 0 0] & hhTextColor==[0 0 0]
			for ChanInd=1:length(hhText)
				set(hhText(ChanInd),'Color',[1 1 1]);
			end
		end
	end
	
	for LineInd=1:3
		hhLine=get(hList(7+LineInd),'Userdata');
		LineColor=get(hhLine(1),'Color');
		if ChanFigBGColor==[1 1 1] & LineColor==[1 1 1]
			for ChanInd=1:length(hhLine)
				set(hhLine(ChanInd),'Color',[0 0 0]);
			end
		end
		if ChanFigBGColor==[0 0 0] & LineColor==[0 0 0]
			for ChanInd=1:length(hhLine)
				set(hhLine(ChanInd),'Color',[1 1 1]);
			end
		end
	end
	for SpecLineInd=1:4
		hSpecLine=get(hList(76+SpecLineInd),'Userdata');
		SpecLineColor=get(hSpecLine,'Color');
		if ChanFigBGColor==[1 1 1] & SpecLineColor==[1 1 1]
			set(hSpecLine,'Color',[0 0 0]);	
		end
		if ChanFigBGColor==[0 0 0] & SpecLineColor==[0 0 0]
			set(hSpecLine,'Color',[1 1 1]);	
		end
	end
	hSpec1Axes=get(hList(76),'Userdata');
	Spec1AxesColor=get(hSpec1Axes,'XColor');
	if ChanFigBGColor==[1 1 1] & Spec1AxesColor==[1 1 1]
		set(hSpec1Axes,'XColor',[0 0 0],'YColor',[0 0 0])	
	end
	if ChanFigBGColor==[0 0 0] & Spec1AxesColor==[0 0 0]
		set(hSpec1Axes,'XColor',[1 1 1],'YColor',[1 1 1])	
	end

	%=============================================================================
	%============ setCursorTextPos
	%=============================================================================	
elseif strcmp(action,'setCursorTextPos'),

	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	MaxAmp=get(hList(53),'Value');
	CursorPoint=get(hList(23),'Value');
	hhText2=get(hList(12),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NActChan=length(kActAxes);
	ColorRGB=get(hList(NListHdr+(ActFileNo-1).*50+16),'Userdata');
	for ChanInd=1:NActChan
		set(hhText2(kActAxes(ChanInd)),'Position',[CursorPoint .8.*MaxAmp]);
	end

	%=============================================================================
	%============ setCursorTextColor
	%=============================================================================	
elseif strcmp(action,'setCursorTextColor'),

	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	hhText2=get(hList(12),'Userdata');
	kActAxes=get(hList(27),'Userdata');
	NActChan=length(kActAxes);
	ColorRGB=get(hList(NListHdr+(ActFileNo-1).*50+16),'Userdata');
	% only, if sensor file opened
	for ChanInd=1:NActChan
		set(hhText2(kActAxes(ChanInd)),'Color',ColorRGB);
	end

	%=============================================================================
	%============ setChanFigBGColorBlack, setChanFigBGColorWhite:
	%============		background color
	%=============================================================================	
elseif strcmp(action,'setChanFigBGColorBlack') | ...
	   strcmp(action,'setChanFigBGColorWhite'),

	hList=get(hPlot2dMenuFig,'Userdata');
	
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	pointer=get(hList(83),'Userdata');
	hBGColor=get(hStyleMenu(1),'children');
	BGColorWhiteLabel=get(hBGColor(2),'Label');
	WhitePointPos=get(hBGColor(2),'Userdata');
	
	BGColorBlackLabel=get(hBGColor(1),'Label');
	BlackPointPos=get(hBGColor(1),'Userdata');
	
	if strcmp(action,'setChanFigBGColorBlack')
		RGBColor=[0 0 0];
		XColor=[1 1 1];
		BGColorWhiteLabel(WhitePointPos)=' ';
		BGColorBlackLabel(BlackPointPos)=setstr(pointer);
	elseif strcmp(action,'setChanFigBGColorWhite')
		RGBColor=[1 1 1];
		XColor=[0 0 0];
		BGColorWhiteLabel(WhitePointPos)=setstr(pointer);
		BGColorBlackLabel(BlackPointPos)=' ';
	end
	set(hList(93),'Color',RGBColor);		%hChanFig
	hSpec1Axes=get(hList(76),'Userdata');
	hSpec2Axes=get(hList(104),'Userdata');
	set(hSpec1Axes,'Color',RGBColor);
%  	set(hSpec2Axes,'Color',RGBColor,'XColor',XColor,'YColor',RGBColor,'ZColor',RGBColor);
% 	hSpec2AxesChildVec=get(hSpec2Axes,'Children');
% 	for i=2:6
% 		set(hSpec2AxesChildVec(i),'Color',XColor)
% 	end
% 	get(hSpec2AxesChildVec(7))
	set(hBGColor(2),'Label',BGColorWhiteLabel);
	set(hBGColor(1),'Label',BGColorBlackLabel);
	%set(hList(65),'Userdata',hTopMenu);
	emegs2d('ChangeBlackWhiteTextLineColor')

elseif strcmp(action,'setSensorAxesWidth01') | ...
	strcmp(action,'setSensorAxesWidth02') | ...
	strcmp(action,'setSensorAxesWidth03') | ...
	strcmp(action,'setSensorAxesWidth04') | ...
	strcmp(action,'setSensorAxesWidth05') | ...
	strcmp(action,'setSensorAxesWidth06') | ...
	strcmp(action,'setSensorAxesWidth07') | ...
	strcmp(action,'setSensorAxesWidth08') | ...
	strcmp(action,'setSensorAxesWidth09') | ...
	strcmp(action,'setSensorAxesWidth10') | ...
	strcmp(action,'setSensorAxesWidth11') | ...
	strcmp(action,'setSensorAxesWidth12') | ...
	strcmp(action,'setSensorAxesWidth13') | ...
	strcmp(action,'setSensorAxesWidth14') | ...
	strcmp(action,'setSensorAxesWidth15') | ...
	strcmp(action,'setSensorAxesWidth16') | ...
	strcmp(action,'setSensorAxesWidth17') | ...
	strcmp(action,'setSensorAxesWidth18') | ...
	strcmp(action,'setSensorAxesWidth19') | ...
	strcmp(action,'setSensorAxesWidth20') | ...
	strcmp(action,'setSensorAxesHeight01') | ...
	strcmp(action,'setSensorAxesHeight02') | ...
	strcmp(action,'setSensorAxesHeight03') | ...
	strcmp(action,'setSensorAxesHeight04') | ...
	strcmp(action,'setSensorAxesHeight05') | ...
	strcmp(action,'setSensorAxesHeight06') | ...
	strcmp(action,'setSensorAxesHeight07') | ...
	strcmp(action,'setSensorAxesHeight08') | ...
	strcmp(action,'setSensorAxesHeight09') | ...
	strcmp(action,'setSensorAxesHeight10') | ...
	strcmp(action,'setSensorAxesHeight11') | ...
	strcmp(action,'setSensorAxesHeight12') | ...
	strcmp(action,'setSensorAxesHeight13') | ...
	strcmp(action,'setSensorAxesHeight14') | ...
	strcmp(action,'setSensorAxesHeight15') | ...
	strcmp(action,'setSensorAxesHeight16') | ...
	strcmp(action,'setSensorAxesHeight17') | ...
	strcmp(action,'setSensorAxesHeight18') | ...
	strcmp(action,'setSensorAxesHeight19') | ...
	strcmp(action,'setSensorAxesHeight20'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	%------------------ change index position in menu ----------------
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	hAxesMenu=get(hStyleMenu(8),'children');
	pointer=get(hList(83),'Userdata');
	if strcmp(action(14:18),'Width')
		TmpInd=2;
		NewVal=String2Value(action(19:20));
	else
		TmpInd=1;
		NewVal=String2Value(action(20:21));
	end
	OldVal=get(hAxesMenu(TmpInd),'Userdata');
	hTmpVec=get(hAxesMenu(TmpInd),'children');
	NTmpVec=length(hTmpVec);
	for Ind=1:NTmpVec
		ValLabel=get(hTmpVec(Ind),'Label');
		PointPos=get(hTmpVec(Ind),'Userdata');
		if (NTmpVec-Ind+1)==NewVal; ValLabel(PointPos)=setstr(pointer);
		elseif (NTmpVec-Ind+1)==OldVal; ValLabel(PointPos)=' ';
		end;
		set(hTmpVec(Ind),'Label',ValLabel);
	end;	
	set(hAxesMenu(TmpInd),'Userdata',NewVal);
	AxesPosMat=get(hList(5),'Userdata');
	hAxesVec=get(hList(6),'Userdata');
	if isempty(AxesPosMat); return; end
	[NChan,NonUse]=size(AxesPosMat);
	hw=NTmpVec-NewVal+1;
	NewWidthHeight=1./hw;
	if AxesPosMat(1,5-TmpInd)~=NewWidthHeight;
		AxesPosMat(:,5-TmpInd)=ones(NChan,1).*NewWidthHeight;
		set(hList(5),'Userdata',AxesPosMat);
		AxesPosMat(:,3-TmpInd)=(norm_1(AxesPosMat(:,3-TmpInd)',4,[],0,1-NewWidthHeight))';
		for ChanInd=1:NChan
			set(hAxesVec(ChanInd),'Position',AxesPosMat(ChanInd,:));
		end
	end
	%=============================================================================
	%============ setSensorLineColorGroups, setSensorLineColorGroups:
	%============		Sensor Line Color
	%=============================================================================	
elseif strcmp(action,'setSensorLineColorDefault') | ...
	strcmp(action,'setSensorLineColorNTrial') | ...
	strcmp(action,'setSensorLineColorStd') | ...
	strcmp(action,'setSensorLineColorGroups') | ...
	strcmp(action,'setSensorLineColorFlipud'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	hAxesVec=get(hList(6),'Userdata');
	NChan=length(hAxesVec);
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	pointer=get(hList(83),'Userdata');
	hSensorLineColor=get(hStyleMenu(7),'children');
	ColorVal=get(hList(61),'Value');

	SensorLineColorDefaultLabel=get(hSensorLineColor(4),'Label');
	SensorLineColorDefaultPointPos=get(hSensorLineColor(4),'Userdata');
	SensorLineColorNTrialLabel=get(hSensorLineColor(3),'Label');
	SensorLineColorNTrialPointPos=get(hSensorLineColor(3),'Userdata');
	SensorLineColorStdLabel=get(hSensorLineColor(2),'Label');
	SensorLineColorStdPointPos=get(hSensorLineColor(2),'Userdata');
	SensorLineColorGroupsLabel=get(hSensorLineColor(1),'Label');
	SensorLineColorGroupsPointPos=get(hSensorLineColor(1),'Userdata');
	
	hExportMenu=get(hTopMenu(3),'children');	
	hExportUserData=get(hExportMenu(1),'children'); 
	hUserDataInfo=get(hExportUserData(1),'children');
	
	if strcmp(action,'setSensorLineColorDefault')
		ColorVec=[1:NChan];
		SensorLineColorDefaultLabel(SensorLineColorDefaultPointPos)=setstr(pointer);
		SensorLineColorNTrialLabel(SensorLineColorNTrialPointPos)=' ';
		SensorLineColorStdLabel(SensorLineColorStdPointPos)=' ';
		SensorLineColorGroupsLabel(SensorLineColorGroupsPointPos)=' ';
		UserDataInfoLabel='Default sensor line color vector';
		Spec2AxesVal=1;
	elseif strcmp(action,'setSensorLineColorNTrial')
		ColorVec=get(hList(NListHdr+(ActFileNo-1).*50+5),'Userdata')';
		SensorLineColorDefaultLabel(SensorLineColorDefaultPointPos)=' ';
		SensorLineColorNTrialLabel(SensorLineColorNTrialPointPos)=setstr(pointer);
		SensorLineColorStdLabel(SensorLineColorStdPointPos)=' ';
		SensorLineColorGroupsLabel(SensorLineColorGroupsPointPos)=' ';
		UserDataInfoLabel='Number of trials sensor line color vector';
		Spec2AxesVal=2;
	elseif strcmp(action,'setSensorLineColorStd')
		StdChanTimeMat=get(hList(NListHdr+(ActFileNo-1).*50+6),'Userdata');
		[NChan,NPoints]=size(StdChanTimeMat);
		ColorVec=sum(StdChanTimeMat')./NPoints;
		SensorLineColorDefaultLabel(SensorLineColorDefaultPointPos)=' ';
		SensorLineColorNTrialLabel(SensorLineColorNTrialPointPos)=' ';
		SensorLineColorStdLabel(SensorLineColorStdPointPos)=setstr(pointer);   
		SensorLineColorGroupsLabel(SensorLineColorGroupsPointPos)=' ';
		UserDataInfoLabel='Std sensor line color vector';
		Spec2AxesVal=3;
	elseif strcmp(action,'setSensorLineColorGroups')
		hTopMenu=get(hList(65),'Userdata');
		hCalcMenu=get(hTopMenu(4),'children');	
		hCalcChanGroup=hCalcMenu(17);
		GroupMat=get(hCalcChanGroup,'Userdata')
		if isempty(GroupMat);
			Message=char('Sorry,');
			Message=char(Message,'');
			Message=char(Message,'no groups available.');
			Message=char(Message,'Please choose groups first.');
			Message=char(Message,'(Calculate: Sensor groups)');
			hmsgbox=msgbox(Message,'Info','help'); 
			return;
		end
		NGroup=0;
		GroupIndVec=[];
		ColorVec=zeros(NChan,1);
		WarnStatusVec=zeros(NChan,1);
		for ChanInd=1:NChan
			GroupInd=find(GroupMat(2,:)==ChanInd);
			if ~isempty(GroupInd)
				if length(GroupInd)>1
					WarnStatusVec(ChanInd)=1;
				end
				ColorVec(ChanInd)=GroupMat(1,GroupInd(1));
			end
		end
		if any(WarnStatusVec)
			Message=char('Info !');
			Message=char(Message,'');
			Message=char(Message,'The following sensors');
			Message=char(Message,'are member of different groups:');
			Message=char(Message,'');
			Message=char(Message,['Sensors: ',int2str(find(WarnStatusVec)')]);			
			hmsgbox=msgbox(Message,'Info','help'); 
		end
		SensorLineColorDefaultLabel(SensorLineColorDefaultPointPos)=' ';
		SensorLineColorStdLabel(SensorLineColorStdPointPos)=' ';
		SensorLineColorGroupsLabel(SensorLineColorGroupsPointPos)=setstr(pointer);   
		SensorLineColorNTrialLabel(SensorLineColorNTrialPointPos)=' ';
		UserDataInfoLabel='Ext. file sensor line color vector';
		Spec2AxesVal=4;
	elseif strcmp(action,'setSensorLineColorFlipud')
		SensorLineColorFlipudLabel=get(hSensorLineColor(5),'Label');
		SensorLineColorFlipudPointPos=get(hSensorLineColor(5),'Userdata');
		if strcmp(SensorLineColorFlipudLabel(SensorLineColorFlipudPointPos),' ');
			SensorLineColorFlipudLabel(SensorLineColorFlipudPointPos)=setstr(pointer);   
		else
			SensorLineColorFlipudLabel(SensorLineColorFlipudPointPos)=' ';
		end
		set(hSensorLineColor(5),'Label',SensorLineColorFlipudLabel);
		emegs2d('setColor')
		return;
	end
	set(hList(94),'Userdata',ColorVec);
	set(hUserDataInfo,'Label',UserDataInfoLabel);
	set(hList(NListHdr+(ActFileNo-1).*50+33),'Userdata',ColorVec);
	set(hExportUserData,'Enable','on');	%Export User data enable on
	set(hSensorLineColor(4),'Label',SensorLineColorDefaultLabel);
	set(hSensorLineColor(3),'Label',SensorLineColorNTrialLabel);
	set(hSensorLineColor(2),'Label',SensorLineColorStdLabel);
	set(hSensorLineColor(1),'Label',SensorLineColorGroupsLabel);
	set(hList(106),'Userdata',Spec2AxesVal);	

	if ColorVal<9
		ColorVal=14;%jet
		LineWidthVal=6;% 3 Act
		set(hList(61),'Value',ColorVal);
		set(hList(98),'Value',LineWidthVal);
		emegs2d('setLineWidth')
	end
	emegs2d('setColor')
	%=============================================================================
	%============ setZerolineVisible, setTriggerVisible, setCursorVisible
	%=============================================================================	
elseif 	strcmp(action,'setZerolineVisible') | strcmp(action,'setZerolineVisibleOn') | strcmp(action,'setZerolineVisibleOff') |...
		strcmp(action,'setTriggerVisible') | strcmp(action,'setTriggerVisibleOn') | strcmp(action,'setTriggerVisibleOff') |...
		strcmp(action,'setCursorVisible') | strcmp(action,'setCursorVisibleOn') | strcmp(action,'setCursorVisibleOff'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	
	if 		~isempty(findstr(action,'Zero')); hLineNo=8;  hSpec1No=77; index=5;
	elseif 	~isempty(findstr(action,'Trig')); hLineNo=9;  hSpec1No=78; index=4;
	elseif 	~isempty(findstr(action,'Curs')); hLineNo=10; hSpec1No=79; index=3;
	end
	hLine=get(hList(hLineNo),'Userdata');
	hLineMenu=get(hStyleMenu(index),'children');
	LineVisibleLabel=get(hLineMenu(3),'Label');
	PointPos=get(hLineMenu(3),'Userdata');
	NActChan=length(hLine);
	hSpec1=get(hList(hSpec1No),'Userdata');
	LineVisible=get(hSpec1,'Visible');
    if      strcmp(action,'setZerolineVisible') & strcmp(LineVisible,'on')
        action='setZerolineVisibleOff';
    elseif  strcmp(action,'setZerolineVisible') & strcmp(LineVisible,'off')
        action='setZerolineVisibleOn';
    elseif  strcmp(action,'setTriggerVisible') & strcmp(LineVisible,'off')
        action='setTriggerVisibleOn';
    elseif  strcmp(action,'setTriggerVisible') & strcmp(LineVisible,'on')
        action='setTriggerVisibleOff';
    elseif  strcmp(action,'setCursorVisible') & strcmp(LineVisible,'off')
        action='setCursorVisibleOn';
    elseif  strcmp(action,'setCursorVisible') & strcmp(LineVisible,'on')
        action='setCursorVisibleOff';
    end
	if  ~isempty(findstr(action,'Off'))
		for ChanInd=1:NActChan
			set(hLine(ChanInd),'Visible','off');
		end
		LineVisibleLabel((PointPos-2):PointPos)='off';
		set(hSpec1,'Visible','off');
	elseif  ~isempty(findstr(action,'On'))
		for ChanInd=1:NActChan
			set(hLine(ChanInd),'Visible','on');
		end
		LineVisibleLabel((PointPos-2):PointPos)='on ';
		set(hSpec1,'Visible','on');	
	end 	
	set((hLineMenu(3)),'Label',LineVisibleLabel);
	
	%=============================================================================
	%============ setZerolineColor...
	%=============================================================================		
elseif 	strcmp(action,'setZeroLineColorBlack') | ...
		strcmp(action,'setZeroLineColorWhite') | ...
		strcmp(action,'setZeroLineColorYellow') | ...
		strcmp(action,'setZeroLineColorRed') | ...
		strcmp(action,'setZeroLineColorGreen') | ...
		strcmp(action,'setZeroLineColorBlue') | ...
		strcmp(action,'setZeroLineColorCyan') | ...
		strcmp(action,'setZeroLineColorMagenta'),
		
	emegs2d('ClearZeroLineColorIndex');
	if strcmp(action,'setZeroLineColorBlack')
		RGBColor=[0 0 0];
		ZeroLineColorVal=1;
	elseif strcmp(action,'setZeroLineColorWhite')
		RGBColor=[1 1 1];
		ZeroLineColorVal=2;
	elseif strcmp(action,'setZeroLineColorYellow')
		RGBColor=[1 1 0];
		ZeroLineColorVal=3;
	elseif strcmp(action,'setZeroLineColorRed')
		RGBColor=[1 0 0];
		ZeroLineColorVal=4;
	elseif strcmp(action,'setZeroLineColorGreen')
		RGBColor=[0 1 0];
		ZeroLineColorVal=6;
	elseif strcmp(action,'setZeroLineColorBlue')
		RGBColor=[0 0 1];
		ZeroLineColorVal=5;
	elseif strcmp(action,'setZeroLineColorCyan')
		RGBColor=[1 0 1];
		ZeroLineColorVal=8;
	elseif strcmp(action,'setZeroLineColorMagenta')
		RGBColor=[0 1 1];
		ZeroLineColorVal=7;
	end
	hList=get(hPlot2dMenuFig,'Userdata');
	hZeroLineVal=get(hList(8),'value');
	hZeroLine=get(hList(8),'Userdata');	
	hZeroLineVal(1)=ZeroLineColorVal;
	set(hZeroLine,'Color',RGBColor);
	set(hList(8),'Userdata',hZeroLine,'value',hZeroLineVal);
	emegs2d('SetZeroLineColorIndex');
	hSpec1ZeroLine=get(hList(77),'Userdata');
	set(hSpec1ZeroLine,'Color',RGBColor);	

	%=============================================================================
	%============ setZeroLineStyle ...
	%=============================================================================			
elseif 	strcmp(action,'setZeroLineStyleSolid') | ...
		strcmp(action,'setZeroLineStyleDash') | ...
		strcmp(action,'setZeroLineStyleDashDot') | ...
		strcmp(action,'setZeroLineStyleDot'),
		
	emegs2d('ClearZeroLineStyleIndex');
	if strcmp(action,'setZeroLineStyleSolid')
		LineStyle='-';
		LineStyleVal=1;
	elseif strcmp(action,'setZeroLineStyleDash')
		LineStyle='--';
		LineStyleVal=2;
	elseif strcmp(action,'setZeroLineStyleDashDot')
		LineStyle='-.';
		LineStyleVal=3;
	elseif strcmp(action,'setZeroLineStyleDot')
		LineStyle=':';
		LineStyleVal=4;
	end
	hList=get(hPlot2dMenuFig,'Userdata');
	hZeroLineVal=get(hList(8),'value');
	hZeroLine=get(hList(8),'Userdata');
	set(hZeroLine,'LineStyle',LineStyle);
	hZeroLineVal(2)=LineStyleVal;
	set(hList(8),'Userdata',hZeroLine,'value',hZeroLineVal);
	emegs2d('SetZeroLineStyleIndex');
	hSpec1ZeroLine=get(hList(77),'Userdata');
	set(hSpec1ZeroLine,'LineStyle',LineStyle);	

	%=============================================================================
	%============ setTriggerLineColor ...
	%=============================================================================		
elseif 	strcmp(action,'setTriggerLineColorBlack') | ...
		strcmp(action,'setTriggerLineColorWhite') | ...
		strcmp(action,'setTriggerLineColorYellow') | ...
		strcmp(action,'setTriggerLineColorRed') | ...
		strcmp(action,'setTriggerLineColorGreen') | ...
		strcmp(action,'setTriggerLineColorBlue') | ...
		strcmp(action,'setTriggerLineColorCyan') | ...
		strcmp(action,'setTriggerLineColorMagenta'),

	emegs2d('ClearTriggerLineColorIndex');	
	if strcmp(action,'setTriggerLineColorBlack')
		RGBColor=[0 0 0];
		ColorVal=1;
	elseif strcmp(action,'setTriggerLineColorWhite')
		RGBColor=[1 1 1];
		ColorVal=2;
	elseif strcmp(action,'setTriggerLineColorYellow')
		RGBColor=[1 1 0];
		ColorVal=3;
	elseif strcmp(action,'setTriggerLineColorRed')
		RGBColor=[1 0 0];
		ColorVal=4;
	elseif strcmp(action,'setTriggerLineColorGreen')
		RGBColor=[0 1 0];
		ColorVal=6;
	elseif strcmp(action,'setTriggerLineColorBlue')
		RGBColor=[0 0 1];
		ColorVal=5;
	elseif strcmp(action,'setTriggerLineColorCyan')
		RGBColor=[1 0 1];
		ColorVal=8;
	elseif strcmp(action,'setTriggerLineColorMagenta')
		RGBColor=[0 1 1];
		ColorVal=7;
	end
	
	hList=get(hPlot2dMenuFig,'Userdata');
	hTriggerLineVal=get(hList(9),'value');
	hTriggerLine=get(hList(9),'Userdata');	
	hTriggerLineVal(1)=ColorVal;
	set(hTriggerLine,'Color',RGBColor);
	set(hList(9),'Userdata',hTriggerLine,'value',hTriggerLineVal);
	emegs2d('SetTriggerLineColorIndex');
	
	hSpec1TrigLine=get(hList(78),'Userdata');
	set(hSpec1TrigLine,'Color',RGBColor);	

	%=============================================================================
	%============ setTriggerLineStyle...
	%=============================================================================		
elseif 	strcmp(action,'setTriggerLineStyleSolid') | ...
		strcmp(action,'setTriggerLineStyleDash') | ...
		strcmp(action,'setTriggerLineStyleDashDot') | ...
		strcmp(action,'setTriggerLineStyleDot'),
	
	emegs2d('ClearTriggerLineStyleIndex');		
	if strcmp(action,'setTriggerLineStyleSolid')
		LineStyle='-';
		LineStyleVal=1
	elseif strcmp(action,'setTriggerLineStyleDash')
		LineStyle='--';
		LineStyleVal=2;
	elseif strcmp(action,'setTriggerLineStyleDashDot')
		LineStyle='-.';
		LineStyleVal=3;
	elseif strcmp(action,'setTriggerLineStyleDot')
		LineStyle=':';
		LineStyleVal=4;
	end
	
	hList=get(hPlot2dMenuFig,'Userdata');
	hTriggerLineVal=get(hList(9),'value');
	hTriggerLine=get(hList(9),'Userdata');
	set(hTriggerLine,'LineStyle',LineStyle);
	hTriggerLineVal(2)=LineStyleVal;
	set(hList(9),'Userdata',hTriggerLine,'value',hTriggerLineVal);
	emegs2d('SetTriggerLineStyleIndex');
	
	hSpec1TrigLine=get(hList(78),'Userdata');
	set(hSpec1TrigLine,'LineStyle',LineStyle);	

	%=============================================================================
	%============ setCursorLineColor...
	%=============================================================================		
elseif 	strcmp(action,'setCursorLineColorBlack') | ...
		strcmp(action,'setCursorLineColorWhite') | ...
		strcmp(action,'setCursorLineColorYellow') | ...
		strcmp(action,'setCursorLineColorRed') | ...
		strcmp(action,'setCursorLineColorGreen') | ...
		strcmp(action,'setCursorLineColorBlue') | ...
		strcmp(action,'setCursorLineColorCyan') | ...
		strcmp(action,'setCursorLineColorMagenta'),
		
	emegs2d('ClearCursorLineColorIndex');
	if strcmp(action,'setCursorLineColorBlack')
		RGBColor=[0 0 0];
		ColorVal=1;
	elseif strcmp(action,'setCursorLineColorWhite')
		RGBColor=[1 1 1];
		ColorVal=2;
	elseif strcmp(action,'setCursorLineColorYellow')
		RGBColor=[1 1 0];
		ColorVal=3;
	elseif strcmp(action,'setCursorLineColorRed')
		RGBColor=[1 0 0];
		ColorVal=4;
	elseif strcmp(action,'setCursorLineColorGreen')
		RGBColor=[0 1 0];
		ColorVal=6;
	elseif strcmp(action,'setCursorLineColorBlue')
		RGBColor=[0 0 1];
		ColorVal=5;
	elseif strcmp(action,'setCursorLineColorCyan')
		RGBColor=[1 0 1];
		ColorVal=8;
	elseif strcmp(action,'setCursorLineColorMagenta')
		RGBColor=[0 1 1];
		ColorVal=7;
	end
	hList=get(hPlot2dMenuFig,'Userdata');
	
	hCursorLine=get(hList(10),'Userdata');
	hCursorLineVal=get(hList(10),'value');
	hCursorLineVal(1)=ColorVal;
	set(hCursorLine,'Color',RGBColor);
	set(hList(10),'Userdata',hCursorLine,'value',hCursorLineVal);
	
	emegs2d('SetCursorLineColorIndex');
	hSpec1CursorLine=get(hList(79),'Userdata');
	set(hSpec1CursorLine,'Color',RGBColor);	

	%=============================================================================
	%============ setCursorLineStyle...
	%=============================================================================	
elseif 	strcmp(action,'setCursorLineStyleSolid') | ...
		strcmp(action,'setCursorLineStyleDash') | ...
		strcmp(action,'setCursorLineStyleDashDot') | ...
		strcmp(action,'setCursorLineStyleDot'),
		
	emegs2d('ClearCursorLineStyleIndex');
	if strcmp(action,'setCursorLineStyleSolid')
		LineStyle='-';
		LineStyleVal=1;
	elseif strcmp(action,'setCursorLineStyleDash')
		LineStyle='--';
		LineStyleVal=2;
	elseif strcmp(action,'setCursorLineStyleDashDot')
		LineStyle='-.';
		LineStyleVal=3;
	elseif strcmp(action,'setCursorLineStyleDot')
		LineStyle=':';
		LineStyleVal=4;
	end
	hList=get(hPlot2dMenuFig,'Userdata');
	
	hCursorLine=get(hList(10),'Userdata');
	hCursorLineVal=get(hList(10),'value');
	hCursorLineVal(2)=LineStyleVal;
	set(hCursorLine,'LineStyle',LineStyle);
	set(hList(10),'Userdata',hCursorLine,'value',hCursorLineVal);
	
	emegs2d('SetCursorLineStyleIndex');
	hSpec1CursorLine=get(hList(79),'Userdata');
	set(hSpec1CursorLine,'LineStyle',LineStyle);
	
	
	%=============================================================================	
	%============ SetDefXTickVal
	%=============================================================================	
elseif strcmp(action,'SetDefXTickVal')
	
	hList=get(hPlot2dMenuFig,'Userdata');
	MinPoint=get(hList(54),'Value');
	MaxPoint=get(hList(55),'Value');
	SampRate = get(hList(60),'Userdata')
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	NPoints=get(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata')
	Domain=get(hList(20),'value');
	TmpSegment=abs(MaxPoint-MinPoint)/10;
	
	%------------------ change Xtick  Time <-> Hz  ----------------
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	hXTickMenu=get(hStyleMenu(2),'children');
	for ind=1:length(hXTickMenu)
		XTickValLabel=get(hXTickMenu(ind),'Label');
		PointPos=get(hXTickMenu(ind),'Userdata');
		if Domain<3 | Domain==6 | Domain==7		% Time, Ms, Wavelet
			XTickValLabel((PointPos-4):(PointPos-3))='ms';
		else			% Frequency, Hz
			XTickValLabel((PointPos-4):(PointPos-3))='Hz';
		end;
		set(hXTickMenu(ind),'Label',XTickValLabel);
	end;	

	if Domain<3 | Domain==6 | Domain==7
		MSHzTmpSegment=(TmpSegment*1000)/SampRate;
	else
		MSHzTmpSegment=TmpSegment.*SampRate./(2.*NPoints);
	end;

	if MSHzTmpSegment <= 5
		emegs2d('setXTickVal5');
	elseif (MSHzTmpSegment <= 10)
		emegs2d('setXTickVal10');
	elseif (MSHzTmpSegment > 10) & (MSHzTmpSegment <= 25)
		emegs2d('setXTickVal25');
	elseif (MSHzTmpSegment > 25) & (MSHzTmpSegment <= 50)
		emegs2d('setXTickVal50');
	elseif (MSHzTmpSegment > 50) & (MSHzTmpSegment <= 100)
		emegs2d('setXTickVal100');
	elseif (MSHzTmpSegment > 100) & (MSHzTmpSegment <= 250)
		emegs2d('setXTickVal250');
	elseif (MSHzTmpSegment > 250) & (MSHzTmpSegment <= 500)
		emegs2d('setXTickVal500');
	else 	
		emegs2d('setXTickVal1000');
	end;

	%=============================================================================
	%============ setXTickValue
	%=============================================================================	
elseif 	strcmp(action,'setXTickVal') | ...
		strcmp(action,'setXTickVal5') | ...
		strcmp(action,'setXTickVal10') | ...
		strcmp(action,'setXTickVal25') | ...
		strcmp(action,'setXTickVal50') | ...
		strcmp(action,'setXTickVal100') | ...
		strcmp(action,'setXTickVal250') | ...
		strcmp(action,'setXTickVal500') | ...
		strcmp(action,'setXTickVal1000'),
		
	hList=get(hPlot2dMenuFig,'Userdata');
	if strcmp(action,'setXTickVal5')
		XTickVal=8;
		segment=5;
	elseif strcmp(action,'setXTickVal10')
		XTickVal=7;
		segment=10;
	elseif strcmp(action,'setXTickVal25')
		XTickVal=6;
		segment=25;
	elseif strcmp(action,'setXTickVal50')
		XTickVal=5;
		segment=50;
	elseif strcmp(action,'setXTickVal100')
		XTickVal=4;
		segment=100;
	elseif strcmp(action,'setXTickVal250')
		XTickVal=3;
		segment=250;
	elseif strcmp(action,'setXTickVal500')
		XTickVal=2;
		segment=500;
	elseif strcmp(action,'setXTickVal1000')
		XTickVal=1;
		segment=1000;
	else XTickVal=get(hList(101),'value');
		segment=get(hList(101),'Userdata');	
	end;	
	%------------------ change index position in menu ----------------
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	hXTickMenu=get(hStyleMenu(2),'children');
	oldXTickVal=get(hList(101),'value');
	pointer=get(hList(83),'Userdata');
	for ind=1:length(hXTickMenu)
		XTickValLabel=get(hXTickMenu(ind),'Label');
		PointPos=get(hXTickMenu(ind),'Userdata');
		if (ind==XTickVal) XTickValLabel(PointPos)=setstr(pointer);
		elseif (ind==oldXTickVal) XTickValLabel(PointPos)=' '; end;
		set(hXTickMenu(ind),'Label',XTickValLabel);
	end;	
	%-----------------------------------------------------------------
	set(hList(101),'Userdata',segment,'value',XTickVal);
	%=============================================================================
	%============ InfoAll: information about all opened files
	%=============================================================================		
elseif strcmp(action,'InfoAll'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	NUsedFiles=length(FileNoVec);
	hInfoAllFig=figure('Units','normal','NumberTitle','off','Position',[0 0 .65 .25],'Name','Info','Color',[0 0 .3]);	
	axes('Position',[0 0 1 1])
	axis('off')
	for FileIndex=1:NUsedFiles
		AvgFileFormat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+22),'Userdata');
		FilePath=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+4),'Userdata');
		ColorRGB =get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+16),'Userdata');
		LineStyle=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+17),'value');
		if 		LineStyle==1; 	StringLineStyle='solid'; 
		elseif 	LineStyle==2;	StringLineStyle='dashed'; 
		elseif 	LineStyle==3;	StringLineStyle='dashed-dotted'; 
		elseif 	LineStyle==4;	StringLineStyle='dotted'; 
		end
		[File]=SepFilePath(FilePath);
		FileInfoString=['No.: ',int2str(FileNoVec(FileIndex)),' ;   File:  ' File ' ;   LineStyle:  ' StringLineStyle];
		if strcmp(AvgFileFormat,'AvgEgis'); ListHdrVal=31; 
		elseif strcmp(AvgFileFormat,'GrandAvgEgis'); ListHdrVal=31; 
		elseif strcmp(AvgFileFormat,'RawEgis'); ListHdrVal=32; 
		end
		if strcmp(AvgFileFormat,'AvgEgis') | strcmp(AvgFileFormat,'GrandAvgEgis') | strcmp(AvgFileFormat,'RawEgis')
			EgisVec=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+ListHdrVal),'Userdata');
			SpecCell=EgisVec(1);
			SpecTrialSubject=EgisVec(2);
			if strcmp(AvgFileFormat,'AvgEgis')
				FileInfoString=[FileInfoString, ';  Cell: ',int2str(SpecCell),';  Subject: ',int2str(SpecTrialSubject)];
			elseif strcmp(AvgFileFormat,'GrandAvgEgis')
				FileInfoString=[FileInfoString, ';  Cell: ',int2str(SpecCell)];
			elseif strcmp(AvgFileFormat,'RawEgis')
				FileInfoString=[FileInfoString, ';  Cell: ',int2str(SpecCell),';  Trial: ',int2str(SpecTrialSubject)];
			end
		end
		htext=text('Units','normal','Position',[.05 1-(0.2+(FileNoVec(FileIndex)-1).*0.2)], 'FontSize', 18 ,...
		'HorizontalAlignment','left','Color',ColorRGB,'String',FileInfoString);
	end;
	clear;
	
	%=============================================================================
	%============ DispFileNames, DispFileNamesVisible
	%=============================================================================		
elseif strcmp(action,'DispFileNames') | strcmp(action,'DispFileNamesVisible'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
    EcfgFilePath=get(hList(2),'Userdata');
    [EcfgFile,EcfgPath]=SepFilePath(EcfgFilePath);
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata');
	
	NUsedFiles=length(FileNoVec);
	for FileIndex=NUsedFiles:-1:1
		AvgFileFormat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+22),'Userdata');
		FilePath=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+4),'Userdata')
		ColorRGB =get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+16),'Userdata');
		LineStyle=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+17),'Value');
		if 		LineStyle==1; 	StringLineStyle=' - '; 
		elseif 	LineStyle==2;	StringLineStyle='---'; 
		elseif 	LineStyle==3;	StringLineStyle='-.-'; 
		elseif 	LineStyle==4;	StringLineStyle='...'; 
		end
		[File]=SepFilePath(FilePath);
		FileInfoString=[File '; ' StringLineStyle];
		if strcmp(AvgFileFormat,'AvgEgis'); ListHdrVal=31; 
		elseif strcmp(AvgFileFormat,'GrandAvgEgis'); ListHdrVal=31; 
		elseif strcmp(AvgFileFormat,'RawEgis'); ListHdrVal=32; 
		end
		if strcmp(AvgFileFormat,'AvgEgis') | strcmp(AvgFileFormat,'GrandAvgEgis') | strcmp(AvgFileFormat,'RawEgis')
			EgisVec=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+ListHdrVal),'Userdata');
			SpecCell=EgisVec(1);
			SpecTrialSubject=EgisVec(2);
			if strcmp(AvgFileFormat,'AvgEgis')
				FileInfoString=[FileInfoString, ' ;  Cell: ',int2str(SpecCell),';  Subj.: ',int2str(SpecTrialSubject)];
			elseif strcmp(AvgFileFormat,'GrandAvgEgis')
				FileInfoString=[FileInfoString, ' ;  Cell: ',int2str(SpecCell)];
			elseif strcmp(AvgFileFormat,'RawEgis')
				FileInfoString=[FileInfoString, ' ;  Cell: ',int2str(SpecCell),';  Trial: ',int2str(SpecTrialSubject)];
			end
		end
		hFileInfoTextVec=get(hList(17),'Userdata');
		hFileInfoText=hFileInfoTextVec(FileNoVec(FileIndex));
		VisibleStatus=get(hFileInfoText,'Visible');
		if strcmp(action,'DispFileNames')
			if strcmp(VisibleStatus,'on'); VisibleStatus='off';
			elseif strcmp(VisibleStatus,'off'); VisibleStatus='on';
			end
		end
		set(hFileInfoText,...
		'String',FileInfoString,...	%
		'Color',ColorRGB,...
		'Position',[.025 .05+(NUsedFiles-FileIndex).*.025],...
		'Visible',VisibleStatus); 
	end;
    set(hList(141),...                      %hEcfgInfoText
		'String',EcfgFile,...	
		'Color','k',...
		'Position',[.025 .025],...
		'Visible',VisibleStatus); 
	%------------------ change index position in menu ----------------
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	hTextMenu=get(hStyleMenu(6),'children');
	pointer=get(hList(83),'Userdata');
	DisplayTextLabel=get(hTextMenu(6),'Label');
	PointPos=get(hTextMenu(6),'Userdata');
	
	if strcmp(VisibleStatus,'off')
		DisplayTextLabel(PointPos)=' ';
	else	
		DisplayTextLabel(PointPos)=setstr(pointer);
	end;	
	set(hTextMenu(6),'Label',DisplayTextLabel);
	%set(hList(65),'Userdata',hTopMenu);
	
	%=============================================================================
	%============ ClearActFile: clears actual selected file
	%=============================================================================		
elseif strcmp(action,'ClearActFile'),

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	FileNoVec=get(hList(56),'Userdata')
	hDataVec=get(hList(NListHdr+(ActFileNo-1).*50+25),'Userdata');
	for ChanInd=1:length(hDataVec)
		set(hDataVec(ChanInd),'Visible','off');
	end
	NoActFileInd=find(FileNoVec==ActFileNo)
	FileNoVec(NoActFileInd)=0
	if length(FileNoVec)>1
		FileNoVec=sort(FileNoVec);
		FileNoVec=FileNoVec(2:length(FileNoVec));
	else 
		FileNoVec=[]; 
	end
	FileIndVec=find(FileNoVec);
	if isempty(FileIndVec); FileIndVec=1; end
	set(hList(1),'Value',FileIndVec(1),'Userdata',FileIndVec(1));
	set(hList(56),'Userdata',FileNoVec);
	
	hFileInfoTextVec=get(hList(17),'Userdata');
	set(hFileInfoTextVec(ActFileNo),'String','');
	if length(FileNoVec) == 1
		set(hList(49),'Value',1);
	elseif length(FileNoVec) == 0
		set(hList(49),'Value',0);
	elseif length(FileNoVec) == 3
		set(hList(49),'Value',6);
	end
	emegs2d('EnableOnOff');	
	BaseMat=get(hList(115),'Userdata');
	[NChan,NonUse]=size(BaseMat);
	BaseMat(:,(ActFileNo-1).*5+1:ActFileNo.*5)=zeros(NChan,5);
	set(hList(115),'Userdata',BaseMat);
	emegs2d('SetActFileNoLabelString');	
    
    
elseif strcmp(action,'ClosePlot2dMenuFig'),
    
    try
        figposition = get(hPlot2dMenuFig,'position');
        utilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2dfigpos.mat');
        filehistpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2dfilehist.mat');
        save(utilpath,'figposition');
        save(filehistpath,'figposition');
        plot2dpathutilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2ddefviewdef.udef');
        emegs2d('SaveViewDefaultFile',plot2dpathutilpath);
        delete(hPlot2dMenuFig);
    catch
        delete(gcf);
    end   
	
elseif strcmp(action,'ClosePlot2dChanFig'),
     
	try
        hList=get(hPlot2dMenuFig,'Userdata');
        chanposition = get(hPlot2dChanFig,'position');
        utilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2dchanpos.mat');
        save(utilpath,'chanposition');
        hList=get(hPlot2dMenuFig,'Userdata');
        %delete(hList(93));
        delete(hPlot2dChanFig);
        close(hPlot2dMenuFig);
    catch
        delete(gcf);
    end

elseif strcmp(action,'CloseGpPlot')  | strcmp(action,'CloseButterflyPlot') | strcmp(action,'CloseZoomChanPlot'),
    
    hList=get(hPlot2dMenuFig,'Userdata');
    if strcmp(action,'CloseGpPlot')
        Plot=findobj('tag','GpPlot');
        Menu=findobj('tag','GpMenu');
    elseif strcmp(action,'CloseButterflyPlot') 
        Plot=findobj('tag','ButterflyPlot');
        Menu=findobj('tag','ButterflyMenu');
    elseif strcmp(action,'CloseZoomChanPlot') 
        Plot=findobj('tag','ZoomChanPlot');
        Menu=findobj('tag','ZoomChanMenu');
        set(hList(46),'Value',1); %ZoomSpecChanVal
    end
    if ~isempty(Plot); delete(Plot); end
    if ~isempty(Menu); delete(Menu); end

    %=============================================================================
	%============ CloseAllFigures: closes all children 0 figures
	%=============================================================================		
elseif strcmp(action,'CloseAllFigures'),
    
    hList=get(hPlot2dMenuFig,'Userdata');
    try
        figposition = get(hPlot2dMenuFig,'position');
        utilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2dfigpos.mat');
        save(utilpath,'figposition');
    catch
    end
    
    try
        chanposition = get(hPlot2dChanFig,'position');
        utilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2dchanpos.mat');
        save(utilpath,'chanposition');
    catch
    end
        
    delete(get(0,'children'))
    clc;
    
    %=============================================================================
	%============ CloseAllButMain: closes all children 0 figures
	%=============================================================================		
elseif strcmp(action,'CloseAllButMain'),
    
    hList=get(hPlot2dMenuFig,'Userdata');
    try
        figposition = get(hPlot2dMenuFig,'position');
        utilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2dfigpos.mat');
        save(utilpath,'figposition');
    catch
    end
    
    try
        chanposition = get(hPlot2dChanFig,'position');
        utilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2dchanpos.mat');
        save(utilpath,'chanposition');
    catch
    end
    
    handles = get(0,'children');
    for r=1:length(handles)
        if isempty(hPlot3dMenuFig)
            if handles(r)~=hPlot2dMenuFig &  handles(r)~=hPlot2dChanFig
                delete(handles(r));
            end
        else
            if handles(r)~=hPlot2dMenuFig & handles(r)~=hPlot3dMenuFig & handles(r)~=hPlot2dChanFig
                delete(handles(r));
            end
        end
    end
    clc;
    %=============================================================================
	%============ restart
	%=============================================================================		
elseif strcmp(action,'restart'),
    
    hList=get(hPlot2dMenuFig,'Userdata');
    filepathcell = get(hList(117),'Userdata');
    plot2dpathutilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2dpathutil.mat');
    save(plot2dpathutilpath,'filepathcell');
    plot2dpathutilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2ddefviewdef.udef');
    try
        emegs2d('SaveViewDefaultFile',plot2dpathutilpath);
    catch
    end
   
    try
        figposition = get(hPlot2dMenuFig,'position');
        utilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2dfigpos.mat');
        save(utilpath,'figposition');
    catch
    end
    
    try
        chanposition = get(hPlot2dChanFig,'position');
        utilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2dchanpos.mat');
        save(utilpath,'chanposition');
    catch
    end
        
    delete(get(0,'children'))
    clear;
    clc
    emegs2d;
   % try
        plot2dpathutilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2dpathutil.mat');
        load(plot2dpathutilpath,'filepathcell','emegs3dstatus');
        plot2dpathutilpath = strrep(which('emegs3d.m'),'emegs3d.m','emegs2ddefviewdef.udef');
        
        if isempty(filepathcell)
            return
        end
        for r=1:length(filepathcell{1})
            emegs2d('OpenAvgFile',filepathcell{1}{r},filepathcell{2}{r},filepathcell{3}{r});
            emegs2d('setActFileNo',r);
            emegs2d('setActAllVisible');
            if r==4
                break;
            end
        end
        emegs2d('ReadViewDefaultFile',plot2dpathutilpath);
        global hPlot2dMenuFig
        hList=get(hPlot2dMenuFig,'Userdata');
        set(hList(117),'Userdata',filepathcell);
        %catch
        %end
    
    
    
	%=============================================================================
	%============ ClearAllFiles: clears all opened files
	%=============================================================================		
elseif strcmp(action,'ClearAllFiles'),

	hList=get(hPlot2dMenuFig,'Userdata');
	hAxesVec=get(hList(6),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	DomainLabelStr=get(hList(20),'String');
	NDomain=size(DomainLabelStr,1);
	if hAxesVec~=0
		NChan=length(hAxesVec);
		for ChanInd=1:NChan
			axes(hAxesVec(ChanInd));
			cla;
		end
	end
	Spec1Axes=get(hList(76),'Userdata');
	Spec1ZeroLine = get(hList(77),'Userdata');
	set(Spec1Axes,'Visible','off');
	set(Spec1ZeroLine,'Visible','off');
	ActFileNo=1;
	set(hList(1),'Value',ActFileNo,'Userdata',ActFileNo);	%ActFileNo
	ColorVal=get(hList(NListHdr+(ActFileNo-1).*50+16),'Value');
	set(hList(61),'Value',ColorVal);
	LineStyleVal=get(hList(NListHdr+(ActFileNo-1).*50+17),'Value');
	set(hList(62),'Value',LineStyleVal);
	set(hList(16),'Userdata',[0 0]); 	% [DataNChan,SensorNChan]
	set(hList(56),'Userdata',[]); 		% FileNoVec
	hFileInfoTextVec=get(hList(17),'Userdata'); % File Info
	for FileIndex=1:length(hFileInfoTextVec)
		set(hFileInfoTextVec(FileIndex),'Userdata',0,'Visible','off');
		hFileInfoTextVec(FileIndex)=0;
	end
	set(hList(17),'Userdata',hFileInfoTextVec);
    set(hList(141),'Userdata',0,'String','','Visible','off');
	set(hList(50),'Userdata',0,'String','0');								% NPoints
	set(hList(52),'Value',0,'Userdata',zeros(NDomain,1),'String','0');		% MinAmp; 
	set(hList(53),'Value',0,'Userdata',zeros(NDomain,1),'String','0');		% MaxAmp;
	set(hList(54),'Value',0,'String','0','Userdata',ones(NDomain,1));		% MinPoint; 
	set(hList(55),'Value',0,'String','0','Userdata',ones(NDomain,1));		% MaxPoint; 
	set(hList(22),'Value',1,'String','1','Userdata',ones(NDomain,1));		% TrigPoint; 
	set(hList(23),'Value',1,'String','0','Userdata',ones(NDomain,1));		% CursorPoint; 
	set(hList(58),'Value',1,'String','0','Userdata',ones(NDomain,1));		% MinBase; 
	set(hList(59),'Value',1,'String','0','Userdata',ones(NDomain,1));		% MaxBase;
	set(hList(60),'Userdata',0,'String','0');								% SampRate
	set(hList(57),'Value',0,'Userdata',zeros(NDomain,1));					% CalcBase; number of domains
	set(hList(49),'Value',0)												% Enable
	set(hList(115),'Userdata',[]);											% BaseMat
    set(hList(134),'Userdata',[]);                                          % TempFiltStruc
    set(hList(135),'Userdata',[]);                                          % SpatFiltStruc
	emegs2d('EnableOnOff');
	emegs2d('SetActFileNoLabelString');	
	%============ Clear Data Set Label String ...
	LabelStr=get(hList(82),'String');										% hOpenAvgFile
	if size(LabelStr,1)>1
		LabelStr=LabelStr(1,:);
		set(hList(82),'Value',1,'String',LabelStr);
	end
	figure(hPlot2dMenuFig);

	%=============================================================================
	%============ Export Data ...
	%=============================================================================		
elseif strcmp(action,'ExportAllAvgFile2SCADS') | ...
    strcmp(action,'ExportActAvgFile2SCADS') | ...
	strcmp(action,'ExportAllAvgFile2KN') | ...
    strcmp(action,'ExportActAvgFile2KN') | ...
	strcmp(action,'ExportAllAvgFile2Ascii') | ...
    strcmp(action,'ExportActAvgFile2Ascii') | ...
	strcmp(action,'ExportAllAvgFile2Besa') | ...
    strcmp(action,'ExportActAvgFile2Besa') | ...
	strcmp(action,'ExportActUserDataAscii') | ...
	strcmp(action,'ExportActUserDataBesa') | ...
    strcmp(action,'ExportFilematrix2SCADS') | ...
    strcmp(action,'ExportFilematrix2KN') | ...
    strcmp(action,'ExportFilematrix2Ascii') | ...
    strcmp(action,'ExportFilematrix2Besa')

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
    FileNoVec=get(hList(56),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	MinPoint=get(hList(54),'Value');
    MaxPoint=get(hList(55),'Value');
    
    if ~isempty(findstr(action,'SCADS'))
        Ext=['.exp.at'];
    elseif ~isempty(findstr(action,'KN'))
        Ext=['.exp.KN'];
    elseif ~isempty(findstr(action,'Ascii'))
        Ext=['.exp.txt'];
    elseif ~isempty(findstr(action,'Besa'))
        Ext=['.exp.avr'];
    end
    if ~isempty(findstr(action,'Act'))
        FileNoVec=FileNoVec(ActFileNo);
        DefFilePath=SetDefPath('r')
	    [DefFile,DefPath]=SepFilePath(DefFilePath)
        DefFileMask=[DefPath,'*',Ext,'.*'];
        [File,Path]=uiputfile(DefFileMask,'Choose a file name:');
        if isempty(find([File,Path])); return; end;	
        ExpFilePath=[Path,File];
    end	   
    NUsedFiles=length(FileNoVec);
    Message=char('');
    
    %Actual and All Datasets
    if isempty(findstr(action,'Filematrix'))
        for FileInd=1:NUsedFiles

            ActFileNo=FileNoVec(FileInd);
            CalcAvgMat=get(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata');
            NChan=get(hList(NListHdr+(1-1).*50+2),'Userdata');
            NPoints=get(hList(NListHdr+(1-1).*50+3),'Userdata');

            if FileInd==1 & (MinPoint~=1 | MaxPoint~=NPoints)
                VisStr=['Visible (Points ',int2str(MinPoint),' - ',int2str(MaxPoint),')'];
                answer = questdlg('Which time interval ?','Info:','Total',VisStr,'Cancel','Total');
                switch answer,
                    case 'Cancel', 
                        return;
                    case VisStr,
                        MinPoint=MinPoint; 
                        MaxPoint=MaxPoint;
                    case 'Total',
                        MinPoint=1; 
                        MaxPoint=NPoints;
                    otherwise
                        uiwait(errordlg('Unknown option!'));
                        return
                end
            end 
            NTrialAvgVec=get(hList(NListHdr+(ActFileNo-1).*50+5),'Userdata');
            StdChanTimeMat=get(hList(NListHdr+(ActFileNo-1).*50+6),'Userdata');
            SampRate=get(hList(NListHdr+(1-1).*50+7),'Userdata');
            AvgRef=get(hList(NListHdr+(ActFileNo-1).*50+8),'Userdata');
            MedMedRawVec=get(hList(NListHdr+(ActFileNo-1).*50+9),'Userdata');
            MedMedAvgVec=get(hList(NListHdr+(ActFileNo-1).*50+10),'Userdata');
            EegMegStatus=get(hList(110),'Userdata');
            NChanExtra=0;

            if ~isempty(findstr(action,'All'))
                ExpFilePath=get(hList(NListHdr+(FileInd-1).*50+4),'Userdata'); %FilePath
                ExpFilePath=[ExpFilePath,Ext];
            end
            Message=char(Message,['Export data set # ',int2str(ActFileNo),' to file:']);
            Message=char(Message,ExpFilePath);
            Message=char(Message,'');

            DI=1000./SampRate;				%Besa
            TrigPoint=get(hList(22),'Value');% Besa position of trigger and cursor	
            TSB=-1.*(TrigPoint-1).*DI;		%Besa time-speed-begin
            SB=1;
            SC=1;
            if ~isempty(findstr(action,'AvgFile2SCADS'))
                if length(StdChanTimeMat)==1 & StdChanTimeMat==0
                    SaveAvgFile(ExpFilePath,CalcAvgMat(:,MinPoint:MaxPoint),NTrialAvgVec,[],SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra);
                else
                    SaveAvgFile(ExpFilePath,CalcAvgMat(:,MinPoint:MaxPoint),NTrialAvgVec,StdChanTimeMat(:,MinPoint:MaxPoint),SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra);
                end
            elseif ~isempty(findstr(action,'AvgFile2KN'))
                Save2KNPC(CalcAvgMat(:,MinPoint:MaxPoint),ExpFilePath,AvgRef,NTrialAvgVec,SampRate);
            elseif ~isempty(findstr(action,'AvgFile2Ascii'))
                SaveAscii(CalcAvgMat(:,MinPoint:MaxPoint),ExpFilePath); 
            elseif ~isempty(findstr(action,'AvgFile2Besa'))
                SaveAsciiBesa(CalcAvgMat(:,MinPoint:MaxPoint),TSB,DI,SB,SC,ExpFilePath)
            elseif strcmp(action,'ExportActUserDataAscii')
                ExpMat=get(hList(94),'Userdata');
                SaveAscii(ExpMat,ExpFilePath);
            elseif strcmp(action,'ExportActUserDataBesa')
                ExpMat=get(hList(94),'Userdata');
                SaveAsciiBesa(ExpMat,TSB,DI,SB,SC,ExpFilePath)
            end
        end
        hmsgbox=msgbox(Message,'Info:','help'); 
        
        
    %Filematrix
    else
        BatchFileDefPath = SetDefPath(1);
        [NFiles,FileMat,NonUse,BatchFilePath]=ReadFileNames([],BatchFileDefPath,'Please choose file(s) or a batch:');
        for FileInd=1:NFiles
            [AvgFile,AvgPath,AvgFilePath] = GetFileNameOfMat(FileMat,FileInd);
            emegs2d('OpenAvgFile',ActFileNo,[],AvgFilePath);
            CalcAvgMat=get(hList(NListHdr+(ActFileNo-1).*50+1),'Userdata');
            NChan=get(hList(NListHdr+(ActFileNo-1).*50+2),'Userdata');
            NPoints=get(hList(NListHdr+(ActFileNo-1).*50+3),'Userdata');
            
            if FileInd==1 & (MinPoint~=1 | MaxPoint~=NPoints)
                VisStr=['Visible (Points ',int2str(MinPoint),' - ',int2str(MaxPoint),')'];
                answer = questdlg('Which time interval ?','Info:','Total',VisStr,'Cancel','Total');
                switch answer,
                    case 'Cancel', 
                        return;
                    case 'Total',
                        MinPoint=1; 
                        MaxPoint=NPoints;
                end % switch
            end 
            NTrialAvgVec=get(hList(NListHdr+(ActFileNo-1).*50+5),'Userdata');
            StdChanTimeMat=get(hList(NListHdr+(ActFileNo-1).*50+6),'Userdata');
            SampRate=get(hList(NListHdr+(ActFileNo-1).*50+7),'Userdata');
            AvgRef=get(hList(NListHdr+(ActFileNo-1).*50+8),'Userdata');
            MedMedRawVec=get(hList(NListHdr+(ActFileNo-1).*50+9),'Userdata');
            MedMedAvgVec=get(hList(NListHdr+(ActFileNo-1).*50+10),'Userdata');
            EegMegStatus=get(hList(110),'Userdata');
            NChanExtra=0;
            
            %FilePath
            ExpFilePath=[AvgFilePath,Ext];
            
            Message=char(Message,['Export data set # ',int2str(ActFileNo),' to file:']);
            Message=char(Message,ExpFilePath);
            Message=char(Message,'');

            DI=1000./SampRate;				%Besa
            TrigPoint=get(hList(22),'Value');% Besa position of trigger and cursor	
            TSB=-1.*(TrigPoint-1).*DI;		%Besa time-speed-begin
            SB=1;
            SC=1;
            if ~isempty(findstr(action,'Filematrix2SCADS'))
                if length(StdChanTimeMat)==1 & StdChanTimeMat==0
                    SaveAvgFile(ExpFilePath,CalcAvgMat(:,MinPoint:MaxPoint),NTrialAvgVec,[],SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra);
                else
                    SaveAvgFile(ExpFilePath,CalcAvgMat(:,MinPoint:MaxPoint),NTrialAvgVec,StdChanTimeMat(:,MinPoint:MaxPoint),SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra);
                end
            elseif ~isempty(findstr(action,'Filematrix2KN'))
                Save2KNPC(CalcAvgMat(:,MinPoint:MaxPoint),ExpFilePath,AvgRef,NTrialAvgVec,SampRate);
            elseif ~isempty(findstr(action,'Filematrix2Ascii'))
                SaveAscii(CalcAvgMat(:,MinPoint:MaxPoint),ExpFilePath); 
            elseif ~isempty(findstr(action,'Filematrix2Besa'))
                SaveAsciiBesa(CalcAvgMat(:,MinPoint:MaxPoint),TSB,DI,SB,SC,ExpFilePath)
            end
        end
        hmsgbox=msgbox(Message,'Info:','help'); 
    end
    
elseif strcmp(action,'ExportECfgFile2MEG') | ...
	strcmp(action,'ExportECfgFile2Besa') | ...
	strcmp(action,'ExportECfgFile2Egis') | ...
	strcmp(action,'ExportECfgFile2SCADS') | ...
	strcmp(action,'ExportECfgFile2CartAscii') | ...
	strcmp(action,'ExportECfgFile2SpherAscii'),

	hList=get(hPlot2dMenuFig,'Userdata');
	EPosSpher=get(hList(3),'Userdata');
	[EPosCart]=change_sphere_cart(EPosSpher,[],1);
	NChan=size(EPosCart,1);
	ENames=get(hList(4),'Userdata');
	
	if strcmp(action,'ExportECfgFile2SCADS')
		SaveEConfig(EPosSpher,ENames);
	elseif strcmp(action,'ExportECfgFile2CartAscii')
		DefFileMask=[int2str(NChan),'.CartAscii'];
		Save2Bem(EPosCart,[],[],1,'Matrix','Ascii',[],[],0,0,DefFileMask);
	elseif strcmp(action,'ExportECfgFile2SpherAscii')
		DefFileMask=[int2str(NChan),'.SpherAscii'];
		Save2Bem(EPosSpher(:,1:2),[],[],1,'Matrix','Ascii',[],[],0,0,DefFileMask);
	elseif strcmp(action,'ExportECfgFile2MEG')
		DefFileMask=[int2str(NChan),'.pmg'];
		EegMegStatusString=get(hList(110),'String');
		if strcmp(EegMegStatusString,'MEG'); 
			SensorPosMat=get(hList(111),'Userdata');
			SensorPosMatTmp=SensorPosMat;
			SensorPosMatTmp(:,5)=-1.*SensorPosMat(:,4);
			SensorPosMatTmp(:,4)=SensorPosMat(:,5);
		else
			SensorPosMat=EPosCart;
			SensorPosMatTmp=SensorPosMat;
		end
		SensorPosMatTmp(:,2)=-1.*SensorPosMat(:,1);
		SensorPosMatTmp(:,1)=SensorPosMat(:,2);
		SaveMEGConfig(SensorPosMatTmp,ENames,DefFileMask);
	end
	%=============================================================================
	%============ setDomain
	%============ call: setMinMaxAmpPoint, SetDefXTickVal, PlotData
	%=============================================================================		
elseif strcmp(action,'setDomain') | strcmp(action,'setPCADomain') | strcmp(action,'SetDomain')

	hList=get(hPlot2dMenuFig,'Userdata');
	NListHdr=get(hList(51),'Userdata');
	Domain=get(hList(20),'Value');
	% 	labelStr='Domain: Time|Domain: Std|Domain: Power FFT|Domain: Phase FFT|Domain: PCA|Domain: Amp. Wavelet|Domain: Phase Wavelet';
	if 		Domain==1; DomainStr='Time';
	elseif	Domain==2; DomainStr='Std';
	elseif	Domain==3; DomainStr=' Power FFT';
	elseif	Domain==4; DomainStr='Phase FFT';
	elseif	Domain==5; DomainStr='ICA; PCA';
	elseif	Domain==6; DomainStr='Amp. Wavelet';
	elseif	Domain==7; DomainStr='Phase Wavelet';
    elseif  Domain==8; DomainStr='Amp. W. II';
	end
	set(hList(20),'Userdata',DomainStr);
	ActFileNo=get(hList(1),'Userdata');
	NPoints=get(hList(NListHdr+3),'Userdata');
	SampRate=get(hList(60),'Userdata');
	hMenuEnable=get(hList(7),'Userdata');
	hMenuTextEnable=get(hList(49),'Userdata');	%	hMenuTextEnable=[hActSpecVisibleText hColorText hLineStyleText hZoomSpecChanText hAllSpecVisibleText hSampRateText hNPointsText]; 
	hMinMaxText=get(hList(21),'Userdata');		%	hMinMaxText=[hMinAmpText hMaxAmpText hMinPointText hMaxPointText hTrigPointText hCursorPointText hMinBaseText hMaxBaseText];
	FileNoVec=get(hList(56),'Userdata');
	TrigPointVec=get(hList(22),'Userdata');
	TrigPoint=TrigPointVec(Domain);
	set(hList(22),'Value',TrigPoint,'String',sprintf('%g',TrigPoint));
	MinAmpVec=get(hList(52),'Userdata');
	MinAmp=MinAmpVec(Domain);
	set(hList(52),'Value',MinAmp,'String',sprintf('%g',round(MinAmp*1000)/1000));  
	MaxAmpVec=get(hList(53),'Userdata');
	MaxAmp=MaxAmpVec(Domain);
	set(hList(53),'Value',MaxAmp,'String',sprintf('%g',round(MaxAmp*1000)/1000));  
	TmpVec=[54,55,58,59,23];	%MinPoint MaxPoint MinBase MaxBase CursPoint
	for i=1:length(TmpVec)
		PointVec=get(hList(TmpVec(i)),'Userdata');
		Point=PointVec(Domain);
		if Domain<3 | Domain==6 | Domain==7	| Domain==8	%Time, Std, Wavelet
			MsHzPoint=round((Point-TrigPoint).*1000./SampRate);
		elseif Domain>2 & Domain<5	%FFT
			MsHzPoint=round(Point.*SampRate./(2.*NPoints));
		elseif Domain==5 			%PCA
			MsHzPoint=Point;
		end
		set(hList(TmpVec(i)),'Value',Point,'String',sprintf('%g',MsHzPoint));
	end
	CalcBaseStatusVec=get(hList(57),'Userdata');
	CalcBaseStatus=CalcBaseStatusVec(Domain);
	set(hList(57),'Value',CalcBaseStatus);
	
	MaxAmp=MaxAmpVec(Domain);
	hSpec1Axes=get(hList(76),'Userdata');
	get(hSpec1Axes)
	MainMatlabVersion=get(hList(100),'Userdata');
	EegMegStatusString=get(hList(110),'String');
	if strcmp(EegMegStatusString,'EEG'); 
		EegMegString1='µV'; 
		EegMegString2='Pot. [µV]';
	else
		EegMegString1='fT'; 
		EegMegString2='Field. [fT]';
   	end
	if Domain==1 | Domain==2		%Time, Std
		set(hMinMaxText(1),'String',['Min. amp. [',EegMegString1,']']); %hMinAmpText
		set(hMinMaxText(2),'String',['Max. amp. [',EegMegString1,']']); %hMaxAmpText
		set(hMinMaxText(3),'String','Min. time. [ms]; # 0'); %hMinPointText
		set(hMinMaxText(4),'String','Max. time. [ms]; # 0'); %hMaxPointText
		set(hMinMaxText(5),'String','Trigger point'); %hTriggerPointText
		set(hMinMaxText(6),'String','Cursor time [ms]; # 0'); %hCursorPointText
		set(hMinMaxText(7),'String','Min. baseline [ms]'); %hMinBaseText	
		set(hMinMaxText(8),'String','Max. baseline [ms]'); %hMaxBaseText	
		%set(hSpec1Axes,'xlabel','Time [ms]','ylabel','Pot.[µV]'); %hSpec1AxesXylabel	MatlabBug
		axes(hSpec1Axes);
		xlabel('Time [ms]');
		ylabel([EegMegString2,']']);
	elseif Domain==3 | Domain==4	 %frequency
		set(hMinMaxText(1),'String',['Min. amp. [',EegMegString1,'/sqrt(Hz)]']); %hMinAmpText
		set(hMinMaxText(2),'String',['Max. amp. [',EegMegString1,'/sqrt(Hz)]']); %hMaxAmpText
		set(hMinMaxText(3),'String','Min. frquz. [Hz]'); %hMinPointText
		set(hMinMaxText(4),'String','Max. frquz. [Hz]'); %hMaxPointText
		set(hMinMaxText(5),'String','Trigger point'); 	%hTriggerPointText
		set(hMinMaxText(6),'String','Cursor frquz. [Hz]'); %hCursorPointText
		set(hMinMaxText(7),'String','Min. base. frquz. [Hz]'); %hMinBaseText	
		set(hMinMaxText(8),'String','Max. base. frquz. [Hz]'); %hMaxBaseText	
		%set(hSpec1Axes,'xlabel','Frequency [Hz]','ylabel','Pot.[‘V/sqrt(Hz)]'); %hSpec1AxesXylabel	
		axes(hSpec1Axes);
		xlabel('Frequency [Hz]');
		ylabel([EegMegString2,'/sqrt(Hz)]']);
	elseif Domain==5	%PCA
		if ~strcmp(action,'setPCADomain'); emegs2d('CalcPCAAllActDat'); return; end
		set(hMinMaxText(1),'String','Min. variance [%]'); %hMinAmpText
		set(hMinMaxText(2),'String','Max. variance [%]'); %hMaxAmpText
		set(hMinMaxText(3),'String','Min. comp. #'); 	%hMinPointText
		set(hMinMaxText(4),'String','Max. comp. #'); 	%hMaxPointText
		set(hMinMaxText(5),'String','Trigger comp. #'); %hCursorPointText
		set(hMinMaxText(6),'String','Cursor comp. #'); %hTriggerPointText
		set(hList(22),'Value',1,'String','1');			%TrigPoint
		set(hList(23),'Value',1,'String','1'); 			%CursPoint
		emegs2d('setMinMaxAmpPoint')
		emegs2d('setCursorPoint')
		emegs2d('setMinMaxAmpPoint')
		axes(hSpec1Axes);
		xlabel('Compoment #');
		ylabel('Variance');
	elseif Domain==6 | Domain==7	| Domain==8		% Wavelet	
		WaveVec=get(hList(NListHdr+(ActFileNo-1).*50+35),'Userdata');
		StartF0=WaveVec(7);
		EndF0=WaveVec(8);
		DeltaF0=WaveVec(9);
		StartF0IndPlot=WaveVec(12);
		EndF0IndPlot=WaveVec(13);
		F0Vec=[StartF0:DeltaF0:EndF0];
		StartF0Plot=F0Vec(StartF0IndPlot);
		EndF0Plot=F0Vec(EndF0IndPlot);
		if Domain==6
			MinStr='Min. amp. [µV/Hz]';
			MaxStr='Max. amp. [µV/Hz]';
		elseif Domain==7
			MinStr='Min. Phaselock [ ]';
			MaxStr='Max. Phaselock [ ]';
        elseif Domain==8
			MinStr='Min. amp. [µV/Hz]';
			MaxStr='Max. amp. [µV/Hz]';
		end
		set(hMinMaxText(1),'String',MinStr); %hMinAmpText
		set(hMinMaxText(2),'String',MaxStr); %hMaxAmpText
		set(hMinMaxText(3),'String','Min. time. [ms]; # 0'); %hMinPointText
		set(hMinMaxText(4),'String','Max. time. [ms]; # 0'); %hMaxPointText
		set(hMinMaxText(5),'String','Trigger point'); %hTriggerPointText
		set(hMinMaxText(6),'String','Cursor time [ms]; # 0'); %hCursorPointText
		set(hMinMaxText(7),'String','Min. baseline [ms]'); %hMinBaseText	
		set(hMinMaxText(8),'String','Max. baseline [ms]'); %hMaxBaseText	
		axes(hSpec1Axes);
		set(hList(77),'Visible','off');	%hSpec1ZeroLine
		xlabel('Time [ms]');
		ylabel('Frequ. [Hz]');
% 		set(hSpec1Axes,'XLabel',,'YLabel','Frequ. [Hz]')
		set(hSpec1Axes,'YLim',[0 1],'YTick',[0 1],'YTickLabel',[round(StartF0Plot.*100)./100 round(EndF0Plot.*100)./100]);
        AxesSizeStatus = get(hList(118),'userdata');
        if isempty(AxesSizeStatus) | AxesSizeStatus==0 
			Message=char('Change width and height of');
			Message=char(Message,'sensor axes in order');
			Message=char(Message,'to optimize visualization.');
			hmsgbox=msgbox(Message,'Info','help'); 
			hChildMsgbox=get(hmsgbox,'Children');
			set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
			pause(1)
			close(hmsgbox)
			emegs2d('setSensorAxesWidth04')
			emegs2d('setSensorAxesHeight04')
            set(hList(118),'userdata',1);
        end
% 		emegs2d('setChanFigBGColorBlack')
	end
	if Domain==5 | Domain==6  | Domain==7 | Domain==8
		set(hList(57),'Enable','off'); 					%CalcBase
		set(hList(129),'Enable','off'); 				%CalcTotalBase
		set(hList(58),'Enable','off'); 					%MinBase
		set(hList(59),'Enable','off'); 					%MaxBase
		set(hList(50),'Enable','off'); 					%NPoints
		set(hList(60),'Enable','off'); 					%SampRate
		set(hMinMaxText(7),'Enable','off'); 			%hMinBaseText	
		set(hMinMaxText(8),'Enable','off'); 			%hMaxBaseText	
		set(hMenuTextEnable(6),'Enable','off'); 		%hSampRateText	
		set(hMenuTextEnable(7),'Enable','off'); 		%hNPointsText	
	else
		set(hList(57),'Enable','on'); 					%CalcBase
		set(hList(129),'Enable','on'); 					%CalcTotalBase
		set(hList(58),'Enable','on'); 					%MinBase
		set(hList(59),'Enable','on'); 					%MaxBase
		set(hList(50),'Enable','on'); 					%NPoints
		set(hList(60),'Enable','on'); 					%SampRate
		set(hMinMaxText(7),'Enable','on'); 				%hMinBaseText	
		set(hMinMaxText(8),'Enable','on'); 				%hMaxBaseText
		set(hMenuTextEnable(6),'Enable','on'); 			%hSampRateText	
		set(hMenuTextEnable(7),'Enable','on'); 			%hNPointsText	
	end
	for FileIndex=1:length(FileNoVec)
		NChan=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+2),'Userdata');
      	NPoints=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+3),'Userdata');
     	if Domain~=5
            if Domain~=8 & Domain~= 7 & Domain~=6
                hSigVec=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+30),'Userdata');
				set(hSigVec,'Visible','off','String',[]);
            end
		end
     	if Domain==1 | Domain==6	 | Domain==7	| Domain==8%Time, Wavelet
			ActTmpMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+24),'Userdata');
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',ActTmpMat); %Actual data set
		elseif Domain==2	%std
			ActTmpMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+6),'Userdata');
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',ActTmpMat); %Actual data set
			emegs2d('CalcFirst')
		elseif Domain==3 | Domain==4 %frequency		s
			NPointsTmp=floor(NPoints./2).*2;	%Take even number of points
			XVec=[1:NPointsTmp./2+1];		%[0 : Nyquist]
			XInterVec=linspace(1,NPointsTmp./2+1,NPoints);
			ActTmpMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
			[FFTDataMat,PFFTDataMat,FrequResol,ch_UseTimeWin,ch_KindTimeWin,RInt]=CalcFFTMat(ActTmpMat(:,1:NPointsTmp),SampRate,0,4,64,1); %0 No window 4 64
			if Domain==3 %Power
				FFTDataMat=PFFTDataMat;
			elseif Domain==4 %Phase
				FFTDataMat=atan(real(FFTDataMat)./imag(FFTDataMat));
			end
			for ChanInd=1:NChan
				ActTmpMat(ChanInd,:)=interp1(XVec,FFTDataMat(ChanInd,1:NPointsTmp./2+1),XInterVec);
			end
			set(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata',ActTmpMat); %Actual data set	
		elseif Domain==5	%PCA
			ActTmpMat=get(hList(NListHdr+(FileNoVec(FileIndex)-1).*50+1),'Userdata');
		end
		if Domain==1 | Domain==5 | Domain==6 | Domain==7 | Domain ==8
         	MinAmpTmp=min(min(ActTmpMat));
         	MaxAmpTmp=max(max(ActTmpMat));
		elseif Domain==2
			MinAmpTmp=0;
         	MaxAmpTmp=max(max(ActTmpMat));
		elseif Domain==3
			MinAmpTmp=0;
			MaxAmpTmp=mean(mean(ActTmpMat));
		elseif Domain==4
			MaxAmpTmp=4.*mean(mean(abs(ActTmpMat)));
			MinAmpTmp=-1.*MaxAmpTmp;			
		end
		if FileIndex==1
			MinAmp=MinAmpTmp;
			MaxAmp=MaxAmpTmp;
		else
			MinAmp=min(MinAmp,MinAmpTmp);
			MaxAmp=min(MaxAmpTmp,MaxAmp);	
		end
		set(hList(NListHdr+(FileIndex-1).*50+11),'Userdata',MinAmpTmp);
		set(hList(NListHdr+(FileIndex-1).*50+12),'Userdata',MaxAmpTmp);
	end
	if MinAmpVec(Domain)==MaxAmpVec(Domain); %if MinMax Amplitudes of domain are not predefined 
		MinAmpVec=get(hList(52),'Userdata');
		if Domain==6 | Domain==7	
			MinAmp=MinAmpVec(1);	%Time
		end
		MinAmpVec(Domain)=MinAmp;
   		set(hList(52),'Value',MinAmp,'Userdata',MinAmpVec,'String',sprintf('%g',round(MinAmp*100)/100));
    	MaxAmpVec=get(hList(53),'Userdata');
		if Domain==6 | Domain==7	
			MaxAmp=MaxAmpVec(1);	%Time
		end
		MinAmpVec(Domain)=MaxAmp;
   		set(hList(53),'Value',MaxAmp,'Userdata',MaxAmpVec,'String',sprintf('%g',round(MaxAmp*100)/100));
	end
	if CalcBaseStatus
		emegs2d('CalcBaseNoCall');	
	end
	if Domain==6 | Domain==7 | Domain==8	%Wavelet
		figure(hList(93));	        %hPlot2dChanFig
		ChanFigBGColor=get(hList(93),'Color');	
		if ChanFigBGColor==[0 0 0]; XColorStr='w'; else; XColorStr='k'; end
		hSpec2Axes=axes('Units','normal','Position',[0.05 0.90 .15 .025],'Box','off');
		XPColor=linspace(0,1);
		pcolor(XPColor,[0 1],ones(2,1)*XPColor); 
		shading interp; 	
		set(hSpec2Axes,'XTick',[0 1],'XTickLabel',[round(MinAmp.*100)./100 round(MaxAmp.*100)./100], 'YTick',[],'YTickLabel',[],'FontSize',10,'XColor',XColorStr);
		if Domain==6
			Str='[µV/Hz]';
		elseif Domain==7
			Str='[ ]';
        elseif Domain==8
			Str='[µV/Hz]';
		end
		text('Units','normal','Position',[.5 -0.4],'Color',XColorStr,'String',Str,'FontSize',10,'Horiz','center');
		ColorMat=jet(128);
		colormap(ColorMat);
		set(hList(104),'Userdata',hSpec2Axes);
	end
	emegs2d('PlotData')
	if Domain==6 | Domain==7 | Domain==8 ; return; end
	emegs2d('setMinMaxAmpPoint');	
	emegs2d('setTrigPointNoCall');	
	emegs2d('setCursorPoint');	
	emegs2d('SetDefXTickVal');
	%=============================================================================
	%============ CalcPCA
	%============ external: CalcPCA(Initialize)
	%=============================================================================
elseif strcmp(action,'CalcPCAActActDat') | ...
	strcmp(action,'CalcPCAActActCov') | ...
	strcmp(action,'CalcPCAActActCor') | ...
	strcmp(action,'CalcPCAActOrgDat') | ...
	strcmp(action,'CalcPCAActOrgCov') | ...
	strcmp(action,'CalcPCAAllOrgCor') | ...
	strcmp(action,'CalcPCAAllActDat') | ...
	strcmp(action,'CalcPCAAllActCov') | ...
	strcmp(action,'CalcPCAAllActCor') | ...
	strcmp(action,'CalcPCAAllOrgDat') | ...
	strcmp(action,'CalcPCAAllOrgCov') | ...
	strcmp(action,'CalcPCAAllOrgCor') | ...
	strcmp(action,'CalcICAActActDat') | ...
	strcmp(action,'CalcICAActActCov') | ...
	strcmp(action,'CalcICAActActCor') | ...
	strcmp(action,'CalcICAActOrgDat') | ...
	strcmp(action,'CalcICAActOrgCov') | ...
	strcmp(action,'CalcICAAllOrgCor') | ...
	strcmp(action,'CalcICAAllActDat') | ...
	strcmp(action,'CalcICAAllActCov') | ...
	strcmp(action,'CalcICAAllActCor') | ...
	strcmp(action,'CalcICAAllOrgDat') | ...
	strcmp(action,'CalcICAAllOrgCov') | ...
	strcmp(action,'CalcICAAllOrgCor') | ...
	strcmp(action,'CalcICACelActDat') | ...
	strcmp(action,'CalcPMAActActDat') | ...
	strcmp(action,'CalcPMAActOrgDat') | ...
	strcmp(action,'CalcPMAAllActDat') | ...
	strcmp(action,'CalcPMAAllOrgDat') | ...
	strcmp(action,'CalcVMAActActDat') | ...
	strcmp(action,'CalcVMAActOrgDat') | ...
	strcmp(action,'CalcVMAAllActDat') | ...
	strcmp(action,'CalcVMAAllOrgDat'),
	
	PCAICAMusic(action)
	
	%=============================================================================
	%============ Plot3d
	%============ external: emegs3d(Initialize)
	%=============================================================================		
elseif strcmp(action,'Plot3d') | strcmp(action,'Plot3dSLC') | strcmp(action,'Plot3dMN') | ...
    strcmp(action,'Plot3dSLCMN') | strcmp(action,'Plot3dUserDef'), 

	hList=get(hPlot2dMenuFig,'Userdata');	
	emegs3d('Initialize');
	if strcmp(action,'Plot3dSLC')
		emegs3d('CalcCortMap')
	elseif strcmp(action,'Plot3dMN')
		emegs3d('CalcMinimumNorm')
    elseif strcmp(action,'Plot3dSLCMN')
        hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
        set(hPlot3dList(12),'Value',4); %h2d3dViewMenu
        emegs3d('set2d3dView');
        set(hPlot3dList(112),'Value',3);%hSpecTaskMenu
        emegs3d('setSpecTask');
    elseif strcmp(action,'Plot3dUserDef')
        Emegs3dUserDef;
	end

	%=============================================================================
	%============ SaveViewDefaultFile
	%=============================================================================	
elseif strcmp(action,'SaveViewDefaultFile')
	
	hList=get(hPlot2dMenuFig,'Userdata');
	
	ECfgFilePath=get(hList(2),'Userdata');		% current file path of sensor configuration file	
	
	ZeroLine=get(hList(8),'Userdata');			% zeroline style and color	
	ZeroLineStyle=get(ZeroLine(1),'LineStyle');
	ZeroLineColor=get(ZeroLine(1),'Color');
	hSpec1=get(hList(77),'Userdata');
    LineVisible=get(hSpec1,'Visible');
    if strcmp(LineVisible,'on'); ZeroLineStatus=1; else; ZeroLineStatus=0; end
    ZeroLineStatus=ZeroLineStatus
    
	TriggerLine=get(hList(9),'Userdata');		% trigger line style and color
	TriggerLineColor=get(TriggerLine(1),'Color');
	TriggerLineStyle=get(TriggerLine(1),'LineStyle');
    hSpec1=get(hList(78),'Userdata');
    LineVisible=get(hSpec1,'Visible');
    if strcmp(LineVisible,'on'); TriggerLineStatus=1; else; TriggerLineStatus=0; end
	TriggerLineStatus=TriggerLineStatus
    
	CursorLine=get(hList(10),'Userdata');		% cursor line style and color
	CursorLineColor=get(CursorLine(1),'Color');
	CursorLineStyle=get(CursorLine(1),'LineStyle');
	hSpec1=get(hList(79),'Userdata');
    LineVisible=get(hSpec1,'Visible');
    if strcmp(LineVisible,'on'); CursorLineStatus=1; else; CursorLineStatus=0; end
    
	TrigPoint=get(hList(22),'Value');			% position of trigger and cursor	
	CursorPoint=get(hList(23),'String');	
	
	ViewVal=get(hList(26),'value');			% current view		
	
	MinAmp=get(hList(52),'Value');			% Amplitudes and time points of sensor subplots
	MaxAmp=get(hList(53),'Value');
	MinPoint=get(hList(54),'String');
	MaxPoint=get(hList(55),'String');
	
	CalcBaseStatus=get(hList(57),'Value');
	MinBase=get(hList(58),'String');			% intervall to calculate baseline
	MaxBase=get(hList(59),'String');
	NListHdr=get(hList(51),'Userdata');			% constant
	ChanFigBGColor=get(hPlot2dMenuFig,'Color');	% background color
    
	FileNoVec=get(hList(56),'Userdata');
	
	for FileNo=1:length(FileNoVec)				% style and color of files
		Color(FileNo)=get(hList(NListHdr+(FileNo-1).*50+16),'Value');
		LineStyle(FileNo)=get(hList(NListHdr+(FileNo-1).*50+17),'Value');
	end;	
	
	if isempty(FileNoVec)
		Message=char('Sorry,');
		Message=char(Message,'');
		Message=char(Message,'no data available.');
		Message=char(Message,'Please open a data set first.');
		hmsgbox=msgbox(Message,'Info','help'); 
		return;
	end;	

	%---------- user input: file name of UserDefaultBinFile (*.udef) ---------------
	ViewDefPath=which('View.udef');
	IndSepPathVec=findstr(ViewDefPath,filesep);
	if ~isempty(IndSepPathVec)	
		[BasePath]=StartPath('View.udef');
	end
    if isempty(varargin)
		[defFileName,defFilePath]=uiputfile(['*.udef'],'Name of default file (*.udef):');
		if defFileName==0; return; end
        if isempty(findstr(defFileName,'.udef'))
			defFileName=[defFileName,'.udef'];
		end;
        FilePath=[defFilePath,defFileName];
    else
        FilePath = varargin{1};
    end
    
    %3dstatus
    %------------------------------
    emegs3dstatus = 0;
    if ~isempty(hPlot3dMenuFig)
        if ishandle(hPlot3dMenuFig)
            emegs3dstatus = 1;
        end
    end
  
	%---------- write data to file -------------------------------------------------
	fid = fopen(FilePath,'w','b');
	
	fwrite(fid,'Version','char');
	ReadViewDefVersion=2; %04.03.02
	fwrite(fid,ReadViewDefVersion,'int16');
	
	fwrite(fid,length(ECfgFilePath),'int8');
	fwrite(fid,ECfgFilePath,'char');
    
   	fwrite(fid,length(ZeroLineStyle),'int8');
	fwrite(fid,ZeroLineStyle,'char');	
	fwrite(fid,ZeroLineColor,'int8');		% 1x3 vector
    fwrite(fid,ZeroLineStatus,'int8');
	    
	fwrite(fid,length(TriggerLineStyle),'int8');
    fwrite(fid,TriggerLineStyle,'char');	
	fwrite(fid,TriggerLineColor,'int8');		% 1x3 vector
    fwrite(fid,TriggerLineStatus,'int8');
    
	fwrite(fid,length(CursorLineStyle),'int8');
  	fwrite(fid,CursorLineStyle,'char');
	fwrite(fid,CursorLineColor,'int8');		% 1x3 vector
    fwrite(fid,CursorLineStatus,'int8');
    
	fwrite(fid,TrigPoint,'float32');
		
	fwrite(fid,length(CursorPoint),'int8');
	fwrite(fid,CursorPoint,'char');
	
	fwrite(fid,ViewVal,'int8');
	
	fwrite(fid,MinAmp,'float32');
	fwrite(fid,MaxAmp,'float32'); 
	
	fwrite(fid,length(MinPoint),'int8');
	fwrite(fid,MinPoint,'char');
	fwrite(fid,length(MaxPoint),'int8');
	fwrite(fid,MaxPoint,'char');
		
	fwrite(fid,length(MinBase),'int8');
	fwrite(fid,MinBase,'char');
	fwrite(fid,length(MaxBase),'int8');
	fwrite(fid,MaxBase,'char');
	fwrite(fid,CalcBaseStatus,'int8');
	fwrite(fid,ChanFigBGColor,'float32');	% 1x3 vector %Geaendert MJ
	fwrite(fid,length(FileNoVec),'int8');
	fwrite(fid,FileNoVec,'int8');			% 1xlength(FileNoVec) vector
	for FileNo=1:length(FileNoVec)
		fwrite(fid,Color(FileNo),'int8');	% one integer value !
		fwrite(fid,LineStyle(FileNo),'char');	% one integer value !
	end;	
    
    fwrite(fid,emegs3dstatus,'int8');
    
    if emegs3dstatus
        
        
        hPlot3dList=get(hPlot3dMenuFig,'Userdata');
        
        HeadModel=get(hPlot3dList(129),'Userdata');
        fwrite(fid,HeadModel,'int8');
        
        CutRealBotVal=get(hPlot3dList(127),'Value');
		fwrite(fid,CutRealBotVal,'int8');
        
        MinPoint3d=get(hPlot3dList(47),'Value');
		fwrite(fid,MinPoint3d,'int8');
        
        MaxPoint3d=get(hPlot3dList(49),'Value');
		fwrite(fid,MaxPoint3d,'int8');
        
        Dim2d3dViewVal=get(hPlot3dList(12),'Value');	%'Spec. Surf (3d)|All Surf I (3d)|All Surf II (3d) |Plot (2d)|Spec. Right'|Columns & Rows;
        fwrite(fid,Dim2d3dViewVal,'int8'); 
        
        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';
        fwrite(fid,HeadView,'int8');
         
        ThetaView=get(hPlot3dList(16),'Userdata');
        fwrite(fid,ThetaView,'int16');
        
        PhiView=get(hPlot3dList(18),'Userdata');
        fwrite(fid,PhiView,'int16');
        
        DistPointVec=get(hPlot3dList(41),'Userdata');
        DistPoint=DistPointVec(1);
        fwrite(fid,DistPoint,'int8');
        
        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');
        fwrite(fid,SensorNameStatus,'int8');
        
        SensorCircleStatus=get(hStyleTextSensorMenu(2),'Userdata');
        fwrite(fid,SensorCircleStatus,'int8');
        
        SensorAsteriskStatus=get(hStyleTextSensorMenu(3),'Userdata');
        fwrite(fid,SensorAsteriskStatus,'int8');
        
        FlipColormapStatus=get(hPlot3dList(118),'Value'); 
        fwrite(fid,FlipColormapStatus,'int8');
        
        ColorMapVal=get(hPlot3dList(20),'Value');
        fwrite(fid,ColorMapVal,'int8');
        
        MinAmp3d=get(hPlot3dList(22),'Userdata');
        fwrite(fid,MinAmp3d,'float32');
        
        MaxAmp3d=get(hPlot3dList(24),'Userdata');
        fwrite(fid,MaxAmp3d,'float32');
        
        CenterAmpStatus3d=get(hPlot3dList(25),'Value');
        fwrite(fid,CenterAmpStatus3d,'int8');
        
        SpecAmpStatus3d=get(hPlot3dList(26),'Value');
        fwrite(fid,SpecAmpStatus3d,'int8');
        
        Print2FileStatus3d=get(hPlot3dList(27),'Value');
        fwrite(fid,Print2FileStatus3d,'int8');
        
        NColor=str2num(get(hPlot3dList(117),'String'));
        fwrite(fid,NColor,'int8');
        
        MoviePauseStatus=get(hPlot3dList(28),'Value');
        fwrite(fid,MoviePauseStatus,'int8');
        
        PlotEPosStatus=get(hPlot3dList(30),'Value');
        fwrite(fid,PlotEPosStatus,'int8');
        
        PlotContourStatus=get(hPlot3dList(35),'Value');
        if HeadModel~=1
            PlotContourStatus=3;
        end
        fwrite(fid,PlotContourStatus,'int8');
        
        
        PlotLatencyStatus=get(hPlot3dList(43),'Value');
        fwrite(fid,PlotLatencyStatus,'int8');
        
        GrayFitVal = get(hPlot3dList(119),'Value');
        fwrite(fid,GrayFitVal,'int8');
        
        ColorAmpTotStatus = get(hPlot3dList(120),'Userdata');
        fwrite(fid,ColorAmpTotStatus,'int8');
        
        UseApp=get(hPlot3dList(72),'Value');
        fwrite(fid,UseApp,'int8');
        
        SLCLambdaApprox=get(hPlot3dList(69),'Value');
        fwrite(fid,SLCLambdaApprox,'float32');
        
        MNLambdaApprox=get(hPlot3dList(109),'Value');
        fwrite(fid,MNLambdaApprox,'float32');
        
        PlusMinusStatusVec=get(hPlot3dList(139),'Userdata');
        
        PlusMinusStatus=PlusMinusStatusVec(1);
        fwrite(fid,PlusMinusStatus,'int8');
        
        ActMethod=get(hPlot3dList(51),'Value');   
        fwrite(fid,ActMethod,'int8');  
        
    end
	fclose(fid);
	clear;
	%=============================================================================
	%============ AutoViewDefaultFile
	%============ call: ... 
	%=============================================================================	
elseif 	strcmp(action,'AutoViewDefaultFile') | strcmp(action,'AutoViewDefaultFileOn') | strcmp(action,'AutoViewDefaultFileOff'),
	
	hList=get(hPlot2dMenuFig,'Userdata');
	hTopMenu=get(hList(65),'Userdata');
	hFileMenu=get(hTopMenu(1),'children');
	hDefFileMenu=get(hFileMenu(1),'children');
	hInfoFileMenu=get(hDefFileMenu(1),'children');
	hAutoDefFileMenu=hDefFileMenu(4);
	if strcmp(action,'AutoViewDefaultFileOn')
		AutoViewDefaultFileStatus=1;
	elseif strcmp(action,'AutoViewDefaultFileOff');
		AutoViewDefaultFileStatus=0;
	elseif strcmp(action,'AutoViewDefaultFile')
		AutoViewDefaultFileStatus=get(hAutoDefFileMenu,'Userdata');
		if AutoViewDefaultFileStatus
			AutoViewDefaultFileStatus=0;
		else
			AutoViewDefaultFileStatus=1;
		end
	end
	pointer=get(hList(83),'Userdata');
	AutoDefFileMenuLabel=get(hAutoDefFileMenu,'Label');
	PointPosEnd=length(AutoDefFileMenuLabel);
	if AutoViewDefaultFileStatus
		AutoDefFileMenuLabel(PointPosEnd)=setstr(pointer);
	else
		AutoDefFileMenuLabel(PointPosEnd)=' ';
	end
	set(hAutoDefFileMenu,'Label',AutoDefFileMenuLabel,'Userdata',AutoViewDefaultFileStatus);

	%=============================================================================
	%============ ReadViewDefaultFile
	%============ call: ... 
	%=============================================================================	
elseif 	strcmp(action,'ReadViewDefaultFile');	
	
    %try
		hList=get(hPlot2dMenuFig,'Userdata');
		hTopMenu=get(hList(65),'Userdata');
		hFileMenu=get(hTopMenu(1),'Children');
		hDefFileMenu=get(hFileMenu(1),'Children');
		hInfoFileMenu=get(hDefFileMenu(1),'Children');
		hAutoDefFileMenu=hDefFileMenu(4);
		AutoViewDefaultFileStatus=get(hAutoDefFileMenu,'Userdata');
		NListHdr=get(hList(51),'Userdata');			% constant
        FileNoVec=get(hList(56),'Userdata');
		ActFileNo=get(hList(1),'Value');
		AvgFileFormat=get(hList(NListHdr+(ActFileNo-1).*50+22),'Userdata');
		ActFilePath=get(hList(NListHdr+(ActFileNo-1).*50+4),'Userdata');
        if ~isempty(ActFilePath) & ~isequal(ActFilePath,0)
            [ActFile,ActPath]=SepFilePath(ActFilePath);
			FileSepVec=findstr(ActFilePath,filesep);
			ActFolder=ActFilePath(FileSepVec(length(FileSepVec)-1)+1:FileSepVec(length(FileSepVec))-1);
        else
            FileNoVec = 1;
        end
		
		if strcmp(AvgFileFormat,'AsciiVec') & isempty(FileNoVec)
			Message=char('Sorry,');
			Message=char(Message,'');
			Message=char(Message,'if the data file format is')
			Message=char(Message,'"AsciiVec" you have to open a data ');
			Message=char(Message,'set before opening a view default file.');
			hmsgbox=msgbox(Message,'Info','help'); 
			return;
		end;	
		ViewDefFilePath=[];
        
		if AutoViewDefaultFileStatus
            ViewDefFile=[ActFolder,'.udef'];
            Message=char('Search for AutoView (.udef) file:');
			Message=char(Message,'');
            Message=char(Message,'Look for ActualFolder.udef:');
            Message=char(Message,ViewDefFile);
			Tmp=exist(ViewDefFile);
			if Tmp==2		
                Message=char(Message,'File exists. Take file:');
                Message=char(Message,ViewDefFile);
                Message=char(Message,'as view default file.');
				Message=char(Message,'');  
			    hmsgbox=msgbox(Message,'Info','help'); 
				ViewDefFilePath=which(ViewDefFile);
            elseif length(ActFile>2)
                ViewDefFile=[ActFile(1:3),'.udef'];
                Message=char(Message,'File does not exist.');
                Message=char(Message,'');        
                Message=char(Message,'Look for First3DigitsOfDataFile.udef:');
                Message=char(Message,ViewDefFile);
                Message=char(Message,'as view default file.'); 
                Message=char(Message,'');    
                Tmp=exist(ViewDefFile);
			    if Tmp==2		
                    Message=char(Message,'File exists. Take file:');
                    Message=char(Message,ViewDefFile);
                    Message=char(Message,'as view default file.');
					Message=char(Message,''); 
			        hmsgbox=msgbox(Message,'Info','help'); 
				    ViewDefFilePath=which(ViewDefFile);
                else
                    Message=char(Message,'File does not exist.');
                    Message=char(Message,''); 
                    Message=char(Message,'Set AutoViewDefaultFileStatus off.'); 
					Message=char(Message,''); 
                    hmsgbox=msgbox(Message,'Info','help'); 
				    ViewDefFilePath=[];
                    AutoViewDefaultFileStatus=0;
                    set(hAutoDefFileMenu,'Userdata',AutoViewDefaultFileStatus);
                end
            else
                Message=char(Message,'File does not exist.');
                Message=char(Message,''); 
                Message=char(Message,'Set AutoViewDefaultFileStatus off.'); 
                hmsgbox=msgbox(Message,'Info','help'); 
				ViewDefFilePath=[];
                AutoViewDefaultFileStatus=0;
                set(hAutoDefFileMenu,'Userdata',AutoViewDefaultFileStatus);
			end
			hmsgboxchild=get(hmsgbox,'Children');
           	set(hmsgboxchild(length(hmsgboxchild)),'Visible','off');
			pause(2)
			close(hmsgbox);
		end
		
        if ~isempty(varargin)
            ViewDefFilePath = varargin{1};
            [ViewDefFile,ViewDefPath] = SepFilePath(ViewDefFilePath);
        end
        
		if isempty(ViewDefFilePath)
			%---------- user input: file name of UserDefaultBinFile (*.udef) ---------------
			ViewDefPath=which('View.udef');
			IndSepPathVec=findstr(ViewDefPath,filesep);
			if ~isempty(IndSepPathVec)	
				ViewDefPath=ViewDefPath(1:IndSepPathVec(length(IndSepPathVec)));
				[ViewDefFile,ViewDefPath]=uigetfile([ViewDefPath,'*.udef'],'Name of default file (*.udef):');
			else
				[ViewDefFile,ViewDefPath]=uigetfile('*.udef','Name of default file (*.udef):');
			end
			ViewDefFilePath=[ViewDefPath,ViewDefFile];
			if isempty(find(ViewDefFilePath)); return; end;	
		end		
		set(hInfoFileMenu(1),'Label',ViewDefFile);
		%---------- read data from view default file ------------------------------------------------
		[ReadViewDefVersion,DefECfgFilePath,DefZeroLineStyle,DefZeroLineColor,DefTriggerLineStyle,DefTriggerLineColor,...
		DefCursorLineStyle,DefCursorLineColor,DefTrigPoint, DefCursorPoint,DefViewVal,DefMinAmp,...
		DefMaxAmp,DefMinPoint,DefMaxPoint,DefMinBase,DefMaxBase, ...
		DefChanFigBGColor,DefFileNoVec,Color,LineStyle,DefCalcBaseStatus,...
        DefZeroLineStatus,DefTriggerLineStatus,DefCursorLineStatus,...
        emegs3dstatus,CutRealBotVal,MinPoint3d,MaxPoint3d,Dim2d3dViewVal,HeadView,ThetaView,PhiView,DistPoint,SensorNameStatus,SensorCircleStatus,...
		SensorAsteriskStatus,FlipColormapStatus,ColorMapVal,MinAmp3d,MaxAmp3d,CenterAmpStatus3d,SpecAmpStatus3d,Print2FileStatus3d,...
		NColor,PlotEPosStatus,PlotContourStatus,PlotLatencyStatus,GrayFitVal,UseApp,SLCLambdaApprox,MNLambdaApprox ,...
		PlusMinusStatusVec,PlusMinusStatus,PlusMinusVal,ActMethod]=ReadViewDef(ViewDefFilePath);
		%----------------------------------------------------------------------------
		for FileNo=1:length(DefFileNoVec)
			set(hList(NListHdr+(FileNo-1).*50+19),'Userdata',Color(FileNo),'value',0);
			set(hList(NListHdr+(FileNo-1).*50+20),'Userdata',LineStyle(FileNo),'value',0);
		end;
		set(hList(90),'Userdata',DefFileNoVec);		% files with default settings
		set(hList(91),'Userdata',DefECfgFilePath);	
		%-------------- open data file with default sensor configuration file --------
        %-------------- set Color and LineStyle of data graphs --------------------------
		if isempty(FileNoVec)	
			set(hList(1),'value',1);	
			emegs2d('OpenAvgFile');
			NewFileNoVec=get(hList(56),'Userdata');
       	else
       	   	ActFileNo = get(hList(1),'Userdata');
       	   	MaxNFiles = min(length(DefFileNoVec),length(FileNoVec));
       	   	for FileNo=1:MaxNFiles
       	        set(hList(1),'Userdata',FileNo);   
       	        emegs2d('setColor');
       	        emegs2d('setLineStyle');   
       	   	end; 
       	   	set(hList(1),'Userdata',ActFileNo);
            
        end
		%--------- set Trigger-, Cursor-, ZeroLineStyle -------------------------------------
       
        hZeroLine=get(hList(8),'Userdata');
        try
       	    set(hZeroLine,'LineStyle',DefZeroLineStyle,'Color',DefZeroLineColor);
        catch;end
        
		hSpec1ZeroLine=get(hList(77),'Userdata');
        try
		    set(hSpec1ZeroLine,'LineStyle',DefZeroLineStyle,'Color',DefZeroLineColor);
        catch;end
       	
        TriggerLine=get(hList(9),'Userdata');
        try
       	    set(TriggerLine,'LineStyle',DefTriggerLineStyle,'Color',DefTriggerLineColor);
        catch;end
		hSpec1TrigLine=get(hList(78),'Userdata');
        try
		    set(hSpec1TrigLine,'LineStyle',DefTriggerLineStyle,'Color',DefTriggerLineColor);	
        catch;end
	
        CursorLine=get(hList(10),'Userdata');
        try
            set(CursorLine,'LineStyle',DefCursorLineStyle,'Color',DefCursorLineColor);
        catch;end
		hSpec1CursorLine=get(hList(79),'Userdata');
        try
		    set(hSpec1CursorLine,'LineStyle',DefCursorLineStyle,'Color',DefCursorLineColor);
        catch;end
        %--------- set BackgrundColor --------------------------------------------------- 
       	set(hPlot2dMenuFig,'Color',DefChanFigBGColor);
		hSpec1Axes=get(hList(76),'Userdata');
        try
		    set(hSpec1Axes,'Color',DefChanFigBGColor)
        catch;end
        %--------- set Trig Point -------------------------------------------------------
        try
		    set(hList(22),'String',sprintf('%2g',DefTrigPoint));
        catch;end
		emegs2d('setTrigPointNoCall');
       	%-------- set MinMaxAmp ------------------------------------------------------
       	MinAmp = get(hList(52),'Value');
        if MinAmp ~= DefMinAmp
            try
			    set(hList(52),'String',sprintf('%2g',DefMinAmp));
            catch;end
			emegs2d('setMinAmpNoCall');
       	end
       	MaxAmp = get(hList(53),'Value');
       	if MaxAmp ~= DefMaxAmp
            try
			set(hList(53),'String',sprintf('%2g',DefMaxAmp));
            catch;end
			emegs2d('setMaxAmpNoCall');
        end   
        %--------- set MinMaxPoint ------------------------------------------------------
       	MinPoint = get(hList(54),'String');
       	emegs2d('setMinPointNoCompNoCall');
        try
		set(hList(55),'String',DefMaxPoint);
        catch;end
		emegs2d('setMaxPointNoCompNoCall');
		%--------- set MinMaxBase  ------------------------------------------------------
        try
		set(hList(57),'Value',DefCalcBaseStatus);
        catch;end% calculate BaseLine radio button
        try
        set(hList(58),'String',DefMinBase);
        catch;end
        emegs2d('setMinBaseNoCompNoCall');
        try
        set(hList(59),'String',DefMaxBase);
        catch;end
        emegs2d('setMaxBaseNoCompNoCall');
		emegs2d('CalcBase');
		%----------------------------------------------------------------------------
		emegs2d('setMinMaxAmpPoint');
        %--------- set CursorPoint ----------------------------------------------------
		set(hList(23),'String',DefCursorPoint);
		emegs2d('setCursorPoint');
        %--------- set Zeroline, Cursor and Trigger Visibility ------------------------
        if DefZeroLineStatus
             emegs2d('setZerolineVisibleOn');
        else
             emegs2d('setZerolineVisibleOff');
        end
        if DefTriggerLineStatus
             emegs2d('setTriggerVisibleOn');
        else
             emegs2d('setTriggerVisibleOff');
        end
        if DefCursorLineStatus
             emegs2d('setCursorVisibleOn');
        else
             emegs2d('setCursorVisibleOff');
        end
        
        
        %-----------3d settings-------------------------------------
        if  emegs3dstatus
            
            emegs3d('Initialize');
            SampRate = get(hList(60),'Userdata');
            NPoints = get(hList(50),'Userdata');
            TrigPoint = get(hList(22),'Userdata');
            Domain = 1;
            
            global hPlot3dMenuFig;
            hPlot3dList = get(hPlot3dMenuFig,'userdata');
            %-- CutRealBot-----------------
            try
            set(hPlot3dList(127),'Value',CutRealBotVal);
            emegs3d('CutRealBot');
            catch;end
            %-- MinTime-----------------
            try
                disp(['settings maxpoint to ',num2str(Point2Ms(MaxPoint3d,Domain,SampRate,TrigPoint(Domain,1))),'...']);
                set(hPlot3dList(47),'String',num2str(Point2Ms(MinPoint3d,Domain,SampRate,TrigPoint(Domain,1),NPoints)));
                emegs3d('setMinPoint');
            catch;end
            %-- MaxTime-----------------
            try
                disp(['settings maxpoint to ',num2str(Point2Ms(MaxPoint3d,Domain,SampRate,TrigPoint(Domain,1))),'...']);
                set(hPlot3dList(49),'String',num2str(Point2Ms(MaxPoint3d,Domain,SampRate,TrigPoint(Domain,1),NPoints)));
                emegs3d('setMaxPoint');
            catch;end
            %--PlotStyle---------------
            try
            set(hPlot3dList(12),'Value',Dim2d3dViewVal);
            emegs3d('set2d3dView');
            catch;end
            %--HeadView-------------------
            try
            set(hPlot3dList(14),'Value',HeadView);
            emegs3d('setHeadView');
            catch;end
            %--ThetaView-------------
            try
            set(hPlot3dList(20),'Value',ThetaView);
            emegs3d('setThetaView');
            catch;end
            %--PhiView-------------
            try
            set(hPlot3dList(21),'Value',PhiView);
            emegs3d('setPhiView');
            catch;end
            %--DistPoint-------------
            try
            set(hPlot3dList(41),'String',num2str(DistPoint));
            emegs3d('setDistPoint');
            catch;end
            
            %--PlotSensorStatus----
%             
%             
%             
            %--SensorNameStatus-------------
%             set(hPlot3dList(),'Value',);
%             emegs3d('');
%             %--SensorCircleStatus-------------
%             set(hPlot3dList(),'Value',);
%             emegs3d('');
%             %--SensorAsteriskStatus-------------
%             set(hPlot3dList(),'Value',);
%             emegs3d('');
            
            
            %--FlipColormapStatus-------------
            try
            set(hPlot3dList(118),'Value',FlipColormapStatus);
            emegs3d('FlipColormap');   
            catch;end         
            %--ColorMapVal-------------
            try
            set(hPlot3dList(20),'Value',ColorMapVal);
            emegs3d('setColorMap');   
            catch;end         
            %--MinAmp3d-------------
            try
            set(hPlot3dList(22),'String',num2str(MinAmp3d));
            emegs3d('setMinAmp');
            catch;end
            %--MaxAmp3d-------------
            try
            set(hPlot3dList(24),'String',num2str(MaxAmp3d));
            emegs3d('setMaxAmp');
            catch;end
            %--CenterAmpStatus3d-------------
            try
            set(hPlot3dList(25),'Value',CenterAmpStatus3d);
            catch;end
            %--SpecAmpStatus3d-------------
            try
            set(hPlot3dList(26),'Value',SpecAmpStatus3d);
            emegs3d('setMaxAmp');
            catch;end
            %--Print2FileStatus3d-------------
            try
            set(hPlot3dList(27),'Value',Print2FileStatus3d);
            emegs3d('setPrint2FileStatus');
            catch;end
            %--NColor-------------
            try
            set(hPlot3dList(117),'String',num2str(NColor));
            catch;end
            %--PlotEPosStatus-------------
            try
            set(hPlot3dList(30),'Value',PlotEPosStatus);
            catch;end
            %--PlotContourStatus-------------
            try
            set(hPlot3dList(35),'Value',PlotContourStatus);
            catch;end
            %--PlotLatencyStatus-------------
            try
            set(hPlot3dList(43),'Value',PlotLatencyStatus); 
            catch;end           
            %--GrayFitVal-------------
            try
            set(hPlot3dList(119),'Value',GrayFitVal);
            catch;end
            
            %--UseApp-------------
            try
            set(hPlot3dList(72),'Value',UseApp);
            emegs3d('setUseApprox');
            catch;end
            %--SLCLambdaApprox-------------
            try
            set(hPlot3dList(69),'String',num2str(SLCLambdaApprox));
            emegs3d('setSLCLambdaApprox');
            catch;end
            %--PlusMinusStatus-------------
%             set(hPlot3dList(41),'String',num2str(DistPoint));
%             emegs3d('setPPlusMinusAmp');
            %--ActMethod-------------
            try
            set(hPlot3dList(51),'Value',ActMethod);  
            catch;end     
            
        end
        %catch
   %     uiwait(errordlg('There was an error while reading or opening the view-default-file!. Remember that you have to open a dataset before opening a view-default-file!'));
   %end

	%=============================================================================
	%============ Generate synthetic data
	%=============================================================================	
elseif strcmp(action,'GenSynthData')

	GenSynthData('Initialize')
	%=============================================================================
	%============ InfoViewDefaultFile
	%=============================================================================	
elseif strcmp(action,'InfoViewDefaultFile')
		
	return;
		
	%=============================================================================
	%============ EnableOnOff
	%=============================================================================	
elseif strcmp(action,'EnableOnOff')

	hList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hList(1),'Userdata');
	NListHdr=get(hList(51),'Userdata');
	hMinMaxText=get(hList(21),'Userdata');	
	hMenuEnable=get(hList(7),'Userdata');
	hMenuTextEnable=get(hList(49),'Userdata');
	
	hTopMenu=get(hList(65),'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');
	hSynthMenu=get(hTopMenu(6),'children');
	hSurfMenu=get(hTopMenu(7),'children');
	hDefFileMenu=get(hFileMenu(1),'children');
	EnableValue=get(hList(49),'Value');
	
	%---------------------------------------------------------------------------
	% EnableValue:	0	no file opened
	%				1	one file opened
	%				3	global power calculated
	%				4	more than one file opened
	%				5	four files opened
	%				6	three files opened (one was cleared)
	%				7	global power not calculated (new file opened)
	%				8	no sensor file opened
	%				9	sensor file opened
	%				10	EGIS RAW data format chosen
	%				11	No EGIS RAW data format chosen

	%---------------------------------------------------------------------------
	if EnableValue==1 | EnableValue==0
		if EnableValue ==1 
			OnOffStr='on';	% on-off-String
			set(hStyleMenu,'Enable','on');
			set(hExportMenu,'Enable','on');
			set(hCalcMenu,'Enable','on');
			set(hViewMenu,'Enable','on');
			set(hSurfMenu,'Enable','on');
			set(hDefFileMenu,'Enable','on');
			%set(hDefFileMenu(1),'Enable','off');% wenn Info belegt, weglassen !
			set(hExportMenu(2),'Enable','off');	% hExportGPRms
            set(hCalcMenu(5),'Enable','off'); 	% hCalcGPMenu
			set(hCalcMenu(14),'Enable','off');	% hCalcDiffMenu	
			set(hCalcMenu(15),'Enable','off');	% hCalcAvgMenu
		else 
			OnOffStr='off';
			set(hStyleMenu,'Enable','off');
			set(hExportMenu,'Enable','off');
			set(hCalcMenu,'Enable','off');
			set(hViewMenu,'Enable','off');
			set(hSurfMenu,'Enable','off');
			set(hDefFileMenu,'Enable','off');
			set(hDefFileMenu(3),'Enable','on');
			%set(hDefFileMenu(1),'Enable','on'); % wenn Info belegt !!!
		end;
        
% 		hCalcMenuChildVec=get(hCalcMenu,'Children');
% 		NCalcMenuChild=size(hCalcMenuChildVec,1)
% 		for i=1:NCalcMenuChild
% 	 		ChildLabel=get(hCalcMenuChildVec(i),'Label')
% 			set(hCalcMenuChildVec(i),'Enable',OnOffStr)
% 		end
			
		set(hList(1),'Enable',OnOffStr);	% hActFileNo
		set(hList(45),'Enable',OnOffStr);	% hActSpecVisible
		set(hList(61),'Enable',OnOffStr);	% hColor
		set(hList(62),'Enable',OnOffStr);	% hLineStyle
        set(hList(98),'Enable',OnOffStr);	% hLineWidth
		set(hList(19),'Enable',OnOffStr); 	% hPlot3d
		set(hList(26),'Enable',OnOffStr); 	% hView
		set(hList(20),'Enable',OnOffStr); 	% hDomain
		set(hList(50),'Enable',OnOffStr);	% hNPoints
		set(hList(52),'Enable',OnOffStr); 	% hMinAmp
		set(hList(53),'Enable',OnOffStr); 	% hMaxAmp
		set(hList(116),'Enable',OnOffStr); 	% hAdjustAmp
		set(hList(117),'Enable',OnOffStr); 	% hCenterAmp
		set(hList(118),'Enable',OnOffStr); 	% hDecAmp
		set(hList(119),'Enable',OnOffStr); 	% hDecDecIncAmp
		set(hList(120),'Enable',OnOffStr); 	% hIncAmp
		set(hList(121),'Enable',OnOffStr); 	% hIncDecIncAmp
		set(hList(122),'Enable',OnOffStr); 	% hMinPointSlider
		set(hList(123),'Enable',OnOffStr); 	% hMaxPointSlider
		set(hList(124),'Enable',OnOffStr); 	% hDecIncStatusAmp
		set(hList(125),'Enable',OnOffStr); 	% hInvertViewAmp
		set(hList(129),'Enable',OnOffStr); 	% hCalcTotalBase
		set(hList(54),'Enable',OnOffStr); 	% hMinPoint
		set(hList(55),'Enable',OnOffStr); 	% hMaxPoint
		set(hList(60),'Enable',OnOffStr);	% hSampRate
		set(hList(22),'Enable',OnOffStr); 	% hTrigPoint
		set(hList(23),'Enable',OnOffStr); 	% hCursorPoint
		set(hList(58),'Enable',OnOffStr); 	% hMinBase
		set(hList(59),'Enable',OnOffStr); 	% hMaxBase
		set(hList(57),'Enable',OnOffStr); 	% hCalcBase
		set(hList(46),'Enable',OnOffStr); 	% hZoomSpecChannel
		set(hList(47),'Enable',OnOffStr); 	% hAllSpecVisible
		set(hList(48),'Enable',OnOffStr); 	% hInfoAll
		set(hMinMaxText,'Enable',OnOffStr);	% hMinMaxText
		set(hMenuEnable,'Enable',OnOffStr);	% hActAllVisible hClearActFile  hInfoFile
											% hPlotGlobPow hPlotBut hSurfDataMatrix
											% hClearAllFiles hPlotMedMedVec
											% hZoomToggleButton
		set(hMenuTextEnable','Enable',OnOffStr);% hActspecVisibleText hColorText hLineStyleText 
											% hZoomSpecChanText hAllSpecVisibleText hSampRateText 
											% hNPointsText
		AvgFileFormatVal=get(hList(NListHdr+(ActFileNo-1).*50+22),'Value');
		[TopMenuNo,SubTopMenuNo]=GetTopMenuListNumber('t-test');
		hSubTopMenu=get(hTopMenu(TopMenuNo),'children');
		if AvgFileFormatVal==9 %SCADS	
			set(hSubTopMenu(SubTopMenuNo),'Enable',OnOffStr);
        elseif AvgFileFormatVal == 14 %Wavelet Amplitude
            set(hSubTopMenu(SubTopMenuNo),'Enable',OnOffStr);
		else
			set(hSubTopMenu(SubTopMenuNo),'Enable','Off');
		end
	elseif EnableValue ==3 
		set(hCalcMenu(5),'Enable','on');  	% hCalcGPMenu
		set(hExportMenu(2),'Enable','on');	% hExportGPRms
	elseif EnableValue ==4
		set(hCalcMenu(14),'Enable','on');	% hCalcDiffMenu
		set(hCalcMenu(15),'Enable','on');	% hCalcAvgMenu
		set(hExportMenu(2),'Enable','off');	% hExportGPRms
	elseif EnableValue ==5 | EnableValue == 6
		if EnableValue == 5 
			OnOffStr='off';
			set(hCalcMenu(15),'Enable','off');	% hCalcAvgMenu
			set(hExportMenu(2),'Enable','off');	% hExportGPRms
		else 
			OnOffStr='on'
		end	
		%set(hList(82),'Enable',OnOffStr);		% hOpenAvgFile
		%set(hTopMenu(1),'Enable',OnOffStr);	% hOpenDataFile %geaendert, vorher hTopMenuEnable(1)
	elseif EnableValue == 7
		set(hCalcMenu(15),'Enable','off');	% hCalcAvgMenu
		set(hExportMenu(2),'Enable','off');	% hExportGPRms
	elseif EnableValue == 8
		set(hExportMenu(3),'Enable','off');	% hExportECfgFile	
	elseif EnableValue == 9
		set(hExportMenu(3),'Enable','on');	% hExportECfgFile	
	elseif EnableValue == 10
		set(hCalcMenu(17),'Enable','on');	% hCalcEditEgisData
	elseif EnableValue == 11
% 		for i=1:size(hCalcMenu,1)
% 			set(hCalcMenu(i),'Enable','On')
% 		end
		set(hCalcMenu(17),'Enable','off');	% hCalcEditEgisData
	end

	%=============================================================================
	%============ Set...LineColorIndex, Set...LineStyleIndex
	%============ Clear...LineColorIndex, Clear...LineStyleIndex
	%=============================================================================	
	
elseif 	  strcmp(action,'SetZeroLineColorIndex') ...
		| strcmp(action,'SetZeroLineStyleIndex') ...
		| strcmp(action,'SetTriggerLineColorIndex') ...
		| strcmp(action,'SetTriggerLineStyleIndex') ...
		| strcmp(action,'SetCursorLineColorIndex') ...
		| strcmp(action,'SetCursorLineStyleIndex') ...
		| strcmp(action,'ClearZeroLineColorIndex') ...
		| strcmp(action,'ClearZeroLineStyleIndex') ...
		| strcmp(action,'ClearTriggerLineColorIndex') ...
		| strcmp(action,'ClearTriggerLineStyleIndex') ...
		| strcmp(action,'ClearCursorLineColorIndex') ...
		| strcmp(action,'ClearCursorLineStyleIndex')
		
	hList=get(hPlot2dMenuFig,'Userdata');
	hTopMenu=get(hList(65),'Userdata');
	hStyleMenu=get(hTopMenu(2),'children');
	pointer=get(hList(83),'Userdata');
	
	if strcmp(action,'SetZeroLineColorIndex') | strcmp(action,'ClearZeroLineColorIndex')

		ZeroLineVal=get(hList(8),'value');
		ZeroLineColorVal=ZeroLineVal(1);
		hZeroLineMenu=get(hStyleMenu(5),'children');
		hZeroLineColorMenu=get(hZeroLineMenu(2),'children');
		ZeroLineColorLabel=get(hZeroLineColorMenu(9-ZeroLineColorVal),'Label');
		PointPosZero=get(hZeroLineColorMenu(9-ZeroLineColorVal),'Userdata');
		if strcmp(action,'SetZeroLineColorIndex')
			ZeroLineColorLabel(PointPosZero)=setstr(pointer);
		else 
			ZeroLineColorLabel(PointPosZero)=' '; 
		end;
		set(hZeroLineColorMenu(9-ZeroLineColorVal),'Label',ZeroLineColorLabel);
		
	elseif  strcmp(action,'SetTriggerLineColorIndex') | strcmp(action,'ClearTriggerLineColorIndex')

		TriggerLineVal=get(hList(9),'value');
		TriggerLineColorVal=TriggerLineVal(1);
		hTriggerLineMenu=get(hStyleMenu(4),'children');
		hTriggerLineColorMenu=get(hTriggerLineMenu(2),'children');
		TriggerLineColorLabel=get(hTriggerLineColorMenu(9-TriggerLineColorVal),'Label');
		PointPosTrigger=get(hTriggerLineColorMenu(9-TriggerLineColorVal),'Userdata');
		if strcmp(action,'SetTriggerLineColorIndex')
			TriggerLineColorLabel(PointPosTrigger)=setstr(pointer);
		else 
			TriggerLineColorLabel(PointPosTrigger)=' '; 
		end;
		set(hTriggerLineColorMenu(9-TriggerLineColorVal),'Label',TriggerLineColorLabel);
		
	elseif  strcmp(action,'SetCursorLineColorIndex') | strcmp(action,'ClearCursorLineColorIndex')

		CursorLineVal=get(hList(10),'value');
		CursorLineColorVal=CursorLineVal(1);
		hCursorLineMenu=get(hStyleMenu(3),'children');
		hCursorLineColorMenu=get(hCursorLineMenu(2),'children');
		CursorLineColorLabel=get(hCursorLineColorMenu(9-CursorLineColorVal),'Label');
		PointPosCursor=get(hCursorLineColorMenu(9-CursorLineColorVal),'Userdata');
		if strcmp(action,'SetCursorLineColorIndex')
			CursorLineColorLabel(PointPosCursor)=setstr(pointer);
		else 
			CursorLineColorLabel(PointPosCursor)=' '; 
		end;
		set(hCursorLineColorMenu(9-CursorLineColorVal),'Label',CursorLineColorLabel);
		
	elseif strcmp(action,'SetZeroLineStyleIndex') | strcmp(action,'ClearZeroLineStyleIndex')

		ZeroLineVal=get(hList(8),'value');
		ZeroLineStyleVal=ZeroLineVal(2);
		hZeroLineMenu=get(hStyleMenu(5),'children');
		hZeroLineStyleMenu=get(hZeroLineMenu(1),'children');
		ZeroLineStyleLabel=get(hZeroLineStyleMenu(5-ZeroLineStyleVal),'Label');
		PointPosZero=get(hZeroLineStyleMenu(5-ZeroLineStyleVal),'Userdata');
		if strcmp(action,'SetZeroLineStyleIndex')
			ZeroLineStyleLabel(PointPosZero)=setstr(pointer);
		else 
			ZeroLineStyleLabel(PointPosZero)=' ';
		end;
		set(hZeroLineStyleMenu(5-ZeroLineStyleVal),'Label',ZeroLineStyleLabel);
		
	elseif strcmp(action,'SetTriggerLineStyleIndex') | strcmp(action,'ClearTriggerLineStyleIndex')
		
		TriggerLineVal=get(hList(9),'value');
		TriggerLineStyleVal=TriggerLineVal(2);
		hTriggerLineMenu=get(hStyleMenu(4),'children');
		hTriggerLineStyleMenu=get(hTriggerLineMenu(1),'children');
		TriggerLineStyleLabel=get(hTriggerLineStyleMenu(5-TriggerLineStyleVal),'Label');
		PointPosTrigger=get(hTriggerLineStyleMenu(5-TriggerLineStyleVal),'Userdata');
		if strcmp(action,'SetTriggerLineStyleIndex')
			TriggerLineStyleLabel(PointPosTrigger)=setstr(pointer);
		else 
			TriggerLineStyleLabel(PointPosTrigger)=' '; 
		end;
		set(hTriggerLineStyleMenu(5-TriggerLineStyleVal),'Label',TriggerLineStyleLabel);
		
	elseif  strcmp(action,'SetCursorLineStyleIndex') | strcmp(action,'ClearCursorLineStyleIndex')
		
		CursorLineVal=get(hList(10),'value');
		CursorLineStyleVal=CursorLineVal(2);
		hCursorLineMenu=get(hStyleMenu(3),'children');
		hCursorLineStyleMenu=get(hCursorLineMenu(1),'children');
		CursorLineStyleLabel=get(hCursorLineStyleMenu(5-CursorLineStyleVal),'Label');
		PointPosCursor=get(hCursorLineStyleMenu(5-CursorLineStyleVal),'Userdata');
		if strcmp(action,'SetCursorLineStyleIndex')
			CursorLineStyleLabel(PointPosCursor)=setstr(pointer);
		else 
			CursorLineStyleLabel(PointPosCursor)=' '; 
		end;
		set(hCursorLineStyleMenu(5-CursorLineStyleVal),'Label',CursorLineStyleLabel);
		
	end;	
elseif strcmp(action,'UserDefAction')
    
    hList=get(hPlot2dMenuFig,'Userdata');
    Message=char('Please define your action!');
	Message=char(Message,'');
    Message=char(Message,'Edit emegs2d.m ');
    Message=char(Message,'(search for UserDefAction)');
	hmsgbox=msgbox(Message,'Info:','help')
    disp(sprintf('Please define your action: Edit emegs2d (search for UserDefAction)'))
else
  	disp(sprintf('emegs2d: action string ''%s'' not recognized, no action taken.',action))
end;

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

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

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

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

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

function [Pointer]=GetPointer;

if strcmp(computer,'MAC2') | strcmp(computer,'MAC')	
    Pointer=195;
elseif strcmp(computer,'PCWIN') | strcmp(computer,'SOL2') | strcmp(computer,'LNX86') | strcmp(computer,'GLNX86')
	Pointer=171;
else
	Pointer=[];
end

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

function [TopMenuNo,SubTopMenuNo]=GetTopMenuListNumber(MenuString)

global hPlot2dMenuFig
hList=get(hPlot2dMenuFig,'Userdata');
hTopMenu=get(hList(65),'Userdata');
TopMenuNo=0;
RunSearch=1;
while TopMenuNo<length(hTopMenu) & RunSearch
	TopMenuNo=TopMenuNo+1;
	SubTopMenuNo=0;
	hSubMenu=get(hTopMenu(TopMenuNo),'children');
	while SubTopMenuNo<length(hSubMenu) & RunSearch
		SubTopMenuNo=SubTopMenuNo+1;
		SubMenuLabel=get(hSubMenu(SubTopMenuNo),'label');
		if ~isempty(findstr(SubMenuLabel,MenuString));
			RunSearch=0;
		end
	end 
end

return;

%=====================================================================================
function [FullPath]=ChangeDir(Str)
if isempty(Str); FullPath=[]; return; end
PathTmp=path;
a=findstr(PathTmp,Str);
if isempty(a); FullPath=[]; return; end
b=findstr(PathTmp,';');
b=[1,b]
c=find(a>b)
FullPath=PathTmp(b(c):b(c+1)-1)
eval(['cd ',FullPath])
return






