function[]=AvgApprox400(action);

%	AvgApprox400.m

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

%==================================================================
if nargin<1; action='InitializeMenu'; end

%================= global variables =============================================
global hAvgMenuFig

if strcmp(action,'InitializeMenu'),

	%============================================================================
	%=========== INITIALIZE MENU ================================================
	%============================================================================
	
	%============== figure with graphs =========================		
   	if strcmp(computer,'MAC2')	
      	ChanFigPosVec=[0 0 0.6 1];	
      	MenuFigPosVec=[.6224 0 .25 1];
		AvgInfoFigPosVec=[0 .55 MenuFigPosVec(1) .45];
		AvgMessageFigPosVec=[0 0 MenuFigPosVec(1) .45];
   	elseif strcmp(computer,'PCWIN') 
      	ChanFigPosVec=[0.005 0.01 .60 0.95];  
      	MenuFigPosVec=[0.61 0.01 0.25 0.935];
		AvgInfoFigPosVec=[0 .5 MenuFigPosVec(1) .5];
		AvgMessageFigPosVec=[0 0 MenuFigPosVec(1) .5];
    elseif strcmp(computer,'SOL2')
      	ChanFigPosVec=[0.01 0.01 .601 0.935];  
      	MenuFigPosVec=[0.6224 0.01 0.25 0.91];
		AvgInfoFigPosVec=[0 .5 MenuFigPosVec(1) .5];
		AvgMessageFigPosVec=[0 0 MenuFigPosVec(1) .5];		
   	end;
   
   	AvgInfoFigString=['Average Info:'];	
	AvgInfoFig=figure('Units','normal','NumberTitle','off',...
			'Position',AvgInfoFigPosVec,...
			'Name',AvgInfoFigString,...
			'Color',[.99 .99 .99]);
	AvgInfoAxes=axes('Units','normal','Position',[0 0 1 1]'); axis('off');
	
	AvgMessageFigString=['Messages:'];	
	AvgMessageFig=figure('Units','normal','NumberTitle','off',...
			'Position',AvgMessageFigPosVec,...
			'Name',AvgMessageFigString,...
			'Color',[.99 .99 .99]);
            
	AvgMessageAxes=axes('Units','normal','Position',[0 0 1 1]'); axis('off');

	%============== figure with menu ===========================		
	AvgMenuFigString=['Average Menu:'];
   	hAvgMenuFig=figure('Units','normal','Position',MenuFigPosVec, ...
        'Name',AvgMenuFigString,'Color',[.99 .99 .99], ...
        'NumberTitle','off');
		
    % Information for all buttons (and menus)
    labelColor=[0.8 0.8 0.8];
    yInitPos=0.90;
    menutop=0.955;
    btnTop = 0.6;
    top=0.75;
    left=0.125;
    btnWid=0.8;
    btnHt=0.0325;
	btnHt_edit=0.050;
    textHeight = 0.05;			% not used !!!!!!!!!!!
    textWidth = 0.06;
    % Spacing between the button and the next command's label
    spacing=0.0175;

    %====================================
    % 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.2 0.2 0.2];
    hConsolFrame=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',frmPos, ...
		'BackgroundColor',ConsoleRGBColor);
		
	%propedit(hConsolFrame)
	%====================================
    
	% The ChannelPlot frame
    	%frmBorder=0.019; frmBottom=0.019; 
    %frmHeight = 1-(3.*frmBorder); frmWidth = 0.725;
    %yPos=frmBottom-frmBorder;
    %frmPos=[frmBorder yPos frmWidth frmHeight+2*frmBorder];
    %hChannelPlot=uicontrol( ...
    %   'Style','frame', ...
    %    'Units','normalized', ...
    %     'Position',frmPos, ...
	%	'BackgroundColor',[0 0 0.3]);
	%propedit(hChannelPlot)

	
 	%==============================================================
    % OpenFiles (EGIS-Session-Format)==============================
	%==============================================================
	
	btnNumber=1;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'AvgApprox400(''OpenFiles'')';
	hOpenFilesMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Open File ', ...
		'Userdata',[], ...
        'Callback',callbackStr,...
		'Enable','on');
	
	%==============================================================
    % Apply OpenFiles (EGIS-Session-Format)========================
	%==============================================================
	
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'AvgApprox400(''ApplyOpenFiles'')';
	hApplyOpenFilesMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Apply files', ...
		'Userdata',[], ...
        'Callback',callbackStr,...
		'Enable','off');
	
			
	%==============================================================
    % Run average =================================================
	% callback: RunAverage ========================================
	%==============================================================
	
	btnNumber=2;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'AvgApprox400(''RunAverage'')';
	hRunAverageMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Run average', ...
		'Userdata',[], ...
        'Callback',callbackStr,...
		'Enable','off');
	

	%==============================================================
    % Selection of GrandCondStatus (popupmenu) ====================
	% default file numer: 1 =======================================
	% callback: setActFileNo ======================================
	%==============================================================
	
	
	btnNumber=2;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./2;
    labelBottom=yPos-textHeight./1.5;
    labelPos = [left+btnWid./2 labelBottom labelWidth textHeight];
   	hGrandCondStatusText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',labelPos, ...
        'Horiz','center', ...
        'String','Average status:', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white',...
		'Enable','on');
		
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
   	labelStr='Over all average|File condition average|Special file condition average|Special files condition average|Co5 file|Co5 Valence';
    callbackStr='AvgApprox400(''SetGrandCondStatus'')';

    hGrandCondStatusMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Userdata',1,...
		'Value',2,...
        'Callback',callbackStr,...
		'Enable','on');

	%==============================================================
    % Set Result Path =============================================
	% callback: SetResultPath =====================================
	%==============================================================
	
	btnNumber=3;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'AvgApprox400(''SetResultPath'')';
	hSetResultPath=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Result Path', ...
		'Userdata',[], ...
        'Callback',callbackStr,...
		'Enable','on');

	%==============================================================
    % Set Resource Path ===========================================
	% callback: SetResourcePath =====================================
	%==============================================================
	
	btnNumber=3;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'AvgApprox400(''SetResourcePath'')';
	hSetResourcePath=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Resource Path', ...
		'Userdata',[], ...
        'Callback',callbackStr,...
		'Enable','on');
	
	%==============================================================
    % SetCalcAvgRef (radio button)=================================
	% callback: SetCalcAvgRef =====================================
	%==============================================================

	btnNumber=4;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt btnWid/3 btnHt];
    callbackStr='AvgApprox400(''SetCalcAvgRef'')';

   	hSetCalcAvgRefMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Calculate', ...
			'Userdata',1,...
			'value',1,...
        	'Callback',callbackStr,...
			'Enable','on');
	
	%==============================================================
    % SetCalcAvgRef (radio button)=================================
	% callback: SetSaveAvgRef =====================================
	%==============================================================

	btnNumber=4;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left+btnWid./3 yPos-btnHt 2.*btnWid./3 btnHt];
    callbackStr='AvgApprox400(''SetSaveAvgRef'')';

   	hSetSaveAvgRef=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Save average reference', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','on');
			
	%==============================================================
    % SetUseHEVecStatus (radio button)=============================
	% callback: SetUseHEVecStatus =================================
	%==============================================================
	btnNumber=5;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt btnWid btnHt];
    callbackStr='AvgApprox400(''SetUseHEVecStatus'')';

   	hSetUseHEVecStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Use header edit status', ...
			'Userdata',0,...
			'value',0,...
        	'Callback',callbackStr,...
			'Enable','on');
			
	%==============================================================
    % SetUseQuestStatus (radio button)=============================
	% callback: SetUseQuestStatus =================================
	%==============================================================
	btnNumber=6;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt btnWid btnHt];
    callbackStr='AvgApprox400(''SetUseQuestStatus'')';

   	hSetUseQuestStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Use trials with ??? status', ...
			'Userdata',0,...
			'value',0,...
        	'Callback',callbackStr,...
			'Enable','on');
	
	
	%==============================================================
    % SetUseWEVecStatus (radio button)=============================
	% callback: SetUseWEVecStatus =================================
	%==============================================================
	btnNumber=7;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt btnWid./2 btnHt];
    callbackStr='AvgApprox400(''SetUseWEVecStatus'')';

   	hSetUseWEVecStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Use WE vector', ...
			'Userdata',1,...
			'value',1,...
        	'Callback',callbackStr,...
			'Enable','on');

	%==============================================================
    % SetUseWEMatStatus (radio button)=============================
	% callback: SetUseWEMatStatus =================================
	%==============================================================
	btnNumber=7;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    callbackStr='AvgApprox400(''SetUseWEMatStatus'')';

   	hSetUseWEMatStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Use WE matrix', ...
			'Userdata',1,...
			'value',1,...
        	'Callback',callbackStr,...
			'Enable','on');
			
	
	%==============================================================
    % SetUseEstVecStatus (radio button)============================
	% callback: SetUseEstVecStatus ================================
	%==============================================================
	btnNumber=8;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt btnWid btnHt];
    callbackStr='AvgApprox400(''SetUseEstVecStatus'')';

   	hSetUseEstVecStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Use sensor status vector', ...
			'Userdata',1,...
			'value',1,...
        	'Callback',callbackStr,...
			'Enable','on');			
			
	%==============================================================
    % SetUseApproxStatus (radio button)============================
	% callback: SetUseApproxStatus ================================
	%==============================================================
	btnNumber=9;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt btnWid btnHt];
    callbackStr='AvgApprox400(''SetUseApproxStatus'')';

   	hSetUseApproxStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Use sensor approximation', ...
			'Userdata',1,...
			'value',1,...
        	'Callback',callbackStr,...
			'Enable','on');
			
	
    %===================================
    % MinStdBaseHandle
    %===================================

	btnNumber=10;   
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hMinStdBaseText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Min. std. baseline [points]',...
		'Enable','on');
		
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 1.*btnHt_edit./2];
	callbackStr = 'AvgApprox400(''setMinStdBase'')';
    
	hMinStdBase = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
		'Value',0,...
        'String','0',...
        'callback',callbackStr,...
		'Enable','on');

		
  	%===================================
	% MaxStdBaseHandle
    %===================================

	btnNumber=10;  
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt_edit 2.*btnWid./3 btnHt_edit./2];
    
	hMaxStdBaseText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Max. std. baseline [points]',...
		'Enable','on');
			
	btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
	callbackStr = 'AvgApprox400(''setMaxStdBase'')';
    
	hMaxStdBase = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
		'Value',0,...
        'String','0',...
        'callback',callbackStr,...
		'Enable','on');		
	
	%==============================================================
    % CalcStd (radio button)===========================
	% callback: SetCalcStd ================================
	%==============================================================
	btnNumber=11;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt btnWid/4 btnHt];
    callbackStr='AvgApprox400(''SetCalcStd'')';

   	hSetCalcStd=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Calc. std', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','on');

		
	%==============================================================
    % TotIntStdBase (radio button)===========================
	% callback: SetUseTotIntStdBase ================================
	%==============================================================
	btnNumber=11;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left+btnWid/4 yPos-btnHt 3.*btnWid/4 btnHt];
    callbackStr='AvgApprox400(''SetUseTotIntStdBase'')';

   	hSetUseTotIntStdBaseMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Use total interval as std. base.', ...
			'Userdata',0,...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','on');

	%==============================================================
    % SetScalpLambda (edit text)==================================
	% callback: SetScalpLambda ===================================
	%==============================================================
   	btnNumber=12;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hSetScalpLambdaText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Scalp Lambda',...
		'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'AvgApprox400(''SetScalpLambda'')';
    
	hSetScalpLambdaMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0.02','Value',0.02, ...
        'callback',callbackStr,...
		'Enable','on');
    
	%==============================================================
    % SetCSDLambda (edit text)==================================
	% callback: SetScalpLambda ===================================
	%==============================================================
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit 2.*btnWid./3 btnHt_edit./2];
    
	hSetCSDLambdaText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','CSD Lambda',...
		'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
	callbackStr = 'AvgApprox400(''SetCSDLambda'')';
    
	hSetCSDLambdaMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0.2','Value',0.2, ...
        'callback',callbackStr,...
		'Enable','on');

	%==============================================================
    % SetScalpScaleBin (edit text)=================================
	% callback: SetScaleBin =======================================
	%==============================================================
   	btnNumber=13;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hSetScalpScaleBinText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Scalp Scale Bins',...
		'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'AvgApprox400(''SetScalpScaleBin'')';
    
	hSetScalpScaleBinMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','100','Value',100, ...
        'callback',callbackStr,...
		'Enable','on');

	%==============================================================
    % SetCSDScaleBin (edit text)===================================
	% callback: SetCSDScaleBin =====================================
	%==============================================================
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit 2.*btnWid./3 btnHt_edit./2];
    
	hSetCSDScaleBinText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','CSD Scale Bins',...
		'Enable','on');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit btnWid./3 btnHt_edit./2];
	callbackStr = 'AvgApprox400(''SetCSDScaleBin'')';
    
	hSetCSDScaleBinMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','10','Value',10, ...
        'callback',callbackStr,...
		'Enable','on');
		
    %==============================================================
    % UseTimeIntFile (radio button)===========================
	% callback: UseTimeIntFile ===============================
	%==============================================================
	btnNumber=14;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./3 btnHt];
    callbackStr='AvgApprox400(''UseTimeIntFile'')';

   	hUseTimeIntFileMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Use -', ...
			'Userdata',[],...
			'Value',0,...
        	'Callback',callbackStr,...
			'Enable','on');
			
	%==============================================================
    % SetTimeIntZero (radio button)===========================
	% callback: SetTimeIntZero ===============================
	%==============================================================
	btnNumber=14;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./3 yPos-btnHt 4.*btnWid./6 btnHt];
    callbackStr='AvgApprox400(''SetTimeIntZero'')';

   	hSetTimeIntZeroMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','zero time interval', ...
			'Userdata',[],...
			'Value',0,...
        	'Callback',callbackStr,...
			'Enable','off');
	
	%==============================================================
    % SetScalpSCADSStatus (radio button)===========================
	% callback: SetScalpSCADSStatus ===============================
	%==============================================================
	btnNumber=15;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt 2.*btnWid./3 btnHt];
    callbackStr='AvgApprox400(''SetScalpSCADSStatus'')';

   	hSetScalpSCADSStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','SCADS Scalp', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','on');
	
   	btnPos=[left+3.*btnWid./5 yPos-btnHt 2.*btnWid./5 btnHt];
    callbackStr='AvgApprox400(''SetCsdSCADSStatus'')';

   	hSetCsdSCADSStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','CSD', ...
			'Value',0,...
        	'Callback',callbackStr,...
			'Enable','on');

	%==============================================================
    % SetScalpEGISStatus (radio button)==========================
	% callback: SetScalpEGISStatus ==============================
	%==============================================================
	btnNumber=16;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt 2.*btnWid./3 btnHt];
    callbackStr='AvgApprox400(''SetScalpEGISStatus'')';

   	hSetScalpEGISStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','EGIS Scalp', ...
			'Value',0,...
        	'Callback',callbackStr,...
			'Enable','on');

   	btnPos=[left+3.*btnWid./5 yPos-btnHt 2.*btnWid./5 btnHt];
    callbackStr='AvgApprox400(''SetCsdEGISStatus'')';

   	hSetCsdEGISStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','CSD', ...
			'Value',0,...
        	'Callback',callbackStr,...
			'Enable','on');

	%==============================================================
    % SetScalpAppStatus (radio button)==========================
	% callback: SetScalpAppStatus ===============================
	%==============================================================
	btnNumber=17;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt 3.*btnWid./5 btnHt];
    callbackStr='AvgApprox400(''SetScalpAppStatus'')';

   	hSetScalpAppStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Approx. Scalp', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','on');

   	btnPos=[left+3.*btnWid./5 yPos-btnHt 2.*btnWid./5 btnHt];
    callbackStr='AvgApprox400(''SetCsdAppStatus'')';

   	hSetCsdAppStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','CSD', ...
			'Value',0,...
        	'Callback',callbackStr,...
			'Enable','on');

	
	%==============================================================
    % SetScalpIndStatus (radio button)=======================
	% callback: SetScalpScalpIndStatus ===========================
	%==============================================================
	btnNumber=18;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt 3.*btnWid./5 btnHt];
    callbackStr='AvgApprox400(''SetScalpIndStatus'')';

   	hSetScalpIndStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Index Scalp', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','on');

	btnPos=[left+3.*btnWid./5 yPos-btnHt 2.*btnWid./5 btnHt];
    callbackStr='AvgApprox400(''SetCsdIndStatus'')';

   	hSetCsdIndStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','CSD', ...
			'Value',0,...
        	'Callback',callbackStr,...
			'Enable','on');
	
	
	%==============================================================
  	% SetScalpAppStatus (radio button)==========================
	% callback: SetScalpAppStatus ===============================
	%==============================================================
	btnNumber=17;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
 	btnPos=[left+btnWid./3 yPos-btnHt 4.*btnWid./6 btnHt];
 	callbackStr='AvgApprox400(''SetAppFileRWStatus'')';

   	hSetAppFileRWStatusMenu=uicontrol( ...
       	 	'Style','radiobutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','write approx. file', ...
			'Userdata',0,...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','off',...
			'Visible','off');
			
	
	%==============================================================
    % EditWeightEditFile (push button)==========================
	% callback: EditWeightEditFile ==============================
	%==============================================================
	btnNumber=19;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt btnWid./2 btnHt];
    callbackStr='AvgApprox400(''EditWeightEditFile'')';

   	hEditWeightEditFileMenu=uicontrol( ...
       	 	'Style','pushbutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Test CON/WE file', ...
        	'Callback',callbackStr,...
			'Enable','on');
			
	
	%==============================================================
    % =======================SetSesFileFormatVal===================
	% callback: SetSesFileFormatVal ===============================
	%==============================================================
    if strcmp(computer,'SOL2')
        SesFileFormatVal=2;
    else
        SesFileFormatVal=3;
    end
    btnNumber=19;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    callbackStr='AvgApprox400(''SetSesFileFormatVal'')';

   	hSetSesFileFormatValMenu=uicontrol( ...
       	 	'Style','pushbutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
			'Userdata',SesFileFormatVal,...
        	'Callback',callbackStr,...
			'Enable','on');
			
	%===================================
	
	
	hAvgInfoTextVec=uicontrol('Value',0,'Visible','off');				%28
	AvgParaVec=[2 0 0 0 0 0 0 0 0];
	%AvgParaVec=[AppVersion NChan NChanCalc NPoints Bits Range BrdGain NFiles NChanExtra]
	hParaVec=uicontrol('Userdata',AvgParaVec,'Visible','off');			%29
	hAvgMessageTextVec=uicontrol('Value',0,'Visible','off');			%28
	hTimeVec=uicontrol('Userdata',[0 0 0],'Visible','off');				%38
	hDataFileRWStatusVec=uicontrol('Visible','off');					%39
	MatlabVersionString=version;										
	MainMatlabVersion=str2num(MatlabVersionString(1));	
	
	hMatlabVersion=uicontrol('Userdata',MatlabVersionString,'Value',MainMatlabVersion,'Visible','off');	%40
	hCondFileMat=uicontrol('Visible','off');							%53
	hCo5hMat=uicontrol('Visible','off');								%54
	hEegMegStatus=uicontrol('Visible','off','Value',1);					%55 Default EEG


	%=======================================================
	%===========UIMENUES====================================
	%=======================================================

	%=======================================================
	%===========TOPMENU FILE================================
	hFileMenu=uimenu('Label','File','ForegroundColor',[0 0 1]);
	callbackStr = 'AvgApprox400(''OpenFiles'')';
	hOpenFile=uimenu(hFileMenu,'Label','Open File','Callback',callbackStr,'Accelerator','h');

	NonUse=0;
	hAvgList=[NonUse hOpenFilesMenu hGrandCondStatusText hGrandCondStatusMenu NonUse ... 
		  	hSetCalcAvgRefMenu hSetSaveAvgRef hSetUseHEVecStatusMenu NonUse hSetUseQuestStatusMenu ... 
			NonUse hSetUseWEMatStatusMenu NonUse hSetUseWEVecStatusMenu NonUse ... 
			hSetUseEstVecStatusMenu NonUse hSetUseApproxStatusMenu NonUse NonUse ...
			NonUse NonUse NonUse hUseTimeIntFileMenu hSetTimeIntZeroMenu ...					%25
			AvgInfoFig AvgInfoAxes hAvgInfoTextVec hParaVec NonUse ...
			NonUse hRunAverageMenu AvgMessageFig AvgMessageAxes NonUse ...
			hApplyOpenFilesMenu hAvgMessageTextVec hTimeVec hDataFileRWStatusVec hMatlabVersion ...
			NonUse NonUse NonUse hSetAppFileRWStatusMenu NonUse ...
			NonUse hEditWeightEditFileMenu hSetSesFileFormatValMenu NonUse NonUse ... %50
			hSetResultPath hSetResourcePath hCondFileMat hCo5hMat hEegMegStatus ...
			hSetScalpLambdaText hSetScalpLambdaMenu hSetCSDLambdaText hSetCSDLambdaMenu NonUse ...
			hSetScalpScaleBinText hSetScalpScaleBinMenu hSetCSDScaleBinText hSetCSDScaleBinMenu NonUse ...
			hSetScalpSCADSStatusMenu hSetCsdSCADSStatusMenu hSetScalpEGISStatusMenu hSetCsdEGISStatusMenu NonUse ...
			hSetScalpAppStatusMenu hSetCsdAppStatusMenu hSetScalpIndStatusMenu hSetCsdIndStatusMenu NonUse ...	%75
			hMinStdBaseText hMinStdBase hMaxStdBaseText hMaxStdBase hSetUseTotIntStdBaseMenu ...
			hSetCalcStd]; 
	
            
	set(hAvgMenuFig,'Visible','on','UserData',hAvgList);
	
	AvgApprox400('InitializeAvgInfo');
	AvgApprox400('InitializeAvgMessage');
    AvgApprox400('SetSesFileFormatVal')
	set(hRunAverageMenu,'Enable','off');
    figure(hAvgMenuFig);
    
% elseif strcmp(action,'SearchBlinks'),
% 
% 	hAvgList=get(hAvgMenuFig,'Userdata');
% 	
% 	DataFileMat=get(hAvgList(2),'Userdata');
% 	AvgParaVec=get(hAvgList(29),'Userdata');
% 	%AvgParaVec=[AppVersion NChan NChanCalc NPoints Bits Range BrdGain NFiles]
% 	AppVersion=AvgParaVec(1);
% 	NChan=AvgParaVec(2);
% 	NChanCalc=AvgParaVec(3);
% 	NPoints=AvgParaVec(4);
% 	NFiles=AvgParaVec(8);
% 	for FileIndex=1:NFiles
% 
% 		set(AvgInfoTextVec(6),'String',num2str(FileIndex));
% 		[DataFile,DataPath,DataFilePath]=GetFileNameOfMat(DataFileMat,FileIndex);
% 	
% 		[Header,DataFile,DataPath,DataFilePath,SampRate,NCells,NTrials,NPoints,...
% 		NChan,LHeader,LCellHdr,BrdGain,ChanZero,ChanGain,HdrVer,Bits,Range,...
%         LEGISData,LSpecCellMat,BytOrd,ExptNam,RunDate,RunTime,SubjID,Handed,...
%         Sex,Age,ExperID,EdVer,CalFlag,LText,LComment,LPad,CellID,CellName,LSpec]=ReadEGISHeader(DataFilePath);
%  
%         AvgParaVec(5)=Bits;
% 	    AvgParaVec(6)=Range;
%         AvgParaVec(7)=BrdGain;
% 
% 
% 		Ok=0;
% 		while ~Ok
% 			clf;
% 			x=[];
% 			if NChanPattern>1
% 				
% 				hfig1=figure('Units','normal','NumberTitle','off','Position',[0,0.5,0.5,0.5],'Name','Choose a trial:');
% 				fprintf('\n');clc;fprintf('Please choose the pattern you want to take:');
% 				pause(2);ch_Take=0;
% 				NChanIndex=0;
% 				while ch_Take==0
% 					NChanIndex=NChanIndex+1;
% 					if NChanIndex>NChanPattern; NChanIndex=1; end
% 					plot(PatternPattern(NChanIndex,:))
% 					fprintf('\n');clc;
% 					fprintf(1,'This is the %g trial in this cell !\n',NChanIndex)
% 					[ch_Take]=IfEmptyInputBo(['Do you want to take this trial ?'],[],[],0,0);
% 				end
% 				PatternPatternTmp=PatternPattern(NChanIndex,:); PatternPattern=[]; PatternPattern=PatternPatternTmp; PatternPatternTmp=[];
% 			end
% 			
% 			[PattPlotStart]=IfEmptyInputValInt('Please insert the start of the plot intervall:',[],[],1,1,length(PatternPattern)-1,1);
% 			[PattPlotEnd  ]=IfEmptyInputValInt('Please insert the end of the plot intervall:',[],[],length(PatternPattern),PattPlotStart+1,length(PatternPattern));
% 
% 			fprintf('\n');clc;fprintf('Please insert start and end of pattern intervall:');
% 			hfig2=figure('Units','normal','NumberTitle','off','Position',[0,0.5,0.5,0.5],'Name','Choose a pattern:');
% 			PlotPatternPattern=PatternPattern(PattPlotStart:PattPlotEnd);
% 			plot(PlotPatternPattern)
% 			hold on
% 			for i=1:2
% 				[xTmp,yTmp]=ginput(1);
% 				x(i)=round(xTmp);
% 				plot(x,PlotPatternPattern(x),'mo');
% 			end
% 			[x(1)]=IfEmptyInputValInt(['Start of pattern to calculate:'],[],...
% 											  [],x(1),1,length(PlotPatternPattern)-1,1);
% 			[x(2)]=IfEmptyInputValInt(['End of pattern to calculate:'],[],...
% 											  [],x(2),x(1)+1,length(PlotPatternPattern),1);
% 			[Ok]=IfEmptyInputBo(['Ok ? Y/N'],[],[],1,1);
% 			close(hfig1); close(hfig2); 
% 		end
% 		Pattern=[PlotPatternPattern(x(1):x(2))];
% 
% 	end

elseif strcmp(action,'SetCalcAvgRef'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	set(hAvgList(7),'Value',1); %SaveAvgRef	
    
elseif strcmp(action,'SetCalcStd'),

	hAvgList=get(hAvgMenuFig,'Userdata');    
	CalcStdStatus=get(hAvgList(81),'Value');
    if ~CalcStdStatus
        set(hAvgList(77),'Value',0,'String','0');
        set(hAvgList(79),'Value',0,'String','0');
    end
    
elseif strcmp(action,'setMinStdBase'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	MinStdBaseString=get(hAvgList(77),'String');
	MinStdBase=get(hAvgList(77),'Value');
	MaxStdBase=get(hAvgList(79),'Value');
    TotIntStdBase=get(hAvgList(80),'Value')
	ParaVec=get(hAvgList(29),'Userdata');
	NPoints=ParaVec(4)
   	ind=find(abs(MinStdBaseString)<32);
    MinStdBaseString(ind)=32*ones(size(ind));
   	MinStdBaseString=MinStdBaseString';	
    MinStdBase=eval(['[' MinStdBaseString(:)' ']'],'-1')'
	if MinStdBase<=0
		MinStdBase=0;
	end
	if MinStdBase>0 & MaxStdBase==0
		MaxStdBase=MinStdBase;
		set(hAvgList(79),'Value',MaxStdBase,'String',sprintf('%g',MaxStdBase));
	end
	if MinStdBase>MaxStdBase
		MinStdBase=MaxStdBase;
	end
	set(hAvgList(77),'Value',MinStdBase,'String',sprintf('%g',MinStdBase));
	if MinStdBase==0
		MaxStdBase=0;
		set(hAvgList(79),'Value',MaxStdBase,'String',sprintf('%g',MaxStdBase));
	end
	if MaxStdBase>0
		set(hAvgList(81),'Value',1); %CalcStd
	end

elseif strcmp(action,'setMaxStdBase'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	MaxStdBaseString=get(hAvgList(79),'String');
	MinStdBase=get(hAvgList(77),'Value')
	MaxStdBase=get(hAvgList(79),'Value');
	ParaVec=get(hAvgList(29),'Userdata');
	NPoints=ParaVec(4);
   	ind=find(abs(MaxStdBaseString)<32);
    MaxStdBaseString(ind)=32*ones(size(ind));
   	MaxStdBaseString=MaxStdBaseString';	
    MaxStdBase=eval(['[' MaxStdBaseString(:)' ']'],'-1')';
	if MaxStdBase<=0
		MaxStdBase=0;
	end
	if MaxStdBase<MinStdBase
		MaxStdBase=MinStdBase;
	end
	set(hAvgList(79),'Value',MaxStdBase,'String',sprintf('%g',MaxStdBase));
	if MaxStdBase==0
		MinStdBase=0;
		set(hAvgList(77),'Value',MinStdBase,'String',sprintf('%g',MinStdBase));
	end
	if MaxStdBase>0 & MinStdBase==0
		MinStdBase=1;
		set(hAvgList(77),'Value',MinStdBase,'String',sprintf('%g',MinStdBase));
	end
	if MaxStdBase>0
		set(hAvgList(81),'Value',1); %CalcStd
	end

elseif strcmp(action,'SetUseTotIntStdBase'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	MinStdBase=get(hAvgList(77),'Value');
	MaxStdBase=get(hAvgList(79),'Value');
    TotIntStdBase=get(hAvgList(80),'Value');
    if TotIntStdBase
        ParaVec=get(hAvgList(29),'Userdata');
	    NPoints=ParaVec(4);
        if NPoints>0
            set(hAvgList(77),'Value',1,'String','1'); %MinStdBase
            set(hAvgList(79),'Value',NPoints,'String',sprintf('%g',NPoints));
        end
		set(hAvgList(81),'Value',1); %CalcStd
    end

elseif strcmp(action,'UseTimeIntFile'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	UseTimeIntFileStatus=get(hAvgList(24),'Value');
	if ~UseTimeIntFileStatus; 
		set(hAvgList(24),'Userdata',[]);
		set(hAvgList(25),'Enable','off','Value',0);
		return; 
	end
	[File,Path]=uigetfile('*','Read time intervals from file:');
	FilePath=[Path,File];
	if isempty(find(FilePath))
		set(hAvgList(24),'Value',0);
		set(hAvgList(25),'Enable','off','Value',0);
		return;
	end;
	fid=fopen(FilePath,'r');
	TimeIntVec=fscanf(fid,'%g');
	fclose(fid);

	[NTimeInt2,NoUse]=size(TimeIntVec);

	if (NTimeInt2./2-round(NTimeInt2./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');
		set(hAvgList(24),'Value',0);
		set(hAvgList(25),'Enable','off','Value',0);
        return;
	else
		NTimeInt=NTimeInt2./2;
		TimeIntMat=reshape(TimeIntVec,2,NTimeInt)';
		set(hAvgList(24),'Userdata',TimeIntMat);
		Message=char('Take the following intervals from file:');
		Message=char(Message,FilePath);
		Message=char(Message,' ');
		for i=1:NTimeInt
			Message=char(Message,['Interval ' int2str(i) ': ' int2str(TimeIntMat(i,1)) ' - ' int2str(TimeIntMat(i,2))]);
		end
        hmsgbox=msgbox(Message,'Info','help');
		set(hAvgList(25),'Enable','on');
	end
	

elseif strcmp(action,'SetResultPath'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	ResultPath=[];
	Message=char('Please choose a path');
	Message=char(Message,'in which you would like to save');
	Message=char(Message,'the result files and press "Save" !');
	hmsgbox=msgbox(Message,'info','help'); 
	[NonUse,ResultPath]=uiputfile('Test@', 'Result path:');
	close(hmsgbox)
	if ResultPath==0; ResultPath=[]; end
	set(hAvgList(51),'Userdata',ResultPath);

elseif strcmp(action,'SetResourcePath'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	ResourcePath=[];
    while isempty(ResourcePath)
		Message=char('Please choose the path');
		Message=char(Message,'of which you would like to import');
		Message=char(Message,'the resource files and press "Save" !');
		hmsgbox=msgbox(Message,'info','help'); 
		[NonUse,ResourcePath] = uiputfile('Test@', 'Resource path:');
		close(hmsgbox)
		if ResourcePath==0; ResourcePath=[]; end
     end
	set(hAvgList(52),'Userdata',ResourcePath);

elseif strcmp(action,'SetSesFileFormatVal'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	
	SesFileFormatVal=get(hAvgList(48),'Userdata');

	if SesFileFormatVal==1 
		set(hAvgList(48),'String','EGIS (*.ses*)','Userdata',2);
		EegMegStatus=1;
		FileExt='*.ses*';
	elseif SesFileFormatVal==2 
		set(hAvgList(48),'String','MSI (*ses.msi*)','Userdata',3);
		EegMegStatus=2;
		FileExt='*ses.msi';
	elseif SesFileFormatVal==3 
		set(hAvgList(48),'String','SCADS (*.E*)','Userdata',1);
		EegMegStatus=1;
		FileExt='*.E*';
	end
	if EegMegStatus==1
		set(hAvgList(6),'Value',1,'Enable','on')		%hCalculateAvgRef
		set(hAvgList(16),'Value',1,'Enable','on')		%hUseSensorStatusVector
		set(hAvgList(61),'Visible','on')
		set(hAvgList(62),'Visible','on')				%hSetScalpScaleBins
		set(hAvgList(63),'Visible','on')
		set(hAvgList(64),'Visible','on')				%hSetCSDScaleBins
		set(hAvgList(68),'Value',0,'Enable','on')		%hSetScalpEGISStatusMenu 
		set(hAvgList(69),'Value',0,'Enable','on')		%hSetCsdEGISStatusMenu
	elseif EegMegStatus==2
		set(hAvgList(6),'Value',0)						%hCalculateAvgRef
		set(hAvgList(16),'Value',0)						%hUseSensorStatusVector
		set(hAvgList(61),'Visible','off')
		set(hAvgList(62),'Visible','off')				%hSetScalpScaleBins
		set(hAvgList(63),'Visible','off')
		set(hAvgList(64),'Visible','off')				%hSetCSDScaleBins
		set(hAvgList(68),'Value',0,'Enable','off')		%hSetScalpEGISStatusMenu 
		set(hAvgList(69),'Value',0,'Enable','off')		%hSetCsdEGISStatusMenu
	end
	set(hAvgList(55),'Value',EegMegStatus,'Userdata',FileExt);

elseif strcmp(action,'InitializeAvgInfo'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	
	AvgInfoFig=hAvgList(26);
	AvgInfoAxes=hAvgList(27);
	GrandCondStatus=get(hAvgList(4),'Value');
	figure(AvgInfoFig);
	axes(AvgInfoAxes);
	
	LeftTextPos=0.05;
	CenterTextPos=0.35;
	TextDist=0.045;
	RGBColor1=[0 0 0];
	FontSize1=16;
    FontSize2=12;
	
	RGBColor2=[0 0 1];
	RGBColor3=[1 0 0];
	RGBColor4=[0 1 0];
	
	TextNo=0;
	
	TextNo=TextNo+1;
	hTotalNFilesText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Total number of files:','FontSize',FontSize1);
	hTotalNFilesVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	hNPointsText=text('Units','normal','Position',[0.5+LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Number of points:','FontSize',FontSize1);
	hNPointsVal=text('Units','normal','Position',[0.5+CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	TextNo=TextNo+1;
	hActFileNText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Actual data file number:','FontSize',FontSize1);
	hActFileNVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	hNChanCalcText=text('Units','normal','Position',[0.5+LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Number of sensors:','FontSize',FontSize1);
	hNChanCalcVal=text('Units','normal','Position',[0.5+CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);
	
	TextNo=TextNo+2;
	hActDataFileNameText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Actual data file name:','FontSize',FontSize1);
	hActDataFileNameVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize2);

	TextNo=TextNo+1;
	hActCondFileNameText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Actual condition file name:','FontSize',FontSize1);
	hActCondFileNameVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize2);

	TextNo=TextNo+2;
	hTotalNCondText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Total number of conditions:','FontSize',FontSize1);
	hTotalNCondVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	hStartTimeText=text('Units','normal','Position',[0.5+LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Start time:','FontSize',FontSize1);
	hStartTimeVal=text('Units','normal','Position',[0.5+CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);
	
	TextNo=TextNo+1;
	hActCondNText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Actual condition number:','FontSize',FontSize1);
	hActCondNVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	hETimeText=text('Units','normal','Position',[0.5+LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Elapsed time:','FontSize',FontSize1);
	hETimeVal=text('Units','normal','Position',[0.5+CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	TextNo=TextNo+1;
	hActCondNameText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Actual condition name:','FontSize',FontSize1);
	hActCondNameVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	hRestTimeText=text('Units','normal','Position',[0.5+LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Remaining time:','FontSize',FontSize1);
	hRestTimeVal=text('Units','normal','Position',[0.5+CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);
	
	TextNo=TextNo+2;
	hTotalNTrialsText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Total number of trials in file:','FontSize',FontSize1);
	hTotalNTrialsVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	hExtraChanText=text('Units','normal','Position',[0.5+LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Number of seperate sensors:','FontSize',FontSize1);
	hExtraChanVal=text('Units','normal','Position',[0.5+CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	TextNo=TextNo+1;
	hActTrialNText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Actual trial number in file:','FontSize',FontSize1);
	hActTrialNVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);
	
	TextNo=TextNo+2;
	hTotalNTrialInCondText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Total number of trials in condition:','FontSize',FontSize1);
	hTotalNTrialInCondVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);
	
	TextNo=TextNo+1;
	hActTrialNInCondText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Actual trial number in condition:','FontSize',FontSize1);
	hActTrialNInCondVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	TextNo=TextNo+2;
	hNGoodChanText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Number of good sensors:','FontSize',FontSize1);
	hNGoodChanVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor4,'FontSize',FontSize1);

	TextNo=TextNo+1;
	hNBadChanText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Number of bad sensors:','FontSize',FontSize1);
	hNBadChanVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor3,'FontSize',FontSize1);

	TextNo=TextNo+2;
	hStdChanText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Sensor number:','FontSize',FontSize1);
	hStdChanVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	TextNo=TextNo+1;
	hStdMeanText=text('Units','normal','Position',[LeftTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor1,'String','Mean std of sensor:','FontSize',FontSize1);
	hStdMeanVal=text('Units','normal','Position',[CenterTextPos 1-TextDist.*TextNo],'HorizontalAlignment','left','Color',RGBColor2,'FontSize',FontSize1);

	AvgInfoTextVec=[hTotalNFilesText hTotalNFilesVal hNPointsText hNPointsVal hActFileNText ...							%5
			hActFileNVal hNChanCalcText hNChanCalcVal hActDataFileNameText hActDataFileNameVal ...						%10
			hTotalNCondText hTotalNCondVal hActCondNText hActCondNVal hActCondNameText ...								%15
			hActCondNameVal hTotalNTrialsText hTotalNTrialsVal hActTrialNText hActTrialNVal ...							%20
			hTotalNTrialInCondText hTotalNTrialInCondVal hActTrialNInCondText hActTrialNInCondVal hNGoodChanText ...	%25
			hNGoodChanVal hNBadChanText hNBadChanVal hStdChanText hStdChanVal ...										%30
			hStdMeanText hStdMeanVal hStartTimeText hStartTimeVal hETimeText ...										%35
			hETimeVal hRestTimeText hRestTimeVal hActCondFileNameText hActCondFileNameVal ...							%40
			hExtraChanText hExtraChanVal];																				%45
	
	set(hAvgList(28),'Userdata',AvgInfoTextVec);	
	AvgApprox400('SetGrandCondStatus');
	figure(hAvgMenuFig)

elseif strcmp(action,'InitializeAvgMessage'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	
	AvgMessageFig=hAvgList(33);
	AvgMessageAxes=hAvgList(34);
	figure(AvgMessageFig);
	axes(AvgMessageAxes);
	RGBColor1=[0 0 0];
	LeftTextPos=0.05;
	CenterTextPos=0.4;
	TextDist=0.05;
	FontSize1=16;
	for i=1:18
		AvgMessageTextVec(i)=text('Units','normal','Position',[LeftTextPos 1-TextDist.*i],'HorizontalAlignment','left','FontSize',FontSize1,'Color',RGBColor1);
	end	
	set(hAvgList(37),'Userdata',AvgMessageTextVec);	
	figure(hAvgMenuFig)

elseif strcmp(action,'ClearAvgMessage'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	AvgMessageTextVec=get(hAvgList(37),'Userdata');	
	RGBColor1=[0 0 0];
	for i=1:length(AvgMessageTextVec)
		set(AvgMessageTextVec,'String',' ','Color',RGBColor1);
	end
	figure(hAvgMenuFig)

elseif strcmp(action,'SetGrandCondStatus'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	GrandCondStatus=get(hAvgList(4),'Value');
	AvgInfoTextVec=get(hAvgList(28),'Userdata');	
	AvgMessageTextVec=get(hAvgList(37),'Userdata');	
	
	if GrandCondStatus==3 	%Special condition file average
		[CondFile,CondPath,CondFilePath]=ReadFilePath([],'*','Please choose a condition file:');
		if CondFile==0;
			set(AvgMessageTextVec(1),'String','No condition file available !');
			set(AvgMessageTextVec(2),'String','Thus, it is not possible to average in "Special condition average status"!');
			set(hAvgList(4),'Value',1);				%GrandCondStatus
			set(hAvgList(32),'Enable','off');		%hRunAverageMenu
			AvgApprox400('SetGrandCondStatus');
			return; 
		end
		set(hAvgList(53),'Userdata',CondFilePath);
		set(AvgInfoTextVec(40),'String',CondFilePath);
	elseif GrandCondStatus==4 	%Special condition files average
		[NCondFiles,CondFileMat]=ReadFileNames([],'*','Choose the condition file(s):');
		set(hAvgList(53),'Userdata',CondFileMat);
	elseif GrandCondStatus==5 | GrandCondStatus==6 	% CO5 file
		return;
	elseif GrandCondStatus==6 	% CO5 Valence
		AvgApprox400('SetCo5Val');
		return;
	end
	if GrandCondStatus~=1 & ~isempty(DataFileMat)	%Condition average
		AvgApprox400('TestCondFiles');
	end
	GrandCondStatus=get(hAvgList(4),'Value');
	if GrandCondStatus==1			%Over all average
		VisibleStatus='off';
		if ~isempty(DataFileMat)
			set(hAvgList(32),'Enable','on');%hRunAverageMenu
		end
		set(AvgInfoTextVec(21),'String','Total number of trials in avg. file:')
		set(AvgInfoTextVec(23),'String','Actual trial number in avg. file:')
	else
		VisibleStatus='on';
		set(AvgInfoTextVec(21),'String','Total number of trials in condition:')
		set(AvgInfoTextVec(23),'String','Actual trial number in condition:')
	end
	set(AvgInfoTextVec(11),'Visible',VisibleStatus)
	set(AvgInfoTextVec(12),'Visible',VisibleStatus)
	set(AvgInfoTextVec(13),'Visible',VisibleStatus)
	set(AvgInfoTextVec(14),'Visible',VisibleStatus)
	set(AvgInfoTextVec(15),'Visible',VisibleStatus)
 	set(AvgInfoTextVec(16),'Visible',VisibleStatus)
	set(AvgInfoTextVec(39),'Visible',VisibleStatus)
	set(AvgInfoTextVec(40),'Visible',VisibleStatus)

elseif strcmp(action,'SetCo5Menu')

	hAvgList=get(hAvgMenuFig,'Userdata');
	hCo5hMat=get(hAvgList(54),'Userdata');	

	[CondFile,CondPath,CondFilePath]=ReadFilePath([],'*.Co5*','Please choose a Co5 condition file:');
	[CondMat] = ReadData(CondFilePath,1,[],'ascii','ascii');
	[NTrials,NCondCol]=size(CondMat);
	for CondColIndex=1:5
		NCond=0;
		CondCondVec=[];
		CondVecTmp=CondMat(:,CondColIndex);
		while ~isempty(CondVecTmp)
			NCond=NCond+1;
			CondCondVec(NCond)=CondVecTmp(1); %Welche Bedingungen wirklich vorkommen
			k=find(CondVecTmp~=CondVecTmp(1));
			CondVecTmp=CondVecTmp(k);
		end	
		[SortCondVec,NonUse]=sort(CondCondVec);
		if CondColIndex==1
			CondCond1Vec=SortCondVec;
		elseif CondColIndex==2
			CondCond2Vec=SortCondVec;
		elseif CondColIndex==3
			CondCond3Vec=SortCondVec;
		elseif CondColIndex==4
			CondCond4Vec=SortCondVec;
		elseif CondColIndex==5
			CondCond5Vec=SortCondVec;
		end
		NCondVec(CondColIndex)=length(SortCondVec);
	end
	if strcmp(computer,'MAC2')	
		Co5FigPosVec=[0 .55 .6224 .45];
	elseif strcmp(computer,'PCWIN') 
		Co5FigPosVec=[0 .5 0.61 .5];
	elseif strcmp(computer,'SOL2')
		Co5FigPosVec=[0 .5 0.6224 .5];
	end;
	Co5FigString=['Co5 Window:'];	
	hCo5Fig=figure('Units','normal','NumberTitle','off','Position',Co5FigPosVec,...
		'Name',Co5FigString,'Color',[0 0 .99],'Userdata',[-2 -2 -2 -2 -2]);
	hCo5Axes=axes('Units','normal','Position',[0 0 1 1]'); axis('off');	
	
	btnWid=.15;
	btnHt=.15;
	spacing=.04;
	left=spacing;

	btnPos=[left .2 btnWid btnHt];
	callbackStr='AvgApprox400(''SetCo5Up'')';
    hSetCo5Up=uicontrol( ... 
       		'Style','pushbutton', ...
       		'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Up', ...
        	'Interruptible','on', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','off');
	
	left=left+btnWid+spacing;
	btnPos=[left .2 btnWid btnHt];
	callbackStr='AvgApprox400(''SetCo5Down'')';
    hSetCo5Down=uicontrol( ... 
       		'Style','pushbutton', ...
       		'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Down', ...
        	'Interruptible','on', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','off');

	left=left+btnWid+spacing;
	btnPos=[left .2 btnWid btnHt];
	callbackStr='AvgApprox400(''SetCo5Act'')';
    hSetCo5Act=uicontrol( ... 
       		'Style','pushbutton', ...
       		'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Actual: 1', ...
        	'Interruptible','on', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','off');
	
	left=left+btnWid+spacing;
	btnPos=[left .2 btnWid btnHt];
	callbackStr='AvgApprox400(''ReadCo5'')';
    hReadCo5=uicontrol( ... 
       		'Style','pushbutton', ...
       		'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Read', ...
        	'Interruptible','on', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','on');

	left=left+btnWid+spacing;
	btnPos=[left .2 btnWid btnHt];
	callbackStr='AvgApprox400(''SaveCo5'')';
    hSaveCo5=uicontrol( ... 
       		'Style','pushbutton', ...
       		'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Save', ...
        	'Interruptible','on', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','on');

	left=spacing;
	btnPos=[left .01 btnWid btnHt];
	callbackStr='AvgApprox400(''SetCo5More'')';
    hSetCo5More=uicontrol( ... 
       		'Style','pushbutton', ...
       		'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','More', ...
        	'Interruptible','on', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','on');
	
	left=left+btnWid+spacing;
	btnPos=[left .01 btnWid btnHt];
	callbackStr='AvgApprox400(''SetCo5Less'')';
    hSetCo5Less=uicontrol( ... 
       		'Style','pushbutton', ...
       		'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Less', ...
        	'Interruptible','on', ...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','off');

	CondStringMat=char('Valence');
	CondStringMat=char(CondStringMat,'When startled');
	CondStringMat=char(CondStringMat,'Old/new sound');
	CondStringMat=char(CondStringMat,'Block');
	CondStringMat=char(CondStringMat,'Sound number');

	left=spacing;
	for CondColIndex=1:5
 		if CondColIndex==1
			SortCondVec=CondCond1Vec;
		elseif CondColIndex==2
			SortCondVec=CondCond2Vec;
		elseif CondColIndex==3
			SortCondVec=CondCond3Vec;
		elseif CondColIndex==4
			SortCondVec=CondCond4Vec;
		elseif CondColIndex==5
			SortCondVec=CondCond5Vec;
		end
		
		btnPos=[left .8 btnWid btnHt];
		hCo5SetCondTextVec(CondColIndex) = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'String',CondStringMat(CondColIndex,:), ...
        'Interruptible','off', ...
		'BackgroundColor',[0 0 .99],...
        'ForegroundColor','white',...
		'Enable','off');
   		
		labelStr=['Non Use:' int2str(CondColIndex)];
		for CondInd=1:NCondVec(CondColIndex); 
			labelStr=[labelStr '| Value: ' int2str(SortCondVec(CondInd))];
		end

		btnPos=[left .75 btnWid btnHt];
   		left=left+btnWid+spacing;

		callbackStr='AvgApprox400(''SetCo5Mat'')';
    	hCo5SetCondMenuVec(CondColIndex)=uicontrol( ... 
       		'Style','popupmenu', ...
       		'Units','normalized', ...
        	'Position',btnPos, ...
        	'String',labelStr, ...
        	'Interruptible','on', ...
			'Userdata',SortCondVec,...
			'Value',1,...
        	'Callback',callbackStr,...
			'Enable','on');
	end
	Co5hMat=[hCo5Fig hCo5Axes hSetCo5More hSetCo5Less hSetCo5Act hReadCo5 hSaveCo5 hSetCo5Up hSetCo5Down hCo5SetCondMenuVec];
	set(hAvgList(54),'Userdata',Co5hMat);	%hCo5hMat

elseif	strcmp(action,'SetCo5Mat') | ...
		strcmp(action,'SetCo5Up')| ...
		strcmp(action,'SetCo5Down')| ...
		strcmp(action,'SetCo5More')| ...
		strcmp(action,'SetCo5Less')| ...
		strcmp(action,'ReadCo5')| ...
		strcmp(action,'SaveCo5'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	hCo5hMat=get(hAvgList(54),'Userdata');
	Co5Mat=get(hCo5hMat(1),'Userdata');
	Co5Act=get(hCo5hMat(5),'Value');
	
	if strcmp(action,'SaveCo5') 
		SaveData(Co5Mat,[],1,[],'ascii','ascii');
		return;
	elseif strcmp(action,'ReadCo5') 
		Co5Mat=ReadData([],1,[],'ascii','ascii');
		[Co5Act,NoUse]=size(Co5Mat);
		for i=1:5
			Cop5Vec=get(hCo5hMat(i+9),'Userdata');
			ActVal=Co5Mat(Co5Act,i);
			if ActVal==-2
				Ind=1;
			else
				Ind=find(Cop5Vec==ActVal)+1;
			end
			set(hCo5hMat(i+9),'Value',Ind);
		end
		if Co5Act==1; 
			set(hCo5hMat(4),'Enable','off'); 
		else
			set(hCo5hMat(4),'Enable','on');
		end
		set(hCo5hMat(5),'Value',Co5Act,'String',['Actual: ' int2str(Co5Act)]);
	elseif strcmp(action,'SetCo5More') 
		Co5MatTmp=-2.*ones(Co5Act+1,5);
		Co5MatTmp(1:Co5Act,:)=Co5Mat;
		Co5Act=Co5Act+1;
		for i=1:5
			set(hCo5hMat(i+9),'Value',1);
		end
		Co5Mat=Co5MatTmp;
		if Co5Act==2; set(hCo5hMat(4),'Enable','on'); end
		set(hCo5hMat(5),'Value',Co5Act,'String',['Actual: ' int2str(Co5Act)]);
	elseif strcmp(action,'SetCo5Less') 
		Co5Act=Co5Act-1;
		Co5Mat=Co5Mat(1:Co5Act,:);
		for i=1:5
			Cop5Vec=get(hCo5hMat(i+9),'Userdata');
			ActVal=Co5Mat(Co5Act,i);
			if ActVal==-2
				Ind=1;
			else
				Ind=find(Cop5Vec==ActVal)+1;
			end
			set(hCo5hMat(i+9),'Value',Ind);
		end
		if Co5Act==1; set(hCo5hMat(4),'Enable','off'); end
		set(hCo5hMat(5),'Value',Co5Act,'String',['Actual: ' int2str(Co5Act)]);
	elseif strcmp(action,'SetCo5Mat') 
		for i=1:5
			Value=get(hCo5hMat(i+9),'Value')-1;
			Userdata=get(hCo5hMat(i+9),'Userdata');
			if Value~=0
				Co5Mat(Co5Act,i)=Userdata(Value);
			end
		end
	end
	set(hCo5hMat(1),'Userdata',Co5Mat);
	clc;
	Co5Mat=Co5Mat
	
elseif strcmp(action,'SetUseWEMatStatus'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	UseWEMatStatus=get(hAvgList(12),'Value');
	if UseWEMatStatus & ~isempty(DataFileMat)
		AvgApprox400('TestWeightEditFiles');	
	end

elseif strcmp(action,'SetUseWEVecStatus'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	UseWEVecStatus=get(hAvgList(14),'Value');
	if UseWEVecStatus & ~isempty(DataFileMat)
		AvgApprox400('TestWeightEditFiles');	
	end

elseif strcmp(action,'SetUseEstVecStatus'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	UseEstVecStatus=get(hAvgList(16),'Value');
	if UseEstVecStatus & ~isempty(DataFileMat)
		AvgApprox400('TestEstFiles');	
	end
	
elseif strcmp(action,'SetUseApproxStatus'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	UseApproxStatus=get(hAvgList(18),'Value');
	if UseApproxStatus & ~isempty(DataFileMat)
		AvgApprox400('TestApproxCoeffFiles');	
	end

	%=============================================================================
	%============ SetScalpLambda | SetCSDLambda
	%============ call: SetScalpLambda | SetCSDLambda
	%=============================================================================	
	
elseif strcmp(action,'SetScalpLambda') | strcmp(action,'SetCSDLambda'),
	 
	hAvgList=get(hAvgMenuFig,'Userdata');
	if 		strcmp(action,'SetScalpLambda'); 	AvgListNo=57;
	elseif 	strcmp(action,'SetCSDLambda'); 		AvgListNo=59;
	end
	v = get(hAvgList(AvgListNo),'Value');
	str = get(hAvgList(AvgListNo),'String');
	
    ind = find(abs(str)<32);
    str(ind) = 32*ones(size(ind));
    str = str';	
    vv = eval(['[' str(:)' ']'],'-1')';
    if vv<0
        vv = v;
	end
    str = sprintf('%g',vv);
	set(hAvgList(AvgListNo),'Value',vv,'String',str);  
	
	%=============================================================================
	%============ SetScalpScaleBin | SetCSDScaleBin
	%============ call: SetScaleBin | SetCSDScaleBin
	%=============================================================================	
elseif strcmp(action,'SetScalpScaleBin') | strcmp(action,'SetCSDScaleBin'),
	 
	hAvgList=get(hAvgMenuFig,'Userdata');
	if 		strcmp(action,'SetScalpScaleBin'); 		AvgListNo=62;
	elseif 	strcmp(action,'SetCSDScaleBin'); 		AvgListNo=64;
	end
	v = get(hAvgList(AvgListNo),'Value');
	str = get(hAvgList(AvgListNo),'String');
	
    ind = find(abs(str)<32);
    str(ind) = 32*ones(size(ind));
    str = str';	
    vv = eval(['[' str(:)' ']'],'-1')';
	vv=round(vv);
    if vv<1
        vv = v;
	end
    str = sprintf('%g',vv);
	set(hAvgList(AvgListNo),'Value',vv,'String',str);  

elseif strcmp(action,'OpenFiles'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	
	AvgInfoTextVec=get(hAvgList(28),'Userdata');
	AvgParaVec=get(hAvgList(29),'Userdata');	
	SesFileFormatVal=get(hAvgList(48),'Userdata');
	EegMegStatus=get(hAvgList(55),'Value');
	FileExt=get(hAvgList(55),'Userdata');
	String=['Choose a session file (',FileExt,'):'];
	
	%AvgParaVec=[AppVersion NChan NChanCalc NPoints Bits Range BrdGain NFiles NChanExtra]
	DefDataFilePath=SetDefPath(1,FileExt);
	[NFiles,DataFileMat]=ReadFileNames([],DefDataFilePath,String);
    if NFiles==0; return; end
	[DefFile,DefPath]=SepFilePath(DataFileMat(NFiles,:));
	SetDefPath(2,DefPath);
    [DataFileSizeVec]=GetFileSize(DataFileMat);
	DataFileRWStatusVec=zeros(size(DataFileSizeVec));
	File2BigStatusVec=find(DataFileSizeVec>20000000);
    if ~isempty(File2BigStatusVec)    
	   DataFileRWStatusVec(File2BigStatusVec)=ones(size(File2BigStatusVec));
    end
    AvgParaVec(8)=NFiles;
	set(hAvgList(2),'Userdata',DataFileMat);
	set(AvgInfoTextVec(2),'Userdata',NFiles,'String',int2str(NFiles))
	set(hAvgList(29),'Userdata',AvgParaVec);
	set(hAvgList(36),'Enable','on');
	set(hAvgList(39),'Userdata',DataFileRWStatusVec);

	AvgApprox400('ApplyOpenFiles');	
	

elseif strcmp(action,'ApplyOpenFiles'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	GrandCondStatus=get(hAvgList(4),'Value');
	UseWEMatStatus=get(hAvgList(12),'Value');
	UseWEVecStatus=get(hAvgList(14),'Value');
	UseEstVecStatus=get(hAvgList(16),'Value');
	UseApproxStatus=get(hAvgList(18),'Value');
	MaxStdBase=get(hAvgList(79),'Value');
	set(hAvgList(32),'Enable','on');		%hRunAverageMenu
	AvgApprox400('TestNChan');
	if GrandCondStatus~=1
		AvgApprox400('TestCondFiles');
	end
	if UseWEMatStatus | UseWEVecStatus
		AvgApprox400('TestWeightEditFiles');
	end
	if UseEstVecStatus 
		AvgApprox400('TestEstFiles');
	end
	if UseApproxStatus
		AvgApprox400('TestApproxCoeffFiles');	
	end
	if MaxStdBase>0
		AvgApprox400('TestStdBase');
	end

elseif strcmp(action,'TestStdBase'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	MinStdBase=get(hAvgList(77),'Value');
	MaxStdBase=get(hAvgList(79),'Value');
	AvgParaVec=get(hAvgList(29),'Userdata');
	SesFileFormatVal=get(hAvgList(48),'Userdata');
	NFiles=AvgParaVec(8);
	for FileIndex=1:NFiles
		[NonUse,NonUse,DataFilePath]=GetFileNameOfMat(DataFileMat,FileIndex);
		if SesFileFormatVal==1 | SesFileFormatVal==2
			[NonUse,NonUse,NonUse,NonUse,NonUse,NonUse,NonUse,NPoints]=ReadEGISHeader(DataFilePath,[],[],[],[],SesFileFormatVal);
		elseif SesFileFormatVal==3
			SetFilePath=PutFileExt2Mat(DataFilePath,'.set');
			[SetFilePath,ParaVec,MEGSensorPosMat,EEGSensorPosMat,MEGSensorNameVec,EEGSensorNameVec,MEGSensorIndexVec,EEGSensorIndexVec]=ReadMsiSet(SetFilePath);
			NPoints=ParaVec(2);
		end
		if MaxStdBase>NPoints;
			Message=char('Attention !!!');
			Message=char(Message,'');
			Message=char(Message,['The number of points (NPoints = ',int2str(NPoints),') in file']);
			Message=char(Message,DataFilePath);
			Message=char(Message,['is smaller than maximum std base (MaxStdBase = ',int2str(MaxStdBase),').']);
			Message=char(Message,'');
			Message=char(Message,'Set MaxStdBase = NPoints !');
			MaxStdBase=NPoints;
			set(hAvgList(79),'Value',MaxStdBase,'String',sprintf('%g',MaxStdBase));
			if MinStdBase>MaxStdBase
				MinStdBase=MaxStdBase;
				set(hAvgList(77),'Value',MinStdBase,'String',sprintf('%g',MinStdBase));
				Message=char(Message,'Set MinStdBase = NPoints !');
			end
			hmsgbox=msgbox(Message,'Info','help');
		end
	end

elseif strcmp(action,'TestNChan'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	AvgRefStatus=get(hAvgList(6),'Value');
	AvgInfoTextVec=get(hAvgList(28),'Userdata');
	AvgParaVec=get(hAvgList(29),'Userdata');
	AvgMessageTextVec=get(hAvgList(37),'Userdata');
	SesFileFormatVal=get(hAvgList(48),'Userdata');
	AvgApprox400('ClearAvgMessage');	
	NFiles=AvgParaVec(8);
	TextNo=1;
	OKNChanStatus=1;
	for FileIndex=1:NFiles
        if FileIndex>5; TextNo=1; end
		[NonUse,NonUse,DataFilePath]=GetFileNameOfMat(DataFileMat,FileIndex);
		if SesFileFormatVal==1 | SesFileFormatVal==2
			[NonUse,NonUse,NonUse,NonUse,NonUse,NonUse,NonUse,NonUse,NChan]=ReadEGISHeader(DataFilePath,[],[],[],[],SesFileFormatVal);
			NChanExtra=0;
		elseif SesFileFormatVal==3
			SetFilePath=PutFileExt2Mat(DataFilePath,'.set');
            set(AvgMessageTextVec(TextNo),'String','Read MSI set from file:','Visible','on');
			TextNo=TextNo+1;
            set(AvgMessageTextVec(TextNo),'String',SetFilePath,'Color',[0 0 1],'Visible','on');
            TextNo=TextNo+2;
            pause(0.01)
			[SetFilePath,ParaVec,MEGSensorPosMat,EEGSensorPosMat,MEGSensorNameVec,EEGSensorNameVec,MEGSensorIndexVec,EEGSensorIndexVec]=ReadMsiSet(SetFilePath);
			NChan=ParaVec(4);       %NMegChan
			NChanExtra=ParaVec(5);  %NEegChan
		end
		if FileIndex==1; NChanTmp=NChan; end
		if NChanTmp~=NChan; 
			set(AvgMessageTextVec(TextNo),'String','Sorry, bad number of channels in file:');
			TextNo=TextNo+1;
			set(AvgMessageTextVec(TextNo),'String',DataFilePath,'Color',[0 0 1]);
			TextNo=TextNo+1;
			set(AvgMessageTextVec(TextNo),'String','All files have to have the same number of channels !');
			TextNo=TextNo+2;
			OKNChanStatus=0; 
		end
	end
	if ~OKNChanStatus
		set(hAvgList(32),'Enable','off');		%hRunAverageMenu
	else
		AvgParaVec(2)=NChan;
		AvgParaVec(9)=NChanExtra;
		if AvgRefStatus; 
			NChanCalc=NChan+1;
		else 
			NChanCalc=NChan;
		end
		AvgParaVec(3)=NChanCalc;
		AvgParaVec(9)=NChanExtra;
		set(AvgInfoTextVec(8),'String',num2str(NChanCalc),'Userdata',NChanCalc);
		set(AvgInfoTextVec(42),'String',num2str(NChanExtra),'Userdata',NChanCalc);
		set(hAvgList(29),'Userdata',AvgParaVec);
	end
	
elseif strcmp(action,'TestCondFiles'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	GrandCondStatus=get(hAvgList(4),'Value');
	AvgInfoTextVec=get(hAvgList(28),'Userdata');
	AvgParaVec=get(hAvgList(29),'Userdata');
	NFiles=AvgParaVec(8);
	AvgMessageTextVec=get(hAvgList(37),'Userdata');	
	ResourcePath=get(hAvgList(52),'Userdata');	
	CondFileMat=get(hAvgList(53),'Userdata');	

	AvgApprox400('ClearAvgMessage');	

	if GrandCondStatus==4
		[NDataFiles,NonUse]=size(DataFileMat);
		[NCondFiles,NonUse]=size(CondFileMat);
		if NCondFiles<NDataFiles
			Message=char(['Sorry, the number of condition files (',int2str(NCondFiles),') is smaller']);
			Message=char(Message,['than the number of data files (',int2str(NDataFiles),').']);
			Message=char(Message,['Thus, only the first ',int2str(NCondFiles),' data files will be used "!']);
			hmsgbox=msgbox(Message,'Info','help');
			set(AvgMessageTextVec(1),'String',['Sorry, the number of condition files (',int2str(NCondFiles),') is smaller']);
			set(AvgMessageTextVec(2),'String',['than the number of data files (',int2str(NDataFiles),').']);
			set(AvgMessageTextVec(3),'String',['Thus, only the first ',int2str(NCondFiles),' data files will be used "!']);
			DataFileMat=DataFileMat(1:NCondFiles,:);
			set(hAvgList(2),'Userdata',DataFileMat);
			NFiles=NCondFiles;
			pause(5);
		elseif NCondFiles>NDataFiles
			Message=char(['Sorry, the number of data files (',int2str(NDataFiles),') is smaller']);
			Message=char(Message,['than the number of condition files (',int2str(NCondFiles),').']);
			Message=char(Message,['Thus, only the first ',int2str(NDataFiles),' condition files will be used "!']);
			hmsgbox=msgbox(Message,'Info','help');
			set(AvgMessageTextVec(1),'String',['Sorry, the number of data files (',int2str(NDataFiles),') is smaller']);
			set(AvgMessageTextVec(2),'String',['than the number of condition files (',int2str(NCondFiles),').']);
			set(AvgMessageTextVec(3),'String',['Thus, only the first ',int2str(NDataFiles),' condition files will be used "!']);
			CondFileMat=CondFileMat(1:NDataFiles,:);
			set(hAvgList(53),'Userdata',CondFileMat);	
			NFiles=NDataFiles;
			pause(5);
		else
			NFiles=NDataFiles;
		end
		AvgParaVec(8)=NFiles;
		set(hAvgList(29),'Userdata',AvgParaVec);
	end

	AvgApprox400('ClearAvgMessage');	

	TextNo=1;
	ExistCondFileStatus=1;
	for FileIndex=1:NFiles
        if TextNo>18; AvgApprox400('ClearAvgMessage'); TextNo=1; end
		if GrandCondStatus==2 | GrandCondStatus==5 | GrandCondStatus==6
			if GrandCondStatus==2
				CondFileExt='.con';
			else
				CondFileExt='.co5';
			end
			[DataFile,NonUse,DataFilePath]=GetFileNameOfMat(DataFileMat,FileIndex);
			if isempty(ResourcePath)
				CondFilePath=[DataFilePath,CondFileExt];
			else
				CondFilePath=[ResourcePath,DataFile,CondFileExt];
			end
		elseif GrandCondStatus==3 
			[NonUse,NonUse,CondFilePath]=GetFileNameOfMat(CondFileMat,1);
		elseif GrandCondStatus==4
			[NonUse,NonUse,CondFilePath]=GetFileNameOfMat(CondFileMat,FileIndex);
		end
		fid=fopen(CondFilePath,'r');
		if fid==-1	
			Message=char('Warning,');
			Message=char(Message,'the following file does not exist:');
			Message=char(Message,CondFilePath);
			Message=char(Message,'(wrong condition file name or position)');
			Message=char(Message,'');
			Message=char(Message,'Thus, it is not possible to average in "condition average status"!');

			set(AvgMessageTextVec(TextNo),'String','Sorry, the following file does not exist:');
			TextNo=TextNo+1;	
			set(AvgMessageTextVec(TextNo),'String',CondFilePath,'Color',[0 0 1]);
			TextNo=TextNo+1;	
			set(AvgMessageTextVec(TextNo),'String','Thus, it is not possible to average in "condition average status"!');
			TextNo=TextNo+2;	
			ExistCondFileStatus=0;
		else
			fclose(fid);
			[CondVec] = ReadData(CondFilePath,1,[],'ascii','ascii');
			if isempty(CondVec); 
				Message=char('Warning,');
				Message=char(Message,'the following file does not contain usable condition data:');
				Message=char(Message,CondFilePath);
				Message=char(Message,'Thus, it is not possible to average in "condition average status"!');
				
				set(AvgMessageTextVec(TextNo),'String','Sorry, the following file does not contain usable condition data:');
				TextNo=TextNo+1;	
				set(AvgMessageTextVec(TextNo),'String',CondFilePath,'Color',[0 0 1]);
				TextNo=TextNo+1;	
				set(AvgMessageTextVec(TextNo),'String','Thus, it is not possible to average in "condition average status"!');
				TextNo=TextNo+2;	
				ExistCondFileStatus=0;
			else
				set(AvgMessageTextVec(TextNo),'String','Use the following file:');
				TextNo=TextNo+1;	
				set(AvgMessageTextVec(TextNo),'String',CondFilePath,'Color',[0 0 1]);
				TextNo=TextNo+2;
				pause(1)
			end
		end
	end
	figure(hAvgMenuFig)
	if ~ExistCondFileStatus
		set(hAvgList(32),'Enable','off');	%hRunAverageMenu
		set(hAvgList(4),'Value',1);			%GrandCondStatus
		Message=char(Message,'');
		Message=char(Message,'Change "Average Status" to "Over All Average" !!');
		Message=char(Message,'');
		hmsgbox=msgbox(Message,'Info','help');
		AvgApprox400('SetGrandCondStatus');	
	end
	

elseif strcmp(action,'TestWeightEditFiles'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	AvgRefStatus=get(hAvgList(6),'Value');
	UseWEMatStatus=get(hAvgList(12),'Value');
	UseWEVecStatus=get(hAvgList(14),'Value');
	AvgInfoTextVec=get(hAvgList(28),'Userdata');	
	AvgParaVec=get(hAvgList(29),'Userdata');
	AvgMessageTextVec=get(hAvgList(37),'Userdata');	
	ResourcePath=get(hAvgList(52),'Userdata');	

	AvgApprox400('ClearAvgMessage');	

	NFiles=AvgParaVec(8);	
	
	TextNo=1;
	ExistWEFileStatus=1;
	for FileIndex=1:NFiles
        if TextNo>18; TextNo=1; AvgApprox400('ClearAvgMessage'); end
		[DataFile,DataPath,DataFilePath]=GetFileNameOfMat(DataFileMat,FileIndex);
		if AvgRefStatus; WEExt='.AR.WE'; else;  WEExt='.WE'; end
		if isempty(ResourcePath)
			WEFilePath=[DataFilePath,WEExt];
		else
			WEFilePath=[ResourcePath,DataFile,WEExt];
		end
		fidWE=fopen(WEFilePath,'r');
		if fidWE==-1	
			set(AvgMessageTextVec(TextNo),'String','Sorry, the following file does not exist:');
			TextNo=TextNo+1;	
			set(AvgMessageTextVec(TextNo),'String',WEFilePath,'Color',[0 0 1]);
			TextNo=TextNo+1;	
			set(AvgMessageTextVec(TextNo),'String','Thus, it is not possible to use a weight edit matrix or weight edit vector !');
			TextNo=TextNo+2;	
			ExistWEFileStatus=0;	
		else
			fclose(fidWE);
			set(AvgMessageTextVec(TextNo),'String','Use the following file:');
			TextNo=TextNo+1;	
			set(AvgMessageTextVec(TextNo),'String',WEFilePath,'Color',[0 0 1]);
			TextNo=TextNo+2;	
			pause(1)
		end
	end
	if ~ExistWEFileStatus
		set(hAvgList(32),'Enable','off');		%hRunAverageMenu
		pause
	end
	figure(hAvgMenuFig)

elseif strcmp(action,'EditWeightEditFile'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	AvgRefStatus=get(hAvgList(6),'Value');
	UseWEMatStatus=get(hAvgList(12),'Value');
	UseWEVecStatus=get(hAvgList(14),'Value');
	AvgInfoTextVec=get(hAvgList(28),'Userdata');	
	AvgParaVec=get(hAvgList(29),'Userdata');
	AvgMessageTextVec=get(hAvgList(37),'Userdata');	
	DefFilePath=SetDefPath(1,'*.WE*');
	[WEFile,WEPath,WEFilePath]=ReadFilePath([],DefFilePath,'Choose WE-file to edit:');
	SetDefPath(2,WEPath);
	fidWE=fopen(WEFilePath,'r');
	NChanTmp=fread(fidWE,1,'int16');
	NTrialsTmp=fread(fidWE,1,'int16');
	WeightEditMat=fread(fidWE,[NChanTmp NTrialsTmp],'int16');
	ChanEditStatusMat=fread(fidWE,[NChanTmp NTrialsTmp],'int16');
	WEVec=fread(fidWE,NTrialsTmp,'int16');
	fclose(fidWE);
	DefFilePath=SetDefPath(1,'*con*');
	[CondFile,CondPath,CondFilePath]=ReadFilePath([],DefFilePath,'Please choose a condition file:');
	SetDefPath(2,CondPath);
	[CondMat]=ReadData(CondFilePath,1,[],'ascii','ascii');
	[NTrials,NCondCol]=size(CondMat);
	CondVec=CondMat(:,1);
	CondVecTmp=CondVec;
	NCond=0;
	CondCondVec=[];
	NCondCondVec=[];
	while ~isempty(CondVecTmp)
		NCond=NCond+1;
		CondCondVec(NCond)=CondVecTmp(1); %Welche Bedingungen wirklich vorkommen
		j=find(CondVecTmp==CondVecTmp(1));
		NCondCondVec(NCond)=length(j);
		k=find(CondVecTmp~=CondVecTmp(1));
		CondVecTmp=CondVecTmp(k);
	end		
	if NCond>1; NCondString=['Found ' int2str(sum(NCondCondVec)) ' total trials in ' int2str(NCond) '(red) conditions n times (green) in file:'];
	else;  		NCondString=['Found just one condition in file:'];
	end	
	CondVecTmp=CondVec(find(WEVec));
	WNCond=0;
	WCondCondVec=[];
	WNCondCondVec=[];
	while ~isempty(CondVecTmp)
		WNCond=WNCond+1;
		WCondCondVec(WNCond)=CondVecTmp(1); %Welche Bedingungen wirklich vorkommen
		j=find(CondVecTmp==CondVecTmp(1));
		WNCondCondVec(WNCond)=length(j);
		k=find(CondVecTmp~=CondVecTmp(1));
		CondVecTmp=CondVecTmp(k);
	end		
	if NCond>1; WNCondString=['Found ' int2str(sum(WNCondCondVec)) ' total trials in ' int2str(WNCond) '(red) conditions n times (green) considering WE file:'];
	else;  		WNCondString=['Found just one condition considering WE file:'];
	end	
	AvgApprox400('ClearAvgMessage');		
	set(AvgMessageTextVec(1),'String',NCondString);
	set(AvgMessageTextVec(2),'String',CondFilePath,'Color',[0 0 1]);
	set(AvgMessageTextVec(4),'String',int2str(CondCondVec),'Color',[1 0 0]);
	set(AvgMessageTextVec(5),'String',int2str(NCondCondVec),'Color',[0 1 0]);
	set(AvgMessageTextVec(7),'String',WNCondString);
	set(AvgMessageTextVec(9),'String',int2str(WCondCondVec),'Color',[1 0 0]);
	set(AvgMessageTextVec(10),'String',int2str(WNCondCondVec),'Color',[0 1 0]);
	return

	hEditWEMatFig=figure('Units','normal','NumberTitle','off',...
			'Position',[0 0 1 1],...
			'Name',['Edit WE-file: ' WEFile],...
			'Color',[.9 .9 .9]);
	hEditWEMatAxes=axes('Position',[.05 .05 .96 .9]);
	surf(WeightEditMat); 
	axis([1 NTrialsTmp 1 NChanTmp 0 1])
	xlabel('Trial #')
	ylabel('Channel #')
	view([0,0,180])
	hData=get(hEditWEMatAxes,'Children');
	Button=1;
	while ~isempty(Button)
		[Trial,Chan,Button] = ginput(1);
		if isempty(Button); 
			close(fEditWEMatFig)
			return;
		end
		if Button==27; %Escape
			close(fEditWEMatFig)
			return;
		end
		Trial=round(Trial-.5);
		Chan=round(Chan-.5);
		if Trial>0 & Trial<=NTrialsTmp & Chan>0 & Chan<=NChanTmp
			if Button==1
				if WeightEditMat(Chan,Trial)==0
					WeightEditMat(Chan,Trial)=1;
				else
					WeightEditMat(Chan,Trial)=0;
				end
			elseif Button==2
				if WeightEditMat(Chan,Trial)==0
					WeightEditMat(:,Trial)=1;
				else
					WeightEditMat(:,Trial)=0;
				end
			elseif Button==3
				if WeightEditMat(Chan,Trial)==0
					WeightEditMat(Chan,:)=1;
				else
					WeightEditMat(Chan,:)=0;
				end
			end
			set(hData,'CData',WeightEditMat);
		end		
	end

elseif strcmp(action,'TestEstFiles'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	AvgRefStatus=get(hAvgList(6),'Value');
	UseWEMatStatus=get(hAvgList(12),'Value');
	UseWEVecStatus=get(hAvgList(14),'Value');
	AvgInfoTextVec=get(hAvgList(28),'Userdata');	
	AvgParaVec=get(hAvgList(29),'Userdata');
	AvgMessageTextVec=get(hAvgList(37),'Userdata');	
	ResourcePath=get(hAvgList(52),'Userdata');	

	AvgApprox400('ClearAvgMessage');	

	NChanCalc=AvgParaVec(3);
	NFiles=AvgParaVec(8);	
	
	TextNo=1;
	ExistEstFileStatus=1;
	for FileIndex=1:NFiles
        if TextNo>18; TextNo=1; AvgApprox400('ClearAvgMessage'); end
		[DataFile,DataPath,DataFilePath]=GetFileNameOfMat(DataFileMat,FileIndex);
		EstExt=['.' int2str(NChanCalc) 'est'];
		if isempty(ResourcePath)
			EstFilePath=[DataFilePath,EstExt];
		else
			EstFilePath=[ResourcePath,DataFile,EstExt];
		end
		fidEst=fopen(EstFilePath,'r');
		if fidEst==-1		
			set(AvgMessageTextVec(TextNo),'String','Sorry, the following file does not exist:');
			TextNo=TextNo+1;	
			set(AvgMessageTextVec(TextNo),'String',EstFilePath,'Color',[0 0 1]);
			TextNo=TextNo+1;	
			set(AvgMessageTextVec(TextNo),'String','Thus, it is not possible to use an sensor status vector !');
			TextNo=TextNo+2;	
			ExistEstFileStatus=0;
		else
			fclose(fidEst);
			set(AvgMessageTextVec(TextNo),'String','Use the following file:');
			TextNo=TextNo+1;	
			set(AvgMessageTextVec(TextNo),'String',EstFilePath,'Color',[0 0 1]);
			TextNo=TextNo+2;	
			pause(1)
		end
	end
	if ~ExistEstFileStatus
		set(hAvgList(32),'Enable','off');		%hRunAverageMenu
		pause
	end
	figure(hAvgMenuFig)

elseif strcmp(action,'TestApproxCoeffFiles'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	DataFileMat=get(hAvgList(2),'Userdata');
	AvgRefStatus=get(hAvgList(6),'Value');
	UseWEMatStatus=get(hAvgList(12),'Value');
	UseWEVecStatus=get(hAvgList(14),'Value');
	AvgInfoTextVec=get(hAvgList(28),'Userdata');	
	AvgParaVec=get(hAvgList(29),'Userdata');
	AvgMessageTextVec=get(hAvgList(37),'Userdata');	
	MainMatlabVersion=get(hAvgList(40),'Value');
	AvgApprox400('ClearAvgMessage');	

	NChanCalc=AvgParaVec(3);
	NFiles=AvgParaVec(8);	
		
	TextNo=1;
	ExistECfgfFileStatus=1;
	
	%==================================================================================
	
	ECfgPathTmp=what('SensorCfg');
	ECfgPath=getfield(ECfgPathTmp,'path');
    if ~strcmp(ECfgPath(length(ECfgPath)),filesep); ECfgPath=[ECfgPath,filesep];end
	ECfgFile=[int2str(NChanCalc) '.ecfg'];
	ECfgFilePath=[ECfgPath,ECfgFile];
	fidECfg=fopen(ECfgFilePath,'r');

	if fidECfg==-1	
		set(AvgMessageTextVec(TextNo),'String','Sorry, the following file does not exist:');
		TextNo=TextNo+1;	
		set(AvgMessageTextVec(TextNo),'String',ECfgFilePath,'Color',[0 0 1]);
		TextNo=TextNo+1;	
		set(AvgMessageTextVec(TextNo),'String','Thus, it is not possible to use sensor approximation !');
		TextNo=TextNo+2;
		TextNo=TextNo+2;
		ExistECfgfFileStatus=0;
	else
		fclose(fidECfg);
		set(AvgMessageTextVec(TextNo),'String','Use the following file:');
		TextNo=TextNo+1;	
		set(AvgMessageTextVec(TextNo),'String',ECfgFilePath,'Color',[0 0 1]);
		TextNo=TextNo+2;	
		pause(1)
	end
	if ~ExistECfgfFileStatus
		set(hAvgList(32),'Enable','off');		%hRunAverageMenu
	end
	figure(hAvgMenuFig)
	
elseif strcmp(action,'RunAverage'),

	hAvgList=get(hAvgMenuFig,'Userdata');
	
	DataFileMat=get(hAvgList(2),'Userdata');	
	GrandCondStatus=get(hAvgList(4),'Value');
	AvgRefStatus=get(hAvgList(6),'Value');
	SaveAvgRefStatus=get(hAvgList(7),'Value');
	UseHEVecStatus=get(hAvgList(8),'Value');
	UseQuestStatus=get(hAvgList(10),'Value');
	UseWEMatStatus=get(hAvgList(12),'Value');
	UseWEVecStatus=get(hAvgList(14),'Value');
	UseEstVecStatus=get(hAvgList(16),'Value');
	UseApproxStatus=get(hAvgList(18),'Value');
	EegMegStatus=get(hAvgList(55),'Value');
	ScalpLambda=get(hAvgList(57),'Value');
	CsdLambda=get(hAvgList(59),'Value');
	ScalpScaleBins=get(hAvgList(62),'Value');
	CsdScaleBins=get(hAvgList(64),'Value');
	AvgInfoFig=hAvgList(26);
	AvgInfoTextVec=get(hAvgList(28),'Userdata');	
	AvgMessageTextVec=get(hAvgList(37),'Userdata');	
	DataFileRWStatusVec=get(hAvgList(39),'Userdata');
	MainMatlabVersion=get(hAvgList(40),'Value');
	SesFileFormatVal=get(hAvgList(48),'Userdata');
	SaveScalpSCADSStatus=get(hAvgList(66),'Value');
	SaveCsdSCADSStatus=get(hAvgList(67),'Value');
	SaveScalpEGISStatus=get(hAvgList(68),'Value');
	SaveCsdEGISStatus=get(hAvgList(69),'Value');
	SaveScalpAppStatus=get(hAvgList(71),'Value');
	SaveCsdAppStatus=get(hAvgList(72),'Value');
	SaveScalpIndStatus=get(hAvgList(73),'Value');
	SaveCsdIndStatus=get(hAvgList(74),'Value');
	AppFileRWStatus=get(hAvgList(44),'Value');

	ResultPath=get(hAvgList(51),'Userdata');	
	ResourcePath=get(hAvgList(52),'Userdata');	
	CondFileMat=get(hAvgList(53),'Userdata');
	MinStdBase=get(hAvgList(77),'Value');
	MaxStdBase=get(hAvgList(79),'Value');
    TotIntStdBase=get(hAvgList(80),'Value');
	CalcStdStatus=get(hAvgList(81),'Value');
	if MaxStdBase>0; CalcStdBaseStatus=1; else; CalcStdBaseStatus=0; end
	AvgParaVec=get(hAvgList(29),'Userdata');
	%AvgParaVec=[AppVersion NChan NChanCalc NPoints Bits Range BrdGain NFiles NChanExtra]
	AppVersion=AvgParaVec(1);
	NChan=AvgParaVec(2);
	NChanCalc=AvgParaVec(3);
	NPoints=AvgParaVec(4);
	NFiles=AvgParaVec(8);
	NChanExtra=AvgParaVec(9);

	if SesFileFormatVal==1 | SesFileFormatVal==2
		DataFileFormat='int16'; NBit=2;
	elseif SesFileFormatVal==3
		DataFileFormat='float'; NBit=4; BrdGain=1;
	end
	UseTimeIntStatus=get(hAvgList(24),'Value');
	SetTimeIntZeroStatus=get(hAvgList(25),'Value')
	if UseTimeIntStatus
		TimeIntMat=get(hAvgList(24),'Userdata');
		[NTimeInt,NonUse]=size(TimeIntMat);
		MaxTimeInt=TimeIntMat(NTimeInt,2);
		NTotTimeInd=0;
		for TimeInt=1:NTimeInt
			NActTimeInd=TimeIntMat(TimeInt,2)-TimeIntMat(TimeInt,1)+1;
			NTotTimeInd=NTotTimeInd+NActTimeInd;
			TimeIndVecTmp=zeros(NTotTimeInd,1);
			if TimeInt>1
				TimeIndVecTmp(1:NTotTimeInd-NActTimeInd)=TimeIndVec;
			end
			TimeIndVecTmp(NTotTimeInd-NActTimeInd+1:NTotTimeInd)=[(TimeIntMat(TimeInt,1):TimeIntMat(TimeInt,2))];
			TimeIndVec=TimeIndVecTmp;
		end
	end
	AppFilePathMat=[];
	AvgFilePathMat=[];
	EgisSaveDataFilePathMat=[];
	StartTime = clock;
    if StartTime(5)<10
        StartTime5String=['0' int2str(StartTime(5))];
    else
        StartTime5String=int2str(StartTime(5));
    end
	set(AvgInfoTextVec(34),'String',[int2str(StartTime(4)) ' : ' StartTime5String],'Userdata',StartTime)
	AvgApprox400('ClearAvgMessage');		
	set(AvgMessageTextVec(1),'String','Run the average:','Color',[0 0 1]);
	
	
	%==================================================================================
	if UseApproxStatus
		CoeffPathTmp=what('Plot3dCoeff40');
		CoeffPath=getfield(CoeffPathTmp,'path');
		if strcmp(CoeffPath(length(CoeffPath)),filesep);CoeffPath=CoeffPath(1:length(CoeffPath)-1); end
		LegPathTmp=what('Plot3dLegCoeff');
		LegPath=getfield(LegPathTmp,'path');
		if strcmp(LegPath(length(LegPath)),filesep); LegPath=LegPath(1:length(LegPath)-1); end
		ECfgPathTmp=what('SensorCfg');
		ECfgPath=getfield(ECfgPathTmp,'path');
		if strcmp(ECfgPath(length(ECfgPath)),filesep); ECfgPath=ECfgPath(1:length(ECfgPath)-1); end
		ECfgFile=[int2str(NChanCalc) '.ecfg'];
		ECfgFilePath=[ECfgPath,filesep,ECfgFile];

		fid=fopen(ECfgFilePath,'r');
		fprintf('Start reading of file...\n\n');
		fprintf(ECfgFilePath)
		fprintf('\n\n');
		[NChanCalc,count] = fread(fid,1,'int16');	
		[ScalpRadius,count] = fread(fid,1,'float32');
		[TmpSpher,count]= fread(fid,[NChanCalc,2],'float32');
		fclose(fid);
		AllEPosSpher=zeros(NChanCalc,3);
		AllEPosSpher(:,1:2)=TmpSpher(1:NChanCalc,:);
		AllEPosSpher(:,3)=ScalpRadius.*ones(NChanCalc,1);
		AllEPosCart = change_sphere_cart(AllEPosSpher,ScalpRadius,1);
		[InvCoeff] = ReadOrCalcCoeff(1,AllEPosCart,AllEPosCart,LegPath,CoeffPath,ECfgFile,32,15, 0, 5001);
		[CsdCoeff] = ReadOrCalcCoeff(3,AllEPosCart,AllEPosCart,LegPath,CoeffPath,ECfgFile,NChanCalc,15,0,5001);
	end
	%===========================================================================

	for FileIndex=1:NFiles

		set(AvgInfoTextVec(6),'String',num2str(FileIndex));
		[DataFile,DataPath,DataFilePath]=GetFileNameOfMat(DataFileMat,FileIndex);
	
		if SesFileFormatVal==1 | SesFileFormatVal==2
			[Header,DataFile,DataPath,DataFilePath,SampRate,NCells,NTrials,NPoints,...
			NChan,LHeader,LCellHdr,BrdGain,ChanZero,ChanGain,HdrVer,Bits,Range,...
       		LEGISData,LSpecCellMat,BytOrd,ExptNam,RunDate,RunTime,SubjID,Handed,...
       	 	Sex,Age,ExperID,EdVer,CalFlag,LText,LComment,LPad,CellID,CellName,LSpec]=ReadEGISHeader(DataFilePath,[],[],[],[],SesFileFormatVal);
			AvgParaVec(4)=NPoints;
        	AvgParaVec(5)=Bits;
	    	AvgParaVec(6)=Range;
        	AvgParaVec(7)=BrdGain;
		elseif SesFileFormatVal==3
			SetFilePath=PutFileExt2Mat(DataFilePath,'.set');
			[SetFilePath,ParaVec,MEGSensorPosMat,EEGSensorPosMat,MEGSensorNameVec,EEGSensorNameVec,MEGSensorIndexVec,EEGSensorIndexVec]=ReadMsiSet(SetFilePath)
			NTotChan=ParaVec(1);
            NPoints=ParaVec(2);
			AvgParaVec(4)=NPoints;
			NTrials=ParaVec(3);
			NMegChan=ParaVec(4);
            NEegChan=ParaVec(5);
			SampRate=ParaVec(6);
            SampPeriod=ParaVec(7);
            
			NChan=NMegChan;
			NChanExtra=NEegChan;
            NChanCalc=NMegChan;
		end
		set(hAvgList(29),'Userdata',AvgParaVec);
        if TotIntStdBase
           AvgApprox400('SetUseTotIntStdBase');
	       MinStdBase=get(hAvgList(77),'Value');
	       MaxStdBase=get(hAvgList(79),'Value');
        end
        set(hAvgList(29),'Userdata',AvgParaVec);
		set(AvgInfoTextVec(10),'String',DataFilePath);
		set(AvgInfoTextVec(4),'String',int2str(NPoints));
		if ~UseTimeIntStatus
			TimeIndVec=[1:NPoints];
		else
			NNoTimeInd=0;
			for i=1:NPoints
				if ~any(TimeIndVec==i)
					NNoTimeInd=NNoTimeInd+1;
					NoTimeIndVec(NNoTimeInd)=i;
				end
			end
			if MaxTimeInt>NPoints;
				Message=char('Sorry,');
				Message=char(Message,'the number of points in the given');
				Message=char(Message,'time interval file is bigger than');
				Message=char(Message,'the number of points in the data file !');
				Message=char(Message,' ');
				Message=char(Message,'Please check the time interval file !');
        		hmsgbox=msgbox(Message,'Info','help');
				return;
			end
		end
		if SesFileFormatVal==1 | SesFileFormatVal==2
			ChanGainVec=400./ChanGain; %µv = (AD value -Zero) x 400/gain Info from Mark Moran 19 Jul 2002
		end
		if SesFileFormatVal==1 | SesFileFormatVal==2
			NBytesInTrial=(NPoints.*NChan).*NBit;	%int16
		elseif SesFileFormatVal==3
			NBytesInTrial=(NPoints.*(NChan+NChanExtra)).*NBit;	%float
		end
		%========================================

		if UseHEVecStatus
			eval(['global LSpecCell1;'])
			HEVec=LSpecCell1(:,1);
			AvgApprox400('ClearAvgMessage');		

			if ~all(HEVec==-1)
				NotEditVec=find(HEVec==-1);
				QuestVec=find(HEVec==0);
				GoodVec=find(HEVec==1);
				BadVec=find(HEVec>1);
				set(AvgMessageTextVec(1),'String','Number of trials with status');
				set(AvgMessageTextVec(3),'String',['Not edit: ' int2str(length(NotEditVec))]);
				set(AvgMessageTextVec(4),'String',['Quest:    ' int2str(length(QuestVec))]);
				set(AvgMessageTextVec(5),'String',['Good:     ' int2str(length(GoodVec))]);
				set(AvgMessageTextVec(6),'String',['Bad:      ' int2str(length(BadVec))]);	
			else
				UseHEVecStatus=0;
				set(AvgMessageTextVec(1),'String','This file is not edited !!!');
			end
			pause(2);

			%=========ACHTUNG===========
			%=========ACHTUNG===========
			% EditVec muss den Wert Eins haben damit der trial gewertet wird 
	
			if UseQuestStatus; 
				if ~isempty(QuestVec);
					HEVec(QuestVec)=ones(size(QuestVec));
				end
			end
		else
			HEVec=ones(NTrials,1);
		end
	
		%========================================
		
		if UseWEMatStatus
			if AvgRefStatus; WEExt='.AR.WE'; else; WEExt='.WE'; end
			if isempty(ResourcePath)
				WEFilePath=[DataFilePath,WEExt];
			else
				WEFilePath=[ResourcePath,DataFile,WEExt];
			end
			fidWE=fopen(WEFilePath,'r');
			AvgApprox400('ClearAvgMessage');		
			set(AvgMessageTextVec(1),'String','Read Weight Edit Matrix from file:');
			set(AvgMessageTextVec(2),'String',WEFilePath);
			NChanTmp=fread(fidWE,1,'int16');
			NTrialsTmp=fread(fidWE,1,'int16');
			WeightEditMat=fread(fidWE,[NChanTmp NTrialsTmp],'int16');
			ChanEditStatusMat=fread(fidWE,[NChanTmp NTrialsTmp],'int16');
			WEVec=fread(fidWE,NTrialsTmp,'int16');
			if all(WEVec==0); 
				set(AvgMessageTextVec(4),'String','Sorry, all trials are set to bad !');
				pause
			end
			fclose(fidWE);
		
			if all(WeightEditMat==1)
				set(AvgMessageTextVec(4),'String','All WeightEditMat  == ones => No use of WeightEditMat');
				pause(1); 
				UseWEMatStatus=0;
			end	
		else	
			WeightEditMat=ones(NChan,NTrials);
			ChanEditStatusMat=zeros(NChan,NTrials);
			WEVec=ones(NTrials,1);
		end
	
		%========================================

		if GrandCondStatus~=1
			if GrandCondStatus==2
				if isempty(ResourcePath)
					CondFilePath=[DataFilePath '.con'];
				else
					CondFilePath=[ResourcePath,DataFile '.con'];%Opens condition file named 'DataFileName'.CON (seperate files for each subject)
				end
			elseif GrandCondStatus==3
				[CondFile,CondPath,CondFilePath]=GetFileNameOfMat(CondFileMat,1);	%Opens the one given condition file
			elseif GrandCondStatus==4
				[CondFile,CondPath,CondFilePath]=GetFileNameOfMat(CondFileMat,FileIndex);	%Opens the seperate given condition files for each subject
			elseif GrandCondStatus==5 | GrandCondStatus==6	%Co5
				if isempty(ResourcePath)
					CondFilePath=[DataFilePath '.CO5'];
				else
					CondFilePath=[ResourcePath,DataFile '.CO5'];%Opens condition file named 'DataFileName'.CO5 (seperate files for each subject)
				end
				if GrandCondStatus==5
					hCo5hMat=get(hAvgList(54),'Userdata');
					Cond5Mat=get(hCo5hMat(1),'Userdata');
					Cond5Vec=Cond5Mat(FileIndex,:);
				end
			end
			set(AvgInfoTextVec(40),'String',CondFilePath);
			[CondMat] = ReadData(CondFilePath,1,[],'ascii','ascii');
			[NRow,NCondVec]=size(CondMat); 
            if NRow>2 & NCondVec<3 | NCondVec==5
                CondMat=CondMat';
                [NRow,NCondVec]=size(CondMat);
            end
			if NRow==1; 
				CondFileFormat=1;
			elseif NRow==2; 
				CondFileFormat=2;
			else
				CondFileFormat=[];
			end
			if CondFileFormat==1
				if NCondVec~=NTrials
					if NCondVec<NTrials
						BadNCondString1=['The number of trials in condition file is smaller than the number of trials in the EGIS file'];
						BadNCondString2=['Take just the number of trials of the condition file'];
						NTrials=NCondVec;
						WeightEditMat=WeightEditMat(:,1:NTrials);
						ChanEditStatusMat=ChanEditStatusMat(:,1:NTrials);
						WEVec=WEVec(1:NTrials);
						HEVec=HEVec(1:NTrials);
					else
						BadNCondString1=['The number of trials in condition file is bigger than the number of trials in the EGIS file'];
						BadNCondString2=['Take just the number of trials of the EGIS file'];
						CondVec=CondVec(1:NTrials);
					end
					set(AvgMessageTextVec(1),'String',BadNCondString1,'Color',[0 0 0]);
					set(AvgMessageTextVec(2),'String',BadNCondString2,'Color',[0 0 0]);
					set(AvgMessageTextVec(4),'String','Press "Return" to continue','Color',[0 0 0]);
					pause
				end
				CondVec=CondMat;
				CondVecTmp=CondMat;
			elseif CondFileFormat==2
				CondVec=-1.*ones(1,NTrials);
				for i=1:NTrials
					Index=find(CondMat(2,:)==i);
					if ~isempty(Index)
						if length(Index)>1; 
							BadString1=['Sorry,'];
							BadString2=['the trial in row # ' int2str(i) ' occurs more often than once !'];
							set(AvgMessageTextVec(1),'String',BadString1,'Color',[0 0 0]);
							set(AvgMessageTextVec(2),'String',BadString2,'Color',[0 0 0]);
							set(AvgMessageTextVec(4),'String','Please check your condition file !','Color',[0 0 0]);
							return
						end
						if Index>NTrials; 
							BadString=['The trial # ' int2str(Index) 'in row #' int2str(i) 'does not correspond to the given data set !'];
							set(AvgMessageTextVec(1),'String',BadString,'Color',[0 0 0]);
							set(AvgMessageTextVec(4),'String','Press "Return" to continue','Color',[0 0 0]);
							pause
						end
						CondVec(i)=CondMat(1,Index);
					end
				end
				CondVecTmp=CondMat(1,:);
			end	%CondFileFormat==1
			if GrandCondStatus==5
				CondVec=-1.*ones(1,NTrials);
				for i=1:5
					if Cond5Vec(i)==-2
						CondMat(i,:)=-2.*ones(1,NTrials);
					end
				end
IndexVec=find((CondMat(1,:)==Cond5Vec(1)|CondMat(1,:)==-2)&(CondMat(2,:)==Cond5Vec(2)|CondMat(2,:)==-2)&(CondMat(3,:)==Cond5Vec(3)|CondMat(3,:)==-2)&(CondMat(4,:)==Cond5Vec(4)|CondMat(4,:)==-2)&(CondMat(5,:)==Cond5Vec(5)|CondMat(5,:)==-2));
				if ~isempty(IndexVec)
					CondVec(IndexVec)=FileIndex.*ones(1,length(IndexVec));
					CondVecTmp=FileIndex;
				else
					CondVecTmp=[];
					CondCondVec=[];
				end
			elseif GrandCondStatus==6
				CondVec=CondMat(1,:)
				CondVecTmp=[1 2 3 4];
			end 
			NCond=0;
			while ~isempty(CondVecTmp)
				NCond=NCond+1;
				CondCondVec(NCond)=CondVecTmp(1); %Welche Bedingungen wirklich vorkommen
				k=find(CondVecTmp~=CondVecTmp(1));
				CondVecTmp=CondVecTmp(k);
			end		
			if NCond>1; NCondString=['Found the following ' int2str(NCond) ' conditions in file:'];
			else;  		NCondString=['Found just one condition in file:'];
			end
			AvgApprox400('ClearAvgMessage');		
			set(AvgMessageTextVec(1),'String',NCondString);
			set(AvgMessageTextVec(2),'String',CondFilePath,'Color',[0 0 1]);
			set(AvgMessageTextVec(4),'String',int2str(CondCondVec),'Color',[0 0 1]);
			pause(2)
		else
			CondCondVec=1;
			NCond=1;
		end	%if GrandCondStatus~=1
	
		%========================================
	
		if UseEstVecStatus
			AvgApprox400('ClearAvgMessage');
			EstExt=['.' int2str(NChanCalc) 'est'];
			if isempty(ResourcePath)
				EstFilePath=[DataFilePath,EstExt];
			else
				EstFilePath=[ResourcePath,DataFile,EstExt];
			end		
			set(AvgMessageTextVec(1),'String','Read sensor status from file:');
			set(AvgMessageTextVec(2),'String',EstFilePath,'Color',[0 0 1]);
			EstFid=fopen(EstFilePath,'r');
			EstVec=fread(EstFid,NChanCalc,'int16'); 
			fclose(EstFid);
			BadChanVec=find(EstVec==0)
			if ~isempty(BadChanVec)
				NBadChan=length(BadChanVec);
				if NBadChan==1;
			     	set(AvgMessageTextVec(4),'String',['Found the following bad channel in this file:']);
            	else
                 	set(AvgMessageTextVec(4),'String',['Found the following ' int2str(NBadChan) ' bad channels in this file:']);
             	end
				set(AvgMessageTextVec(5),'String',int2str(BadChanVec'),'Color',[1 0 0]);
				WeightEditMat(BadChanVec,:)=zeros(NBadChan,NTrials);
			else
				set(AvgMessageTextVec(1),'String','No bad channels in this file.');
			end
		end

		%========================================
		if ~UseWEVecStatus & ~UseHEVecStatus
			HWEditVec=ones(NTrials,1);	
		elseif UseWEVecStatus & ~UseHEVecStatus
			HWEditVec=WEVec;
			ch_UseEVec=1;
		elseif ~UseWEVecStatus & UseHEVecStatus
			HWEditVec=HEVec;
			ch_UseEVec=1;
		elseif UseWEVecStatus & UseHEVecStatus
			HWEditVec=HEVec.*WEVec;
			ch_UseEVec=0;
		end
		if GrandCondStatus~=1
			set(AvgInfoTextVec(12),'String',num2str(NCond));
		end
   	 	CondIndex=0;
 		if GrandCondStatus==1
			TrialsToAvgVec=find(HWEditVec(1:NTrials)==1);
			NTrialsToAvgVec=length(TrialsToAvgVec);
   	 	else
	   		for CondIndex=1:NCond	
            	EditVec=HWEditVec(1:NTrials);
				CondName=CondCondVec(CondIndex);
				NotTakeVec=find(CondVec~=CondName);
				EditVec(NotTakeVec)=2.*ones(length(NotTakeVec),1);
				TrialsToAvgVec=find(EditVec==1);
				NTrialsToAvgVec(CondIndex)=length(TrialsToAvgVec);
       	 	end
   	 	end
		%========================================

		if SaveScalpSCADSStatus | SaveScalpEGISStatus | SaveScalpAppStatus | SaveScalpIndStatus
			StartIndex=1;
		else
			StartIndex=2;
		end
		if SaveCsdSCADSStatus | SaveCsdEGISStatus | SaveCsdAppStatus | SaveCsdIndStatus
			EndIndex=2;
		else
			EndIndex=1;
		end
		
		for ScalpCsdIndex=StartIndex:EndIndex

			if ScalpCsdIndex==1		%Scalp
				if UseApproxStatus
					Lambda=ScalpLambda.*InvCoeff(1,1);
					ForCoeff=InvCoeff';
				end
				ScaleBins=ScalpScaleBins;
				SaveSCADSStatus=SaveScalpSCADSStatus;
				SaveEGISStatus=SaveScalpEGISStatus;
				SaveAppStatus=SaveScalpAppStatus;
				SaveIndStatus=SaveScalpIndStatus;
				set(AvgInfoFig,'Name','Average Scalp Potential Info:');
			elseif ScalpCsdIndex==2	%Csd
				if UseApproxStatus
					Lambda=CsdLambda.*InvCoeff(1,1);
					ForCoeff=CsdCoeff;
				end
				ScaleBins=CsdScaleBins;	
				SaveSCADSStatus=SaveCsdSCADSStatus;
				SaveEGISStatus=SaveCsdEGISStatus;
				SaveAppStatus=SaveCsdAppStatus;
				SaveIndStatus=SaveCsdIndStatus;
				set(AvgInfoFig,'Name','Average CSD Info:');
			end
		
		%========================================

		for CondIndex=1:NCond
			EditVec=HWEditVec(1:NTrials);
			NoiseVec=ones(NChanCalc,1);

			if GrandCondStatus~=1 
				CondName=CondCondVec(CondIndex);
				NotTakeVec=find(CondVec~=CondName);
              	TakeVec=find(CondVec==CondName);
				EditVec(NotTakeVec)=2.*ones(length(NotTakeVec),1);
				set(AvgInfoTextVec(14),'String',num2str(CondIndex));
				set(AvgInfoTextVec(16),'String',num2str(CondName));
			end

			TrialsToAvgVec=find(EditVec==1);
			NTrialsToAvg=length(TrialsToAvgVec);
			%=====================================================

			if NTrialsToAvg==0; 
				AvgApprox400('ClearAvgMessage');	
				if GrandCondStatus==1	
					set(AvgMessageTextVec(1),'String',['Sorry, no trial in file:'],'Color',[1 0 0]);
					set(AvgMessageTextVec(2),'String',[DataFilePath],'Color',[0 0 1]);
				else
					set(AvgMessageTextVec(1),'String',['Sorry, no trial in condition ' int2str(CondName) ' !'],'Color',[1 0 0]);
				end
				pause(5)
			else
				if UseApproxStatus
					InvCoeff=InvCoeff+Lambda.*eye(NChanCalc);				
					TmpDataMat=zeros(NChanCalc,NPoints);
					if SesFileFormatVal==1 | SesFileFormatVal==2
						OrigDataFid=fopen(DataFilePath,'r');
						Header=fread(OrigDataFid,LHeader,'int8');
						fclose(OrigDataFid);
					end
				end
				%=====================================================
				AvgMat=zeros(NChanCalc+NChanExtra,NPoints);
				DataMat=zeros(NChanCalc,NPoints);
				if NChanExtra>0
					DataExtraMat=zeros(NChanCalc+NChanExtra,NPoints);
					ExtraMat=zeros(NChanExtra,NPoints);
				end
				AvgIndex=0;
				if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
					AppFileRWStatus=1;
					if MainMatlabVersion>4
						LBitAppData=NTrialsToAvg.*(NChanCalc+NChanExtra).*NPoints.*4;
						if LBitAppData<2500000
							AppFileRWStatus=0;
							App3dMat=zeros(NTrialsToAvg,(NChanCalc+NChanExtra),NPoints);
						end
					end
					set(hAvgList(44),'Value',AppFileRWStatus);
	
					LAppHeader=1000;					
					if GrandCondStatus~=1
						AppExt=['.app' int2str(CondName)];
					else
						AppExt='.appg';
					end
					if ScalpCsdIndex==2
						AppExt=['.csd' AppExt];
					end
					if isempty(ResultPath)
						AppFilePath=[DataFilePath,AppExt];
					else
						AppFilePath=[ResultPath,DataFile,AppExt];
					end
					if SaveAppStatus | AppFileRWStatus
						[AppFilePathMat]=AddFileName2Mat(AppFilePathMat,AppFilePath)
						AppFid=fopen(AppFilePath,'w');
       	     			if AppFid==-1
       	         			[AppFile,AppPath]=SepFilePath(AppFilePath);
                			AppFilePath=[AlternSavePath,AppFile];
                			AppFid=fopen(AppFilePath,'w');
                			if AppFid==-1
                    			Message=char('Sorry,');
                    			Message=char(Message,'it is not possible to write data to file:');
                    			Message=char(Message,' ');
                    			Message=char(Message,AppFilePath);
                    			Message=char(Message,' ');
								hmsgbox=msgbox(Message,'Error','error');
                    			return;
                			end
            			end
						fwrite(AppFid,AppVersion,'int16');
						fwrite(AppFid,LAppHeader,'int16');
						fwrite(AppFid,ScaleBins,'int16');
						fwrite(AppFid,NChanCalc,'int16');
						fwrite(AppFid,NPoints,'int16');
						fwrite(AppFid,NTrialsToAvg,'int16');
						fwrite(AppFid,SampRate,'int16');
						fwrite(AppFid,AvgRefStatus,'int16');
						fwrite(AppFid,EegMegStatus,'int16');
						fwrite(AppFid,NChanExtra,'int16');
						AppTell=ftell(AppFid);
						ZeroVec=zeros(LAppHeader-AppTell,1);
						fwrite(AppFid,ZeroVec,'int8');
					end
				end %if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
				%======================================================
		
				OrigDataFid=fopen(DataFilePath,'r');
				if SesFileFormatVal==1 | SesFileFormatVal==2
					fseek(OrigDataFid,LHeader,'bof');
				end
				%========================================
			
				fprintf('\n');clc;
				if UseWEMatStatus 
					if ~UseApproxStatus
						SumEditVec=(sum(WeightEditMat(:,TrialsToAvgVec)'))';
						NTrialAvgChanVec=SumEditVec;
					else
						SumEditVec=NTrialsToAvg.*ones(NChanCalc,1);
						if NTrialsToAvg==1
							NTrialAvgChanVec=WeightEditMat(:,TrialsToAvgVec);
						else
							NTrialAvgChanVec=(sum(WeightEditMat(:,TrialsToAvgVec)'))';
						end
					end
				else
					SumEditVec=NTrialsToAvg.*ones(NChanCalc,1);
					NTrialAvgChanVec=SumEditVec;
				end
				NAvgTrials=0;
				MedMedRawVec=zeros(NTrials,1);
				MedMedAvgVec=zeros(NTrials,1);
				set(AvgInfoTextVec(18),'String',num2str(NTrials));
        		TrialInCondVec=find(EditVec==1);
        		set(AvgInfoTextVec(22),'String',int2str(length(TrialInCondVec)));
				AllChanOnes=ones(1,NChanCalc);
				for TrialInd=1:NTrials
					if EditVec(TrialInd)==1
						NAvgTrials=NAvgTrials+1;
						if UseWEMatStatus
							GoodChanVec=find(WeightEditMat(:,TrialInd)==1);	
							BadChanVec=find(WeightEditMat(:,TrialInd)==0);	
							NGoodChan=length(GoodChanVec);
							NBadChan=NChanCalc-NGoodChan;
						else
							GoodChanVec=[1:NChanCalc];
							BadChanVec=[];
							NGoodChan=NChanCalc;
							NBadChan=0;
						end
						set(AvgInfoTextVec(20),'String',num2str(TrialInd));
						set(AvgInfoTextVec(24),'String',num2str(NAvgTrials));
						set(AvgInfoTextVec(26),'String',num2str(NGoodChan));
						set(AvgInfoTextVec(28),'String',num2str(NBadChan));
						pause(.0001)
						if NChanExtra==0
							DataMat=fread(OrigDataFid,[NChan,NPoints],DataFileFormat);
						else
							DataExtraMat=fread(OrigDataFid,[NChan+NChanExtra,NPoints],DataFileFormat);
							ExtraMat=DataExtraMat(NChan+1:NChan+NChanExtra,:);
							DataMat=DataExtraMat(1:NChan,:);
						end
						if (SesFileFormatVal==1 | SesFileFormatVal==2) & BrdGain~=1 
							DataMat=DataMat./BrdGain; %µv = (AD value -Zero) x 400/gain Info from Mark Moran 19 Jul 2002
						end
						%==========================================================
						if ~SetTimeIntZeroStatus	
							if EegMegStatus==1
								for TimeInd=1:NPoints
									DataMat(:,TimeInd)=(DataMat(:,TimeInd)-ChanZero).*ChanGainVec;
								end
							end
							if AvgRefStatus
								AvgRefMat=zeros(NChanCalc,NPoints);
								AvgRefMat(1:NChan,:)=DataMat; DataMat=[];
								AvgRefVec=(sum(AvgRefMat(GoodChanVec,:)))./(length(GoodChanVec));
								for TimeInd=1:NPoints
									AvgRefMat(GoodChanVec,TimeInd)=AvgRefMat(GoodChanVec,TimeInd)-ones(NGoodChan,1).*AvgRefVec(TimeInd);
								end
								AvgRefMat(NChanCalc,:)=-1.*AvgRefVec;
								DataMat=AvgRefMat; AvgRefMat=[];
							end
						else %if SetTimeIntZeroStatus
							DataMat(:,NoTimeIndVec)=zeros(NChan,NNoTimeInd);
							for TimeInd=1:length(TimeIndVec)
								DataMat(:,TimeIndVec(TimeInd))=(DataMat(:,TimeIndVec(TimeInd))-ChanZero).*ChanGainVec;
							end
							if AvgRefStatus
								AvgRefMat=zeros(NChanCalc,NPoints);
								AvgRefMat(1:NChan,:)=DataMat; DataMat=[];
								AvgRefVec=(sum(AvgRefMat(GoodChanVec,:)))./(length(GoodChanVec));
								for TimeInd=1:length(TimeIndVec)
									AvgRefMat(GoodChanVec,TimeIndVec(TimeInd))=AvgRefMat(GoodChanVec,TimeIndVec(TimeInd))-ones(NGoodChan,1).*AvgRefVec(TimeIndVec(TimeInd));
								end
								AvgRefMat(NChanCalc,:)=-1.*AvgRefVec;
								DataMat=AvgRefMat; AvgRefMat=[];
							end
						end
						%=========================================================
						if ScalpCsdIndex==1
							if UseApproxStatus
								if ~isempty(BadChanVec)
									TmpDataMat=DataMat(GoodChanVec,:);
									c0=mean(TmpDataMat);
									TmpDataMat=TmpDataMat-(c0'*ones(1,NGoodChan))';
									DipStrength = InvCoeff(GoodChanVec,GoodChanVec) \ TmpDataMat;
									TmpDataMat=(DipStrength' * ForCoeff(GoodChanVec,:))';
									TmpDataMat=TmpDataMat+(c0'*AllChanOnes)';	
									DataMat(BadChanVec,:)=TmpDataMat(BadChanVec,:);
								end
								MedMedRawVec(TrialInd)=median(median(abs(DataMat(:,TimeIndVec))));
								AvgMat(1:NChanCalc,:)=AvgMat(1:NChanCalc,:)+DataMat;
								MaxAbsVec=max(abs(DataMat(:,TimeIndVec)'));	
							else	
								MedMedRawVec(TrialInd)=median(median(abs(DataMat(GoodChanVec,TimeIndVec))));
								AvgMat(GoodChanVec,:)=AvgMat(GoodChanVec,:)+DataMat(GoodChanVec,:);
								if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
									MaxAbsVec=max(abs(DataMat(GoodChanVec,TimeIndVec)'));
								end
							end
						elseif ScalpCsdIndex==2
							TmpDataMat=DataMat(GoodChanVec,:);
							c0=mean(TmpDataMat);
							TmpDataMat=TmpDataMat-(c0'*ones(1,NGoodChan))';
							DipStrength = InvCoeff(GoodChanVec,GoodChanVec) \ TmpDataMat;
							TmpDataMat=(DipStrength' * ForCoeff(GoodChanVec,:))';
							DataMat=TmpDataMat+(c0'*AllChanOnes)';	
							MedMedRawVec(TrialInd)=median(median(abs(DataMat)));
							AvgMat=AvgMat+DataMat;
							if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
								MaxAbsVec=max(abs(DataMat));
							end
						end
						if NChanExtra>0
							AvgMat(NChanCalc+1:NChanCalc+NChanExtra,:)=AvgMat(NChanCalc+1:NChanCalc+NChanExtra,:)+ExtraMat;
						end
						MedMedAvgVec(TrialInd)=median(median(abs(AvgMat(1:NChanCalc,TimeIndVec))));
						if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
							MaxIndVec=find(MaxAbsVec.*ScaleBins>32768);
						end
						%=========================================================

                		if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
							if ~isempty(MaxIndVec)
								AvgApprox400('ClearAvgMessage');		
								set(AvgMessageTextVec(1),'String','Warning:','Color',[1 0 0]);
								set(AvgMessageTextVec(2),'String','Bad scaling in SaveAppData !!!!!','Color',[1 0 0]);
								set(AvgMessageTextVec(4),'String',['Channels: ',int2str(MaxIndVec)],'Color',[1 0 0]);
								Message=char('Warning,');
								Message=char(Message,'bad scaling in SaveAppData !!!!!');
								Message=char(Message,'');
								Message=char(Message,['File:         ',DataFile]);
								if GrandCondStatus~=1
									Message=char(Message,['Condition: ',int2str(CondName)]);
								end
								Message=char(Message,['Trial:       ',int2str(NAvgTrials)]);
								Message=char(Message,['Channels:  ',int2str(MaxIndVec)]);
								Message=char(Message,'');
% 								hmsgbox=msgbox(Message,'Warning','warn'); 
								MaxIndVec=[];
							end
							if AppFileRWStatus
								if EegMegStatus==1		%EEG
									if NChanExtra==0
										fwrite(AppFid,DataMat'.*ScaleBins,DataFileFormat);
									else
										DataExtraMat(1:NChanCalc,:)=DataMat;
										fwrite(AppFid,DataExtraMat'.*ScaleBins,DataFileFormat);
									end
								elseif EegMegStatus==2	%MEG
									if NChanExtra==0
										fwrite(AppFid,DataMat',DataFileFormat);
									else
										DataExtraMat(1:NChanCalc,:)=DataMat;
										fwrite(AppFid,DataExtraMat',DataFileFormat);
									end
								end
							else
								if NChanExtra==0
									App3dMat(NAvgTrials,:,:)=DataMat;
								else
									DataExtraMat(1:NChanCalc,:)=DataMat;
									App3dMat(NAvgTrials,:,:)=DataExtraMat;
								end
							end
						end %if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
						ElapsedTime=etime(clock,StartTime);
						set(AvgInfoTextVec(36),'String',[int2str(floor(ElapsedTime./60)) ' min'],'Userdata',ElapsedTime)
						%set(AvgInfoTextVec(38),'String',int2str(ElapsedTime),'Userdata',ElapsedTime)
						%==========================================================
					else			%	if EditVec(TrialInd)==1
						fseek(OrigDataFid,NBytesInTrial,'cof');
					end			%	if EditVec(TrialInd)==1	
				end	%for TrialInd
    
        		NotZeroIndexVec=find(SumEditVec~=0);
				for TimeInd=1:NPoints
					AvgMat(NotZeroIndexVec,TimeInd)=AvgMat(NotZeroIndexVec,TimeInd)./SumEditVec(NotZeroIndexVec);
				end
				if NChanExtra>0
					AvgMat(NChanCalc+1:NChanCalc+NChanExtra,:)=AvgMat(NChanCalc+1:NChanCalc+NChanExtra,:)./NTrialsToAvg;
				end
				if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
					if ~AppFileRWStatus & SaveAppStatus
						fwrite(AppFid,App3dMat,DataFileFormat);
						fclose(AppFid);
					elseif AppFileRWStatus
						fclose(AppFid);
					end
				end
				fclose(OrigDataFid); 
				
				%========================================
				if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
					if AppFileRWStatus
						if CalcStdBaseStatus
							[AvgMatTmp]=CalcBaseline(AvgMat,MinStdBase,MaxStdBase);
						end
						StdTrialTimeMat=zeros(NTrialsToAvg,NPoints);
						StdChanTimeMat=zeros(NChanCalc+NChanExtra,NPoints);
		
						AppFid=fopen(AppFilePath,'r');
						if AppFid==-1;  
							error('fopen AppFid error'); 
						end		
						if NTrialsToAvg>1
							for ChanInd=1:NChanCalc+NChanExtra
								if CalcStdBaseStatus
									AvgTmp=AvgMatTmp(ChanInd,:);
								else
									AvgTmp=AvgMat(ChanInd,:);
								end
								SeekStatus=fseek(AppFid,LAppHeader+(ChanInd-1).*NPoints.*NBit,-1);
								if SeekStatus==-1; 
									error('fseek1 error'); 
								end	
								for TrialInd=1:NTrialsToAvg
									if TrialInd>1
										SeekStatus=fseek(AppFid,(NChanCalc+NChanExtra-1).*NPoints.*NBit,0);
										if SeekStatus==-1; 
											error('fseek2 error'); 
										end				
									end
									DataTmp=(fread(AppFid,NPoints,DataFileFormat))';
									if EegMegStatus==1		%EEG
										DataTmp=DataTmp./ScaleBins;
									end
									if CalcStdBaseStatus
										[DataTmp]=CalcBaseline(DataTmp,MinStdBase,MaxStdBase);
									end	
									StdTrialTimeMat(TrialInd,:)=DataTmp;
									DiffTmp=DataTmp-AvgTmp;	
									StdTmp=std(DiffTmp);
								end
								%===============================================
								StdChanTimeMat(ChanInd,:)=std(StdTrialTimeMat); %std over trials
								%===============================================
								MeanStdChanVec(ChanInd)=mean(StdChanTimeMat(ChanInd,:));
								set(AvgInfoTextVec(30),'String',[num2str(ChanInd),' of ',num2str(NChanCalc+NChanExtra)])
								set(AvgInfoTextVec(32),'String',num2str(MeanStdChanVec(ChanInd)))
								pause(0.0001);
							end
						end
						fclose(AppFid); 	
					else      %if AppFileRWStatus
						if NTrialsToAvg>1
							if CalcStdBaseStatus
								for TrialInd=1:NTrialsToAvg
									[App3dMat(TrialInd,:,:)]=CalcBaseline(squeeze(App3dMat(TrialInd,:,:)),MinStdBase,MaxStdBase);
								end
							end
							App3dMat(NAvgTrials,:,:)=DataMat;
							StdChanTimeMat=std(App3dMat);
						end
					end	%if AppFileRWStatus
				end %if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
				%========================================
				if ~AvgRefStatus & EegMegStatus==1	%EEG
					AvgNChan=NChan+1;
					%Der NChan+1 Kanal wird fuer die gemittelte Referenz reserviert
					AvgMatTmp=zeros(AvgNChan,NPoints);
					AvgMatTmp(1:AvgNChan-1,:)=AvgMat; AvgMat=[]; AvgMat=AvgMatTmp; AvgMatTmp=[];
					%SumEditVec beinhaltet die gemittelten trials pro Kanal
					%Der AvgNChan Wert des SumEditVec beinhaltet den Median Wert des Vektors SumEditVec(1:AvgNChan-1)
					SumEditVecTmp=zeros(AvgNChan,1);
					SumEditVecTmp(1:AvgNChan-1)=SumEditVec;
					SumEditVecTmp(AvgNChan)=median(SumEditVec);
					SumEditVec=[]; SumEditVec=SumEditVecTmp; SumEditVecTmp=[];
					NoiseVecTmp=zeros(AvgNChan,1);
					NoiseVecTmp(1:AvgNChan-1)=NoiseVec;
					NoiseVecTmp(AvgNChan)=median(NoiseVecTmp);
					NoiseVec=[]; NoiseVec=NoiseVecTmp; NoiseVecTmp=[];
				else
					AvgNChan=NChanCalc+NChanExtra;
				end
				SumNoiseVec=(1./NoiseVec).*SumEditVec;
				if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
					if ~AvgRefStatus & EegMegStatus==1	%EEG
						SaveStdChanTimeMat=zeros(AvgNChan,NPoints);
						SizeStdChanTimeMat=size(StdChanTimeMat);
						if length(SizeStdChanTimeMat)==3
							Tmp=zeros(NChanCalc,NPoints);
							Tmp(:,:)=StdChanTimeMat(1,:,:);
							SaveStdChanTimeMat(1:NChanCalc,:)=Tmp;
						else
							SaveStdChanTimeMat(1:NChanCalc,:)=StdChanTimeMat;
						end
						SaveNTrialAvgChanVec=zeros(AvgNChan,1);
						SaveNTrialAvgChanVec(1:NChan)=NTrialAvgChanVec; 
					else
						SaveStdChanTimeMat=StdChanTimeMat;
						SaveNTrialAvgChanVec=NTrialAvgChanVec;
					end
				end
				%=================================Save this averaged condition to file=================================
				if GrandCondStatus==1
					AvgExt='.atg';
					AvgIndExt='.ig';
				else
					AvgExt=['.at',num2str(CondName)];
					AvgIndExt=['.i' num2str(CondName)];
				end
				if ScalpCsdIndex==2
					AvgExt=['.csd' AvgExt];
				end
				if isempty(ResultPath)
					AvgFilePath=[DataFilePath,AvgExt];
					AvgTrialIndFilePath=[DataFilePath,AvgIndExt];
				else
					AvgFilePath=[ResultPath,DataFile,AvgExt];
					AvgTrialIndFilePath=[ResultPath,DataFile,AvgIndExt];
				end
                MEGShortenFileNameStatus=1
                Tmp=findstr('.ses',AvgFilePath)
                if MEGShortenFileNameStatus & ~isempty(Tmp)
                      AvgFilePath=[AvgFilePath(1:Tmp(1)-1),AvgFilePath(Tmp(1)+4:length(AvgFilePath))]                
                end
                Tmp=findstr('.ses',AvgTrialIndFilePath)
                if MEGShortenFileNameStatus & ~isempty(Tmp)
                   AvgTrialIndFilePath=[AvgTrialIndFilePath(1:Tmp(1)-1),AvgTrialIndFilePath(Tmp(1)+4:length(AvgTrialIndFilePath))]                
                end
				if isempty(AvgFilePathMat)
					AvgFilePathMat=char(AvgFilePath);
					AvgTrialIndFilePathMat=char(AvgTrialIndFilePath);
				else
					AvgFilePathIndVec=[];
					AvgFilePathIndVec=strmatch(AvgFilePathMat,AvgFilePath);
					if ~isempty(AvgFilePathIndVec)
						AddExt=['_' int2str(length(AvgFilePathIndVec))];
						if isempty(ResultPath)
							AvgFilePath=[DataFilePath,AddExt,AvgExt];
							AvgTrialIndFilePath=[DataFilePath,AddExt,AvgIndExt];
						else
							AvgFilePath=[ResultPath,DataFile,AddExt,AvgExt];
							AvgTrialIndFilePath=[ResultPath,DataFile,AddExt,AvgIndExt];
						end
					end 
					AvgFilePathMat=char(AvgFilePathMat,AvgFilePath);
					AvgTrialIndFilePathMat=char(AvgTrialIndFilePathMat,AvgTrialIndFilePath);
				end
				if isempty(TrialsToAvgVec); 
					TrialsToAvgVec=0; 
					IsTrialInFile=0;
				else
					IsTrialInFile=1;
				end
				AvgApprox400('ClearAvgMessage');	
				if SaveScalpIndStatus	
					set(AvgMessageTextVec(1),'String','Save the trial index vector in file:','Color',[1 0 0]);
					set(AvgMessageTextVec(2),'String',AvgTrialIndFilePath,'Color',[0 0 1]);
					SaveData(TrialsToAvgVec,AvgTrialIndFilePath,1,[],'ascii','ascii',[],[],[],1,1,0);
				end
				if ~CalcStdStatus
					SaveStdChanTimeMat=zeros(size(AvgMat));
				end
				if SaveSCADSStatus	
					if IsTrialInFile
						set(AvgMessageTextVec(4),'String','Save the SCADS averaged data in file:','Color',[1 0 0]);
                        if AvgRefStatus	
							set(AvgMessageTextVec(5),'String',[AvgFilePath,'.ar'],'Color',[0 0 1]);
							SaveAvgFile([AvgFilePath,'.ar'],AvgMat,SaveNTrialAvgChanVec,SaveStdChanTimeMat,SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra);
						else
							set(AvgMessageTextVec(5),'String',AvgFilePath,'Color',[0 0 1]);
							SaveAvgFile(AvgFilePath,AvgMat,SaveNTrialAvgChanVec,SaveStdChanTimeMat,SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra);
							if EegMegStatus==1 & SaveAvgRefStatus %EEG
								%===================Calculate the average reference====================================================
								AvgRefMat=zeros(size(AvgMat));
								AvgRefMat(NChanCalc+1,:)=-1.*sum(AvgMat)./NChanCalc;
								for TimeInd=1:NPoints
									AvgRefMat(1:NChan,TimeInd)=AvgMat(1:NChan,TimeInd)+AvgRefMat(NChan+1,TimeInd).*ones(NChan,1);
								end
								SaveAvgFile([AvgFilePath,'.ar'],AvgRefMat,SaveNTrialAvgChanVec,SaveStdChanTimeMat,SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra);
							end 
						end
					end
				end
				pause(1)
				set(AvgInfoTextVec(30),'String',' ')
				set(AvgInfoTextVec(32),'String',' ')
				if CalcStdStatus | SaveScalpAppStatus | SaveCsdAppStatus
					if ~SaveAppStatus & AppFileRWStatus 
						delete([AppFilePath]);
					end
				end
   			end %if NTrialsToAvg==0 

       	 	%===============Save to EGIS average file==============================================
			if SaveScalpEGISStatus & sum(NTrialsToAvgVec)~=0
        		if CondIndex==1
     	     	  	NSubjects=1;
					NCells=NCond;
       		    	AvgLData=NPoints*NChanCalc.*NCells.*NSubjects.*2;
					EgisExt='.ave';
					if ScalpCsdIndex==2
						EgisExt=['.csd' EgisExt];
					end
					if isempty(ResultPath)
            			EgisSaveDataFilePath=[DataFilePath,EgisExt];
					else
            			EgisSaveDataFilePath=[ResultPath,DataFile,EgisExt];
					end
					if isempty(EgisSaveDataFilePathMat)
						EgisSaveDataFilePathMat=char(EgisSaveDataFilePath);
					else
						EgisSaveDataFilePathIndVec=[];
						EgisSaveDataFilePathIndVec=strmatch(EgisSaveDataFilePathMat,EgisSaveDataFilePath);
						if ~isempty(EgisSaveDataFilePathIndVec)
							AddExt=['_' int2str(length(EgisSaveDataFilePathIndVec))];
							if isempty(ResultPath)
								EgisSaveDataFilePath=[DataFilePath,AddExt,EgisExt];
							else
								EgisSaveDataFilePath=[ResultPath,DataFile,AddExt,EgisExt];
							end
						end 
						EgisSaveDataFilePathMat=char(EgisSaveDataFilePathMat,EgisSaveDataFilePath);
					end
        			set(AvgMessageTextVec(7),'String','Save the EGIS averaged data in file:','Color',[1 0 0]);
					set(AvgMessageTextVec(8),'String',EgisSaveDataFilePath,'Color',[0 0 1]);
        			fprintf(EgisSaveDataFilePath);
        			fprintf('\n\n');
        			EgisAvgFid=fopen(EgisSaveDataFilePath,'w');
        
        			fwrite(EgisAvgFid,BytOrd,'uint8');
					fwrite(EgisAvgFid,HdrVer,'int16');
        			TellAvgLHeader=ftell(EgisAvgFid);
       				AvgLHeader=1;           
        			fwrite(EgisAvgFid,AvgLHeader,'int16');
        			fwrite(EgisAvgFid,AvgLData,'int32');
        			fwrite(EgisAvgFid,ExptNam,'char');
        			fwrite(EgisAvgFid,zeros(12,1),'int8');  %reserved for futur use
       				fwrite(EgisAvgFid,0,'int16');           %LastDone
        			fwrite(EgisAvgFid,ScaleBins,'int16');        
        			fwrite(EgisAvgFid,0,'int16');           %ScaleCal
        			fwrite(EgisAvgFid,0,'int16');           %BaseDur
        			fwrite(EgisAvgFid,zeros(6,1),'int8');   %reserved for futur use
       		
					fwrite(EgisAvgFid,NCells,'int16');
        			fwrite(EgisAvgFid,NChanCalc,'int16');
        			fwrite(EgisAvgFid,LComment,'int16');
        			fwrite(EgisAvgFid,LText,'int16');
        			fwrite(EgisAvgFid,LPad,'int16');
        			fwrite(EgisAvgFid,BrdGain,'int16');
        			AvgLCellHdr=zeros(NCond,1);
        			fwrite(EgisAvgFid,AvgLCellHdr,'int16');
        			fwrite(EgisAvgFid,zeros(4.*NChanCalc,1),'int8'); %reserved for futur use

	   				for CellInd=1:NCells
						fwrite(EgisAvgFid,CondCondVec(CellInd),'int16');
						fwrite(EgisAvgFid,CellName,'char');
						fwrite(EgisAvgFid,NSubjects,'int16');
						fwrite(EgisAvgFid,NPoints,'int16');
						fwrite(EgisAvgFid,SampRate,'int16');
						fwrite(EgisAvgFid,LSpec,'int16');	
       					for SubjectInd=1:NSubjects
							fwrite(EgisAvgFid,NTrialsToAvgVec(CellInd),'int16');
							fwrite(EgisAvgFid,RunDate,'int16');
							fwrite(EgisAvgFid,RunTime,'int16');
							fwrite(EgisAvgFid,SubjID,'int16');
							fwrite(EgisAvgFid,Handed,'int16');
							fwrite(EgisAvgFid,Sex,'int16');
							fwrite(EgisAvgFid,Age,'int16');
							fwrite(EgisAvgFid,ExperID,'int16');
							fwrite(EgisAvgFid,EdVer,'int16');
							fwrite(EgisAvgFid,CalFlag,'int16');
						end
			   		end
    		    	AvgLHeader=ftell(EgisAvgFid);
       	 			fwrite(EgisAvgFid,zeros(AvgLData+NChanCalc.*NCond,1),'int16'); %2.*AvgLData./2
       	 			fseek(EgisAvgFid,TellAvgLHeader,-1);
        			fwrite(EgisAvgFid,AvgLHeader,'int16');
        			fseek(EgisAvgFid,AvgLHeader,-1);
    			end %if CondIndex==1
				if NTrialsToAvg==0
					AvgMat=zeros(NChanCalc,NPoints); 
					SaveStdChanTimeMat=zeros(NChanCalc,NPoints); 
					SaveNTrialAvgChanVec=zeros(NChanCalc,1); 
				end
    			fseek(EgisAvgFid,AvgLHeader+(CondIndex-1).*NChanCalc.*NPoints.*2,-1);
        		fwrite(EgisAvgFid,AvgMat.*ScaleBins,'int16');
   				fseek(EgisAvgFid,AvgLHeader+AvgLData+(CondIndex-1).*NChanCalc.*NPoints.*2,-1);
        		fwrite(EgisAvgFid,SaveStdChanTimeMat.*ScaleBins,'int16');
				fseek(EgisAvgFid,AvgLHeader+2.*AvgLData+(CondIndex-1).*NChanCalc.*2,-1);
				fwrite(EgisAvgFid,SaveNTrialAvgChanVec,'int16');
				if CondIndex==NCond; 
					fclose(EgisAvgFid); 
				end
			end	%if SaveScalpEGISStatus
        	%========================================================================      
		end	%Condition
        %========================================================================      
		end	%ScalpCsdIndex
       	%========================================================================      
	end	%File
	for i=1:15
		set(AvgMessageTextVec(1),'String',' ');
	end
	set(AvgMessageTextVec(1),'String','Averaging procedure finished','Color',[1 1 1]);
end	%RunAverage
return;
				
