function GenSynthData(action)

%	GenSynthData

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

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

global hGenSynthDataMenuFig
global hPlot2dMenuFig


%============================================================================
%=========== Initialize  ====================================================
%============================================================================
if strcmp(action,'Initialize'),
	
  	NonUse=0;
  	CortRadiusCm = 8.15; 		%radius of shell 1 (brain or cort)
	TmpAddyPos=-.015;
   
   if strcmp(computer,'MAC2')	
       MenuFigPosVec=[0.7 0 0.2 1];
   elseif strcmp(computer,'PCWIN') 
       MenuFigPosVec=[0.68 0.05 0.2 0.88];
   elseif strcmp(computer,'SOL2')
       MenuFigPosVec=[0.7 0.01 0.2 0.91];		
   end;
	
	hGenSynthDataMenuFig=figure('Units','normal',...
		'Position',MenuFigPosVec, ...
      	'Name','Synthetic Data Menu:', ...
		'Color',[.99 .99 .99], ...
      	'NumberTitle','off');
	
	hPlot2dList=get(hPlot2dMenuFig,'Userdata');
 	SpherStatus=get(hPlot2dList(3),'Value');
	Domain=get(hPlot2dList(20),'value');
	EEGMEGStatusString=get(hPlot2dList(110),'String');
	if strcmp(EEGMEGStatusString,'EEG')
		if Domain<3
			EEGMEGString='µV';
		else
			EEGMEGString='µV/sqrt(Hz)';
		end
	else
		if Domain<3
			EEGMEGString='fT';
		else
			EEGMEGString='fT/sqrt(Hz)';
		end
	end

	 % Information for all buttons (and menus)
    labelColor=[0.8 0.8 0.8];
    yInitPos=0.90;
    menutop=0.955;
    btnTop = 0.6;
    top=0.75;
    left=0.125;
    btnWid=0.8;
    btnHt=0.04;
	btnHt_edit=0.050;
    textHeight = 0.05;			% not used !!!!!!!!!!!
    textWidth = 0.06;
    % Spacing between the button and the next command's label
    spacing=0.015;

    %====================================
    % The CONSOLE frame
	
    frmBorder=0.05; 
	frmLeft=left-frmBorder;
	frmBottom=0.010; 
    frmHeight = 1-3.*frmBottom; 
	frmWidth = btnWid+2*frmBorder;
    yPos=frmBottom-frmBorder;
    frmPos=[frmLeft frmBottom frmWidth frmHeight];
	ConsoleRGBColor=[0 .3 .3];
    hConsolFrame=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',frmPos, ...
		'BackgroundColor',ConsoleRGBColor);
		
    %====================================
    
	% DataFileFormat Routine text label 
    btnNumber=1;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./2;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hDataFileFormatText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',labelPos, ...
        'Horiz','center', ...
        'String','Data File Format', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
   
    % The DataFileFormat Routine Selection Menu
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
    labelStr='Do not save|Matlab Matrix|EGIS Session|AvgApprox (.app)|Besa (.avr)';
    callbackStr='GenSynthData(''chDataFileFormat'');';
    
	hDataFileFormatMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
		'Value',1,...
        'Interruptible','on', ...
        'Callback',callbackStr,...
		'Enable','on');
		
	%====================================
    
	% ActDipole Routine text label 
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./2;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+btnWid./2;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hActDipoleText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',labelPos, ...
        'Horiz','center', ...
        'String','Actual Dipole', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
   
    % The ActDipole Routine Selection Menu
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    labelStr='More | Less | Dipole 1 | Dipole 2';
    callbackStr='GenSynthData(''chActDipole'');';
    
	hActDipoleMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Value',4,...
       'Callback',callbackStr);

	%====================================
    
	% PatternStyle Routine text label 
    	btnNumber=2;
    	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    	labelWidth = btnWid./2;
    	labelBottom=yPos-textHeight./1.5;
    	labelLeft = left;
    	labelPos = [labelLeft labelBottom labelWidth textHeight];
    	hPatternStyleText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
			'Position',labelPos, ...
        'Horiz','center', ...
        'String','Pattern Style', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
   
    	% The PatternStyle Routine Selection Menu
    	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    	btnPos=[left yPos-btnHt btnWid./2 btnHt];
    	labelStr='Linear|Cosinus|Sinus|Interactiv|File';
    	callbackStr='GenSynthData(''chPatternStyle'');';
    
	hPatternStyleMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
        'Userdata',[2 3],...
		'Value',2, ...
        'Callback',callbackStr);

	%====================================
    
	% Simple Dipole Routine text label 
    btnNumber=2;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./2;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+btnWid./2;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hSimpleDipoleStyleText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',labelPos, ...
        'Horiz','center', ...
        'String','Simple Dipole', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
   
    % The Simple Dipole Routine Selection Menu
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    labelStr='Left|Right|Front|Back|Top|Bottom';
    callbackStr='GenSynthData(''chSimpleDipole'');';
    
	hSimpleDipoleStyleMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Value',1, ...
        'Callback',callbackStr);
		
	%====================================
	% NPointsHandle

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

    btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setNPoints'')';
    
	hNPointsMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','100','Userdata',100, ...
        'callback',callbackStr);
	
    %====================================
	% SampRateHandle

	btnNumber=3;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hSampRateText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Sampling Rate [Hz]:');

    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setSampRate'')';
    
	hSampRateMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','100','Userdata',100, ...
        'callback',callbackStr);
	
   
    %===================================
  	
	% FrequencyHandle
   	btnNumber=4;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos 2.*btnWid./3 btnHt_edit./2];
    
	hFrequText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
			'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Frequency [Hz]:');

    
	btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setFrequ'')';
    
	hFrequMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','1','Userdata',[1 1], ...
        'callback',callbackStr);
        
	%===================================
  	
	% PhaseHandle
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hPhaseText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Phase [deg]:');

    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setPhase'')';
    
	hPhaseMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
			'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Userdata',[0 0], ...
        'callback',callbackStr);
	
	%===================================
  	%===================================
	%===================================
  	%===================================
	

	% XPosSlider Handle
   	btnNumber=5;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid btnHt./2];
   	callbackStr = 'GenSynthData(''setXPosSlider'')';
    
	hXPosSliderMenu = uicontrol( ...
        'Style','slider', ...
        'Units','normalized', ...
	'Position',btnPos, ...
    'Horiz','center', ...
    'Background','white', ...
    'Foreground','black', ...
	'Min',-CortRadiusCm,...
	'Max',CortRadiusCm,...
	'SliderStep',[0.01,0.1],...
    'Value',4, ...
    'callback',callbackStr);
		

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

    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setXPos'')';
    
	hXPosMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','4',...
		'Value',4, ...
        'callback',callbackStr);
	
	%===================================
  	%===================================

	% YPosSlider Handle
   	btnNumber=6;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid btnHt./2];
   	callbackStr = 'GenSynthData(''setYPosSlider'')';
    
	hYPosSliderMenu = uicontrol( ...
        'Style','slider', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
		'Min',-CortRadiusCm,...
		'Max',CortRadiusCm,...
		'SliderStep',[0.01,0.1],...
        'Value',0, ...
        'callback',callbackStr);
		

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

    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setYPos'')';
    
	hYPosMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0',...
		'Value',0, ...
        'callback',callbackStr);
	
	
	%===================================
  	%===================================

	% ZPosSlider Handle
   	btnNumber=7;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid btnHt./2];
   	callbackStr = 'GenSynthData(''setZPosSlider'')';
    
	hZPosSliderMenu = uicontrol( ...
        'Style','slider', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
		'Min',-CortRadiusCm,...
		'Max',CortRadiusCm,...
		'SliderStep',[0.01,0.1],...
        'Value',6, ...
        'callback',callbackStr);
		

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

    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setZPos'')';
    
	hZPosMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','6',...
		'Value',6, ...
        'callback',callbackStr);
		
	%===================================
  	%===================================

	% XDipMomSlider Handle
   	btnNumber=8;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid btnHt./2];
   	callbackStr = 'GenSynthData(''setXDipMomSlider'')';
    
	hXDipMomSliderMenu = uicontrol( ...
        'Style','slider', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
		'Min',-10,...
		'Max',10,...
		'SliderStep',[0.01,0.1],...
        'Value',-10, ...
        'callback',callbackStr);
		

	% XDipMomHandle
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hXDipMomText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','X - Moment [nA]:');

    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setXDipMom'')';
    
	hXDipMomMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','-10',...
		'Value',-10, ...
        'callback',callbackStr);
	
	%===================================
  	%===================================

	% YPosSlider Handle
   	btnNumber=9;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid btnHt./2];
   	callbackStr = 'GenSynthData(''setYDipMomSlider'')';
    
	hYDipMomSliderMenu = uicontrol( ...
        'Style','slider', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
		'Min',-10,...
		'Max',10,...
		'SliderStep',[0.01,0.1],...
        'Value',0, ...
        'callback',callbackStr);
		

	% YDipMomHandle
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hYDipMomText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Y - Moment [nA]:');

    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setYDipMom'')';
    
	hYDipMomMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0',...
		'Userdata',0, ...
        'callback',callbackStr);
	
	
	%===================================
  	%===================================

	% ZDipMomSlider Handle
   	btnNumber=10;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid btnHt./2];
   	callbackStr = 'GenSynthData(''setZDipMomSlider'')';
    
	hZDipMomSliderMenu = uicontrol( ...
        'Style','slider', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
		'Min',-10,...
		'Max',10,...
		'SliderStep',[0.01,0.1],...
        'Value',0, ...
        'callback',callbackStr);
		

	% ZDipMomHandle
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hZDipMomText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Z - Moment [nA]:');

    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setZDipMom'')';
    
	hZDipMomMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0',...
		'Value',0, ...
        'callback',callbackStr);
	
	%===================================
  	%===================================
	%===================================

	% UseEOGStatus
	btnNumber=11;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid./2 btnHt./2];
   	callbackStr = 'GenSynthData(''setUseEOGStatus'')';
    
	hUseEOGStatus = uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
		'String','Add Eye', ...
		'Userdata',[],...
		'Value',0,...
        'Background','white', ...
        'Foreground','black', ...
        'callback',callbackStr);

	% UseBEOGStatus
	btnNumber=11;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos btnWid./2 btnHt./2];
   	callbackStr = 'GenSynthData(''setUseBEOGStatus'')';
    
	hUseBEOGStatus = uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
		'String','Blink', ...
		'Userdata',[],...
		'Value',0,...
        'Background','white', ...
        'Foreground','black', ...
        'callback',callbackStr);
		
	% UseLEOGStatus
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt./2 btnWid./2 btnHt./2];
   	callbackStr = 'GenSynthData(''setUseLEOGStatus'')';
    
	hUseLEOGStatus = uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
		'String','Left Eye', ...
		'Userdata',[],...
		'Value',1,...
        'Background','white', ...
        'Foreground','black', ...
        'callback',callbackStr);
	
	% UseREOGStatus
    btnPos=[left+btnWid./2 yPos-btnHt./2 btnWid./2 btnHt./2];
   	callbackStr = 'GenSynthData(''setUseREOGStatus'')';
    
	hUseREOGStatus = uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
		'String','Right Eye', ...
		'Userdata',[],...
		'Value',1,...
        'Background','white', ...
        'Foreground','black', ...
        'callback',callbackStr);
	
	%===================================
	% HVEOGCorStatus
		
	btnNumber=12;   
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);	
    btnPos=[left yPos-btnHt./2 btnWid./2 btnHt./2];
   	callbackStr = 'GenSynthData(''setVEOGCorStatus'')';
    
	hHEOGCorStatus = uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
		'String','Hor. Cor.', ...
		'Userdata',[],...
		'Value',0,...
        'Background','white', ...
        'Foreground','black', ...
        'callback',callbackStr);
		
    btnPos=[left+btnWid./2 yPos-btnHt./2 btnWid./2 btnHt./2];
   	callbackStr = 'GenSynthData(''setVEOGCorStatus'')';
    
	hVEOGCorStatus = uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
		'String','Vert. Cor.', ...
		'Userdata',[],...
		'Value',1,...
        'Background','white', ...
        'Foreground','black', ...
        'callback',callbackStr);
		
	%===================================
	% HVEOGMoveStatus
	
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt./2];
   	callbackStr = 'GenSynthData(''setHEOGMovStatus'')';
    
	hHEOGMovStatus = uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
		'String','Hor. Mov.', ...
		'Userdata',[],...
		'Value',0,...
        'Background','white', ...
        'Foreground','black', ...
        'callback',callbackStr);
		
	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt./2];
   	callbackStr = 'GenSynthData(''setVEOGMovStatus'')';
    
	hVEOGMovStatus = uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
		'String','Vert. Mov.', ...
		'Userdata',[],...
		'Value',1,...
        'Background','white', ...
        'Foreground','black', ...
        'callback',callbackStr);
		
	%===================================
	%===================================
	%====================================
	btnNumber=13;

    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'GenSynthData(''chCartSpher'')';
	hCartSpher=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Cartesian', ...
		'Enable','on', ...
        'Callback',callbackStr);
	
    %====================================
	%Rand text label 
    btnNumber=13;
    
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelWidth = btnWid./2;
    labelBottom=yPos-textHeight./1.5;
    labelLeft = left+btnWid./2;
    labelPos = [labelLeft labelBottom labelWidth textHeight];
    hRandText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',labelPos, ...
        'Horiz','center', ...
        'String','Rand Method', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
   
    %The Rand Selection Menu
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    labelStr='Normally distributed; RANDN|Uniformly distributed; RAND';
    callbackStr='GenSynthData(''chRand'');';
    
	hRandMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Value',1, ...
        'Callback',callbackStr);
    
    hMeanNoise=0;
% 	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
%     btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
% 	callbackStr = 'GenSynthData(''chMeanNoise'')';
% 	hMeanNoise=uicontrol( ...
% 		'Style','radiobutton', ...
%         'Units','normalized', ...
%         'Position',btnPos, ...
%         'String','Mean noise', ...
% 		'Userdata',[],...
% 		'Value',1,...
%         'Callback',callbackStr,...
% 		'Enable','on');
	%===================================
  	%===================================	
	btnNumber=14;     
   
	% Number of trials Text Handle
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hNTrialsText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Number of trials:');

    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setNTrials'')';
    
	hNTrialsMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','1',...
		'Value',1, ...
        'callback',callbackStr);
		
	%===================================
  	%===================================
	% UnCorrNoise Slider Handle
   	btnNumber=15;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid btnHt./2];
   	callbackStr = 'GenSynthData(''setUnCorrNoiseSlider'')';
    
	hUnCorrNoiseSliderMenu = uicontrol( ...
        'Style','slider', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
		'Min',0,...
		'Max',1000,...
		'SliderStep',[.001,.1],...
        'Value',0, ...
        'callback',callbackStr);
		

	% UnCorrNoise Text Handle
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hUnCorrNoiseText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Uncorr. noise; N/S []:');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setUnCorrNoise'')';
    
	hUnCorrNoiseMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0',...
		'Value',0, ...
        'callback',callbackStr);
		
	%===================================
  	%===================================

	% CorrNoise Slider Handle
   	btnNumber=16;     
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos btnWid btnHt./2];
   	callbackStr = 'GenSynthData(''setCorrNoiseSlider'')';
    
	hCorrNoiseSliderMenu = uicontrol( ...
        'Style','slider', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
		'Min',0,...
		'Max',1000,...
		'SliderStep',[.001,.1],...
        'Value',0, ...
        'callback',callbackStr);
		

	% CorrNoise Text Handle
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hCorrNoiseText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Corr. noise; N/S []:');

    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'GenSynthData(''setCorrNoise'')';
    
	hCorrNoiseMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0',...
		'Value',0, ...
        'callback',callbackStr);
		
	%===================================
	%===================================
	
	btnNumber=17;
   	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
  	btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'GenSynthData(''Apply'')';
	hApply=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Apply', ...
		'Userdata',1, ...
		'Enable','on', ...
        'Callback',callbackStr);
	
	%====================================

    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'GenSynthData(''AddDipoles'')';
	hAddDipoles=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Add Dipoles', ...
		'Value',0, ...
		'Enable','on', ...
        'Callback',callbackStr);
	
	%====================================

	NDipoles=2;
	GenSynthParaVec=[CortRadiusCm NDipoles];
	hGenSynthParaVec=uicontrol('Userdata',GenSynthParaVec,'Visible','off');						%1
	hDipStrength1=uicontrol('Visible','off');													%22
	hDipStrength2=uicontrol('Visible','off');													%23
	hDipStrength3=uicontrol('Visible','off');													%24
	
	hLFLoc=uicontrol('Userdata',[],'Visible','off');											%25
	hLFCoeff=uicontrol('Userdata',[],'Visible','off');											%26
	%NonUse																						%27
	hDipPosMomMat=uicontrol('Userdata',[-4 0 6 -10 0 0;4 0 6 10 0 0],'Visible','off');			%36
	hNoiseLFCoeff=uicontrol('Visible','off');													%52

	hEyesLFCoeff=uicontrol('Visible','off');													%61


	hGenSynthList=[	hGenSynthParaVec hXPosMenu hXPosSliderMenu hYPosMenu hYPosSliderMenu ...
				hZPosMenu hZPosSliderMenu hDataFileFormatText hDataFileFormatMenu hActDipoleText ...
				hActDipoleMenu hPatternStyleText hPatternStyleMenu hNPointsText hNPointsMenu ...
				hSampRateText hSampRateMenu hFrequText hFrequMenu hPhaseText ...
				hPhaseMenu hDipStrength1 hDipStrength2 hDipStrength3 hLFLoc ...		%25
				hLFCoeff NonUse hXDipMomMenu hXDipMomSliderMenu hYDipMomMenu ...
				hYDipMomSliderMenu hZDipMomMenu hZDipMomSliderMenu NonUse NonUse ...
				hDipPosMomMat hAddDipoles hCartSpher hXDipMomText hYDipMomText ...
				hZDipMomText hSimpleDipoleStyleText hSimpleDipoleStyleMenu NonUse hApply ...
				hUnCorrNoiseMenu hUnCorrNoiseSliderMenu hCorrNoiseMenu hCorrNoiseSliderMenu hUnCorrNoiseText ... %50
				hCorrNoiseText hNoiseLFCoeff NonUse NonUse NonUse ...
				hMeanNoise hNTrialsText hNTrialsMenu hRandText hRandMenu ...
				hEyesLFCoeff hHEOGCorStatus hVEOGCorStatus hHEOGMovStatus hVEOGMovStatus ...
				hUseLEOGStatus hUseREOGStatus hUseEOGStatus hUseBEOGStatus];														
					
	set(hGenSynthDataMenuFig,'Visible','on','UserData',hGenSynthList);
   
	set(hGenSynthList(11),'Value',4); %ActDipoleVal
	GenSynthData('chActDipole')
	GenSynthData('setDipStrength')
	set(hGenSynthList(11),'Value',3); %ActDipoleVal
	GenSynthData('chActDipole')
	GenSynthData('setDipStrength')
	GenSynthData('chCartSpher')
	%===================================
  	%===================================
  	%===================================
  	%===================================

	
	
elseif strcmp(action,'chCartSpher'),
	
	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	CartSpherString=get(hGenSynthList(38),'String');
	if strcmp(CartSpherString,'Cartesian')
		CartSpherString='Spherical';
		XDipMomString='Azimutal-Moment [nA]';
		YDipMomString='Polar-Moment [nA]';
		ZDipMomString='Radial-Moment [nA]';
	else
		CartSpherString='Cartesian';
		XDipMomString='X - Moment [nA]';
		YDipMomString='Y - Moment [nA]';
		ZDipMomString='Z - Moment [nA]';
	end
	set(hGenSynthList(38),'String',CartSpherString);
	set(hGenSynthList(39),'String',XDipMomString);
	set(hGenSynthList(40),'String',YDipMomString);
	set(hGenSynthList(41),'String',ZDipMomString);

		
elseif strcmp(action,'chDataFileFormat'),
	
	return
	%===================================

elseif strcmp(action,'chActDipole'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	GenSynthParaVec=get(hGenSynthList(1),'UserData');
	NDipoles=GenSynthParaVec(2);
	NPoints=get(hGenSynthList(15),'Userdata');
	ActDipoleVal=get(hGenSynthList(11),'Value');
	ActDipole=ActDipoleVal-2;
	labelStr='More | Less ';
	
	DipStrength1=get(hGenSynthList(22),'Userdata');
	DipStrength2=get(hGenSynthList(23),'Userdata');
	DipStrength3=get(hGenSynthList(24),'Userdata');
	
	DipPosMomMat=get(hGenSynthList(36),'Userdata');
	
	if ActDipoleVal==1	%More
      NDipoles=NDipoles+1;	
	  PatternStyleVec=get(hGenSynthList(13),'Userdata');
 	  PatternStyleVecTmp=ones(NDipoles,1);
      PatternStyleVecTmp(1:NDipoles-1)=PatternStyleVec;
      set(hGenSynthList(13),'Userdata',PatternStyleVecTmp);
      FrequVec=get(hGenSynthList(19),'Userdata');
      FrequVecTmp=ones(NDipoles,1);
      FrequVecTmp(1:NDipoles-1)=FrequVec;
      set(hGenSynthList(19),'Userdata',FrequVecTmp);
      PhaseVec=get(hGenSynthList(21),'Userdata');
      PhaseVecTmp=zeros(NDipoles,1);
      PhaseVecTmp(1:NDipoles-1)=PhaseVec;
      set(hGenSynthList(21),'Userdata',PhaseVecTmp);
      
      DipStrengthTmp=ones(NDipoles,NPoints);

		if ~isempty(DipStrength1); DipStrengthTmp(1:NDipoles-1,:)=DipStrength1; end
		DipStrength1=DipStrengthTmp;
		if ~isempty(DipStrength2); DipStrengthTmp(1:NDipoles-1,:)=DipStrength2; end
		DipStrength2=DipStrengthTmp;
		if ~isempty(DipStrength3); DipStrengthTmp(1:NDipoles-1,:)=DipStrength3; end
		DipStrength3=DipStrengthTmp;
		
		DipPosMomMatTmp=ones(NDipoles,6);
		DipPosMomMatTmp(NDipoles,1:3)=[0 4 6];
		DipPosMomMatTmp(NDipoles,4:6)=[0 0 10];
		if ~isempty(DipPosMomMat); DipPosMomMatTmp(1:NDipoles-1,:)=DipPosMomMat; end
		DipPosMomMat=DipPosMomMatTmp;
		ActDipole=NDipoles;

	elseif ActDipoleVal==2	%Less

		if NDipoles<2; 
			NDipoles=0;
			DipStrength1=[];
			DipStrength2=[];
			DipStrength3=[];
			DipPosMomMat=[];
		else 
         NDipoles=NDipoles-1;
		 PatternStyleVec=get(hGenSynthList(13),'Userdata');
		 set(hGenSynthList(13),'Userdata',PatternStyleVec(1:NDipoles));
         FrequVec=get(hGenSynthList(19),'Userdata');
      	set(hGenSynthList(19),'Userdata',FrequVec(1:NDipoles));
      	PhaseVec=get(hGenSynthList(21),'Userdata');
      	set(hGenSynthList(21),'Userdata',PhaseVec(1:NDipoles));

			DipStrengthTmp=zeros(NDipoles,NPoints);
			DipStrengthTmp=DipStrength1(1:NDipoles,:);
			DipStrength1=DipStrengthTmp;
			DipStrengthTmp=DipStrength2(1:NDipoles,:);
			DipStrength2=DipStrengthTmp;
			DipStrengthTmp=DipStrength3(1:NDipoles,:);
			DipStrength3=DipStrengthTmp;
			
			DipPosMomMatTmp=ones(NDipoles,6);
			if ~isempty(DipPosMomMat); DipPosMomMatTmp=DipPosMomMat(1:NDipoles,:); end
			DipPosMomMat=DipPosMomMatTmp;
			
		end
		ActDipole=NDipoles;
	end
	if ActDipole>0
		for DipoleInd=1:NDipoles
			labelStr=[labelStr '| Dipole: ' int2str(DipoleInd)];
		end
	end

	set(hGenSynthList(11),'String',labelStr,'Userdata',ActDipole+2,'Value',ActDipole+2);
		
	if ActDipole>0
		set(hGenSynthList(2),'Value',DipPosMomMat(ActDipole,1),'String',sprintf('%g',round(DipPosMomMat(ActDipole,1).*100)./100),'Enable','on');  
		set(hGenSynthList(3),'Value',DipPosMomMat(ActDipole,1),'Enable','on');  %xposslider
		set(hGenSynthList(4),'Value',DipPosMomMat(ActDipole,2),'String',sprintf('%g',round(DipPosMomMat(ActDipole,2).*100)./100),'Enable','on');  
		set(hGenSynthList(5),'Value',DipPosMomMat(ActDipole,2),'Enable','on');  %yposslider
		set(hGenSynthList(6),'Value',DipPosMomMat(ActDipole,3),'String',sprintf('%g',round(DipPosMomMat(ActDipole,3).*100)./100),'Enable','on');  
		set(hGenSynthList(7),'Value',DipPosMomMat(ActDipole,3),'Enable','on');  %zposslider	
		
		set(hGenSynthList(28),'Value',DipPosMomMat(ActDipole,4),'String',sprintf('%g',round(DipPosMomMat(ActDipole,4).*100)./100),'Enable','on');  
		set(hGenSynthList(29),'Value',DipPosMomMat(ActDipole,4),'Enable','on');  %xposslider
		set(hGenSynthList(30),'Value',DipPosMomMat(ActDipole,5),'String',sprintf('%g',round(DipPosMomMat(ActDipole,5).*100)./100),'Enable','on');  
		set(hGenSynthList(31),'Value',DipPosMomMat(ActDipole,5),'Enable','on');  %yposslider
		set(hGenSynthList(32),'Value',DipPosMomMat(ActDipole,6),'String',sprintf('%g',round(DipPosMomMat(ActDipole,6).*100)./100),'Enable','on');  
		set(hGenSynthList(33),'Value',DipPosMomMat(ActDipole,6),'Enable','on');  %zposslider	
		PatternStyleVec=get(hGenSynthList(13),'Userdata');
		set(hGenSynthList(13),'Value',PatternStyleVec(ActDipole));
		FrequVec=get(hGenSynthList(19),'Userdata');
		set(hGenSynthList(19),'String',sprintf('%g',round(FrequVec(ActDipole).*100)./100));  
		PhaseVec=get(hGenSynthList(21),'Userdata');
		set(hGenSynthList(21),'String',sprintf('%g',round(PhaseVec(ActDipole).*100)./100));  

	else
		set(hGenSynthList(2),'Enable','off')
		set(hGenSynthList(3),'Enable','off')
		set(hGenSynthList(4),'Enable','off')
		set(hGenSynthList(5),'Enable','off')
		set(hGenSynthList(5),'Enable','off')
		set(hGenSynthList(7),'Enable','off')
		
		set(hGenSynthList(28),'Enable','off')
		set(hGenSynthList(29),'Enable','off')
		set(hGenSynthList(30),'Enable','off')
		set(hGenSynthList(31),'Enable','off')
		set(hGenSynthList(32),'Enable','off')
		set(hGenSynthList(33),'Enable','off')
		
	end
	
	GenSynthParaVec(2)=NDipoles;
	set(hGenSynthList(1),'UserData',GenSynthParaVec);
	
	set(hGenSynthList(22),'Userdata',DipStrength1);
	set(hGenSynthList(23),'Userdata',DipStrength2);
	set(hGenSynthList(24),'Userdata',DipStrength3);

	set(hGenSynthList(36),'Userdata',DipPosMomMat);
	if ActDipole>0; GenSynthData('setDipStrength'); end

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

elseif strcmp(action,'chPatternStyle'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
   PatternStyleVal=get(hGenSynthList(13),'Value');
   ActDipoleVal=get(hGenSynthList(11),'Value');
   PatternStyleVec=get(hGenSynthList(13),'Userdata');
   PatternStyleVec(ActDipoleVal-2)=PatternStyleVal;
   set(hGenSynthList(13),'Userdata',PatternStyleVec);

   if PatternStyleVal>3;%interactiv, file
      EnableString='off';   
   else	%linear, cosinus, sinus
      EnableString='on';   
   end
   set(hGenSynthList(18),'Enable',EnableString);
   set(hGenSynthList(19),'Enable',EnableString);
   set(hGenSynthList(20),'Enable',EnableString);
   set(hGenSynthList(21),'Enable',EnableString);
	GenSynthData('setDipStrength')
	
	
%===================================

elseif strcmp(action,'setNPoints'),

   	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
   	ActDipoleValTmp=get(hGenSynthList(11),'Value');
   	v=get(hGenSynthList(15),'Userdata');
   	str=get(hGenSynthList(15),'String');
   	ind = find(abs(str)<32);
   	str(ind) = 32*ones(size(ind));
   	str = str';	
   	vv = eval(['[' str(:)' ']'],'-1')';
   	if length(vv)~=1
        vv = v;	
	end
	if vv>10000; vv=10000;
	elseif vv<1; vv=1;
   	end
   	NPoints=vv;
   	set(hGenSynthList(15),'Userdata',NPoints,'String',sprintf('%g',round(NPoints.*100)./100));  
    if NPoints~=v
      	GenSynthParaVec=get(hGenSynthList(1),'Userdata');
     	NDipoles=GenSynthParaVec(2);
     	DipStrength1=get(hGenSynthList(22),'Userdata');
		DipStrength2=get(hGenSynthList(23),'Userdata');
      	DipStrength3=get(hGenSynthList(24),'Userdata');
  		if NPoints<v
         	DipStrength1=DipStrength1(:,1:NPoints);
         	DipStrength2=DipStrength2(:,1:NPoints);
			DipStrength3=DipStrength3(:,1:NPoints);
		elseif NPoints>v
         	DipStrength1Tmp=zeros(NDipoles,NPoints);
         	DipStrength2Tmp=zeros(NDipoles,NPoints);
			DipStrength3Tmp=zeros(NDipoles,NPoints);
			DipStrength1Tmp(:,1:v)=DipStrength1;
			DipStrength2Tmp(:,1:v)=DipStrength2;
         	DipStrength3Tmp(:,1:v)=DipStrength3;
         	DipStrength1=DipStrength1Tmp;
         	DipStrength2=DipStrength2Tmp;
         	DipStrength3=DipStrength3Tmp;
      	end
     	set(hGenSynthList(22),'Userdata',DipStrength1);
     	set(hGenSynthList(23),'Userdata',DipStrength2);
     	set(hGenSynthList(24),'Userdata',DipStrength3);
  	end
	
%===================================

elseif strcmp(action,'setSampRate'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	hPlot2dList=get(hPlot2dMenuFig,'Userdata');

	v=get(hGenSynthList(17),'Userdata');
	str=get(hGenSynthList(17),'String');
   ind = find(abs(str)<32);
   str(ind) = 32*ones(size(ind));
   str = str';	
   vv = eval(['[' str(:)' ']'],'-1')';
   if length(vv)~=1
        vv = v;	
	end
	if vv>1000; vv=1000;
	elseif vv<0.01; vv=0.01;
	end
	
	set(hGenSynthList(17),'Userdata',vv,'String',sprintf('%g',round(vv.*100)./100));  
	set(hPlot2dList(60),'Userdata',vv,'String',sprintf('%g',round(vv.*100)./100));
	Plot2d('setSampRate')
%===================================

elseif strcmp(action,'setFrequ'),

   	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
   	ActDipoleVal=get(hGenSynthList(11),'Value');ActDipoleVal=ActDipoleVal-2;
   	FrequVec=get(hGenSynthList(19),'Userdata');
   	v=FrequVec(ActDipoleVal);
	str=get(hGenSynthList(19),'String');
   	ind = find(abs(str)<32);
   	str(ind) = 32*ones(size(ind));
   	str = str';	
  	vv = eval(['[' str(:)' ']'],'-1')';
   	if length(vv)~=1; vv = v; end
	if vv>500; vv=500;
	elseif vv<0.01; vv=0.01;
   	end
   	FrequVec(ActDipoleVal)=vv;
	set(hGenSynthList(19),'Userdata',FrequVec,'String',sprintf('%g',round(vv.*100)./100));  
   	GenSynthData('setDipStrength')
   
	%===================================

elseif strcmp(action,'setPhase'),

   hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
   ActDipoleVal=get(hGenSynthList(11),'Value');ActDipoleVal=ActDipoleVal-2;
   PhaseVec=get(hGenSynthList(21),'Userdata');
   v=PhaseVec(ActDipoleVal);
	str=get(hGenSynthList(21),'String');
    	ind = find(abs(str)<32);
    	str(ind) = 32*ones(size(ind));
    	str = str';	
    	vv = eval(['[' str(:)' ']'],'-1')';
    	if length(vv)~=1
        vv = v;	
	end
	if vv>=360; vv=vv-360;
	elseif vv<=-360; vv=vv+360;
	end
	PhaseVec(ActDipoleVal)=vv;
	set(hGenSynthList(21),'Userdata',PhaseVec,'String',sprintf('%g',round(vv.*100)./100));  
	GenSynthData('setDipStrength')
  	%===================================
  	%===================================
  	%===================================
  	%===================================

elseif strcmp(action,'chSimpleDipole'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	SimpleDipoleVal=get(hGenSynthList(43),'Value');
	GenSynthParaVec=get(hGenSynthList(1),'UserData');
	CortRadiusCm=GenSynthParaVec(1);
	if SimpleDipoleVal==1 %Left
		xyz=[-CortRadiusCm 0 0];
	elseif SimpleDipoleVal==2 %Right
		xyz=[CortRadiusCm 0 0];
	elseif SimpleDipoleVal==3 %Front
		xyz=[0 CortRadiusCm 0];
	elseif SimpleDipoleVal==4 %Back
		xyz=[0 -CortRadiusCm 0];
	elseif SimpleDipoleVal==5 %Top
		xyz=[0 0 CortRadiusCm];
	elseif SimpleDipoleVal==6 %Bottom
		xyz=[0 0 -CortRadiusCm];
	end
	set(hGenSynthList(2),'Value',xyz(1),'String',sprintf('%g',round(xyz(1).*100)./100)); 
	set(hGenSynthList(3),'Value',xyz(1));	
	set(hGenSynthList(4),'Value',xyz(2),'String',sprintf('%g',round(xyz(2).*100)./100)); 
	set(hGenSynthList(5),'Value',xyz(2));	
	set(hGenSynthList(6),'Value',xyz(3),'String',sprintf('%g',round(xyz(3).*100)./100)); 
	set(hGenSynthList(7),'Value',xyz(3));	
	GenSynthData('setDipPosMomMat')
	GenSynthData('Apply')
	
elseif strcmp(action,'setXPos'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	GenSynthParaVec=get(hGenSynthList(1),'UserData');
	CortRadiusCm=GenSynthParaVec(1);
	v=get(hGenSynthList(2),'Value');
	y=get(hGenSynthList(4),'Value');
	z=get(hGenSynthList(6),'Value');
	str=get(hGenSynthList(2),'String');
    ind = find(abs(str)<32);
    str(ind) = 32*ones(size(ind));
    str = str';	
    vv = eval(['[' str(:)' ']'],'-1')';
	if length(vv)~=1; vv=v; end
	xyz=sqrt(sum([vv y z].^2));
    if xyz>CortRadiusCm | xyz==0;
		set(hGenSynthList(45),'Enable','off');
	else
		set(hGenSynthList(45),'Enable','on');
	end
	set(hGenSynthList(2),'Value',vv,'String',sprintf('%g',round(vv.*100)./100)); 
	set(hGenSynthList(3),'Value',vv);	
	GenSynthData('setDipPosMomMat')

elseif strcmp(action,'setXPosSlider'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	GenSynthParaVec=get(hGenSynthList(1),'UserData');
	CortRadiusCm=GenSynthParaVec(1);
	vv=get(hGenSynthList(3),'Value');
	x=get(hGenSynthList(2),'Value');
	y=get(hGenSynthList(4),'Value');
	z=get(hGenSynthList(6),'Value');
	xyz=sqrt(sum([vv y z].^2));
	if xyz>CortRadiusCm | xyz==0;
		set(hGenSynthList(45),'Enable','off');
	else
		set(hGenSynthList(45),'Enable','on');
	end
	set(hGenSynthList(2),'Value',vv,'String',sprintf('%g',round(vv.*100)./100)); 
	GenSynthData('setDipPosMomMat')

elseif strcmp(action,'setYPos'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	GenSynthParaVec=get(hGenSynthList(1),'UserData');
	CortRadiusCm=GenSynthParaVec(1);
	x=get(hGenSynthList(2),'Value');
	v=get(hGenSynthList(4),'Value');
	z=get(hGenSynthList(6),'Value');
	str=get(hGenSynthList(4),'String');
    ind = find(abs(str)<32);
    str(ind) = 32*ones(size(ind));
    str = str';	
    vv = eval(['[' str(:)' ']'],'-1')';
	if length(vv)~=1; vv=v; end
	xyz=sqrt(sum([x vv z].^2));
    if xyz>CortRadiusCm | xyz==0;
		set(hGenSynthList(45),'Enable','off');
	else
		set(hGenSynthList(45),'Enable','on');
	end
	set(hGenSynthList(4),'Value',vv,'String',sprintf('%g',round(vv.*100)./100)); 
	set(hGenSynthList(5),'Value',vv);	
	GenSynthData('setDipPosMomMat')

elseif strcmp(action,'setYPosSlider'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	GenSynthParaVec=get(hGenSynthList(1),'UserData');
	CortRadiusCm=GenSynthParaVec(1);
	vv=get(hGenSynthList(5),'Value');
	x=get(hGenSynthList(2),'Value');
	y=get(hGenSynthList(4),'Value');
	z=get(hGenSynthList(6),'Value');
	xyz=sqrt(sum([x vv z].^2));
	if xyz>CortRadiusCm | xyz==0;
		set(hGenSynthList(45),'Enable','off');
	else
		set(hGenSynthList(45),'Enable','on');
	end
	set(hGenSynthList(4),'Value',vv,'String',sprintf('%g',round(vv.*100)./100)); 
	GenSynthData('setDipPosMomMat')
	
elseif strcmp(action,'setZPos'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	GenSynthParaVec=get(hGenSynthList(1),'UserData');
	CortRadiusCm=GenSynthParaVec(1);
	x=get(hGenSynthList(2),'Value');
	y=get(hGenSynthList(4),'Value');
	v=get(hGenSynthList(6),'Value');
	str=get(hGenSynthList(6),'String');
    ind = find(abs(str)<32);
    str(ind) = 32*ones(size(ind));
    str = str';	
    vv = eval(['[' str(:)' ']'],'-1')';
	if length(vv)~=1; vv=v; end
	xyz=sqrt(sum([x y vv].^2));
    if xyz>CortRadiusCm | xyz==0;
		set(hGenSynthList(45),'Enable','off');
	else
		set(hGenSynthList(45),'Enable','on');
	end
	set(hGenSynthList(6),'Value',vv,'String',sprintf('%g',round(vv.*100)./100)); 
	set(hGenSynthList(7),'Value',vv);	
	GenSynthData('setDipPosMomMat')

elseif strcmp(action,'setZPosSlider'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	GenSynthParaVec=get(hGenSynthList(1),'UserData');
	CortRadiusCm=GenSynthParaVec(1);
	vv=get(hGenSynthList(7),'Value');
	x=get(hGenSynthList(2),'Value');
	y=get(hGenSynthList(4),'Value');
	z=get(hGenSynthList(6),'Value');
	xyz=sqrt(sum([x y vv].^2));
	if xyz>CortRadiusCm | xyz==0;
		set(hGenSynthList(45),'Enable','off');
	else
		set(hGenSynthList(45),'Enable','on');
	end
	set(hGenSynthList(6),'Value',vv,'String',sprintf('%g',round(vv.*100)./100)); 
	GenSynthData('setDipPosMomMat')
	
	%===================================
  	%===================================
  	%===================================
  	%===================================

elseif strcmp(action,'setXDipMomSlider'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	vv=get(hGenSynthList(29),'Value');
	set(hGenSynthList(28),'Value',vv,'String',sprintf('%g',round(vv.*100)./100)); 
	GenSynthData('setDipPosMomMat')

elseif strcmp(action,'setYDipMomSlider'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	vv=get(hGenSynthList(31),'Value');
	set(hGenSynthList(30),'Value',vv,'String',sprintf('%g',round(vv.*100)./100)); 
	GenSynthData('setDipPosMomMat')
	
elseif strcmp(action,'setXDipMom') | strcmp(action,'setYDipMom') | strcmp(action,'setZDipMom'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
    if strcmp(action,'setXDipMom')
        vListNo=28;
        vvListNo=29;
    elseif strcmp(action,'setYDipMom')
        vListNo=30;
        vvListNo=31;
    elseif strcmp(action,'setZDipMom')
        vListNo=32;
        vvListNo=33;
    end
    v=get(hGenSynthList(vListNo),'Value');
	vStr=get(hGenSynthList(vListNo),'String');
    [v,vStr]=String2Value(vStr,v,-10,10,[],1);
	set(hGenSynthList(vListNo),'Value',v,'String',vStr);  
    set(hGenSynthList(vvListNo),'Value',v);

	GenSynthData('setDipPosMomMat')
	
elseif strcmp(action,'setXDipMomSlider') | strcmp(action,'setYDipMomSlider') | strcmp(action,'setZDipMomSlider'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
     if strcmp(action,'setXDipMomSlider')
        vListNo=28;
        vvListNo=29;
    elseif strcmp(action,'setYDipMomSlider')
        vListNo=30;
        vvListNo=31;
    elseif strcmp(action,'setZDipMomSlider')
        vListNo=32;
        vvListNo=33;
    end
	vv=get(hGenSynthList(vvListNo),'Value');
	set(hGenSynthList(vListNo),'Value',vv,'String',sprintf('%g',round(vv.*100)./100)); 
	GenSynthData('setDipPosMomMat')
	
	%===================================
  	%===================================
  	%===================================
  	%==================================


elseif strcmp(action,'setDipPosMomMat'),

  	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
   	PosVec(1)=get(hGenSynthList(2),'Value');  
	PosVec(2)=get(hGenSynthList(4),'Value');  
	PosVec(3)=get(hGenSynthList(6),'Value');  
	MomVec(1)=get(hGenSynthList(28),'Value'); 
	MomVec(2)=get(hGenSynthList(30),'Value');  
	MomVec(3)=get(hGenSynthList(32),'Value');  
	
	DipPosMomMat=get(hGenSynthList(36),'UserData');
	ActDipoleVal=get(hGenSynthList(11),'Value');
	ActDipole=ActDipoleVal-2;
	CartSpherString=get(hGenSynthList(38),'String');
	if strcmp(CartSpherString,'Cartesian')
		LPos=sqrt(sum(PosVec.^2));
		LMom=sqrt(sum(MomVec.^2));
		LPos12=sqrt(sum(PosVec(1:2).^2));
		LMom12=sqrt(sum(MomVec(1:2).^2));
		
		if LMom~=0
			if LPos==0;
				NormPosVec=[0 0 0];
			else
				NormPosVec=PosVec./LPos;
			end
			NormMomVec=MomVec./LMom;
			if LPos12==0	% z-axis
				NormPosVec12=[0 0];
			else
				NormPosVec12=PosVec(1:2)./LPos12;
			end
			if LMom12==0
				PhiMom=0;
			else
				NormMomVec12=MomVec(1:2)./LMom12;
				PhiMom=sin(acos(NormPosVec12*NormMomVec12'));
				if MomVec(2)==0
					PhiMom=0;
				else
					PhiMom=PhiMom.*MomVec(2)./abs(MomVec(2));
				end
				if PosVec(2)>0 | (PosVec(2)==0 & PosVec(1)>0)
					PhiMom=-1.*PhiMom;
				end
			end
			ThetaMom=NormMomVec(3).*cos(NormPosVec(3));
			RadMom=NormPosVec*NormMomVec';
			MomVec=[PhiMom ThetaMom RadMom];
			LMomTmp=sqrt(sum(MomVec.^2));
			MomVec=MomVec./LMomTmp.*LMom;
		end
	end
   	DipPosMomMat(ActDipole,1:3)=PosVec;
	DipPosMomMat(ActDipole,4:6)=MomVec;

   	set(hGenSynthList(36),'UserData',DipPosMomMat);

	%===================================
	%==============Noise================
	%===================================
elseif strcmp(action,'setNTrials'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
    
    NTrials=get(hGenSynthList(58),'Value')
	NTrialsStr=get(hGenSynthList(58),'String')
    [NTrials,NTrialsStr]=String2Value(NTrialsStr,NTrials,1,[],1,1);
	set(hGenSynthList(58),'Value',NTrials,'String',NTrialsStr);  
	
elseif strcmp(action,'setUnCorrNoise'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
    
    UnCorrNoise=get(hGenSynthList(46),'Value')
	UnCorrNoiseStr=get(hGenSynthList(46),'String')
    [UnCorrNoise,UnCorrNoiseStr]=String2Value(UnCorrNoiseStr,UnCorrNoise,0,10,[],1);
	set(hGenSynthList(46),'Value',UnCorrNoise,'String',UnCorrNoiseStr);  
	set(hGenSynthList(47),'Value',UnCorrNoise);
	
elseif strcmp(action,'setUnCorrNoiseSlider'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	vv=get(hGenSynthList(47),'Value');
	set(hGenSynthList(46),'Value',vv,'String',sprintf('%g',round(vv.*100)./100)); 

elseif strcmp(action,'setCorrNoise'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
    	
    CorrNoise=get(hGenSynthList(48),'Value')
	CorrNoiseStr=get(hGenSynthList(48),'String')
    [CorrNoise,CorrNoiseStr]=String2Value(CorrNoiseStr,CorrNoise,0,10,[],1);
	set(hGenSynthList(48),'Value',CorrNoise,'String',CorrNoiseStr);  
	set(hGenSynthList(49),'Value',CorrNoise);
	
elseif strcmp(action,'setCorrNoiseSlider'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	vv=get(hGenSynthList(49),'Value');
	set(hGenSynthList(48),'Value',vv,'String',sprintf('%g',round(vv.*100)./100)); 

	%===================================
  	%===================================
elseif strcmp(action,'CalcLeadField') | strcmp(action,'CalcEyesLeadField'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	hPlot2dList=get(hPlot2dMenuFig,'Userdata');
	GenSynthParaVec=get(hGenSynthList(1),'UserData');
	CortRadiusCm=GenSynthParaVec(1);
	CortRadiusM=CortRadiusCm./100;
	BasePath=get(hPlot2dList(18),'Userdata');
  	PathLFCoeff=[BasePath 'Plot3dInvCoeff'];
  	Tmp=get(hPlot2dList(16),'Userdata');
  	SensorNChan=Tmp(2);
   
	EEGMEGStatusString=get(hPlot2dList(110),'String');
	DipPosMomMat=get(hGenSynthList(36),'UserData');
	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	CartSpherString=get(hGenSynthList(38),'String');
	if strcmp(CartSpherString,'Cartesian')
		CoorFlag='xyz';
	else
		CoorFlag='sph';
	end
	if strcmp(action,'CalcLeadField')
  		LeadLoc=DipPosMomMat(:,1:3)./100;
	elseif strcmp(action,'CalcEyesLeadField')
		xTmp=3;
		yTmp=6.3-2;
		zTmp=-3.4;
		LeadLoc=[-xTmp yTmp zTmp;xTmp yTmp zTmp]./100;
		EyePhi=atan(xTmp/yTmp);
	end
  	[NDip,NonUse]=size(LeadLoc);
  	LeadLocTmp=ones(NDip+3,3).*0.01;
  	LeadLocTmp(1:NDip,:)=LeadLoc;
   
   if SensorNChan==0
		SensorNChan=129; %257;
     	set(hPlot2dList(3),'Userdata',SensorNChan);
     	set(hPlot2dList(16),'Userdata',[SensorNChan SensorNChan]);
		Plot2d('chDefECfg');	
	end
   SensorCfgFilePath=get(hPlot2dList(2),'Userdata');
   [SensorCfgFile,SensorCfgPath]=SepFilePath(SensorCfgFilePath);
   if strcmp(EEGMEGStatusString,'EEG')
  		EPosSpher=get(hPlot2dList(3),'Userdata');
   		[SensorMat] = change_sphere_cart(EPosSpher,0.092, 1);
    elseif strcmp(EEGMEGStatusString,'MEG')
   		SensorMat=get(hPlot2dList(111),'Userdata');	%hSensorPosNormMat
	end
% 	 %================================================== 
%    	if strcmp(computer,'MAC2')	
%       		FigPosVec=[0 0 0.6 1];	
%    	elseif strcmp(computer,'PCWIN') 
%       		FigPosVec=[0.005 0.05 .60 0.88];  
%       	elseif strcmp(computer,'SOL2')
%       		FigPosVec=[0.01 0.01 .601 0.935];  
%    	end;
% 	figure(	'Units','normal',...
% 	 		'Position',FigPosVec,...
% 			'Color',[1 1 1],...
% 			'Name','Synthetic Dipole Positions and Moments:',...
% 			'NumberTitle','off')
% 			
% 	 axes('Units','Normal','Position',[0 0 1 1])
% 	 [X,Y,Z] = sphere(20);
% 	 X=X.*CortRadiusM;
% 	 Y=Y.*CortRadiusM;
% 	 Z=Z.*CortRadiusM;
% 	
%    surf(X,Y,Z,zeros(size(Z)))
% 	 PlotECPositions(CortRadiusM,3,0,[0 0 0],1,EPosSpher,1,1,0,0,int2str([1:SensorNChan]))
% 	 axis(1.1.*CortRadiusM.*[-1 1 -1 1 -1 1])
% 	 axis('off')
% 	 pause
% 	 %================================================== 
% LeadLocTmp'
% pause
% SensorMat
% pause
  	 [LFCoeff,orientations,v]=compute_lfdmat(LeadLocTmp',SensorMat',EEGMEGStatusString,'xyz',[]);
     MaxMaxLFCoeff=max(max(LFCoeff))
	 if strcmp(action,'CalcLeadField') 
  	 	set(hGenSynthList(26),'Userdata',LFCoeff);
	elseif strcmp(action,'CalcEyesLeadField')
		set(hGenSynthList(61),'Userdata',LFCoeff);
	end
 	%===================================
  	%===================================
	
elseif strcmp(action,'CalcCorrNoiseLeadField'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	hPlot2dList=get(hPlot2dMenuFig,'Userdata');
	GenSynthParaVec=get(hGenSynthList(1),'UserData');
	CortRadiusCm=GenSynthParaVec(1);
	CortRadiusM=CortRadiusCm./100;
	NoiseRadiusCm=6;
	NoiseRadiusM=NoiseRadiusCm./100;
	
	BasePath=get(hPlot2dList(18),'Userdata');
  	PathLFCoeff=[BasePath 'Plot3dInvCoeff'];
  	Tmp=get(hPlot2dList(16),'Userdata');
  	SensorNChan=Tmp(2);
   
	EEGMEGStatusString=get(hPlot2dList(110),'String');
	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	CartSpherString=get(hGenSynthList(38),'String')
	if strcmp(CartSpherString,'Cartesian')
		CoorFlag='xyz';
	else
		CoorFlag='sph';
	end
	
	NSqrtNoiseLoc=6;
	NNoiseLoc=NSqrtNoiseLoc.^2;
	[XNoise,YNoise,ZNoise]=sphere(NSqrtNoiseLoc-1);
	XNoise=XNoise.*NoiseRadiusM;
	YNoise=YNoise.*NoiseRadiusM;
	ZNoise=ZNoise.*NoiseRadiusM;
	[NoiseLeadLoc]=change_nn_n3(XNoise,YNoise,ZNoise);
   	[NNoiseLeadLoc,NoUse]=size(NoiseLeadLoc);
	Index1=0;
	Index3=0;
	BadLocIndVec=0;
	while Index1<NNoiseLeadLoc
		Index1=Index1+1;
		Index2=Index1+1;
		Tmp=NoiseLeadLoc(Index1,:);
		while Index2<=NNoiseLeadLoc
			if sum(abs(Tmp-NoiseLeadLoc(Index2,:)))==0;
				NewBadVec=find(BadLocIndVec==Index2);
				if isempty(NewBadVec)
					Index3=Index3+1;
					BadLocIndVec(Index3)=Index2;
				end
			end	
			Index2=Index2+1;	
		end
	end
	Index2=0;
	for Index1=1:NNoiseLeadLoc
		if isempty(find(BadLocIndVec==Index1))
			Index2=Index2+1;
			NoiseLeadLocIndVec(Index2)=Index1;
		end
	end
	NoiseLeadLoc=NoiseLeadLoc(NoiseLeadLocIndVec,:);
	%LeftIndVec=find(NoiseLeadLoc(:,1)<0)
	%NoiseLeadLoc=NoiseLeadLoc(LeftIndVec,:)
	[NNoiseDip,NonUse]=size(NoiseLeadLoc);
  	NoiseLeadLocTmp=ones(NNoiseDip+3,3).*0.01;
  	NoiseLeadLocTmp(1:NNoiseDip,:)=NoiseLeadLoc;
	
   if SensorNChan==0
		SensorNChan=129;
     	set(hPlot2dList(3),'Userdata',SensorNChan);
     	set(hPlot2dList(16),'Userdata',[SensorNChan SensorNChan]);
		Plot2d('chDefECfg');	
	end
   SensorCfgFilePath=get(hPlot2dList(2),'Userdata');
   [SensorCfgFile,SensorCfgPath]=SepFilePath(SensorCfgFilePath);
   if strcmp(EEGMEGStatusString,'EEG')
  		EPosSpher=get(hPlot2dList(3),'Userdata');
   		[SensorMat] = change_sphere_cart(EPosSpher,0.092, 1);
    elseif strcmp(EEGMEGStatusString,'MEG')
   		SensorMat=get(hPlot2dList(111),'Userdata');	%hSensorPosNormMat
	end
	Message=char(['Calculate leadfield coefficients of ',int2str(NNoiseDip),' noise sources.']);
	Message=char(Message,[]);			
	Message=char(Message,['Radius: ',sprintf('%g',round(NoiseRadiusCm.*100)./100),' cm.']);
	hmsgbox=msgbox(Message,'Info:','help');
	hChildMsgbox=get(hmsgbox,'Children');
    hChild2Msgbox=get(hChildMsgbox(2),'Children');
	set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
	pause(.1);
	[NoiseLFCoeff, orientations, v] = compute_lfdmat(NoiseLeadLocTmp',SensorMat',EEGMEGStatusString,'xyz',[]);
    MaxMaxNoiseLFCoeff=max(max(NoiseLFCoeff))
  	set(hGenSynthList(52),'Userdata',NoiseLFCoeff);
	close(hmsgbox);

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

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	UseEOGStatus=get(hGenSynthList(68),'Value');
	
elseif strcmp(action,'setDipStrength'),

	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	ActDipoleVal=get(hGenSynthList(11),'Value');
	ActDipole=ActDipoleVal-2;
	NPoints=get(hGenSynthList(15),'Userdata');
	SampRate=get(hGenSynthList(17),'Userdata');
	PatternStyleVal=get(hGenSynthList(13),'Value');
	
	DipStrength1=get(hGenSynthList(22),'Userdata');
	DipStrength2=get(hGenSynthList(23),'Userdata');
    DipStrength3=get(hGenSynthList(24),'Userdata');
   
   if PatternStyleVal==1
      DipStrength1(ActDipole,:)=ones(1,NPoints);
      DipStrength2(ActDipole,:)=ones(1,NPoints);
      DipStrength3(ActDipole,:)=ones(1,NPoints);
	elseif PatternStyleVal==2 | PatternStyleVal==3
		FrequVec=get(hGenSynthList(19),'Userdata');Frequ=FrequVec(ActDipole);
		PhaseVec=get(hGenSynthList(21),'Userdata');Phase=PhaseVec(ActDipole);
		if PatternStyleVal==3; %sinus
			Phase=Phase+180;
		end
		Tmp=NPoints.*Frequ./SampRate;
		DipStrength1(ActDipole,:)=cos(linspace(pi.*Phase./180,2.*pi.*Tmp+pi.*Phase./180,NPoints));
		DipStrength2(ActDipole,:)=cos(linspace(pi.*Phase./180,2.*pi.*Tmp+pi.*Phase./180,NPoints));
		DipStrength3(ActDipole,:)=cos(linspace(pi.*Phase./180,2.*pi.*Tmp+pi.*Phase./180,NPoints));
	elseif PatternStyleVal==4	%interactive
		[Pattern,ch_Pattern]=DefinePattern([],1,2,[],[],3,NPoints,2,0,0,0);
		DipStrength1(ActDipole,:)=Pattern;
		DipStrength2(ActDipole,:)=Pattern;
     	DipStrength3(ActDipole,:)=Pattern;
  	elseif PatternStyleVal==5	%file
		[PatternMat] = ReadBem([],1,'Matrix','Ascii');
      	[NDim,NPointsTmp]=size(PatternMat);
      if NDim==NPoints & (NPointsTmp==3 | NPointsTmp==1)
         PatternMat=PatternMat';[NPointsTmp,NDim]=size(PatternMat);
      end
      if NPointsTmp~=NPoints
        Message=char('Sorry,');
        Message=char(Message,'');
		Message=char(Message,'this file has to be of ');
		Message=char(Message,'ascii matrix header format');
		Message=char(Message,['containing ' int2str(NPoints) ' rows(number of points)']);
        Message=char(Message,'and 1 or 3 columns !');
        Message=char(Message,'');
        Message=char(Message,'This file contains');
        Message=char(Message,[int2str(NPointsTmp),' points and ',int2str(NDim),' columns.']);
		hmsgbox=msgbox(Message,'Warning','warn');
        return;
      end
      if NDim==1
        DipStrength1(ActDipole,:)=PatternMat;
        DipStrength2(ActDipole,:)=PatternMat;
		DipStrength3(ActDipole,:)=PatternMat;
      else 
        DipStrength1(ActDipole,:)=PatternMat(1,:);
        DipStrength2(ActDipole,:)=PatternMat(2,:);
		DipStrength3(ActDipole,:)=PatternMat(3,:);
		end
   end
	set(hGenSynthList(22),'Userdata',DipStrength1);
	set(hGenSynthList(23),'Userdata',DipStrength2);
    set(hGenSynthList(24),'Userdata',DipStrength3);
      
elseif strcmp(action,'Apply'),
   
   	hGenSynthList=get(hGenSynthDataMenuFig,'UserData');
	
	hPlot2dList=get(hPlot2dMenuFig,'Userdata');
	ActFileNo=get(hPlot2dList(1),'Userdata');
	DataFileFormat=get(hGenSynthList(9),'Value');
	SampRate=get(hGenSynthList(17),'Userdata');
	NPlot2dNListHdr=get(hPlot2dList(51),'Userdata');
	FileNoVec=get(hPlot2dList(56),'Userdata');
	if isempty(FileNoVec)
		FileNoVec=ActFileNo;
	end
	if ~any(FileNoVec==ActFileNo)
		FileNoVec(length(FileNoVec)+1)=ActFileNo;
		FileNoVec=sort(FileNoVec);
	end
	set(hPlot2dList(56),'Userdata',FileNoVec);
	RefChanInd=get(hPlot2dList(NPlot2dNListHdr+(FileNoVec(ActFileNo)-1).*50+8),'Userdata');
	
	hTopMenu=get(hPlot2dList(65),'Userdata');
   	hSynthMenu=get(hTopMenu(3),'children');
   	set(hSynthMenu(1),'Userdata',1); 
   
   	GenSynthData('CalcLeadField')

	ActDipoleVal=get(hGenSynthList(11),'Value');
	ActDipole=ActDipoleVal-2;
	NPlot2dListHdr=get(hPlot2dList(51),'Userdata');
	BasePath=get(hPlot2dList(18),'Userdata');
	
	LeadLoc=get(hGenSynthList(25),'Userdata');
	LFCoeff=get(hGenSynthList(26),'Userdata');
	
	DipStrength1=get(hGenSynthList(22),'Userdata');
	DipStrength2=get(hGenSynthList(23),'Userdata');
	DipStrength3=get(hGenSynthList(24),'Userdata');
	
  	DipPosMomMat=get(hGenSynthList(36),'UserData');

	GenSynthParaVec=get(hGenSynthList(1),'UserData');
	NDipoles=GenSynthParaVec(2);
	NPoints=get(hGenSynthList(15),'Userdata');

	
	AddDipolesVal=get(hGenSynthList(37),'Value');
	EEGMEGStatusString=get(hPlot2dList(110),'String');
    if strcmp(EEGMEGStatusString,'EEG')
        EEGMEGStatus=1;
    elseif strcmp(EEGMEGStatusString,'MEG')
        EEGMEGStatus=2;
    end
	HEOGCorStatus=get(hGenSynthList(62),'Value');
	VEOGCorStatus=get(hGenSynthList(63),'Value');
	HEOGMovStatus=get(hGenSynthList(64),'Value');
	VEOGMovStatus=get(hGenSynthList(65),'Value');
	BEOGMovStatus=get(hGenSynthList(69),'Value');
	UseLEOGStatus=get(hGenSynthList(66),'Value');
	UseREOGStatus=get(hGenSynthList(67),'Value');
	UseEOGStatus=get(hGenSynthList(68),'Value');
	

	if AddDipolesVal==1
		Vec1=[1:3:NDipoles*3-2];
		Vec2=[2:3:NDipoles*3-1];
		Vec3=[3:3:NDipoles*3];
		
		DipMom1=DipPosMomMat(:,4);
		DipMom2=DipPosMomMat(:,5);
		DipMom3=DipPosMomMat(:,6);
		for i=1:NDipoles
			DipStrength1(i,:)=DipStrength1(i,:)*DipMom1(i);
			DipStrength2(i,:)=DipStrength2(i,:)*DipMom2(i);
			DipStrength3(i,:)=DipStrength3(i,:)*DipMom3(i);
		end
		
    	SignalData=(DipStrength1' * LFCoeff(:,Vec1)' + ...
					DipStrength2' * LFCoeff(:,Vec2)' + ...
					DipStrength3' * LFCoeff(:,Vec3)')';	
		
		if NDipoles==1
			SyntheticDataString=['Synthetic dipole ' int2str(ActDipole)];
		else
			SyntheticDataString='Sum of synthetic dipoles 1' ;
			for i=2:NDipoles-1
				SyntheticDataString=[SyntheticDataString ', ' int2str(i) ];
			end
			SyntheticDataString=[SyntheticDataString ' & ' int2str(NDipoles)];
		end
	else
		Vec1=(ActDipole-1).*3+1;
		Vec2=(ActDipole-1).*3+2;
		Vec3=ActDipole.*3;
		DipMom1=DipPosMomMat(ActDipole,4);
		DipMom2=DipPosMomMat(ActDipole,5);
		DipMom3=DipPosMomMat(ActDipole,6);
		
		SignalData=(DipMom1.*DipStrength1(ActDipole,:)' * LFCoeff(:,Vec1)' + ...
					DipMom2.*DipStrength2(ActDipole,:)' * LFCoeff(:,Vec2)' + ...
					DipMom3.*DipStrength3(ActDipole,:)' * LFCoeff(:,Vec3)')';	
		SyntheticDataString=['Synthetic dipole ' int2str(ActDipole)];
	end
	
	[NChan,NPoints]=size(SignalData);
	if strcmp(EEGMEGStatusString,'EEG')
		if length(RefChanInd)>1
			RefVec=sum(SignalData(RefChanInd,:))./length(RefChanInd);
		else
			if RefChanInd==0	%Average reference
				RefVec=sum(SignalData)./NChan;
			else
				RefVec=SignalData(RefChanInd,:);
			end
		end
		for ChanInd=1:NChan
			SignalData(ChanInd,:)=SignalData(ChanInd,:)-RefVec;
		end
	end
	%=====Noise======
	UnCorrNoiseVal=get(hGenSynthList(46),'Value');
	CorrNoiseVal=get(hGenSynthList(48),'Value');
	%MeanNoise=get(hGenSynthList(56),'Value');
    RandVal=get(hGenSynthList(60),'Value');
	NTrials=get(hGenSynthList(58),'Value');
	StdMat=zeros(NChan,NPoints);
	MedMedRawVec=zeros(NTrials,1);
	MedMedAvgVec=zeros(NTrials,1);
	AllDataMat=zeros(NTrials,NChan,NPoints);

	if UnCorrNoiseVal>0 | CorrNoiseVal>0 | UseEOGStatus
		SignalDataNoNoise=SignalData;
		SignalTrialData=zeros(NChan,NPoints);
		if UnCorrNoiseVal>0
			UnCorrNoiseData=zeros(NChan,NPoints);
		end
		if CorrNoiseVal>0
			CorrNoiseData=zeros(NChan,NPoints);
			NoiseLFCoeff=get(hGenSynthList(52),'Userdata');
			%NoiseLFCoeff=[]
			if isempty(NoiseLFCoeff);
				GenSynthData('CalcCorrNoiseLeadField');
				NoiseLFCoeff=get(hGenSynthList(52),'Userdata');
			end
			[NChan,NNoiseDip3Tmp]=size(NoiseLFCoeff);
			NNoiseDip=NNoiseDip3Tmp./3-3;
			Vec1=[1:3:NNoiseDip*3-2];
			Vec2=[2:3:NNoiseDip*3-1];
			Vec3=[3:3:NNoiseDip*3];
		end
		if NTrials>1
			Message=char(['Calculate 1   of total ',int2str(NTrials),' synthetic trials:']);
			Message=char(Message,[]);
			Message=char(Message,[]);
			hmsgbox=msgbox(Message,'Info:','help');
			hChildMsgbox=get(hmsgbox,'Children');
            hChild2Msgbox=get(hChildMsgbox(2),'Children');
			%set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
		end
		
		for TrialInd=1:NTrials
 			SignalTrialData=SignalData;
% 			SignalTrialData=zeros(size(SignalTrialData));
% 			SignalTrialData(:,1:NPoints-TrialInd+1)=SignalData(:,TrialInd:NPoints)
% 			if TrialInd>1
% 				SignalTrialData(:,NPoints-TrialInd+1:NPoints)=SignalData(:,1:TrialInd);
% 			end
			if NTrials>1
				Message=char(['Calculate ',int2str(TrialInd),' of total ',int2str(NTrials),' synthetic trials: ']);
				if strcmp(EEGMEGStatusString,'EEG')
					Message=char(Message,[]);
					if length(RefChanInd)>1
						TmpMsg=['Linked reference channels: ',int2str(RefChanInd(1)),'  ']
						for i=2:length(RefChanInd)
							TmpMsg=[TmpMsg,int2str(RefChanInd(i)),' ']
						end
					else
						if RefChanInd==0
							TmpMsg='Average reference';
						else
							TmpMsg=['Reference channel: ',int2str(RefChanInd)];
						end
					end
					Message=char(Message,TmpMsg);
				end
                if strcmp(computer,'MAC2')
				    set(hChildMsgbox(2),'String',Message);
			    else
				    set(hChild2Msgbox,'String',Message);
			    end
				pause(.01);
			end
			if UnCorrNoiseVal>0
                if RandVal==1
				    UnCorrNoiseTrialData=UnCorrNoiseVal.*randn(NChan,NPoints);
                elseif RandVal==2
                    UnCorrNoiseTrialData=UnCorrNoiseVal.*rand(NChan,NPoints);
                end
				if strcmp(EEGMEGStatusString,'EEG')
					if length(RefChanInd)>1
						RefVec=sum(UnCorrNoiseTrialData(RefChanInd,:))./length(RefChanInd);
					else
						if RefChanInd==0	%Average reference
							RefVec=sum(UnCorrNoiseTrialData)./NChan;
						else
							RefVec=UnCorrNoiseTrialData(RefChanInd,:);
						end
					end
					for ChanInd=1:NChan
						UnCorrNoiseTrialData(ChanInd,:)=UnCorrNoiseTrialData(ChanInd,:)-RefVec;
					end
				end
% 				if MeanNoise
% 					if sqrt(sum(SignalData.^2))==0
% 						NoiseFac=0;
% 					else	
% 						NoiseFac=UnCorrNoiseVal./mean(sqrt(sum(UnCorrNoiseTrialData.^2))./sqrt(sum(SignalData.^2)));
% 					end
% 					UnCorrNoiseTrialData=NoiseFac.*UnCorrNoiseTrialData;
% 				else
% 					if sqrt(sum(SignalData.^2))==0
% 						NoiseFac=0;
% 					else	
% 						NoiseFacVec=UnCorrNoiseVal./sqrt(sum(CorrNoiseTrialData.^2)./sqrt(sum(SignalData.^2)));
% 					end
% 					for i=1:NPoints
% 						UnCorrNoiseTrialData(:,i)=NoiseFacVec(i).*UnCorrNoiseTrialData(:,i);
% 					end
% 				end
				SignalTrialData=SignalData+UnCorrNoiseTrialData;
			end	%if UnCorrNoiseVal>0
			%if TrialInd==1; CorrNoiseVal=CorrNoiseVal.*10; end
			if CorrNoiseVal>0
                if RandVal==1
				    NoiseDipStrength1=randn(NNoiseDip,NPoints);
				    NoiseDipStrength2=randn(NNoiseDip,NPoints);
				    NoiseDipStrength3=randn(NNoiseDip,NPoints);
                elseif RandVal==2
                    NoiseDipStrength1=rand(NNoiseDip,NPoints);
				    NoiseDipStrength2=rand(NNoiseDip,NPoints);
				    NoiseDipStrength3=rand(NNoiseDip,NPoints);
                end
				
				CorrNoiseTrialData=CorrNoiseVal.*	(NoiseDipStrength1' * NoiseLFCoeff(:,Vec1)' + ...
									 				NoiseDipStrength2' * NoiseLFCoeff(:,Vec2)' + ...
									 				NoiseDipStrength3' * NoiseLFCoeff(:,Vec3)')';
%                 MaxMaxCorrNoiseTrialData=max(max(CorrNoiseTrialData))
%                 MaxMaxSignalData=max(max(SignalData))
%                 MaxMaxSignalTrialData=max(max(SignalTrialData))
				if strcmp(EEGMEGStatusString,'EEG')
					if length(RefChanInd)>1
						RefVec=sum(CorrNoiseTrialData(RefChanInd,:))./length(RefChanInd);
					else
						if RefChanInd==0	%Average reference
							RefVec=sum(CorrNoiseTrialData)./NChan;
						else
							RefVec=CorrNoiseTrialData(RefChanInd,:);
						end
					end
					for ChanInd=1:NChan
						CorrNoiseTrialData(ChanInd,:)=CorrNoiseTrialData(ChanInd,:)-RefVec;
					end
				end		
% 				if MeanNoise
% 					if sqrt(sum(SignalData.^2))==0
% 						NoiseFac=0;
% 					else	
% 						NoiseFac=CorrNoiseVal./mean(sqrt(sum(CorrNoiseTrialData.^2))./sqrt(sum(SignalData.^2)));
% 					end
% 					CorrNoiseTrialData=NoiseFac.*CorrNoiseTrialData;
% 				else
% 					if sqrt(sum(SignalData.^2))==0
% 						NoiseFac=0;
% 					else	
% 						NoiseFacVec=CorrNoiseVal./sqrt(sum(CorrNoiseTrialData.^2)./sqrt(sum(SignalData.^2)));
% 					end
% 					for i=1:NPoints
% 						CorrNoiseTrialData(:,i)=NoiseFacVec(i).*CorrNoiseTrialData(:,i);
% 					end
% 				end	
				SignalTrialData=SignalTrialData+CorrNoiseTrialData;
			end	%if CorrNoiseVal>0
			%=================================================================================================
			%==========Add Eye Movements======================================================================
			%=================================================================================================
			CorrEyeStatus=1;
			if UseEOGStatus
				if TrialInd==1
					SaveReadStatus=3		%1=Save; 2=Read; 3=Neither
					if SaveReadStatus~=3	
						HorVertFileName=[int2str(NChan) '_' int2str(NPoints) '_'];
						if ~BEOGMovStatus
							if HEOGMovStatus & ~VEOGMovStatus
								HorVertFileName=[HorVertFileName 'HEOG'];
							elseif ~HEOGMovStatus & VEOGMovStatus
								HorVertFileName=[HorVertFileName 'VEOG'];
							elseif HEOGMovStatus & VEOGMovStatus
								HorVertFileName=[HorVertFileName 'HVEOG'];
							end
						else
							if HEOGMovStatus & ~VEOGMovStatus
								HorVertFileName=[HorVertFileName 'BHEOG'];
							elseif ~HEOGMovStatus & VEOGMovStatus
								HorVertFileName=[HorVertFileName 'BVEOG'];
							elseif HEOGMovStatus & VEOGMovStatus
								HorVertFileName=[HorVertFileName 'BHVEOG'];
							end
						end
					end
					if BEOGMovStatus
						BEOGTrialRatio=10; % ~ 10% of all trials are blink contaminated
						Message=char(['Approximately ',int2str(BEOGTrialRatio),' % of all synthetic']);
						Message=char(Message,'trials are contaminated with blinks');
						hBlinkMsgbox=msgbox(Message,'Info:','help');
						if NTrials>100./BEOGTrialRatio
							BlinkTrialVec=(100./BEOGTrialRatio).*randperm(floor(NTrials./(100./BEOGTrialRatio)))
						else
							Tmp=randperm(NTrials);	% at least one trial is blink contaminated
							BlinkTrialVec=Tmp(1);
						end
					end
					if HEOGMovStatus | VEOGMovStatus
						EyesLFCoeff=get(hGenSynthList(61),'Userdata');
						if isempty(EyesLFCoeff);
							GenSynthData('CalcEyesLeadField')
							EyesLFCoeff=get(hGenSynthList(61),'Userdata');
						end
						NEyeDipoles=2;
						EyePhi=atan(3/7);
						EyeTheta=atan(0/7);
						RadThetaPhiMat=zeros(5,NPoints);
						RadThetaPhiTrialMat=zeros(5,NPoints,NTrials);
 						RadVec=ones(1,NPoints); 
						SinEyePhiVec=sin(EyePhi).*RadVec;
						SinEyeThetaVec=sin(EyeTheta).*RadVec;
						LEyeDipMom=25;
						REyeDipMom=25;
					end
				end
			
				if SaveReadStatus~=2	%Save or Neither
					if CorrEyeStatus
						RandPermVec=rand(1).*norm_1(DipStrength1(1,:),2);
					else
						RandPermVec=(randperm(NPoints)-(NPoints./2+1))./(NPoints./2);	%[-1:1]
					end
					if VEOGMovStatus
						MaxThetaAngle=30;%deg
						ThetaVec=sin(RandPermVec.*MaxThetaAngle.*pi./180)-SinEyeThetaVec; %Theta
					elseif HEOGMovStatus
						ThetaVec=-SinEyeThetaVec;	
					end
					if HEOGMovStatus
						MaxPhiAngle=30;%deg
						LPhiVec=sin(RandPermVec.*MaxPhiAngle.*pi./180)-SinEyePhiVec; %LPhi
						RPhiVec=sin(RandPermVec.*MaxPhiAngle.*pi./180)+SinEyePhiVec; %RPhi
					elseif VEOGMovStatus
						LPhiVec=-SinEyePhiVec; 	%LPhi
						RPhiVec=SinEyePhiVec; 	%RPhi
					end
					if BEOGMovStatus
						MinBlinkPoints=30;
						BlinkPointRandPermVec=randperm(NPoints);
						TmpVec=[-MinBlinkPoints:NPoints-MinBlinkPoints];
						BlinkPointVec=TmpVec(BlinkPointRandPermVec);
					end
					if VEOGMovStatus | HEOGMovStatus
						RadThetaPhiMat(1,:)=LPhiVec;
						RadThetaPhiMat(2,:)=RPhiVec;
						RadThetaPhiMat(3,:)=ThetaVec;
						RadThetaPhiMat(4,:)=RadVec;
					end
					if BEOGMovStatus
						RadThetaPhiMat(5,1:length(BlinkPointVec))=BlinkPointVec;
					end
					if SaveReadStatus==1	%Save
						RadThetaPhiTrialMat(:,:,TrialInd)=RadThetaPhiMat;
					end
				else	%Read
					if TrialInd==1
						load HorVertFileName
					end
					RadThetaPhiMat=RadThetaPhiTrialMat(:,:,TrialInd);
				end
				if SaveReadStatus==1 & TrialInd==NTrials %Save
					save HorVertFileName RadThetaPhiMat
				end
			
				if HEOGMovStatus | VEOGMovStatus
					EyesDipStrength1=zeros(NEyeDipoles,NPoints);
					EyesDipStrength2=zeros(NEyeDipoles,NPoints);
					EyesDipStrength3=zeros(NEyeDipoles,NPoints);
	
					if UseLEOGStatus
						LNormEyeMove=sqrt(sum(RadThetaPhiMat([1 3 4],:).^2));
						EyesDipStrength1(1,:)=LEyeDipMom.*(RadThetaPhiMat(1,:)./LNormEyeMove);	%LPhi
						EyesDipStrength2(1,:)=LEyeDipMom.*(RadThetaPhiMat(3,:)./LNormEyeMove);	%Theta
%     					EyesDipStrength3(1,:)=LEyeDipMom.*(RadThetaPhiMat(4,:)./LNormEyeMove);	%Rad
					end
					if UseREOGStatus
						RNormEyeMove=sqrt(sum(RadThetaPhiMat([2 3 4],:).^2));
						EyesDipStrength1(2,:)=REyeDipMom.*(RadThetaPhiMat(2,:)./RNormEyeMove);	%RPhi
						EyesDipStrength2(2,:)=REyeDipMom.*(RadThetaPhiMat(3,:)./RNormEyeMove);	%Theta
%    					EyesDipStrength3(2,:)=REyeDipMom.*(RadThetaPhiMat(4,:)./RNormEyeMove);	%Rad
					end	
				
					EyeVec1=[1:3:NEyeDipoles*3-2];
					EyeVec2=[2:3:NEyeDipoles*3-1];
					EyeVec3=[3:3:NEyeDipoles*3];				
				
					EyeMoveData=(	EyesDipStrength1' * EyesLFCoeff(:,EyeVec1)' + ...
									EyesDipStrength2' * EyesLFCoeff(:,EyeVec2)' + ...
									EyesDipStrength3' * EyesLFCoeff(:,EyeVec3)')';	
									
					MeanEyeMoveData=mean(EyeMoveData');
					for ChanInd=1:NChan
						EyeMoveData(ChanInd,:)=EyeMoveData(ChanInd,:)-MeanEyeMoveData(ChanInd).*ones(1,NPoints);
					end					
				else
					EyeMoveData=zeros(NChan,NPoints);
				end
								
				if BEOGMovStatus & any(BlinkTrialVec==TrialInd)		
					BlinkData=get(hGenSynthList(69),'Userdata');
					if isempty(BlinkData)
						BlinkFilePath=which('Blink.129.100');
						if strcmp(BlinkFilePath,'..')
							[BlinkFile,BlinkPath]=uigetfile(['*Blink.129.100'],'Search for "Blink.129.100"');
							if ~strcmp(BlinkFilePath,'Blink.129.100');
								UseBEOGStatus=0; 
								set(hGenSynthList(69),'Value',UseBEOGStatus);
								return;
							end
						end
						BlinkData=ReadData(BlinkFilePath,1);
						set(hGenSynthList(69),'Userdata',BlinkData);
					end
					BlinkStartPoint=RadThetaPhiMat(5,TrialInd);
					BlinkDataStartPoint=max([1,-1.*(BlinkStartPoint-2)]);
					BlinkDataEndPoint=min([100,NPoints-BlinkStartPoint+1]);
					NBlinkDataPoints=BlinkDataEndPoint-BlinkDataStartPoint+1;
					EyeMoveData(:,max([1,BlinkStartPoint]):min([NPoints,BlinkStartPoint+100-1]))=...
					EyeMoveData(:,max([1,BlinkStartPoint]):min([NPoints,BlinkStartPoint+100-1]))+...
					BlinkData(:,BlinkDataStartPoint:BlinkDataEndPoint);
				end
								
				if strcmp(EEGMEGStatusString,'EEG')
					if length(RefChanInd)>1
						RefVec=sum(EyeMoveData(RefChanInd,:))./length(RefChanInd);
					else
						if RefChanInd==0	%Average reference
							RefVec=sum(EyeMoveData)./NChan;
						else
							RefVec=EyeMoveData(RefChanInd,:);
						end
					end
					for ChanInd=1:NChan
						EyeMoveData(ChanInd,:)=EyeMoveData(ChanInd,:)-RefVec;
					end
				end		
				NoEyeMoveData=SignalTrialData;
				SignalTrialData=SignalTrialData+EyeMoveData;
				
				NoCorHEOG=SignalTrialData(128,:)-SignalTrialData(125,:);
				NoCorVLEOG=SignalTrialData(26,:)-SignalTrialData(127,:);
				NoCorVREOG=SignalTrialData(8,:)-SignalTrialData(126,:);
				if TrialInd==1;
					if HEOGCorStatus | VEOGCorStatus
						FigName='EOG and Correction';
					else
						FigName='EOG';
					end
					hEOGFig=figure('Units','normal','Position',[.5 .66 .5 .33],'Name',FigName,'NumberTitle','off');
					axes('Units','Normal','Position',[0 0 1 1]); axis('off');
					text('Units','normal','FontSize',[12],'Position',[0.2 .95],'Color',[1 0 0],'String','Vertical Eye Movement');
					text('Units','normal','FontSize',[12],'Position',[0.55 .95],'Color',[0 0 1],'String','Horizontal Eye Movement');
					axes('Units','Normal','Position',[0.15 0.1 .8 .8]);
				else
					figure(hEOGFig);
				end			
				
				%====Calculate EOG 
				if HEOGCorStatus | VEOGCorStatus	
					if HEOGCorStatus & VEOGCorStatus
						StartEyeCorIndex=1; EndEyeCorIndex=2;
					elseif HEOGCorStatus & ~VEOGCorStatus
						StartEyeCorIndex=1; EndEyeCorIndex=1;
					elseif ~HEOGCorStatus & VEOGCorStatus
						StartEyeCorIndex=2; EndEyeCorIndex=2;
					end
					for EyeCorIndex=StartEyeCorIndex:EndEyeCorIndex
						HEOG=SignalTrialData(128,:)-SignalTrialData(125,:);
						VLEOG=SignalTrialData(26,:)-SignalTrialData(127,:)
						VREOG=SignalTrialData(8,:)-SignalTrialData(126,:);
						if EyeCorIndex==1
							EOG=HEOG;
						elseif EyeCorIndex==2
							EOG=VLEOG;
						end
						AvgEOG=sum(EOG)./NPoints;
						SubEOG=EOG-ones(1,NPoints).*AvgEOG;
					
						RawEEG=SignalTrialData;
						AvgEEGVec=sum(SignalTrialData')'./NPoints;
						SubEEG=zeros(size(RawEEG));
						AvgEEG=zeros(NChan,NPoints);
						for i=1:NPoints
							AvgEEG(:,i)=AvgEEGVec;
						end
						SubEEG=RawEEG-AvgEEG;
					
						[SortSubEOGVal,SortSubEOGInd]=sort(SubEOG);
						[SortSortSubEOGIndVal,SortSortSubEOGIndInd]=sort(SortSubEOGInd);
						for i=1:NChan
							SortSubEEG(i,:)=SubEEG(i,SortSubEOGInd);
						end
						%PolyFit
						PolyfitDeg=1;
						PolyAvgMat=SignalTrialData;
						PolyCoeffMat=zeros(NChan,PolyfitDeg+1);
						x=SortSubEOGVal;
						xi=x;
						for ChanInd=1:NChan
							p=polyfit(x,SortSubEEG(ChanInd,:),PolyfitDeg);
							PolyCoeffMat(ChanInd,:)=p;
							PolyAvgMat(ChanInd,:)=polyval(p,xi);
 							PolyAvgMat(ChanInd,:)=PolyAvgMat(ChanInd,SortSortSubEOGIndInd);
						end
						SignalTrialData=RawEEG-PolyAvgMat;
						
					end	%for EyeCorIndex=StartEyeCorIndex:EndEyeCorIndex
					CorHEOG=SignalTrialData(128,:)-SignalTrialData(125,:);
					CorVLEOG=SignalTrialData(26,:)-SignalTrialData(127,:)
					CorVREOG=SignalTrialData(8,:)-SignalTrialData(126,:);
					plot(NoCorHEOG,'b')
 					hold on
 					plot(CorHEOG,'b--')
					plot(NoCorVLEOG,'r')		
 	   				plot(CorVLEOG,'r--')
  					xlabel('Time []'); 
					ylabel('Potential [µV]');
					hold off;
					%========================================================================
				else %if HEOGCorStatus | VEOGCorStatus	
					plot(NoCorHEOG,'b'); 
					hold on; 
					plot(NoCorVLEOG,'r'); 
					xlabel('Time []'); 
					ylabel('Potential [µV]');
					hold off;
				end %if HEOGCorStatus | VEOGCorStatus	
			end %if UseEOGStatus
			AllDataMat(TrialInd,:,:)=SignalTrialData;
			%=============================
		end	%for TrialInd
		
% 		S2N=sqrt(sum((SignalData-SignalDataNoNoise).^2))./sqrt(sum(SignalDataNoNoise.^2));
% 		figure
% 		plot(S2N)
% 		mean(S2N)
% 		pause
	else	%if UnCorrNoiseVal>0 | CorrNoiseVal>0 | UseEOGStatus
		SignalTrialData=SignalData;
		for TrialInd=1:NTrials
			AllDataMat(TrialInd,:,:)=SignalData;
		end
	end		%if UnCorrNoiseVal>0 | CorrNoiseVal>0 | UseEOGStatus
    if strcmp(EEGMEGStatusString,'MEG')
		AllDataMat=AllDataMat./10.^4;
	end
    BasePath=pwd;
    if ~strcmp(BasePath(end),filesep)
        BasePath=[BasePath,filesep];
    end
	if DataFileFormat==3	%Egis session
		AllDataMat=AllDataMat.*100;
		SaveFilePath=[BasePath,'SynthEgis.E1'];
		WriteMat2EGIS(AllDataMat,SaveFilePath);
	elseif DataFileFormat==4	%AvgApprox (.app)
		SaveFilePath=[BasePath,'SynthApprox.app'];
 		ScaleBins=max([1,floor(32767./max(max(max(abs(AllDataMat)))))]);
		WriteMat2App(AllDataMat,SaveFilePath,[],ScaleBins,SampRate,1,EEGMEGStatus,0);
	elseif DataFileFormat==5	%Besa (.avr)
		SaveFilePath=[BasePath,'SynthApprox.avr'];
 		SaveFid=fopen(SaveFilePath,'w');
		if SaveFid==-1; 
			fprintf(1,'Sorry, can not open file\n\n')
			fprintf(1,SaveFilePath)
			fprintf(1,'\n\n')
			fprintf(1,'for writing.\n\n')
		else
			DI=1000./SampRate;
			TSB=0;		%Time-Speed-Begin
			fprintf(1,'Write %g trials containing %g sensors and %g points to file:\n\n',NTrials,NChan,NPoints);
			Message=char(['Write ' int2str(NTrials) ' trials containing ' int2str(NChan) ' channels and ' int2str(NPoints) ' points to file:']);
			Message=char(Message,[]);
			Message=char(Message,SaveFilePath);
			hmsgbox=msgbox(Message,'Info:','help');
			pause(.001);
			fprintf(SaveFid, 'Npts= %d  TSB= %f  DI= %f  SB= 1.000  SC= 1.0\n',NPoints,TSB,DI);
			for TrialInd=1:NTrials
				fprintf('Trial %g of %g ...\n',TrialInd,NTrials)
				for ChanInd=1:NChan
					fprintf(SaveFid,'%g ',AllDataMat(TrialInd,ChanInd,:));
					fprintf(SaveFid,'\n');
				end
			end
			fclose(SaveFid);
		end
	end
	MedMedRawVec(TrialInd)=median(median(abs(SignalTrialData)));
	MedMedAvgVec(TrialInd)=sum(MedMedRawVec);
	if NTrials>1
		SignalDataTmp=sum(AllDataMat)./NTrials;
		SignalData(:,:)=SignalDataTmp(1,:,:);
		StdMatTmp=std(AllDataMat);
		StdMat(:,:)=StdMatTmp(1,:,:);
	else
		SignalData=SignalTrialData;
		StdMat=zeros(NChan,NPoints);
	end
	if DataFileFormat==2
		save AllDataMat AllDataMat
	end
	%===================

	FileNoVec=get(hPlot2dList(56),'Userdata');	
	if isempty(FileNoVec)
		FileNoVec=ActFileNo;
	end
	if ~any(FileNoVec==ActFileNo)
		FileNoVec(length(FileNoVec)+1)=ActFileNo;
		FileNoVec=sort(FileNoVec);
	end
	set(hPlot2dList(56),'Userdata',FileNoVec);
	Plot2d('chSyntheticData')
	set(hPlot2dList(16),'Userdata',[NChan,NChan]);
	set(hPlot2dList(NPlot2dListHdr+(ActFileNo-1).*50+1),'Userdata',SignalData);
	set(hPlot2dList(NPlot2dListHdr+(ActFileNo-1).*50+24),'Userdata',SignalData);
	set(hPlot2dList(NPlot2dListHdr+(ActFileNo-1).*50+2),'Userdata',NChan);
	set(hPlot2dList(NPlot2dListHdr+(ActFileNo-1).*50+3),'Userdata',NPoints);
	set(hPlot2dList(NPlot2dListHdr+(ActFileNo-1).*50+4),'Userdata',SyntheticDataString);
	set(hPlot2dList(NPlot2dListHdr+(ActFileNo-1).*50+5),'Userdata',1);
	set(hPlot2dList(NPlot2dListHdr+(ActFileNo-1).*50+6),'Userdata',StdMat);
	set(hPlot2dList(NPlot2dListHdr+(ActFileNo-1).*50+7),'Userdata',SampRate);
	SampRateString = sprintf('%g',SampRate);
	set(hPlot2dList(60),'Userdata',SampRate,'String',SampRateString);
	NPointsPlot2dOld=get(hPlot2dList(50),'Userdata');
	NPointsString = sprintf('%g',NPoints);
	set(hPlot2dList(50),'Userdata',NPoints,'String',NPointsString);
	set(hPlot2dList(NPlot2dListHdr+(ActFileNo-1).*50+9),'Userdata',MedMedRawVec);
	set(hPlot2dList(NPlot2dListHdr+(ActFileNo-1).*50+10),'Userdata',MedMedAvgVec);
	set(hPlot2dList(NPlot2dListHdr+(ActFileNo-1).*50+4),'Userdata',[BasePath SyntheticDataString]);	%FilePath
 	%=== Visible Status of Actual Data Set ===
 	hActAllVisible=hPlot2dList(109);
 	VisibleStatusVec=get(hActAllVisible,'Userdata');
   	ActVisibleStatus=VisibleStatusVec(ActFileNo);
   	set(hActAllVisible,'Value',ActVisibleStatus);
	
	Plot2d('SetFirstVal'); 
	Plot2d('CalcFirst');
	if NPointsPlot2dOld~=NPoints
		Plot2d('Calc2dTimeAxes');
		MinBase=get(hPlot2dList(58),'Value');
		MaxBase=get(hPlot2dList(59),'Value');
		if MinBase>NPoints
			set(hPlot2dList(58),'Value',NPoints,'String',int2str(NPoints));
			Plot2d('setMinBaseNoCompNoCall');
		end
		if MaxBase>NPoints
			set(hPlot2dList(59),'Value',NPoints,'String',int2str(NPoints));
			Plot2d('setMinBaseNoCompNoCall');
		end
		Plot2d('CalcBase');
	end
	Plot2d('setColor');
	Plot2d('setLineStyle');
	%--------- set menu index -----------
	Plot2d('SetZeroLineColorIndex');
	Plot2d('SetTriggerLineColorIndex');
	Plot2d('SetCursorLineColorIndex');
	Plot2d('SetZeroLineStyleIndex');
	Plot2d('SetTriggerLineStyleIndex');
	Plot2d('SetCursorLineStyleIndex');
	Plot2d('SetDefXTickVal');	
	Plot2d('setActAllVisible')
	Plot2d('SetActFileNoLabelString');
	%------------------------------------
	hFileInfoTextVec=get(hPlot2dList(17),'Userdata');
	hFileInfoText=hFileInfoTextVec(ActFileNo);
	VisibleStatus=get(hFileInfoText,'Visible');
	if strcmp(VisibleStatus,'on'); Plot2d('DispFileNamesVisible'); end
	%--------- set enable value ----------
	if length(FileNoVec)==1
		set(hPlot2dList(49),'value',1);	
	elseif length(FileNoVec)==2
		set(hPlot2dList(49),'value',4);
	elseif length(FileNoVec)==4
		set(hPlot2dList(49),'value',5);
	else
		set(hPlot2dList(49),'value',7);	
	end;		
	Plot2d('EnableOnOff');	
 	Plot2d('PlotData');
	%--------------------------------------
	%Plot2d('setSensorLineColorDefault')
   	set(hPlot2dList(108),'Value',0);		%hOpenAvgFileStatus
   	set(hSynthMenu(1),'Userdata',0); 		%SynthDataStatus

end

return;
