function[DDPFileMat]=DipDensApp(action)
%   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.                                                                      
%
% Das Programm erzeut 1 file (Endungen: dipole density plot = .ddp
%
% (c) Wienbruch 2000, 2001, Junghoefer 2001
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<1; action='InitializeMenu'; end

%================= global variables =============================================
global hDDPMENUFIG

if strcmp(action,'InitializeMenu'),

	%============================================================================
	%=========== INITIALIZE MENU ================================================
	%============================================================================
			
	%============== figure with graphs =========================		
   	 if strcmp(computer,'MAC2')	
       	MenuFigPosVec=[.8 0 .2 1];
    elseif strcmp(computer,'PCWIN') 
       	MenuFigPosVec=[.78 .05 .2 .82];
   	elseif strcmp(computer,'SOL2')
       	MenuFigPosVec=[.8 .01 .2 .91];		
   	end

	%============== figure with menu ===========================		
	DDPMenuFigString=['Dipole Density Plot Menu:'];
   	hDDPMENUFIG=figure('Units','normal','Position',MenuFigPosVec,'Name',DDPMenuFigString,'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.04;
	btnHt_edit=0.05;    
    textHeight = 0.05;
    textWidth = 0.06;
   	% Spacing between the button and the next command's label
   	spacing=0.015;

   	%====================================
   	% The CONSOLE frame
   	frmBorder=0.05; 
	frmLeft=left-frmBorder;
	frmBottom=0.010; 
   	frmHeight = 1-3.*frmBottom; 
	frmWidth = btnWid+2*frmBorder;
   	yPos=frmBottom-frmBorder;
   	frmPos=[frmLeft frmBottom frmWidth frmHeight];
	ConsoleRGBColor=[.5 .2 0];
   	hConsolFrame=uicontrol( ...
       	'Style','frame', ...
        'Units','normalized', ...
       	'Position',frmPos, ...
        'BackgroundColor',ConsoleRGBColor);

	%==================================================
   	btnNumber=1;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelPos=[left yPos-btnHt_edit./8 btnWid btnHt_edit./2];
	h = uicontrol( ...
	    'Style','text', ...
	    'Units','normalized', ...
	    'Position',labelPos, ...
	    'Horiz','center', ...
	    'String','=== Calculate DDP Menu ===', ...
	    'Interruptible','off', ...
	    'Background',ConsoleRGBColor, ...
	    'Foreground','white');
		
 	%==============================================================
    % OpenAppFiles (AppSCADS-Session-Format)==============================
	%==============================================================
	btnNumber=1;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'DipDensApp(''OpenAppFiles'')';
	hOpenAppFilesMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Open App File(s)', ...
        'Userdata',[], ...
        'Callback',callbackStr,...
        'Enable','off', ...
		'Visible','off');
	
	%==============================================================
    % Set Result Path =============================================
	% callback: SetResultPath =====================================
	%==============================================================
	btnNumber=1;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'DipDensApp(''SetResultPath'')';
	hSetResultPath=uicontrol( ...
        	'Style','pushbutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Result Path', ...
		    'Userdata',[], ...
            'Callback',callbackStr,...
		    'Enable','on');

	%======================================================
    % Run DDP Analysis ======================================
	% callback: RunDDP ========================================
	%======================================================
	btnNumber=2;
   	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
   	btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'DipDensApp(''RunDDP'')';
	hRunDDPMenu=uicontrol( ...
        	'Style','pushbutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Run DDP', ...
		    'Userdata',[], ...
        	'Callback',callbackStr,...
		    'Enable','off', ...
			'Visible','off');
	
    %========================================
	% callback: SetEegMegStatus =============
	%========================================
	btnNumber=2;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'DipDensApp(''SetEegMegStatus'')';
	hSetEegMegStatus=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','EEG', ...
		'Value',1, ...
		'Callback',callbackStr,...
		'Enable','on');
		
    if strcmp(computer,'SOL2')
        set(hSetEegMegStatus,'String','MEG','Value',2);
    end
	%===============================================
	% SubERPStatus (radio button)===========================
	% callback: SubERPStatus ==============================
	%===============================================
	btnNumber=3;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt btnWid./2 btnHt];

	hSubERPStatus=uicontrol( ...
       'Style','radiobutton', ...
       'Units','normalized', ...
       'Position',btnPos, ...
       'String','Sub. ERP/ERF', ...
	    'Value',1,...
	    'Enable','off', ...
		'Visible','off');
    
    
	%=================================================
    % SetStartF0 (edit text)==================================
	% callback: SetStartF0 ==================================
	%==================================================
   	btnNumber=5;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos 2.*btnWid./3 btnHt_edit./2];
    
	hSetStartF0Text = uicontrol( ...
       'Style','text', ...
       'Units','normalized', ...
	    'Position',btnPos, ...
       'Horiz','left', ...
       'Foreground','black', ...
       'String','Min. Frequency [Hz]:',...
	    'Enable','off');
    
    btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
	callbackStr = 'DipDensApp(''SetStartF0'')';
    
	hSetStartF0Menu = uicontrol( ...
       'Style','edit', ...
       'Units','normalized', ...
	   'Position',btnPos, ...
       'Horiz','center', ...
       'Background','white', ...
       'Foreground','black', ...
       'String','10','Value',10, ...
       'Callback',callbackStr,...
	    'Enable','off');
	
	%==============================================================
    % SetEndF0 (edit text)==================================
	% callback: SetEndF0 ===================================
	%==============================================================
   	btnNumber=5;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hSetEndF0Text = uicontrol( ...
       'Style','text', ...
       'Units','normalized', ...
	    'Position',btnPos, ...
       'Horiz','left', ...
       'Foreground','black', ...
       'String','Max. Frequency [Hz]:',...
	    'Enable','off');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
    callbackStr = 'DipDensApp(''SetEndF0'')';
    
	hSetEndF0Menu = uicontrol( ...
       'Style','edit', ...
       'Units','normalized', ...
	   'Position',btnPos, ...
       'Horiz','center', ...
       'Background','white', ...
       'Foreground','black', ...
       'String','50','Value',50, ...
       'Callback',callbackStr,...
       'Enable','off');
	
	
	%=================================================
    % SetNChan (edit text)==================================
	% callback: SetNChan ===================================
	%==================================================
   	btnNumber=7;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    	btnPos=[left yPos 2.*btnWid./3 btnHt_edit./2];
    
	hSetNChanText = uicontrol( ...
       'Style','text', ...
       'Units','normalized', ...
       'Position',btnPos, ...
       'Horiz','left', ...
       'Foreground','black', ...
       'String','Number of Sensors:',...
       'Enable','off');
    
    btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
	callbackStr = 'DipDensApp(''SetNChan")';
    
	hSetNChanMenu = uicontrol( ...
       'Style','edit', ...
       'Units','normalized', ...
       'Position',btnPos, ...
       'Horiz','center', ...
       'Background','white', ...
       'Foreground','black', ...
       'String','0','Value',0, ...
       'Callback',callbackStr,...
       'Enable','off');
	
	%=================================================
    % SetNChanExtra (edit text)=============================
	% callback: SetNChan =================================
	%==================================================
   	btnNumber=7;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hSetNChanExtraText = uicontrol( ...
       'Style','text', ...
       'Units','normalized', ...
       'Position',btnPos, ...
       'Horiz','left', ...
       'Foreground','black', ...
       'String','Number of Ext. Sensors:',...
       'Enable','off');
   
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'DipDensApp(''SetNChanExtra")';
    
	hSetNChanExtraMenu = uicontrol( ...
       'Style','edit', ...
       'Units','normalized', ...
	    'Position',btnPos, ...
       'Horiz','center', ...
       'Background','white', ...
       'Foreground','black', ...
       'String','0','Value',0, ...
       'Callback',callbackStr,...
	    'Enable','off');
	
	%=================================================
    % SetNPoints (edit text)==================================
	% callback: SetNPoints ===================================
	%==================================================
   	btnNumber=8;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos 2.*btnWid./3 btnHt_edit./2];
    
	hSetNPointsText = uicontrol( ...
       'Style','text', ...
       'Units','normalized', ...
       'Position',btnPos, ...
       'Horiz','left', ...
       'Foreground','black', ...
       'String','Number of Orig. Points:',...
       'Enable','off');
    
    btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
	callbackStr = 'DipDensApp(''SetNPoints'')';
    
	hSetNPointsMenu = uicontrol( ...
       'Style','edit', ...
       'Units','normalized', ...
       'Position',btnPos, ...
       'Horiz','center', ...
       'Background','white', ...
       'Foreground','black', ...
       'String','0','Value',0, ...
       'Callback',callbackStr,...
       'Enable','off');
	
	
	%=================================================
    	% SetNTrials (edit text)==================================
	% callback: SetNTrials ===================================
	%==================================================
   	btnNumber=9;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    	btnPos=[left yPos 2.*btnWid./3 btnHt_edit./2];
    
	hSetNTrialsText = uicontrol( ...
       'Style','text', ...
       'Units','normalized', ...
		'Position',btnPos, ...
       'Horiz','left', ...
       'Foreground','black', ...
       'String','Number of Trials:',...
		'Enable','off');
    
   	btnPos=[left+2.*btnWid./3 yPos btnWid./3 btnHt_edit./2];
	callbackStr = 'DipDensApp(''SetNTrials'')';
    
	hSetNTrialsMenu = uicontrol( ...
       'Style','edit', ...
       'Units','normalized', ...
	    'Position',btnPos, ...
       'Horiz','center', ...
       'Background','white', ...
       'Foreground','black', ...
       'String','0','Value',0, ...
       'Callback',callbackStr,...
	    'Enable','off');
	
	%=================================================
    % SetSampRate (edit text)================================
	% callback: SetSampRate ================================
	%==================================================
   	btnNumber=9;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt_edit./2 2.*btnWid./3 btnHt_edit./2];
    
	hSetSampRateText = uicontrol( ...
       'Style','text', ...
       'Units','normalized', ...
	   'Position',btnPos, ...
       'Horiz','left', ...
       'Foreground','black', ...
       'String','Sampling Rate [Hz]:',...
	   'Enable','off');
    
    btnPos=[left+2.*btnWid./3 yPos-btnHt_edit./2 btnWid./3 btnHt_edit./2];
	callbackStr = 'DipDensApp(''SetSampRate'')';
    
	hSetSampRateMenu = uicontrol( ...
       'Style','edit', ...
       'Units','normalized', ...
	    'Position',btnPos, ...
       'Horiz','center', ...
       'Background','white', ...
       'Foreground','black', ...
       'String','0','Value',0, ...
       'Callback',callbackStr,...
	    'Enable','off');
	
    
    
    
    
    
    
    %=======================================================
	%=======================================================
	%=======================================================
	%=======================================================
	%=======================================================
   	btnNumber=10;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelPos=[left yPos-btnHt_edit./8 btnWid btnHt_edit./2];
	h = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',labelPos, ...
	'Horiz','center', ...
	'String','=== Plot DDP Menu ===', ...
	'Interruptible','off', ...
	'Background',ConsoleRGBColor, ...
	'Foreground','white');

    %============================================================
    % OpenHistFile (Hist.Text-Format)============================
	%============================================================
	btnNumber=10;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'DipDensApp(''OpenHistFile'')';
	hOpenHistFileMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Open Hist File', ...
        'Userdata',[], ...
        'Callback',callbackStr,...
        'Enable','on');
    
    %===========================================================
    % RunHistPlot (Hist.Text-Format)============================
	%===========================================================
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'DipDensApp(''PrepRunHistPlot'')';
	hRunHistPlotMenu=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Run Hist Plot', ...
        'Userdata',[], ...
        'Callback',callbackStr,...
        'Enable','on');
    
    %====================================
   	%===============DataType=============
	%===================================	
    btnNumber=11;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelWidth = btnWid./2;
	labelBottom=yPos-textHeight./1.5;
	labelLeft = left;
	labelPos = [labelLeft labelBottom labelWidth textHeight];
	hDataTypeText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
	    'Position',labelPos, ...
        'Horiz','center', ...
        'String','Data type', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
	
	% The Data Type Routine Selection Menu
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt btnWid./2 btnHt];
	labelStr='   Histogram   |Sum of dipole moment|Raleigh test';
	callbackStr='DipDensApp(''setDataType'');';
    
	hDataTypeMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
	    'Value',1, ...
        'Callback',callbackStr);
    
    %====================================
   	%===============Normalize Data=======
	%===================================	
    btnNumber=11;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelWidth = btnWid./2;
	labelBottom=yPos-textHeight./1.5;
	labelLeft = left+btnWid./2;
	labelPos = [labelLeft labelBottom labelWidth textHeight];
	hNormTypeText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
	    'Position',labelPos, ...
        'Horiz','center', ...
        'String','Norm type', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
	
	% The Data Type Routine Selection Menu
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	labelStr='None|Number of selected dipoles|Number of analyzed time slices|Sampling interval';
	callbackStr='DipDensApp(''setNormType'');';
    
	hNormTypeMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
	    'Value',2, ...
        'Callback',callbackStr);
    
    %====================================
   	%===============p-level=======
	%===================================	
    btnNumber=12;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelWidth = btnWid./2;
	labelBottom=yPos-textHeight./1.5;
	labelLeft = left;
	labelPos = [labelLeft labelBottom labelWidth textHeight];
	hPLevelText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
	    'Position',labelPos, ...
        'Horiz','center', ...
        'String','p - level', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
	
	% The p-level Routine Selection Menu
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt btnWid./2 btnHt];
	labelStr='All (0)|p=0.05|p=0.01|p=0.001';
	callbackStr='DipDensApp(''setPLevel'');';
    
	hPLevelMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
	    'Value',1, ...
        'Callback',callbackStr,...
        'Enable','off');
    
    
    %====================================
   	%===============Display Method=======
	%===================================	
    btnNumber=12;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelWidth = btnWid./2;
	labelBottom=yPos-textHeight./1.5;
	labelLeft = left+btnWid./2;
	labelPos = [labelLeft labelBottom labelWidth textHeight];
	hDispMethodText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
	    'Position',labelPos, ...
        'Horiz','center', ...
        'String','Display Method', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');
	
	% The Display Method Routine Selection Menu
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	labelStr='Contour lines|Filled contours|Colored boxes';
	callbackStr='DipDensApp(''setDispMethod'');';
    
	hDispMethodMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
	    'Value',2, ...
        'Callback',callbackStr);
    

    %==============================================================
    % ColorMap (popupmenu)=========================================
	% callback: setColorMap =======================================
	%==============================================================
	
	btnNumber=13;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	labelWidth = btnWid./2;
	labelBottom=yPos-textHeight./1.5;
	labelLeft = left;
	labelPos = [labelLeft labelBottom labelWidth textHeight];
	
	hColorMapText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',labelPos, ...
        'Horiz','center', ...
        'String','Color Map', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');

	% The ColorMap Routine Selection Menu
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt btnWid./2 btnHt];
	labelStr='hsv|hot|cool|jet|pink|flag|copper|gray|bone';
	callbackStr='DipDensApp(''setColorMap'');';
    
	hColorMapMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
	    'Value',4, ...
        'Callback',callbackStr);
    
    %==============================================================
    % PrintMedia (popupmenu)=======================================
	% callback: setPrintMedia =====================================
    %==============================================================
	
	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];
	
	hPrintMediaText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',labelPos, ...
        'Horiz','center', ...
        'String','Print Media', ...
        'Interruptible','off', ...
        'BackgroundColor',ConsoleRGBColor, ...
        'ForegroundColor','white');

	% The PrintMedia Routine Selection Menu
	
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	labelStr='None|Printer|Tiff file';
	callbackStr='DipDensApp(''setPrintMedia'');';
    
	hPrintMediaMenu=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
	    'Value',1, ...
        'Callback',callbackStr);

    %===============================================
	% ClearFigStatus (radio button)=================
	%===============================================
	btnNumber=14;
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
	btnPos=[left yPos-btnHt btnWid./2 btnHt];

	hClearFigStatus=uicontrol( ...
       'Style','radiobutton', ...
       'Units','normalized', ...
       'Position',btnPos, ...
       'String','Clear figure', ...
	   'Value',1,...
	   'Enable','on');
   
    %=======================================================
	%=======================================================
	%=======================================================
	%=======================================================
	%=======================================================
   	btnNumber=16;     
	yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    labelPos=[left yPos-btnHt_edit./8 btnWid btnHt_edit./2];
	h = uicontrol( ...
	'Style','text', ...
	'Units','normalized', ...
	'Position',labelPos, ...
	'Horiz','center', ...
	'String','=== Avg. & Diff. DDP Menu ===', ...
	'Interruptible','off', ...
	'Background',ConsoleRGBColor, ...
	'Foreground','white');
	
	%==============================================================
    % OpenDDPFiles (ddp-Format)======================================
	%==============================================================
	
	btnNumber=16;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'DipDensApp(''OpenDDPFiles'')';
	hOpenDDPFilesMenu=uicontrol( ...
        	'Style','pushbutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Open DDP File(s) ', ...
		    'Userdata',[], ...
        	'Callback',callbackStr,...
		    'Enable','off');
		
	%==============================================================
    % AverageWaFiles (DDP-Format)========================================
	%==============================================================
	btnNumber=17;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'DipDensApp(''AvgDDPFiles'')';
	hAvgDDPFilesMenu=uicontrol( ...
        	'Style','pushbutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Avg. DDP Files', ...
		    'Userdata',[], ...
        	'Callback',callbackStr,...
		    'Enable','off');
		
	%==============================================================
    %	DifferenceDDPFiles (DDP-Format)=====================================
	%==============================================================
	btnNumber=17;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'DipDensApp(''DiffDDPFiles'')';
	hDiffDDPFilesMenu=uicontrol( ...
        	'Style','pushbutton', ...
        	'Units','normalized', ...
        	'Position',btnPos, ...
        	'String','Diff. DDP Files', ...
		    'Userdata',[], ...
        	'Callback',callbackStr,...
		    'Enable','off');
 
    %=======================================================
	%=======================================================
    %=======================================================
	%===========UIMENUES====================================
	%=======================================================
	
	%==============================================================
    % Menu: File ==================================================
	%==============================================================
	hFileMenu=uimenu('Label','File','ForegroundColor',[0 0 1],'Enable','on');
				
		callbackStr='DipDensApp(''OpenFileMatrix'')';
		hFileOpenFileMatrixMenu=uimenu(hFileMenu,'Label','Open file matrix','Callback',callbackStr);
		callbackStr='DipDensApp(''SaveFileMatrix'')';
		hFileSaveFileMatrixMenu=uimenu(hFileMenu,'Label','Save file matrix','Callback',callbackStr,'Enable','off');
		callbackStr='DipDensApp(''AddFile2FileMatrix'')';
		hFileAddFile2FileMatrixMenu=uimenu(hFileMenu,'Label','Add file(s) to file matrix','Callback',callbackStr,'Enable','off');
		callbackStr='DipDensApp(''UseFileMatrix'')';
		hFileUseFileMatrixMenu=uimenu(hFileMenu,'Label','Use file matrix','Callback',callbackStr,'Enable','off','Userdata',0);

    %==============================================================
	%============================================
	% hList(5)
	hTopMenu=[hFileMenu];
    hhTopMenu=uicontrol('Userdata',hTopMenu,'Visible','off'); 			%5
    %=======================================================
	%=======================================================
	hDDPMat=uicontrol('Visible','off');                                 %4
	hF0FrequVec=uicontrol('Visible','off');                             %41
	hF0IndexVec=uicontrol('Visible','off');                             %42
	hBatchFileDefPath=uicontrol('Visible','off'); 						%60
	hFileMat=uicontrol('Visible','off'); 								%63

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

	NonUse=0;
	hList=[hOpenAppFilesMenu hSetResultPath hRunDDPMenu,hDDPMat,hhTopMenu ...				    %5
	NonUse NonUse hSetStartF0Text hSetStartF0Menu hSetEndF0Text ...				                %10
	hSetEndF0Menu NonUse NonUse NonUse NonUse ...			                                    %15
	NonUse NonUse NonUse hSubERPStatus NonUse ...			                                    %20
	hOpenDDPFilesMenu NonUse hAvgDDPFilesMenu hDiffDDPFilesMenu NonUse ...			            %25
	hSetNChanText hSetNChanMenu hSetNPointsText hSetNPointsMenu hSetNTrialsText ...				%30
	hSetNTrialsMenu hSetSampRateText hSetSampRateMenu NonUse NonUse ...	                        %35
	NonUse NonUse NonUse NonUse NonUse ...								                        %40
	hF0FrequVec hF0IndexVec NonUse NonUse NonUse ...					                        %45
	hSetNChanExtraText hSetNChanExtraMenu hSetEegMegStatus NonUse NonUse ...                    %50
    hOpenHistFileMenu hDataTypeText hDataTypeMenu hNormTypeText hNormTypeMenu ...               %55	
    hPLevelText hPLevelMenu hDispMethodText hDispMethodMenu hBatchFileDefPath ...               %60
    hColorMapText hColorMapMenu hFileMat hRunHistPlotMenu NonUse ...                            %65
    hPrintMediaText hPrintMediaMenu hClearFigStatus];	                                        %70                               										
	
	set(hDDPMENUFIG,'UserData',hList);
    
elseif  strcmp(action,'OpenFileMatrix') 

	hList=get(hDDPMENUFIG,'Userdata');
	hTopMenu=get(hList(5),'Userdata');
	hFileMenu=get(hTopMenu(1),'children');
	UseFileMatrixStatus=get(hFileMenu(1),'Userdata');
	BatchFileDefPath=get(hList(60),'Userdata');
	if isempty(BatchFileDefPath)
		[BatchFileDefPath]=SetDefPath(1,'*.hist*');
	end	
	[NFiles,FileMat,NonUse,BatchFilePath]=ReadFileNames([],BatchFileDefPath,'Please choose file(s):');
	if NFiles==0; return; end
	[BatchFile,BatchPath]=SepFilePath(BatchFilePath);
	set(hList(60),'Userdata',BatchPath);
	set(hList(63),'Value',NFiles,'Userdata',FileMat);
	set(hFileMenu(3),'Enable','on');%SaveFileMat
	set(hFileMenu(2),'Enable','on')	%AddFileName2FileMat
	set(hFileMenu(1),'Enable','on')	%UseFileMat
	if UseFileMatrixStatus==0; 
		DipDensApp('UseFileMatrix')
		Message=char('Set "Use File Matrix" status "on".');
		hMsg=msgbox(Message,'Info','help'); 
		hMsgChild=get(hMsg,'Children');
		set(hMsgChild(length(hMsgChild)),'Visible','off');
		pause(1)
		close(hMsg)
	else
	    DipDensApp('FileMatrixInfo')
	end
	
elseif  strcmp(action,'SaveFileMatrix') 
    
    hList=get(hDDPMENUFIG,'Userdata');
	hTopMenu=get(hList(5),'Userdata');
	FileMat=get(hList(63),'Userdata');
	NFiles=get(hList(63),'Value');
	DipDensApp('FileMatrixInfo')
	[SaveFile,SavePath,SaveFilePath]=WriteFilePath('FileMatrix.txt','Save file matrix to file:');
	if SaveFile==0; return; end
	fid=fopen(SaveFilePath,'w','b');
	for FileIndex=1:NFiles
		fprintf(fid,[FileMat(FileIndex,:),'\n']);
	end
	fclose(fid);
	
elseif  strcmp(action,'AddFile2FileMatrix') 
    
    hList=get(hDDPMENUFIG,'Userdata');
	hTopMenu=get(hList(5),'Userdata');
	FileMatOld=get(hList(63),'Userdata');
	NFilesOld=get(hList(63),'Value');
	[NFiles,FileMat]=ReadFileNames([],'*','Please choose file(s) to add:');
	if NFiles==0; return; end
	NFiles=NFiles+NFilesOld;
	FileMat=char(FileMatOld,FileMat);
	set(hList(63),'Userdata',FileMat,'Value',NFiles);
	DipDensApp('FileMatrixInfo')

elseif  strcmp(action,'UseFileMatrix') 
    
    hList=get(hDDPMENUFIG,'Userdata');
	hTopMenu=get(hList(5),'Userdata');
	hFileMenu=get(hTopMenu(1),'children');
	Pointer=GetPointer; %(local function)
	UseFileMatrixLabel=get(hFileMenu(1),'Label');
	UseFileMatrixStatus=get(hFileMenu(1),'Userdata');
	if UseFileMatrixStatus==1; 
		UseFileMatrixStatus=0;
		PointPosEnd=length(UseFileMatrixLabel)-3;
		UseFileMatrixLabel=UseFileMatrixLabel(1:PointPosEnd);
	else
		UseFileMatrixStatus=1;
		UseFileMatrixLabel=[UseFileMatrixLabel,'  ',setstr(Pointer)];
		DipDensApp('FileMatrixInfo')
	end
	set(hFileMenu(1),'Label',UseFileMatrixLabel,'Userdata',UseFileMatrixStatus)
	
elseif  strcmp(action,'FileMatrixInfo') 

	hList=get(hDDPMENUFIG,'Userdata');
	hTopMenu=get(hList(5),'Userdata');
	FileMat=get(hList(63),'Userdata');
	NFiles=get(hList(63),'Value');
	fprintf(1,'\n'); clc;
	if NFiles==1
		Message=char(['The actual file matrix contains the following file:']);
		fprintf(1,'The actual file matrix contains the following file:\n\n');
	else
		Message=char(['The actual file matrix contains the following ',int2str(NFiles),' files:']);
		fprintf(1,'The actual file matrix contains the following %g files:\n\n',NFiles);
	end
	Message=char(Message,' ');
	Message=char(Message,FileMat);
	Message=char(Message,'');
	Message=char(Message,'');
	hmsgbox=msgbox(Message,'Info','help'); 
	disp(FileMat)

    %============================================================================	
	%============ set Data Type
	%============================================================================	
    
elseif strcmp(action,'setDataType'),
   
    hList=get(hDDPMENUFIG,'Userdata');
    DataTypeVal=get(hList(53),'Value');
    if DataTypeVal~=3 %Raleigh test
        set(hList(57),'Value',1,'Enable','off'); %p-value
    else
        set(hList(57),'Value',1,'Enable','on');
    end;
	%============================================================================	
	%============ set EEG / MEG Status
	%============================================================================	
elseif strcmp(action,'SetEegMegStatus'),

	hList=get(hDDPMENUFIG,'Userdata');
	hSetEegMegStatus=hList(48);
	EegMegStatusString=get(hSetEegMegStatus,'String');
	if strcmp(EegMegStatusString,'EEG')
		EegMegStatusString='MEG';
		EegMegStatusVal=2;
	else
		EegMegStatusString='EEG';
		EegMegStatusVal=1;
	end
	set(hSetEegMegStatus,'String',EegMegStatusString,'Value',EegMegStatusVal);
	
elseif  strcmp(action,'AppFileMatrixInfo') | strcmp(action,'WaFileMatrixInfo') 

	hList=get(hDDPMENUFIG,'Userdata'); 
	if  strcmp(action,'AppFileMatrixInfo')
		hListNo=1;
	elseif strcmp(action,'WaFileMatrixInfo') 
		hListNo=21;
	end
	FileMat=get(hList(hListNo),'Userdata')
	NFiles=size(FileMat,1);
	
	if NFiles>1
		fprintf(1,'\n'); clc;
		Message=char(['The actual file matrix contains the following ',int2str(NFiles),' files:']);
		fprintf(1,'The actual file matrix contains the following %g files:\n\n',NFiles);
	else
		return;
	end
	Message=char(Message,' ');
	Message=char(Message,FileMat);
	Message=char(Message,'');
	Message=char(Message,'');
	hmsgbox=msgbox(Message,'Info','help'); 
	disp(FileMat)
	
elseif strcmp(action,'OpenAppFiles'),

	hList=get(hDDPMENUFIG,'Userdata');
	ResultPath=get(hList(2),'Userdata');
	NTap=get(hList(7),'Value');
	StartF0=get(hList(9),'Value');
	EndF0=get(hList(11),'Value');
	DeltaF0=get(hList(13),'Value');
	PadDataStatus=get(hList(20),'Value');
	FileExt='*.app*'; 
	String='Choose an App. file (*.app*):';
	DefFilePath=SetDefPath(1,FileExt)
	[NFiles,FileMat,VersionString,BatchFilePath]=ReadFileNames(FileMat,DefFilePath,String);
	if NFiles==0; return; end
	set(hList(1),'Userdata',FileMat);
	DipDensApp('SetResultFilePath')
	DipDensApp('AppFileMatrixInfo')
	set(hList(3),'Enable','on');	%RunDDP
	set(hList(43),'Enable','on');	%SurfDDPMatFrequ
	set(hList(44),'Enable','on');	%SurfDDPMatTime
	[File,Path,FilePath]=GetFileNameOfMat(FileMat,1);
	[DataMat,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,chAvgRef,File,Path,FilePath,EegMegStatus,NChanExtra]=ReadAppData(FilePath,0);
	set(hList(27),'Value',NChan,'String',sprintf('%g',NChan));
	set(hList(47),'Value',NChanExtra,'String',sprintf('%g',NChanExtra));
	set(hList(29),'Value',NPoints,'String',sprintf('%g',NPoints));
	set(hList(31),'Value',NTrials,'String',sprintf('%g',NTrials));
	set(hList(33),'Value',SampRate,'String',sprintf('%g',SampRate));
	EegMegStatusString=get(hList(48),'String');
	if (EegMegStatus==2 & strcmp(EegMegStatusString,'EEG')) | (EegMegStatus==1 & strcmp(EegMegStatusString,'MEG'))
		DipDensApp('SetEegMegStatus')
		EegMegStatusString=get(hList(48),'String');
	end
	DipDensApp('PadDataStatus')
	DipDensApp('SetNTap')
	NTap=get(hList(7),'Value');
	if NTap>0
		set(hList(38),'Enable','on');	%SurfNTapMat
	end;
    
elseif strcmp(action,'setColorMap'),

	hList=get(hDDPMENUFIG,'Userdata');
    ColorMapVal=get(hList(62),'Value');
    NRowColorMap=256
    FlipColormapStatus=0
    if ColorMapVal==1
		ColorMat=hsv(NRowColorMap);
	elseif ColorMapVal==2
		ColorMat=hot(NRowColorMap);
	elseif ColorMapVal==3
		ColorMat=cool(NRowColorMap);
	elseif ColorMapVal==4
		ColorMat=jet(NRowColorMap);
	elseif ColorMapVal==5
		ColorMat=pink(NRowColorMap);
	elseif ColorMapVal==6
		ColorMat=flag(NRowColorMap);
	elseif ColorMapVal==7
		ColorMat=copper(NRowColorMap);
	elseif ColorMapVal==8
		ColorMat=gray(NRowColorMap);
    elseif ColorMapVal==9
		ColorMat=bone(NRowColorMap);
	end
    if FlipColormapStatus; ColorMat=flipud(ColorMat); end	
    set(hList(62),'Userdata',Colormat); %ColorMapVal;
    
elseif strcmp(action,'OpenHistFile'),

	hList=get(hDDPMENUFIG,'Userdata');

	FileExt='*.hist*'; 
	String='Choose an Hist. file (*.hist*):';
	DefFilePath=SetDefPath('r',FileExt)
    [HistFile,HistPath,HistFilePath]=ReadFilePath([],DefFilePath,'Choose a hist file (*.hist*)');
	if HistFile==0; return; end
    SetDefPath('w',HistPath);
    set(hList(51),'Userdata',HistFilePath);
    
elseif strcmp(action,'ReadHistData'),

	hList=get(hDDPMENUFIG,'Userdata');
    HistFilePath=get(hList(51),'Userdata')
    [HistFile,HistPath]=SepFilePath(HistFilePath);
    [HistFid,FidMessage]=fopen(HistFilePath);
    if HistFid==-1
         hmsgbox=msgbox(FidMessage,'Info','help'); 
         return;
    end
    %************************reading header**********************************
    [HistFilePath,NOB,XMAX,YMAX,ZMAX,sxmin,sxmax,symin,symax,szmin,szmax,divisions,nop,not,si,ncol,axiss]=read_hist_header(HistFid);
    nsmp=get_nsmp(HistFid);
    % get number of samples in file
    Data=read_hist_data(HistFid,nsmp,ncol); %get data
    fclose(HistFid);
    HistData.Data=Data;
    HistData.NOB=NOB;
    HistData.XMAX=XMAX;
    HistData.YMAX=YMAX;
    HistData.ZMAX=ZMAX;    
    HistData.sxmin=sxmin;
    HistData.sxmax=sxmax; 
    HistData.symin=symin;
    HistData.symax=symax;
    HistData.szmin=szmin;
    HistData.szmax=szmax;
    HistData.divisions=divisions;
    HistData.nop=nop;
    HistData.not=not;    
    HistData.si=si;    
    HistData.ncol=ncol;    
    HistData.nsmp=nsmp;
    HistData.Axiss=axiss;
    HistData.File=HistFile;
    HistData.Path=HistPath; 
    HistData.FilePath=HistFilePath;
    set(hList(64),'Userdata',HistData);
  
elseif strcmp(action,'PrepRunHistPlot'),

	hList=get(hDDPMENUFIG,'Userdata'); 	
    hTopMenu=get(hList(5),'Userdata');
    hFileMenu=get(hTopMenu(1),'children');
    BatchFileStatus=get(hFileMenu(1),'Userdata');
    if ~BatchFileStatus    
        HistFilePath=get(hList(51),'Userdata');
        if exist(HistFilePath) 
            DipDensApp('RunHistPlot')
        else
            Message=char('Hist file:');
            Message=char(Message,[HistFilePath]);
            Message=char(Message,'does not exist !');
            Message=char(Message,'');
            Message=char(Message,'Please choose a different file.');
            hmsgbox=msgbox(Message,'Info','help'); 
            DipDensApp('OpenHistFile')
            return;
        end
    else
       FileMat=get(hList(63),'Userdata')
       NFiles=get(hList(63),'Value')
       FirstIndex=1;
       for FileInd=1:NFiles
           HistFilePath=FileMat(FileInd,:)
           if exist(HistFilePath)
                Message=char('Plot Dipole Density of file:'); 
                Message=char(Message,' ');
			    Message=char(Message,HistFilePath);
			    Message=char(Message,' ');
			    Message=char(Message,['File #    ',int2str(FileInd),' of ',int2str(NFiles)]);
			    Message=char(Message,' ');
			    if FirstIndex
				    hMsgbox=msgbox(Message,'DDP Progress Info:','help');
				    hChildMsgbox=get(hMsgbox,'children');
				    hChild2Msgbox=get(hChildMsgbox(2),'children');
				    set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');
                else
                    if strcmp(computer,'SOL2')
	    	            set(hChild2Msgbox,'String',Message);
		            else
			            set(hChildMsgbox(2),'String',Message);
                    end;
                    pause(.001)
			    end;
               FirstIndex=0;
			   pause(.01);
               set(hList(51),'Userdata',HistFilePath);
               DipDensApp('RunHistPlot')
            else
                Message=char('Hist file:');
                Message=char(Message,[HistFilePath]);
                Message=char(Message,'does not exist !');
                Message=char(Message,'');
                if FileInd<NFiles
                    Message=char(Message,'Take next file of list.');
                end
                hMsgbox=msgbox(Message,'Info','help'); 
            end
       end
   end
    
elseif strcmp(action,'RunHistPlot'),

	hList=get(hDDPMENUFIG,'Userdata'); 	
    DipDensApp('ReadHistData');
    ResultPath=get(hList(2),'Userdata');
    if isempty(ResultPath); ResultPath=pwd; end
	StartF0=get(hList(9),'Value');
	EndF0=get(hList(11),'Value');
    DataTypeVal=get(hList(53),'Value');
    NormTypeVal=get(hList(55),'Value');
    PLevelVal=get(hList(57),'Value');
    DispMethodVal=get(hList(59),'Value');
    ColorMat=get(hList(62),'Userdata'); 
    PrintMediaVal=get(hList(67),'Value');     
    ClearFigStatus=get(hList(68),'Value'); 

    HistData=get(hList(64),'Userdata');
    Data=HistData.Data; 
    NOB=HistData.NOB;
    XMAX=HistData.XMAX;
    YMAX=HistData.YMAX;
    ZMAX=HistData.ZMAX;    
    sxmin=HistData.sxmin;
    sxmax=HistData.sxmax; 
    symin=HistData.symin;
    symax=HistData.symax;
    szmin=HistData.szmin;
    szmax=HistData.szmax;
    divisions=HistData.divisions;
    nop=HistData.nop;
    not=HistData.not;    
    si=HistData.si;    
    ncol=HistData.ncol;    
    nsmp=HistData.nsmp;
    axiss=HistData.Axiss;
    HistFile=HistData.File;
    HistPath=HistData.Path; 
    HistFilePath=HistData.FilePath;
  
    colormap(ColorMat);		

    % Berechne Spaltensumme
    summe = sum(Data,1);
    total_dipoles = summe(1);
    if total_dipoles ~= nop
        error('total_dipoles ~= nop');
    end,

    ZData=zeros(divisions,divisions,divisions);
    
    x=axiss(:,1);
    y=axiss(:,2);
    z=axiss(:,3);

    % Berechne Gaussfunktion
    %
    ux=(x-mean(x))./std(x); % reduzierte Variable der X-Werte
    uy=(y-mean(y))./std(y); % reduzierte Variable der Y-Werte

    scalefactor=(max(x)-min(x)+max(y)-min(y))/(max(ux)-min(ux)+max(uy)-min(uy));
    ux=scalefactor.*ux;
    uy=scalefactor.*uy;
    [UX,UY]=meshgrid(ux,uy);
    Gauss=exp(-UX.^2-UY.^2);
    if DataTypeVal==1
        for k=1:nsmp
            ZData(Data(k,2),Data(k,3),Data(k,4))=Data(k,1);
        end,
    elseif DataTypeVal==2
        for k=1:nsmp
             ZData(Data(k,2),Data(k,3),Data(k,4))=Data(k,5);
        end,
    elseif DataTypeVal==3
        for k=1:nsmp
            ZData(Data(k,2),Data(k,3),Data(k,4))=Data(k,6);
        end,% check for significance of random walk distance 
        if PLevelVal>1
            if PLevelVal==2         %0.05
                k1=6; k2=7;
            elseif PLevelVal==3     %0.01
                k1=6; k2=8;   
            elseif PLevelVal==4     %0.001
                k1=6; k2=9;  
            end
            for k=1:nsmp
                if Data(k,k1)<Data(k,k2) 
                    ZData(Data(k,2),Data(k,3),Data(k,4)) = 0.0;
                end,
            end,
        end, %if PLevelVal
    end %if DataTypeVal
    if DataTypeVal==1
        if NormTypeVal==1 
            ZData=ZData./nop;
        elseif NormTypeVal==2
            ZData=ZData./(not.*si);
        elseif NormTypeVal==3
            ZData=ZData./not;
        end,
    end,

    ZDataMin=min(min(min(ZData)));
    ZDataMax=max(max(max(ZData)));
    
    %
    % create Plots
    %
    pixelsize=(sxmax-sxmin)./divisions;

    [YI,XI]= meshgrid(y,x);

    xfig=3; %Anzahl Plots pro Zeile
    yfig=4; %Anzahl Plots pro Spalte
    NSubPlot=xfig.*yfig;
    figcount  = 0;
    xfigcount = 0;
    yfigcount = 0;
    SubPlotCount=1;
    %conlev = [0.001,0.002,0.005,0.01,0.02,0.05,0.1,0.2,0.5,...
    %          1,2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000,100000];
    conlev = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9];
    conlev = conlev.*ZDataMax;
    NDivStep=1;        
    for j=1:NDivStep:divisions 
        SubPlotCount=SubPlotCount+1;
        
        if figcount==0 | SubPlotCount>NSubPlot
            bdwidth = 5;
            topbdwidth = 80;
            xsize=600;
            ysize=800;
            scnsize=get(0,'ScreenSize');
            pos1=[scnsize(3)-xsize-bdwidth,scnsize(4)-ysize-topbdwidth,xsize,ysize];
            Str1=['DDP of file:  ',strrep(HistFile,'#','')];
            Str2=['Inf-Sub: ',num2str(z(j)),' - ',num2str(z(j+min([8,length(z)-j]))),' cm'];
            FigName=[Str1,';  ',Str2];
            hFig=figure('Units','pixel',...
		            'Position',pos1, ...
       	            'Name',FigName, ...
		            'Color',[.99 .99 .99], ...
                    'NumberTitle','off');
            hTextAxes=axes('Units','normal','Position',[0 .775 1 .225]);
            axis('off');
            % Textinfos
            patient = strrep(HistFile,'_',':');
            text('Units','normal','Position',[.5 .85],'Color','black','String',Str1,'FontSize',14,'HorizontalAlignment','center','FontWeight','bold')
            text('Units','normal','Position',[.5 .7],'Color','black','String',Str2,'FontSize',14,'HorizontalAlignment','center','FontWeight','bold')
            text('Units','normal','Position',[.05 .4],'Color','black','String',strcat(strrep(NOB,'#','')),'FontSize',12)
            text('Units','normal','Position',[.05 .3],'Color','black','String',strcat(strrep(strrep(XMAX,'#',''),'_','')),'FontSize',12)
            text('Units','normal','Position',[.05 .2],'Color','black','String',strcat(strrep(strrep(YMAX,'#',''),'_','')),'FontSize',12)
            text('Units','normal','Position',[.05 .1],'Color','black','String',strcat(strrep(strrep(ZMAX,'#',''),'_','')),'FontSize',12)
      
            if DataTypeVal==1; 
                TextTmp='Histogram';
            elseif DataTypeVal==2; 
                 TextTmp='Avg Q';  
            elseif DataTypeVal==3; 
                 TextTmp='Random walk Q'; 
            end;            
            text('Units','normal','Position',[.6 .3],'Color','black','String',TextTmp,'FontSize',12)
            if NormTypeVal==1; 
                TextTmp='No normalization';
            elseif NormTypeVal==2; 
                 TextTmp='Normalized: total number of calculated dipoles';  
            elseif NormTypeVal==3; 
                 TextTmp='Normalized: selected dipoles per second'; 
             elseif NormTypeVal==4; 
                 TextTmp='Normalized: number of selected timeslices'; 
            end            
            text('Units','normal','Position',[.6 .2],'Color','black','String',TextTmp,'FontSize',12)
            if PLevelVal==1; 
                TextTmp='No significance level';
            elseif PLevelVal==2; 
                 TextTmp='Significance level: p=0.05';  
            elseif PLevelVal==3; 
                 TextTmp='Significance level: p=0.01'; 
             elseif PLevelVal==4; 
                 TextTmp='Significance level: p=0.001'; 
            end;           
            text('Units','normal','Position',[.6 .1],'Color','black','String',TextTmp,'FontSize',12)
            SubPlotCount=1+xfig;
            figcount=figcount+1;
        end;
  
        clear ZD;
        if DispMethodVal==1 | DispMethodVal==2
            ZD=conv2(ZData(:,:,j),Gauss,'same'); %returns the central part of the convolution
        elseif DispMethodVal==3 
            ZD=ZData(:,:,j);
        end;

        ZDMax=max(max(ZD));
        ZDMin=min(min(ZD));
        subplot(yfig,xfig,SubPlotCount);        
        axis off;
        %if ZDMax>0
        if 1
            if DispMethodVal==1
                if ZDMin<ZDMax
                    contour(YI,XI,fliplr(ZD),conlev);
                end;
            elseif DispMethodVal==2   
                if ZDMin<ZDMax
                    contourf(YI,XI,fliplr(ZD),conlev);
                end;
            elseif DispMethodVal==3   
                imagesc(y,x,flipud(fliplr(ZD)));
            end;    
            caxis([0 ZDMax]);        
            axis on;
            colorbar;
            grid on;
            if any([1 4 7 10]==SubPlotCount)
                ylabel('Post-Ant');
            end;
            if any([10 11 12]==SubPlotCount)
                xlabel('L-R');
            end;
            t2 = sprintf('%.2f', z(j) );
            title(strcat('Inf-Sup: ', t2) );
        end;
        if SubPlotCount==NSubPlot | j==divisions
     %      PRINT figures
            orient tall
            if PrintMediaVal==2
                print -dpsc -r0  
            elseif PrintMediaVal==3
                HistFilePath
                printfilepath=[ResultPath,HistFile,'.tif']
                print(gcf,'-dtiff','-noui',printfilepath)
                %unix(ucmd)
            end;
            if ClearFigStatus
                pause(2)
                close(hFig);
            end;
        end;
        pause(.001);
    end;
    
elseif strcmp(action,'OpenDDPFiles'),

	hList=get(hDDPMENUFIG,'Userdata');
	ResultPath=get(hList(2),'Userdata');
	hSetAwaPwaStatus=hList(22);
	AwaPwaStatus=get(hSetAwaPwaStatus,'String');
	if strcmp(AwaPwaStatus,'Amplitude')
		FileExt='*.awa*'; 
		String='Choose an amplitude file (*.awa*):';
	elseif strcmp(AwaPwaStatus,'Phaselock')
		FileExt='*.pwa*'; 
		String='Choose a phaselock file (*.pwa*):';
	end
	DefFilePath=SetDefPath(1,FileExt);
	[NFiles,FileMat,VersionString,BatchFilePath]=ReadFileNames(FileMat,DefFilePath,String);
	if NFiles==0; return; end
	set(hList(21),'Userdata',FileMat);
	DipDensApp('WaFileMatrixInfo')
	if NFiles>1
		set(hList(23),'Enable','on');	%Avg
		set(hList(24),'Enable','on');	%Diff
	else
		set(hList(23),'Enable','off');
		set(hList(24),'Enable','off');
	end
	
elseif strcmp(action,'SetAwaPwaStatus'),

	hList=get(hDDPMENUFIG,'Userdata');
	hSetAwaPwaStatus=hList(22);
	AwaPwaStatus=get(hSetAwaPwaStatus,'String');
	if strcmp(AwaPwaStatus,'Amplitude')
		AwaPwaStatus='Phaselock';
		set(hList(21),'String','Open pwa files:'); 
	elseif strcmp(AwaPwaStatus,'Phaselock')
		AwaPwaStatus='Amplitude';
		set(hList(21),'String','Open awa files:'); 
	end
	set(hSetAwaPwaStatus,'String',AwaPwaStatus);
	set(hList(21),'Userdata',[]);
	set(hList(23),'Enable','off');	%Avg
	set(hList(24),'Enable','off');	%Diff
		
elseif strcmp(action,'AvgDDPFiles')

	hList=get(hDDPMENUFIG,'Userdata');
	ResultPath=get(hList(2),'Userdata');
	FileMat=get(hList(21),'Userdata');
	hSetAwaPwaStatus=hList(22);
	AwaPwaStatus=get(hSetAwaPwaStatus,'String');
	[SaveFile,SavePath,SaveFilePath]=GetFileNameOfMat(FileMat,1);
	if strcmp(AwaPwaStatus,'Amplitude')
		initFile='GrandMean.awa';
	elseif strcmp(AwaPwaStatus,'Phaselock')
		initFile='GrandMean.pwa';
	end
	[SaveFile,SavePath,SaveFilePath]=WriteFilePath(initFile,'Choose avg. file name:');
	if ~isempty(ResultPath)
		SaveFilePath=[ResultPath,SaveFile];
	end
	%[DataMat,SaveFilePath,SizeDataMat,NDim,Version,SampRate,AvgRef,StartF0,EndF0,DeltaF0,NTap,SigmaM]=AvgDDPData(FileMat,SaveFilePath);

elseif strcmp(action,'DiffDDPFiles')

	hList=get(hDDPMENUFIG,'Userdata');
	ResultPath=get(hList(2),'Userdata');
	FileMat=get(hList(21),'Userdata');
	hSetAwaPwaStatus=hList(22);
	AwaPwaStatus=get(hSetAwaPwaStatus,'String');
	[SaveFile,SavePath,SaveFilePath]=GetFileNameOfMat(FileMat,1);
	if strcmp(AwaPwaStatus,'Amplitude')
		initFile='Diff.awa';
	elseif strcmp(AwaPwaStatus,'Phaselock')
		initFile='Diff.pwa';
	end
	[SaveFile,SavePath,SaveFilePath]=WriteFilePath(initFile,'Choose diff. file name:');
	if ~isempty(ResultPath)
		SaveFilePath=[ResultPath,SaveFile];
	end
	%[DataMat,SaveFilePath,SizeDataMat,NDim,Version,SampRate,AvgRef,StartF0,EndF0,DeltaF0,NTap,SigmaM]=DiffDDPData(FileMat,SaveFilePath);
	
elseif strcmp(action,'SetResultPath'),

	hList=get(hDDPMENUFIG,'Userdata');
	FileMat=get(hList(1),'Userdata');
	ResultPath=[];
	WriteDlgTitle = 'Save Path';
	WriteDef = {pwd};
	WritePrompt = {'Enter full path to save data:'};
    	while isempty(ResultPath)
	    	WritePath=inputdlg(WritePrompt,WriteDlgTitle,1,WriteDef);
		if isempty(WritePath); return; end
		WritePath=char(WritePath);
		if ~strcmp(WritePath(length(WritePath)),filesep)
			WritePath=[WritePath,filesep];
		end;
		if exist(WritePath)
			ResultPath=WritePath;
		end;
	end;
	disp(ResultPath)
	set(hList(2),'Userdata',ResultPath);
	if ~isempty(FileMat)
		DipDensApp('SetResultFilePath')
	end

elseif strcmp(action,'SetResultFilePath'),

	hList=get(hDDPMENUFIG,'Userdata');
	FileMat=get(hList(1),'Userdata');
	NFiles=size(FileMat,1);
	ResultPath=get(hList(2),'Userdata');
	AwaFileMat=[];
	PwaFileMat=[];
	for FileInd=1:NFiles
		ExtStr=[];
		[File,Path,FilePath]=GetFileNameOfMat(FileMat,FileInd);
		Tmp=findstr(File,'.app');
		if isempty(Tmp)
			Tmp=length(File)+1;
		else
			if Tmp<length(File+5)
				ExtStr=[File(Tmp+4:length(File))];
			end
		end
		if ~isempty(ResultPath); Path=ResultPath; end
		[AwaFileMat]=AddFileName2Mat(AwaFileMat,[Path,File(1:Tmp-1),'.awa',ExtStr],0);
		[PwaFileMat]=AddFileName2Mat(PwaFileMat,[Path,File(1:Tmp-1),'.pwa',ExtStr],0);
	end
	fprintf('Save Amplitude Matrix to file:\n\n')
	disp(AwaFileMat)
	fprintf('\n\n\n')
	fprintf('Save Phaselock Matrix to file:\n\n')
	disp(PwaFileMat)
	set(hList(4),'Userdata',AwaFileMat);
	set(hList(5),'Userdata',PwaFileMat);
	
elseif strcmp(action,'SetStartF0') | ...
	strcmp(action,'SetEndF0') | ...
	strcmp(action,'SetDeltaF0'),	

	hList=get(hDDPMENUFIG,'Userdata');
	SampRate=get(hList(33),'Value');
	NPointsPad=get(hList(35),'Value');
	FFac=SampRate./NPointsPad;
	StartF0=get(hList(9),'Value');
	StartF0Str=get(hList(9),'String');
	EndF0=get(hList(11),'Value');
	EndF0Str=get(hList(11),'String');
	DeltaF0=get(hList(13),'Value');
	DeltaF0Str=get(hList(13),'String');
	
	if strcmp(action,'SetStartF0')
		[StartF0,StartF0Str]=String2Value(StartF0Str,StartF0,0,EndF0,[],1);
		StartF0=FFac.*round(StartF0./FFac);
		set(hList(9),'Value',StartF0,'String',sprintf('%g',round(StartF0.*10^4)./10^4));
	elseif strcmp(action,'SetEndF0')
		[EndF0,EndF0Str]=String2Value(EndF0Str,EndF0,StartF0,[],[],1);
		EndF0=FFac.*round(EndF0./FFac);
		set(hList(11),'Value',EndF0,'String',sprintf('%g',round(EndF0.*10^4)./10^4));
	elseif strcmp(action,'SetDeltaF0')
		[DeltaF0,DeltaF0Str]=String2Value(DeltaF0Str,DeltaF0,0.1,EndF0-StartF0,0,1);
		DeltaF0=FFac.*round(DeltaF0./FFac);
		set(hList(13),'Value',DeltaF0,'String',sprintf('%g',round(DeltaF0.*10^4)./10^4));
	end
	F0FrequVec=[StartF0:DeltaF0:EndF0];
	NF0Vec=length(F0FrequVec);
	StartF0Index=StartF0./FFac+1;
	EndF0Index=EndF0./FFac+1;
	F0IndexVec=[StartF0Index:1:EndF0Index];
	set(hList(41),'Value',NF0Vec,'Userdata',F0FrequVec);
	set(hList(42),'Value',NF0Vec,'Userdata',F0IndexVec);

elseif strcmp(action,'SetNTap'),	

	hList=get(hDDPMENUFIG,'Userdata');
	NTap=get(hList(7),'Value');
	NTapStr=get(hList(7),'String');
	NPoints=get(hList(29),'Value');
	if NPoints==0
		[NTap,NTapStr]=String2Value(NTapStr,NTap,[],[],1);
	else
		[NTap,NTapStr]=String2Value(NTapStr,NTap,0,floor(NPoints./2),1,1);
	end
	set(hList(7),'Value',NTap,'String',NTapStr);
	if NTap==0;
		TapMat=[];
		set(hList(38),'Userdata',TapMat,'Enable','off');
	else
		if NPoints>0
			set(hList(38),'Enable','on');
		end
	end
	
elseif strcmp(action,'SetNStore'),	

	hList=get(hDDPMENUFIG,'Userdata');
	NStore=get(hList(18),'Value');
	NStoreStr=get(hList(18),'String');
	[NStore,NStoreStr]=String2Value(NStoreStr,NStore,1,[],1);
	set(hList(18),'Value',NStore,'String',NStoreStr);
	
elseif strcmp(action,'SetSigmaM'),	

	hList=get(hDDPMENUFIG,'Userdata');
	SigmaM=get(hList(15),'Value');
	SigmaMStr=get(hList(15),'String');
	[SigmaM,SigmaMStr]=String2Value(SigmaMStr,SigmaM,1,10,1,1);
	set(hList(15),'Value',SigmaM,'String',SigmaMStr);
	
elseif strcmp(action,'CalcDDPMat'),	

	hList=get(hDDPMENUFIG,'Userdata');
	NF0Vec=get(hList(42),'Value');
	F0IndexVec=get(hList(42),'Userdata');
	SigmaM=get(hList(15),'Value');
	NPointsPad=get(hList(35),'Value');
	DDPMat=zeros(NPointsPad,NF0Vec);
	for F0Ind=1:NF0Vec
		SigmaF=F0IndexVec(F0Ind)./SigmaM;
		A=1/(sqrt(SigmaF.*sqrt(pi)));
		for PointInd=1:NPointsPad;
			DDPMat(PointInd,F0Ind)=A.*exp(-((PointInd-F0IndexVec(F0Ind)).^2)./(2.*SigmaF.^2));
		end
	end 
	fprintf(1,'Size of DDPlet Matrix: %g x %g\n',NPointsPad,NF0Vec)
	set(hList(25),'Userdata',DDPMat);
	
elseif strcmp(action,'SurfDDPMatFrequ') | strcmp(action,'SurfDDPMatTime'),	

	hList=get(hDDPMENUFIG,'Userdata');
	DipDensApp('CalcDDPMat')
	DDPMat=get(hList(25),'Userdata');
	SampRate=get(hList(33),'Value');
	NPointsPad=get(hList(35),'Value');
	NF0Vec=get(hList(41),'Value');
	F0FrequVec=get(hList(41),'Userdata');
	F0FrequVec=round(F0FrequVec.*100)./100;
	if strcmp(action,'SurfDDPMatFrequ')
		FigPos=[.5 .5 .5 .5];
		Name='DDPlet in Frequency Domain';
		MaxPoint=NPointsPad./2+1;
		MaxY=SampRate./2;
		TmpX=char('Frequency [Hz]:');
		TmpTmpX=char(TmpX,'(Min.-Max. Frequ.)');
		TmpTmpY=char(TmpX,'(0-Nyquist Frequ.)');
	elseif strcmp(action,'SurfDDPMatTime')
		FigPos=[0 .5 .5 .5];
		Name='DDPlet in Time Domain';	
		DDPMat=abs(ifft(DDPMat,NPointsPad,1));
		MaxPoint	=NPointsPad;
		MaxY=NPointsPad.*1000./SampRate;
		TmpX=char('Frequency [Hz]:');
		TmpTmpX=char(TmpX,'(Min.-Max. Frequ.)');
		TmpTmpY=char('Time [ms]:');
	end
	hFig=figure('Units','normal','NumberTitle','off','Position',FigPos,'Name',Name);
	surf(DDPMat(1:MaxPoint,1:NF0Vec))
	axis([1,NF0Vec,1,MaxPoint,min(min(DDPMat)),max(max(DDPMat))])
	XTickVec=get(gca,'xtick');
 	XTickLabelVec=F0FrequVec(XTickVec);
	set(gca,'XTickLabel',XTickLabelVec);
	YTickVec=get(gca,'ytick');
	TmpVec=linspace(0,MaxY,MaxPoint);
	TmpVec=round(TmpVec.*100)./100;
	set(gca,'YTickLabel',TmpVec(YTickVec));
	xlabel(TmpTmpX)
	ylabel(TmpTmpY)
	zlabel('Amplitude [ ]:')
	title(Name)

elseif strcmp(action,'CalcTapMat'),	

	hList=get(hDDPMENUFIG,'Userdata');
	NTap=get(hList(7),'Value');
	NPoints=get(hList(29),'Value');
	NChan=get(hList(27),'Value');
	NChanExtra=get(hList(47),'Value');
	NChanAct=NChan+NChanExtra;
	TapVec1=(cos(linspace(pi./2,pi,NTap)).^2)';
	TapVec2=(cos(linspace(0,pi./2,NTap)).^2)';
	TapMat=ones(NChanAct,NPoints);
	TapMat(:,1:NTap)=TapMat(:,1:NTap)*diag(TapVec1);
	TapMat(:,NPoints-NTap+1:NPoints)=TapMat(:,NPoints-NTap+1:NPoints)*diag(TapVec2);
	set(hList(38),'Userdata',TapMat);

elseif strcmp(action,'SurfTapMat'),	

	hList=get(hDDPMENUFIG,'Userdata');
	DipDensApp('CalcTapMat')
	TapMat=get(hList(38),'Userdata');
	SampRate=get(hList(33),'Value');
	NPoints=get(hList(29),'Value');
	NChanAct=get(hList(27),'Value');
	hFig=figure('Units','normal','NumberTitle','off','Position',[0 .5 .5 .5],'Name','Taper Matrix');
	surf(TapMat)
	axis([1,NPoints,1,NChanAct,min(min(TapMat)),max(max(TapMat))])
	XTickVec=get(gca,'xtick');
	set(gca,'XTickLabel',XTickVec.*1000./SampRate);
	ylabel('Sensor #:')
	xlabel('Time [ms]:')
	zlabel('Amplitude [  ]:')
			
elseif strcmp(action,'RunDDP'),	

	hList=get(hDDPMENUFIG,'Userdata');
	FileMat=get(hList(1),'Userdata');
	NFiles=size(FileMat,1);
	AwaFileMat=get(hList(4),'Userdata');
	PwaFileMat=get(hList(5),'Userdata');
	
	NTap=get(hList(7),'Value');
	StartF0=get(hList(9),'Value');
	EndF0=get(hList(11),'Value');
	DeltaF0=get(hList(13),'Value');
	NF0Vec=get(hList(41),'Value');
	F0FrequVec=get(hList(41),'Userdata')
	SigmaM=get(hList(15),'Value');
	NPoints=get(hList(29),'Value');
	NPointsPad=get(hList(35),'Value');
	SavePhaseStatus=get(hList(16),'Value');
	NStore=get(hList(18),'Value');
	SubERPStatus=get(hList(19),'Value');
	PadDataStatus=get(hList(20),'Value');
	SurfTrialStatus=get(hList(39),'Value');
	SurfERPStatus=get(hList(40),'Value');
	EegMegStatusString=get(hSetEegMegStatus,'String');

	SensorVec=[];
	
	[FileSizeVec]=GetFileSize(FileMat);

	Message=char(zeros(9,1));
	hProgressMsgbox=msgbox(Message,'Progress Info:','help')
	hChildProgressMsgbox=get(hProgressMsgbox,'children');
    hChild2ProgressMsgbox=get(hChildProgressMsgbox(2),'children');
    set(hChildProgressMsgbox(3),'Visible','off');
	
	for FileInd=1:NFiles
		[File,Path,FilePath]=GetFileNameOfMat(FileMat,FileInd);
		FileMessage=char('Calculate DDPlet ...');
		FileMessage=char(FileMessage,'');
		FileMessage=char(FileMessage,['File ',int2str(FileInd),' of ',int2str(NFiles)]);
		FileMessage=char(FileMessage,File);
		FileMessage=char(FileMessage,'');
		if SubERPStatus
			if strcmp(EegMegStatusString,'EEG')
				Message=char(FileMessage,'Calculate evoked potential...');
			else
				Message=char(FileMessage,'Calculate evoked field...');
			end
		else
			Message=FileMessage;
		end
		Message=char(FileMessage,'');
		if strcmp(computer,'SOL2')
	    	set(hChild2ProgressMsgbox,'String',char(FileMessage,''));
		else
			set(hChildProgressMsgbox(2),'String',char(FileMessage,''));
		end
		pause(.001);
		DataMat=[];	
		if  FileSizeVec(FileInd)<10^6
			[DataMat,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,chAvgRef,...
			NonUse,NonUse,NonUse,EegMegStatus,NChanExtra]=ReadAppData(FilePath,'all');
			NChanAct=NChan+NChanExtra;
			set(hList(27),'String',sprintf('%g',NChan));
			set(hList(29),'String',sprintf('%g',NPoints));
			set(hList(31),'String',sprintf('%g',NTrials));
			set(hList(47),'String',sprintf('%g',NChanExtra));
			if isempty(SensorVec)
				SensorVec=[1:NChanAct];  %Sensors to analyze
			end
			DataMat=DataMat(:,SensorVec,:);
		end
		if SubERPStatus
			%  compute ERP
			fprintf(1,'Read data from file:\n');
			fprintf(1,FilePath);
			fprintf(1,'\n');
			if  ~isempty(DataMat)
				ERP=squeeze(mean(DataMat,1));
			else
				[ERP,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,chAvgRef,...
				NonUse,NonUse,NonUse,EegMegStatus,NChanExtra]=ReadAppData(FilePath);
				NChanAct=NChan+NChanExtra;
				for TrialInd =2:NTrials
					fprintf(1,'%g of %g\n',TrialInd,NTrials)
     				[TrialMat]=ReadAppData(FilePath,TrialInd);
     				ERP=ERP+TrialMat;
					if TrialInd==1 | round(TrialInd/10)==TrialInd/10
						if strcmp(computer,'SOL2')
							set(hChild2ProgressMsgbox,'String',char(Message,['Trial ',int2str(TrialInd),' of ',int2str(NTrials),' ...']));
						else
							set(hChildProgressMsgbox(2),'String',char(Message,['Trial ',int2str(TrialInd),' of ',int2str(NTrials),' ...']));
						end
						pause(.001)
					end
     			end
				if isempty(SensorVec)
					SensorVec=[1:NChanAct];  %Sensors to analyze
				end
     			ERP=ERP(SensorVec,:)./NTrials;
			end
			NChanAct=length(SensorVec);
			if SurfERPStatus
				hFig=figure('Units','normal','NumberTitle','off','Position',[0 .5 .5 .5],'Name','Averaged Event Related Potential');
				MinAmp=min(min(ERP));
				MaxAmp=max(max(ERP));
				fprintf('\n\n');
				fprintf('Minimum Amplitude: %g µV\n\n',MinAmp);
				fprintf('Maximum Amplitude: %g µV\n\n',MaxAmp);
				surf(ERP)
				axis([1,NPoints,1,NChanAct,MinAmp,MaxAmp])
				XTickVec=get(gca,'xtick');
				set(gca,'XTickLabel',XTickVec.*1000./SampRate);
				ylabel('Sensor #:')
				xlabel('Time [ms]:')
				zlabel('Amplitude [µV]:')
				title(['Min. Amp: ',sprintf('%g',MinAmp), ' µV;  Max. Amp.: ',sprintf('%g',MaxAmp),' µV'])
				pause(.01)	
			end
		else	%if SubERPStatus
			[NonUse,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,chAvgRef,...
			NonUse,NonUse,NonUse,EegMegStatus,NChanExtra]=ReadAppData(FilePath,0);
			NChanAct=NChan+NChanExtra;
			if isempty(SensorVec)
				SensorVec=[1:NChanAct];  %Sensors to analyze
			end
			if strcmp(computer,'SOL2')
				set(hChild2ProgressMsgbox,'String',Message);
			else
				set(hChildProgressMsgbox(2),'String',Message);
			end
			pause(.001);
		end	%if SubERPStatus
		fprintf(1,'\n');
  		fprintf(1,'Number of sensors: %g \n',NChanAct);
    	fprintf(1,'Number of points: %g\n\n',NPoints);		
		PadMat=zeros(NChanAct,NPointsPad);
		if NTap>0
			DipDensApp('CalcTapMat')
			TapMat=get(hList(38),'Userdata');
		end
		%Calculate DDPlet
		Message=char(FileMessage,'Calculate DDPlet ...');
		if strcmp(computer,'SOL2')
			set(hChild2ProgressMsgbox,'String',Message);
		else
			set(hChildProgressMsgbox(2),'String',Message);
		end
		pause(.001);
		DipDensApp('CalcDDPMat')
		DDPMat=get(hList(25),'Userdata');
		
		SumPower = [];
		AvgDDPPower = [];
		NF0OnesVec=ones(NF0Vec,1);
		AwaMat=zeros(NChanAct,NPoints,NF0Vec);
		RayMat=AwaMat;
		for TrialInd=1:NTrials
			if TrialInd==1 | floor(TrialInd./10)==TrialInd./10
				fprintf(1,'\n')
				fprintf(1,'Trial %g of %g\n',TrialInd,NTrials);
			else
				fprintf(1,'.')
			end
			Message=char(FileMessage,['Trial ',int2str(TrialInd),' of ',int2str(NTrials)]);
			if strcmp(computer,'SOL2')
				set(hChild2ProgressMsgbox,'String',Message);
			else
				set(hChildProgressMsgbox(2),'String',Message);
			end
			pause(.001);
			if isempty(DataMat);
				[TrialMat]=ReadAppData(FilePath,TrialInd);
				TrialMat=TrialMat(SensorVec,:);
			else
				TrialMat=squeeze(DataMat(TrialInd,:,:));
			end
			if NTap>0
				TrialMat=TrialMat.*TapMat;
			end
			if SubERPStatus
				PadMat(:,1:NPoints)=TrialMat-ERP;	% ERP Subtract
			else
				PadMat(:,1:NPoints)=TrialMat;
			end
    			FFTMat=fft(PadMat,NPointsPad,2);
			for ChanInd=1:NChanAct
				TmpMat=(DDPMat.*(NF0OnesVec*FFTMat(ChanInd,:))')';
				TmpMat=(ifft(TmpMat,NPointsPad,2))';
				TmpMat=TmpMat(1:NPoints,:);
				AwaMat(ChanInd,:,:)=abs(TmpMat);
				if SavePhaseStatus == 1
					RayMat(ChanInd,:,:)=TmpMat./squeeze(AwaMat(ChanInd,:,:));
				end
			end
			if TrialInd==1
				SumAwaMat=AwaMat;
				if SavePhaseStatus == 1
		 			SumRayMat=RayMat;
				end
			else 	
				SumAwaMat=SumAwaMat+AwaMat;
				if SavePhaseStatus == 1
					SumRayMat=SumRayMat+RayMat;
				end
			end
			if SurfTrialStatus
				if TrialInd==1
					hFig=figure('Units','normal','NumberTitle','off','Position',[0 0 .5 .5],'Name','Trial 1');
				else
					figure(hFig);
					set(hFig,'Name',['Trial ',sprintf('%g',TrialInd)]);
				end
				MeanMat=squeeze(mean(AwaMat,1))';
				MinAmp=min(min(MeanMat));
				MaxAmp=max(max(MeanMat));
				fprintf('\n\n');
				fprintf('Min. Amplitude: %g\n\n',MinAmp);
				fprintf('Max. Amplitude: %g\n\n',MaxAmp);
				surf(MeanMat)
                axis([1,NPoints,1,NF0Vec,MinAmp,MaxAmp])
				view(0,90)
				shading interp
				XTickVec=get(gca,'xtick');
				XTickLabelVec=XTickVec.*1000./SampRate;
				set(gca,'xtick',XTickVec,'XTickLabel',XTickLabelVec);
				YTickVec=get(gca,'ytick');
 				YTickLabelVec=F0FrequVec(YTickVec);
				set(gca,'ytick',YTickVec,'YTickLabel',YTickLabelVec);
				xlabel('Time [ms]:')
				ylabel('Frequency [Hz]:')
				title(['Min. Amp: ',sprintf('%g',MinAmp),';  Max. Amp.: ',sprintf('%g',MaxAmp)])
				pause(.01)	
% 					hFigChild=get(hFig,'children');
% 					hFigChildChild=get(hFigChild,'children');
% 				else
% 					set(hFig,'Name',['Trial ',sprintf('%g',TrialInd)]);
% 					set(hFigChildChild,'ZData',MeanMat);
% 					set(hFigChildChild,'SpecularColorReflectance',1)
% 					pause(.01)
% 				end
			end
		end
		if NStore ~= 1 
			fprintf(1,'Resize Matrix:\n\n')
			SumAwaMat=SumAwaMat(:,[1:NStore:NPoints],:);
			if SavePhaseStatus == 1
				SumRayMat=SumRayMat(:,[1:NStore:NPoints],:);
			end
		end;
		SumAwaMat= SumAwaMat./NTrials;
		if SavePhaseStatus == 1
			PhaseMat=abs(SumRayMat./NTrials);
		end
		[AwaFile,AwaPath,AwaFilePath]=GetFileNameOfMat(AwaFileMat,FileInd);
		SaveDDPletData(SumAwaMat,AwaFilePath,[],[],[],SampRate,chAvgRef,StartF0,EndF0,DeltaF0,NTap,SigmaM,EegMegStatus,NChanExtra,1);
		if SavePhaseStatus == 1
			[PlfFile,PlfPath,PlfFilePath]=GetFileNameOfMat(PwaFileMat,FileInd);
			SaveDDPletData(PhaseMat,PlfFilePath,[],[],[],SampRate,chAvgRef,StartF0,EndF0,DeltaF0,NTap,SigmaM,EegMegStatus,NChanExtra,2);
		end
	end
	Message=char('');
	Message=char(Message,'');
	Message=char(Message,'DDP calculation completed.');
	if strcmp(computer,'SOL2')
		set(hChild2ProgressMsgbox,'String',Message);
	else
		set(hChildProgressMsgbox(2),'String',Message);
	end
	set(hChildProgressMsgbox(3),'Visible','on');
else
  	disp(sprintf('DipDensApp: action string ''%s'' not recognized, no action taken.',action))
end,
return;

%=====================================================================================
function [Pointer]=GetPointer;

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