function [] = EditAEM(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.                                                                      

global hAllFig EditMatTmp

% Possible actions and button callbacks:
%   InitializeMenu
%   firstcalculations
%	ResetThreshold
%	setKindThresFac

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

MatlabVersionString=version;						
MainMatlabVersion=str2num(MatlabVersionString(1));
if MainMatlabVersion<5
	fprintf('\n'); clc;
    fprintf('EditAEM kann nur nur unter Matlab5 gestartet werden !!!\n\n');
   	fprintf('EditAEM4 kann nur nur unter Matlab4 gestartet werden !!!');
    return;
end

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

	
if strcmp(action,'firstcalculations')
	
	%==================================
	hList=get(hAllFig,'Userdata');
	
	EditMat=get(hList(7),'Userdata');
	NChan=get(hList(43),'Userdata');
	NTrials=get(hList(44),'Userdata');
	PlotChanStatusVec=get(hList(10),'Userdata');
	PlotChanVec=find(PlotChanStatusVec==1);

	ch_ThetaCorr=get(hList(28),'value');
	if ch_ThetaCorr
		ThetaCorrVec=get(hList(28),'Userdata');
	end
	
	ch_NoiseCorr=get(hList(29),'value');
	if ch_NoiseCorr
		NoiseCorrVec=get(hList(29),'Userdata');
	end

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

	if ch_ThetaCorr
		for TrialInd=1:NTrials
			EditMat(:,TrialInd)=EditMat(:,TrialInd)./ThetaCorrVec;
		end
	end	
	if ch_NoiseCorr
		for TrialInd=1:NTrials
			EditMat(:,TrialInd)=EditMat(:,TrialInd)./NoiseCorrVec;
		end
	end
	set(hList(7),'Userdata',EditMat);

	%==================================
	MinEditMat=(min(EditMat(PlotChanVec,:)'))';
	MinMinEditMat=min(MinEditMat);
	MinMinEditMat=round(MinMinEditMat.*100)./100;
	set(hList(3),'Userdata',MinMinEditMat,'String',sprintf('%g',MinMinEditMat));
	EditMatTmp=EditMat;
	EditMatTmp(EditMatTmp>999999)=0;
	MaxEditMat=(max(EditMatTmp(PlotChanVec,:)'))';
	MaxMaxEditMat=max(MaxEditMat);
	MaxMaxEditMat=round(MaxMaxEditMat.*100)./100;
	MeanEditMat=(mean(EditMatTmp(PlotChanVec,:)'))';
	MeanMeanEditMat=mean(MeanEditMat);
	MedEditMat=(median(EditMatTmp(PlotChanVec,:)'))';
	MedMedEditMat=median(MedEditMat);
	DefaultMaxViewFac=4;
	set(hList(4),'Userdata',DefaultMaxViewFac.*MedMedEditMat,'String',sprintf('%g',DefaultMaxViewFac.*MedMedEditMat)); %MaxView

	set(hList(35),'Userdata',MinEditMat);
	set(hList(36),'Userdata',MaxEditMat);
	set(hList(37),'Userdata',MeanEditMat);
	set(hList(38),'Userdata',MedEditMat);
	set(hList(39),'Userdata',MinMinEditMat);
	set(hList(40),'Userdata',MaxMaxEditMat);
	set(hList(41),'Userdata',MeanMeanEditMat);
	set(hList(42),'Userdata',MedMedEditMat);

  	EditAEM('CalcThresVec');

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

	%==================================
	
	hList=get(hAllFig,'Userdata');
	KindThresFac=get(hList(2),'Userdata');
	ThresFac=get(hList(5),'Userdata');
	ThresVec=get(hList(8),'Userdata');
	
	ChangedThStatusVec=get(hList(9),'Userdata');
	ChangedThIndVec=find(ChangedThStatusVec==1);
	NotChangedThIndVec=find(ChangedThStatusVec==0);
		
	KindEditMat=get(hList(26),'Userdata');
	
	MinEditMat=get(hList(35),'Userdata');
	MaxEditMat=get(hList(36),'Userdata');
	MeanEditMat=get(hList(37),'Userdata');
	MedEditMat=get(hList(38),'Userdata');
	MinMinEditMat=get(hList(39),'Userdata');
	MaxMaxEditMat=get(hList(40),'Userdata');
	MeanMeanEditMat=get(hList(41),'Userdata');
	MedMedEditMat=get(hList(42),'Userdata');

	EStVec=get(hList(53),'Userdata'); 
	
	if ~strcmp(KindEditMat,'Flat') & ~isempty(NotChangedThIndVec)	
		if strcmp(KindThresFac,'MeanVec');
			ThresVec(NotChangedThIndVec)=ones(length(NotChangedThIndVec),1).*MeanEditMat(NotChangedThIndVec).*ThresFac;
		elseif strcmp(KindThresFac,'MeanVal');
			ThresVec(NotChangedThIndVec)=ones(length(NotChangedThIndVec),1).*ThresFac.*MeanMeanEditMat;
			SpecVal=ThresFac.*MeanMeanEditMat;
			set(hList(20),'Userdata',SpecVal,'String',sprintf('%g',SpecVal));
		elseif strcmp(KindThresFac,'MedianVec');
			ThresVec(NotChangedThIndVec)=ones(length(NotChangedThIndVec),1).*MedEditMat(NotChangedThIndVec).*ThresFac;
		elseif  strcmp(KindThresFac,'MedianVal');
			ThresVec(NotChangedThIndVec)=ones(length(NotChangedThIndVec),1).*ThresFac.*MedMedEditMat;
			SpecVal=ThresFac.*MedMedEditMat;
			set(hList(20),'Userdata',SpecVal,'String',sprintf('%g',SpecVal));
		elseif  strcmp(KindThresFac,'SpecVal');
			ThresVec(NotChangedThIndVec)=ones(length(NotChangedThIndVec),1).*ThresFac;
			SpecVal=ThresFac;
			set(hList(20),'Userdata',SpecVal,'String',sprintf('%g',SpecVal));
		end
		if ~isempty(EStVec);
			BadChanVec=find(EStVec==0);
			if ~isempty(BadChanVec)
				ThresVec(BadChanVec)=zeros(size(BadChanVec));
				ChangedThStatusVec(BadChanVec)=ones(size(BadChanVec));
				set(hList(9),'Userdata',ChangedThStatusVec);
			end
		end
	end
	if strcmp(KindEditMat,'Flat')
		ThresVec(NotChangedThIndVec)=0.5.*ones(length(NotChangedThIndVec),1);
	end
	set(hList(8),'Userdata',ThresVec);
	hhAxesVec=get(hList(11),'Userdata');
	if hhAxesVec==0
		EditAEM('InitializeChannels');
	else
		EditAEM('UpdateDisplay');
	end
	EditAEM('SaveTVMFile');
	
elseif strcmp(action,'InitializeChannels'),

	hList=get(hAllFig,'Userdata');
	hAllChanAxes=hList(1);
	KindThresFac=get(hList(2),'Userdata');
	ThresFac=get(hList(5),'Userdata');
	EditMat=get(hList(7),'Userdata');
	NChan=get(hList(43),'Userdata');
	NTrials=get(hList(44),'Userdata');
	MinView=get(hList(3),'Userdata');
	MaxView=get(hList(4),'Userdata');
	set(hList(4),'Userdata',MaxView,'String',sprintf('%g',MaxView));
	ThresVec=get(hList(8),'Userdata');
	ChangedThStatusVec=get(hList(9),'Userdata');
	PlotChanStatusVec=get(hList(10),'Userdata');
	KindEditMat=get(hList(26),'Userdata');
	AvgRefStatus=get(hList(51),'Userdata');
	MaxYbMedFac=get(hList(49),'Userdata');
	MatlabVersionString=version;
	MainMatlabVersion=str2num(MatlabVersionString(1));
	
	ECfgFile=[int2str(NChan) '.ecfg'];
    ECfgFilePath=which(ECfgFile);
	
	if ECfgFilePath==0 | strcmp(ECfgFilePath,'..')
		[ECfgPath,ECfgPath,ECfgFilePath]=ReadFilePath([],ECfgFile,['Look for file:' ECfgFile]);
	end

	[NChan,SpherRadius,EPosSpher,ENames,EConfigFile,EConfigPath,EConfigFilePath]=ReadEConfig(ECfgFilePath);
	[kTop,AxesTop,kFront,AxesFront,kBack,AxesBack,kLeft,...
	AxesLeft,kRight,AxesRight,kNorm,AxesNorm,kAll,AxesAll,...
	TopStatusVec,FrontStatusVec,BackStatusVec,LeftStatusVec,RightStatusVec,NormStatusVec,AllStatusVec] = ...
	Calc2dTimeAxes(EPosSpher,PlotChanStatusVec);
	AxesAllXFac=0.75;
	hw=13;
	AxesAll=AxesAll.*hw./(hw+1);
	for ChanInd=1:NChan	
		AxesPosMat(ChanInd,:)=[AxesAll(ChanInd,1).*AxesAllXFac,AxesAll(ChanInd,2),1/hw.*AxesAllXFac,1/hw];
	end
	
    % Set up the special channel axes
	Nx=50;
	NxTmp=4.*Nx;
	x=linspace(MinView,MaxView,Nx); 
    hBarVec=zeros(NChan,1);
    xbMat=zeros(NChan,NxTmp);
    ybMat=zeros(NChan,NxTmp);
	for ChanInd=1:NChan
		[n,x]=hist(EditMat(ChanInd,:),x);
        hBar=bar(x,n);   
        set(hBar,'Visible','off');
        xb=get(hBar,'XData');
        yb=get(hBar,'YData');
        xbMat(ChanInd,:)=reshape(xb,1,NxTmp);
        ybMat(ChanInd,:)=reshape(yb,1,NxTmp);
		MaxYbVec(ChanInd)=max(max(yb));
	end
	MaxYb=MaxYbMedFac.*median(MaxYbVec);
	set(hAllChanAxes,'Color',[0 0 0]);
	%==================================
	LREarFontSize=20;
    LeftEarStart1=.05;
    LeftEarStart2=.405;
    RightEarStart1=.9;
    RightEarStart2=.405;
    if ~isempty(NChan)
        if NChan>255
            LeftEarStart1=.15;
            LeftEarStart2=.45;
            RightEarStart1=.8;
            RightEarStart2=.45;
        end
    end
	hText5(1)=text('Units','normal','Position',[LeftEarStart1 LeftEarStart2],'Color','w','FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','left','Visible','on','String','Left');	%Left (Ear)
	hText5(2)=text('Units','normal','Position',[LeftEarStart1 LeftEarStart2-.03],'Color','w','FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','left','Visible','on','String','Ear');	% (Left) Ear
	hText5(3)=text('Units','normal','Position',[RightEarStart1 RightEarStart2],'Color','w','FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','left','Visible','on','String','Right');	%Right (Ear)
	hText5(4)=text('Units','normal','Position',[RightEarStart1 RightEarStart2-.03],'Color','w','FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','left','Visible','on','String','Ear');	%(Right) Ear
	hText5(5)=text('Units','normal','Position',[.5 .975],'Color','w','FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','center','Visible','on','String','Nose');	% Nose
	hText5(6)=text('Units','normal','Position',[.3 .89],'Color','w','FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','center','Visible','on','String','Left Eye');	% Left Eye
	hText5(7)=text('Units','normal','Position',[.7 .89],'Color','w','FontSize',LREarFontSize,'FontWeight','bold',...
	'HorizontalAlignment','center','Visible','on','String','Right Eye');	% Right Eye

	text('Units','normal','Position',[.02 .07],'HorizontalAlignment','Left','Color','g','FontSize',10,'String','Number of Good Trials:');
	text('Units','normal','Position',[.02 .055],'HorizontalAlignment','Left','Color','r','FontSize',10,'String','Number of  Bad  Trials:');
	text('Units','normal','Position',[.02 .04],'HorizontalAlignment','Left','Color','w','FontSize',10,'String','Good / Total Trials x 100 %:');
	text('Units','normal','Position',[.02 .025],'HorizontalAlignment','Left','Color','m','FontSize',10,'String','Sensor #:');
   	text('Units','normal','Position',[.02 .01],'HorizontalAlignment','Left','Color','w','FontSize',10,'String','File:');
	KindEditFile=get(hList(30),'Userdata');
	if strcmp(KindEditFile,'AEM');
		FilePath=get(hList(23),'Userdata');
	elseif strcmp(KindEditFile,'TVM');
		FilePath=get(hList(24),'Userdata');
	end
	hFilePathText=text('Units','normal','Position',[.075 .01],'HorizontalAlignment','Left','Color','w','FontSize',10,'String',FilePath);
	%==================================
	for ChanInd=1:NChan
		SpecThres=ThresVec(ChanInd);
        xb=xbMat(ChanInd,:);
        yb=ybMat(ChanInd,:);
		hAxesVec(ChanInd)=axes('Units','normal','Position',AxesPosMat(ChanInd,:),'Box','off','XLim',[MinView MaxView],'YLim',[0 MaxYb]);
		hDataVec(ChanInd)=line('XData',xb,'YData',yb,'Color','y','LineStyle','-');
		hBotLine(ChanInd)=line('XData',[xb(1) xb(length(xb))],'YData',[0 0],'Color','w','LineStyle','-');
		if ChangedThStatusVec(ChanInd); ThresLineColor='b'; else; ThresLineColor='r'; end
		hThresLine(ChanInd)=line('XData',[SpecThres SpecThres],'YData',[0 MaxYb],'Color',ThresLineColor,'LineStyle','--');
		if strcmp(KindEditMat,'Absolute') | strcmp(KindEditMat,'Maximum Std') | strcmp(KindEditMat,'Transit') | strcmp(KindEditMat,'Flat');
			GoodTrials=find(EditMat(ChanInd,:)<SpecThres);
		elseif strcmp(KindEditMat,'Minimum Std');
			GoodTrials=find(EditMat(ChanInd,:)>SpecThres);
		end
		NGoodTrials=length(GoodTrials);
		NBadTrials=NTrials-NGoodTrials;
		GoodTrialsPH=round(NGoodTrials./NTrials.*100);
		hThText1(ChanInd)=text('Position',[SpecThres .5.*MaxYb],'String',num2str(GoodTrialsPH),'FontSize',[12],'Color','w','HorizontalAlignment','left');
		hThText2(ChanInd)=text('Position',[SpecThres .66.*MaxYb],'String',num2str(NBadTrials),'FontSize',[12],'Color','r','HorizontalAlignment','left');
		hThText3(ChanInd)=text('Position',[SpecThres .82.*MaxYb],'String',num2str(NGoodTrials),'FontSize',[12],'Color','g','HorizontalAlignment','left');
		if ChangedThStatusVec(ChanInd); ChanTextColor='b'; else; ChanTextColor='m'; end
		hThText4(ChanInd)=text('Position',[SpecThres .34.*MaxYb],'String',[num2str(ChanInd)],'FontSize',[12],'Color',ChanTextColor,'HorizontalAlignment','left');
		axis('off');
	end

	set(hList(11),'Userdata',hAxesVec);
	set(hList(22),'Userdata',AxesPosMat);
	set(hList(12),'Userdata',hDataVec);
	set(hList(13),'Userdata',hBotLine);
	set(hList(14),'Userdata',hThresLine);
	set(hList(15),'Userdata',hThText1);
	set(hList(16),'Userdata',hThText2);
	set(hList(17),'Userdata',hThText3);
	set(hList(18),'Userdata',hThText4);
	set(hList(19),'Userdata',MaxYbVec);
	set(hList(46),'Userdata',xbMat);
	set(hList(47),'Userdata',ybMat);
	set(hList(48),'Userdata',MaxYb);
	set(hList(60),'Userdata',EPosSpher);
	set(hList(62),'Userdata',hFilePathText);
	%====================================
    %====================================

elseif strcmp(action,'InitializeMenu'),

	%====================================
    %====================================
	%==================================
	
	ChanFigString=['Choose threshold:'];
    hAllFig=figure('Units','normal',...
		'Position',[0 0 0.8 1], ...
		'Color',[0 0 0],...
        'Name',ChanFigString, ...
        'NumberTitle','off');
	hAllChanAxes=axes('Position',[0 0 .75 1],'Visible','off');
    hFigVec(1)=hAllFig;
		
    % Information for all buttons (and menus)
    labelColor=[0.8 0.8 0.8];
    yInitPos=0.90;
    menutop=0.95;
    btnTop = 0.6;
    top=0.75;
    left=0.785;
    btnWid=0.175;
    btnHt=0.04;
    textHeight = 0.05;
    textWidth = 0.06;
    % Spacing between the button and the next command's label
    spacing=0.019;

    %====================================
    % The CONSOLE frame
    frmBorder=0.019; frmBottom=0.04; 
    frmHeight = 0.92; frmWidth = btnWid;
    yPos=frmBottom-frmBorder;
    frmPos=[left-frmBorder yPos frmWidth+2*frmBorder frmHeight+2*frmBorder];
	ConsoleRGBColor=[0.3 0 0.3];
    hConsolFrame=uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',frmPos, ...
		'BackgroundColor',ConsoleRGBColor);

    %====================================
    % The Kind of thres fac Selection Menu
	
    btnNumber=1;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid/2 btnHt];
    labelStr='MeanVec|MeanVal|MedianVec|MedianVal|SpecVal';
    callbackStr='EditAEM(''setKindThresFac'')';

    hKindThresFac=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Userdata','MedianVec',...
		'Value',3,...
        'Callback',callbackStr);

    %====================================
    % The Close Figures Menu
	
    btnNumber=1;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid/2 yPos-btnHt btnWid/2 btnHt];
    labelStr='All except main|All';
    callbackStr='EditAEM(''CloseFigures'')';

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

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

    btnPos=[left+btnWid./2 yPos-btnHt./2 btnWid./2 1.*btnHt./2];
	callbackStr = 'EditAEM(''setMinView'')';
    
	hMinView = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Userdata',0, ...
        'callback',callbackStr);

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

	% MaxViewHandle
    
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt./2];
	callbackStr = 'EditAEM(''setMaxView'')';
    
	hMaxView = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Userdata',0, ...
        'callback',callbackStr);

    %===================================
 	% ThFacTextHandle
    
	btnNumber=3;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt./2 btnWid./2 btnHt./2];
    
	h = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Thres Fac:');
    
    btnPos=[left+btnWid./2 yPos-btnHt./2 btnWid./2 btnHt./2];
	callbackStr = 'EditAEM(''setThresFac'')';
    
	hThresFac = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','1.5',...
		'Userdata',1.5, ...
        'callback',callbackStr);
 	
	%===================================
 	% SpecValTextHandle
    
	btnNumber=3;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid btnHt./2];
    
	h = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Spec Val:');
    
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt./2];
	callbackStr = 'EditAEM(''setSpecVal'')';
    
	hSpecVal = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0','Userdata',0, ...
        'callback',callbackStr);

	%===================================
 	% Std Factor
    
	btnNumber=4;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt./2 btnWid./2 btnHt./2];
    
	hStdFacText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Std. Factor:');
    
    btnPos=[left+btnWid./2 yPos-btnHt./2 btnWid./2 btnHt./2];
	callbackStr = 'EditAEM(''setStdFac'')';
    if strcmp(computer,'SOL2')
        StdFacVal=3;
    else
        StdFacVal=3;
    end
	hStdFacMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String',int2str(StdFacVal),...
		'Value',StdFacVal, ...
        'callback',callbackStr);
	
	%===================================
 	% Std Exponent
    
	btnNumber=4;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt./2];
    
	hStdExpText = uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','left', ...
        'Foreground','black', ...
        'String','Std. Exponent:');
    
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt./2];
	callbackStr = 'EditAEM(''setStdExp'')';
    
	hStdExpMenu = uicontrol( ...
        'Style','edit', ...
        'Units','normalized', ...
		'Position',btnPos, ...
        'Horiz','center', ...
        'Background','white', ...
        'Foreground','black', ...
        'String','0.25',...
		'Value',0.25, ...
        'callback',callbackStr);
		
	%GoalMat(ChanInd,SpecThresInd)=sqrt(NGoodTrials)./StdVal.^StdExp;
	%====================================
	
   	% Update Display push button 
	btnNumber=5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt/2 btnWid./2 btnHt./2];
	callbackStr = 'EditAEM(''UpdateDisplay'')';
   
    hUpdateDisplay=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Update Display:', ...
        'Callback',callbackStr);
	
    %====================================
	
   	% Fast Auto Edit I push button 
	btnNumber=5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt./2];
	callbackStr = 'EditAEM(''FastAutoEdit1'')';
   
    hFastAutoEdit1=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Fast Auto I', ...
        'Callback',callbackStr);
			
	%====================================
	
   	% Fast Auto Edit II push button 
	btnNumber=5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt./2 btnWid./2 btnHt./2];
	callbackStr = 'EditAEM(''FastAutoEdit2'')';
   
    hFastAutoEdit2=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Fast Auto II', ...
        'Callback',callbackStr);
	
	%====================================
	
   	% Fast Auto Edit III push button 
	btnNumber=5;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt./2];
	callbackStr = 'EditAEM(''FastAutoEdit3'')';
   
    hFastAutoEdit3=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Fast Auto III', ...
        'Callback',callbackStr);
		
    %====================================
    % ResetThreshold push button 
	btnNumber=6;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''ResetThreshold'')';
   
    hResetThres=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Reset thresholds:', ...
        'Callback',callbackStr);
	
	 %====================================
    % SetThreshold push button 
	btnNumber=6;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''SetThreshold'')';
   
    hSetThres=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Set thresholds:', ...
        'Callback',callbackStr);
		
	%====================================
    % Info EditMat push button 
	btnNumber=7;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''InfoEditMat'')';
   
    hInfoEditMat=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Edit Mat.:', ...
		'Userdata',0,...
        'Callback',callbackStr);
	
	%====================================
    % Info ThresVec push button 
	btnNumber=7;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''InfoThresVec'')';
   
    hInfoThresVec=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Thres. Vec.:', ...
		'Userdata',0,...
        'Callback',callbackStr);
	
	%====================================
    % Info ChangedThStatusVec push button 
	btnNumber=8;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid btnHt];
	callbackStr = 'EditAEM(''InfoChangedThStatusVec'')';
   
    hInfoChangedThStatusVec=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Info ChangedThStatus:', ...
		'Userdata',0,...
        'Callback',callbackStr);
	
	%====================================
    % Info PlotChanStatusVec push button 
	btnNumber=9;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid btnHt];
	callbackStr = 'EditAEM(''InfoPlotChanStatusVec'')';
	 hInfoPlotChanStatusVec=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Info PlotChanStatus:', ...
		'Userdata',0,...
        'Callback',callbackStr);
	
	%====================================
    % ChangeAccAllThresInter  push button 
	btnNumber=10;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''AccChangeAllThresInter'')';
	hAccChangeAllThresInter=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Edit Precise:', ...
        'Callback',callbackStr);
	%====================================
    
	% ChangeFastAllThresInter  push button 
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''FastChangeAllThresInter'')';
	hFastChangeAllThresInter=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Edit Fast:', ...
        'Callback',callbackStr);
	
	%====================================
    %====================================
    if strcmp(computer,'SOL2')
        AvgRefStr='No Avg. Ref.';
        AvgRefUserData=0;
    else
        AvgRefStr='Avg. Ref.';
        AvgRefUserData=1;
    end
    % ChangeAccAllThresInter  push button 
	btnNumber=11;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''SetAvgRefStatus'')';
	hSetAvgRefStatus=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',AvgRefStr, ...
		'Userdata',AvgRefUserData, ...
        'Callback',callbackStr);
	
	%====================================
    %====================================
    % SetMinSensorMaxStdStatus  push button 
	btnNumber=11;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''SetMinSensorMaxStdStatus'')';
	hSetMinSensorMaxStdStatus=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Max. Std.', ...
		'Userdata',1, ...
        'Callback',callbackStr);
		
	%====================================
	% ChangeSpecThresInter radio button 
	btnNumber=12;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''ChangeSpecChanThres'')';
	hChangeSpecChanThres=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Spec. Sensor:', ...
		 'value',0,'Userdata',0, ...
        'Callback',callbackStr);
		
	%====================================
    
	% Result path push button 
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''SetResultPath'')';
	hSetResultPath=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Result path:', ...
		'Userdata',[], ...
        'Callback',callbackStr);
		
	%====================================
    
	% Open AEM File push button 
	btnNumber=13;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''OpenAEMFile'')';
	hOpenAEMFile=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Open AEM file:', ...
		'Userdata','0', ...
        'Callback',callbackStr);
	%====================================
    
	% Open TVM File push button 
	btnNumber=13;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''OpenTVMFile'')';
	hOpenTVMFile=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Open TVM file:', ...
		'Userdata','0', ...
        'Callback',callbackStr);
	%====================================

	% Save TVM - File push button 
	btnNumber=14;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''SaveTVMFile'')';
	hSaveTVMFile=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Save TVM-file:', ...
		'Userdata','0', ...
        'Callback',callbackStr);
	
	%====================================

	% Save WE-File push button 
	btnNumber=14;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''SaveWEFile'')';
	hSaveWEFile=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Save WE-file:', ...
		'Userdata','0', ...
        'Callback',callbackStr);
	
	%====================================
    % The Kind of EditMat Selection Menu
	
    btnNumber=15;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
    labelStr='Absolute|Minimum Std|MaximumStd|Transit|Flat';
    callbackStr='EditAEM(''setKindEditMat'')';

    hKindEditMat=uicontrol( ...
        'Style','popupmenu', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String',labelStr, ...
        'Interruptible','on', ...
		'Userdata','Absolute',...
		'Value',1,...
        'Callback',callbackStr);
	
	%====================================
    % The Kind of EditMat Selection Menu
	
    btnNumber=15;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
    callbackStr='EditAEM(''AutoEdit'')';

    hAutoEdit=uicontrol( ...
        'Style','pushbutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Auto Edit', ...
        'Interruptible','on', ...
        'Callback',callbackStr);
		
	%====================================
	
   	% ch_ThetaCorr radio button 
	btnNumber=16;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''ChoiceThetaCorr'')';
	hChoiceThetaCorr=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Theta Corr.:', ...
		 'value',0,'Userdata',0, ...
        'Callback',callbackStr);
		
	%====================================
	
   	% ch_NoiseCorr radio button 
	btnNumber=16;
    yPos=menutop-(btnNumber-1)*(btnHt+spacing);
    btnPos=[left+btnWid./2 yPos-btnHt btnWid./2 btnHt];
	callbackStr = 'EditAEM(''ChoiceNoiseCorr'')';
	hChoiceNoiseCorr=uicontrol( ...
        'Style','radiobutton', ...
        'Units','normalized', ...
        'Position',btnPos, ...
        'String','Noise Corr.:', ...
		 'value',0,'Userdata',0, ...
        'Callback',callbackStr);

	%====================================
	%====================================
	
	
	hhAxesVec=uicontrol('Userdata',0,'Visible','off');
	hAxesPosMat=uicontrol('Userdata',0,'Visible','off');
	hhDataVec=uicontrol('Userdata',0,'Visible','off');
	hhBotLine=uicontrol('Userdata',0,'Visible','off');
	hhThresLine=uicontrol('Userdata',0,'Visible','off');
	hhThText1=uicontrol('Userdata',0,'Visible','off');
	hhThText2=uicontrol('Userdata',0,'Visible','off');
	hhThText3=uicontrol('Userdata',0,'Visible','off');
	hhThText4=uicontrol('Userdata',0,'Visible','off');
	hMaxYbVec=uicontrol('Userdata',0,'Visible','off');
	KindEditFile=uicontrol('Userdata','0','Visible','off');
	hThetaCorrVec=uicontrol('Userdata','0','Visible','off');
	hNoiseCorrVec=uicontrol('Userdata','0','Visible','off');
	hChanEditStatusMat=uicontrol('Userdata','0','Visible','off');
	hWeightTrialStatus=uicontrol('Userdata','0','Visible','off');
	hAvgRefStatus=uicontrol('Userdata','0','value',0,'Visible','off');
	hMinEditMat=uicontrol('Userdata','0','value',0,'Visible','off'); 
	hMaxEditMat=uicontrol('Userdata','0','value',0,'Visible','off'); 
	hMeanEditMat=uicontrol('Userdata','0','value',0,'Visible','off'); 
	hMedEditMat=uicontrol('Userdata','0','value',0,'Visible','off'); 
	hMinMinEditMat=uicontrol('Userdata','0','value',0,'Visible','off'); 
	hMaxMaxEditMat=uicontrol('Userdata','0','value',0,'Visible','off'); 
	hMeanMeanEditMat=uicontrol('Userdata','0','value',0,'Visible','off'); 
	hMedMedEditMat=uicontrol('Userdata','0','value',0,'Visible','off'); 
	hNChan=uicontrol('Userdata','0','Visible','off'); 
	hNTrials=uicontrol('Userdata','0','Visible','off'); 
	hNoUse=uicontrol('Userdata','0','Visible','off'); 
	hxbMat=uicontrol('Userdata','0','Visible','off'); 
	hybMat=uicontrol('Userdata','0','Visible','off'); 
	hMaxYb=uicontrol('Userdata',0,'Visible','off');
	hMaxYbMedFac=uicontrol('Userdata',1.5,'Visible','off');
	hEStVec=uicontrol('Visible','off');
	LambdaApprox=0.02;
	hInvCoeff=uicontrol('Value',LambdaApprox,'Visible','off');
	hAllEPosSpher=uicontrol('Visible','off');
	hHistFigVec=uicontrol('Visible','off');
    hFilePathText=uicontrol('Visible','off'); 
	
	hList=[hAllChanAxes hKindThresFac hMinView hMaxView hThresFac ...
		hResetThres hInfoEditMat hInfoThresVec hInfoChangedThStatusVec hInfoPlotChanStatusVec ...
		hhAxesVec hhDataVec hhBotLine hhThresLine hhThText1 ...
		hhThText2 hhThText3 hhThText4 hMaxYbVec hSpecVal ...
		hChangeSpecChanThres hAxesPosMat hOpenAEMFile hOpenTVMFile hSaveTVMFile ...					%25
		hKindEditMat hAvgRefStatus hChoiceThetaCorr hChoiceNoiseCorr KindEditFile ...
		hSaveWEFile hSetThres hChanEditStatusMat hWeightTrialStatus hMinEditMat ...
		hMaxEditMat hMeanEditMat hMedEditMat hMinMinEditMat hMaxMaxEditMat ...
		hMeanMeanEditMat hMedMedEditMat hNChan hNTrials hNoUse ...
		hxbMat hybMat hMaxYb hMaxYbMedFac hSetResultPath ...										%50
		hSetAvgRefStatus hSetMinSensorMaxStdStatus hEStVec hAutoEdit hInvCoeff ...
		hStdFacText hStdFacMenu hStdExpText hStdExpMenu hAllEPosSpher ...
		hHistFigVec hFilePathText hCloseFigures];										
	
    set(hAllFig,'Visible','on','UserData',hList);
	%====================================
	%====================================
	
elseif strcmp(action,'ReadCoeff'),

	hList=get(hAllFig,'Userdata');
	NChan=get(hList(43),'Userdata');
	LambdaApprox=get(hList(55),'Value');

	CoeffPathTmp=what('Plot3dCoeff40');
	CoeffPath=getfield(CoeffPathTmp,'path');
	if strcmp(CoeffPath(length(CoeffPath)),filesep);CoeffPath=CoeffPath(1:length(CoeffPath)-1); end
	LegPathTmp=what('Plot3dLegCoeff');
	LegPath=getfield(LegPathTmp,'path');
	if strcmp(LegPath(length(LegPath)),filesep); LegPath=LegPath(1:length(LegPath)-1); end
	ECfgPathTmp=what('SensorCfg');
	ECfgPath=getfield(ECfgPathTmp,'path');
	if strcmp(ECfgPath(length(ECfgPath)),filesep); ECfgPath=ECfgPath(1:length(ECfgPath)-1); end
		
	ECfgFile=[int2str(NChan) '.ecfg'];
	ECfgFilePath=[ECfgPath,filesep,ECfgFile];
	fidECfg=fopen(ECfgFilePath,'r');
	
	fprintf('Start reading of file...\n\n');
	fprintf(ECfgFilePath)
	fprintf('\n\n');
	[NChan,count]=fread(fidECfg,1,'int16');	
	[ScalpRadius,count]=fread(fidECfg,1,'float32');
	[TmpSpher,count]=fread(fidECfg,[NChan,2],'float32');
	fclose(fidECfg);
	AllEPosSpher=zeros(NChan,3);
	AllEPosSpher(:,1:2)=TmpSpher(1:NChan,:);
	AllEPosSpher(:,3)=ScalpRadius.*ones(NChan,1);
	AllEPosCart = change_sphere_cart(AllEPosSpher,ScalpRadius,1);
	[InvCoeff] = ReadOrCalcCoeff(1,AllEPosCart,AllEPosCart,LegPath,CoeffPath,ECfgFile,32,15, 0, 5001);
	set(hList(55),'Userdata',InvCoeff);
	set(hList(60),'Userdata',AllEPosSpher);
    
elseif strcmp(action,'CloseFigures'),
    
    hList=get(hAllFig,'Userdata');
    hCloseFig=hList(63);
    CloseFigStatus=get(hCloseFig,'Value');
    hFigVec=get(hCloseFig,'Userdata')
    if CloseFigStatus==2
        for i=2:length(hFigVec)
            if hFigVec(i)>0
                close(hFigVec(i));
            end
        end
        close(hFigVec(1));
        hFigVec=[];
    elseif CloseFigStatus==1 & length(hFigVec)>1
        for i=2:length(hFigVec)
            if hFigVec(i)>0 & i~=7
                close(hFigVec(i));
            end
        end
        hFigVec=hFigVec(1);
    end
    
elseif strcmp(action,'FastAutoEdit1') | strcmp(action,'FastAutoEdit2') | strcmp(action,'FastAutoEdit3'),

	hList=get(hAllFig,'Userdata');
    if strcmp(action,'FastAutoEdit1')
        EditAEM('OpenAEMFile');
    end
	EditAEM('AutoEdit');
    pause(.01);
	set(hList(26),'Value',3);	%KindEditVal; Max. Std
	EditAEM('setKindEditMat');
	if strcmp(action,'FastAutoEdit3'),
		set(hList(26),'Value',4);	%KindEditVal; Transit
		EditAEM('setKindEditMat');
	end
	EditAEM('SaveWEFile');
	
elseif strcmp(action,'AutoEdit'),

	hList=get(hAllFig,'Userdata');
	MinView=get(hList(3),'Userdata');
	MaxView=get(hList(4),'Userdata');
	EditMat=get(hList(7),'Userdata');
	NChan=get(hList(43),'Userdata');
	NTrials=get(hList(44),'Userdata');
	ThresVec=get(hList(8),'Userdata');
	ChangedThStatusVec=get(hList(9),'Userdata');
	StdFac=get(hList(57),'Value');
	StdExp=get(hList(59),'Value');
	KindEditVal=get(hList(26),'Value');
	KindEditStr=get(hList(26),'Userdata');
	LambdaApprox=get(hList(55),'Value');
	InvCoeff=get(hList(55),'Userdata');
    hFigVec=get(hList(63),'Userdata');
	if isempty(InvCoeff);
		EditAEM('ReadCoeff');InvCoeff=get(hList(55),'Userdata');
	end
% 	InvCoeff=InvCoeff+eye(NChan).*LambdaApprox.*InvCoeff(1,1);
	NThresInd=100;
	SpecThresVec=linspace(MinView,MaxView,NThresInd);
	MedVec=median(EditMat');
	
	for ChanInd=1:NChan
		StartIndVec=find(SpecThresVec>MedVec(ChanInd));
		if ~isempty(StartIndVec)
			StartInd=StartIndVec(1);
			for SpecThresInd=StartInd:NThresInd
				GoodTrials=find(EditMat(ChanInd,:)<SpecThresVec(SpecThresInd));	
				NGoodTrials=length(GoodTrials);
 				StdVal=std(EditMat(ChanInd,GoodTrials));
				GoalMat(ChanInd,SpecThresInd)=sqrt(NGoodTrials)./StdVal.^StdExp;
			end
		end
	end
	
	PenVec=zeros(NChan,1);
	[ThresValVec,ThresIndVec]=max(GoalMat');
	ZeroIndVec=find(ThresValVec==0);
	NotZeroIndVec=find(ThresValVec);
	NNotZeroIndVec=length(NotZeroIndVec);
	OnesNNotZeroIndVec=ones(1,NNotZeroIndVec);
	WeightMat=InvCoeff(NotZeroIndVec,NotZeroIndVec);
	WeightMat=(WeightMat-min(min(WeightMat)).*ones(size(WeightMat)));
	WeightMat=WeightMat./max(max(WeightMat));
	for ChanInd=1:NNotZeroIndVec
		AbsDiffTmp=abs(OnesNNotZeroIndVec.*ThresValVec(NotZeroIndVec(ChanInd))-ThresValVec(NotZeroIndVec));
		WeightVec=WeightMat(:,ChanInd)';
		PenVec(NotZeroIndVec(ChanInd))=sum(AbsDiffTmp.*WeightVec)./sum(WeightVec);
	end
	MedPenVec=median(PenVec(NotZeroIndVec));
	StdPenVec=std(PenVec(NotZeroIndVec));
	BadIndVec=find(PenVec>MedPenVec+StdFac.*StdPenVec);
	if KindEditVal==1 | KindEditVal==2 | KindEditVal==5
		FigPosVec=[0.66 0 0.33 .33];
	elseif KindEditVal==3
		FigPosVec=[0.66 0.33 0.33 .33];
	elseif KindEditVal==4
		FigPosVec=[0.66 0.66 0.33 .33];
    end
    KindEditVal=KindEditVal
	hThresFig=figure('Units','normal','Position',FigPosVec,'Name',['Sum of Diff. of "' KindEditStr '" Thresholds:'],'NumberTitle','off');
	hFigVec(1+KindEditVal)=hThresFig
    set(hList(63),'Userdata',hFigVec);
    plot(PenVec)
	hold on
	plot(BadIndVec,PenVec(BadIndVec),'x')
	plot(ZeroIndVec,PenVec(ZeroIndVec),'x')
	plot([0 NChan],[MedPenVec MedPenVec],'g--');
	plot([0 NChan],[MedPenVec+StdFac.*StdPenVec MedPenVec+StdFac.*StdPenVec],'r--');
	axis([0 NChan 0 1.1.*max(PenVec)])
	xlabel('Sensor #')
	pause(.01)
	ThresVec=PenVec;
	for ChanInd=1:length(NotZeroIndVec)
		ThresVec(NotZeroIndVec(ChanInd))=SpecThresVec(ThresIndVec(NotZeroIndVec(ChanInd)))+MinView;
	end
	ThresVec(BadIndVec)=zeros(size(BadIndVec));
	set(hList(8),'Userdata',ThresVec);
 	set(hList(9),'Userdata',ones(NChan,1));
	EditAEM('UpdateDisplay');
	
elseif strcmp(action,'SetMinSensorMaxStdStatus'),

	hList=get(hAllFig,'Userdata');
	MinSensorMaxStdStatus=get(hList(52),'Userdata');
	if MinSensorMaxStdStatus
		MinSensorMaxStdStatus=0;
		set(hList(52),'String','Min. Sensors.','Userdata',MinSensorMaxStdStatus);
	else
		MinSensorMaxStdStatus=1;
		set(hList(52),'String','Max. Std','Userdata',MinSensorMaxStdStatus);
	end
	
elseif strcmp(action,'SetAvgRefStatus'),

	hList=get(hAllFig,'Userdata');
	AvgRefStatus=get(hList(51),'Userdata');
	if AvgRefStatus
		AvgRefStatus=0;
		set(hList(51),'String','No Avg. Ref.','Userdata',AvgRefStatus);
	else
		AvgRefStatus=1;
		set(hList(51),'String','Avg. Ref.','Userdata',AvgRefStatus);
	end
	
elseif strcmp(action,'SetResultPath'),

	hList=get(hAllFig,'Userdata');
	ResultPath=[];
    while isempty(ResultPath)
		Message=char('Please choose a path');
		Message=char(Message,'in which you would like to save');
		Message=char(Message,'the result files and press "Save" !');
		hmsgbox=msgbox(Message,'info','help'); 
		[NonUse,ResultPath] = uiputfile('Test@', 'Result path:');
		close(hmsgbox)
		if ResultPath==0; ResultPath=[]; end
     end
	set(hList(50),'Userdata',ResultPath);
	
elseif strcmp(action,'OpenAEMFile'),

	hList=get(hAllFig,'Userdata');
	AvgRefStatus=get(hList(51),'Userdata');
	if AvgRefStatus; 
		FileExt='*.AEM.AR'; 
		String='Choose the AEM.AR file:';
	else; 
		FileExt='*.AEM'; 
		String='Choose the AEM file:';
	end
	DefFilePath=SetDefPath(1,FileExt);
	[AEMFile,AEMPath,AEMFilePath]=ReadFilePath([],DefFilePath,String);
	if AEMFile==0; return; end
	SetDefPath(2,AEMPath);
    hFilePathText=get(hList(62),'Userdata');  
    set(hFilePathText,'String',AEMFilePath);    %AEMFilePath
	set(hList(30),'Userdata','AEM');
	set(hList(23),'Userdata',AEMFilePath);
% 	hFileText=text('Position',[0.05 0.05],'HorizontalAlignment','left','FontSize',12,'Visible','on','Color','w','String',AEMFile)
% 	get(hFileText)
	fid=fopen(AEMFilePath,'r');
	NChan=fread(fid,1,'int16');
	set(hList(43),'Userdata',NChan);
	NTrials=fread(fid,1,'int16');
	set(hList(44),'Userdata',NTrials);
	EditMat=fread(fid,[NChan,NTrials],'float32');
	set(hList(7),'Userdata',EditMat);
	set(hList(8),'Userdata',zeros(NChan,1));           %ThresVec
	set(hList(9),'Userdata',zeros(NChan,1));           %ChangedThStatusVec
	set(hList(10),'Userdata',ones(NChan,1));           %PlotChanStatusVec
	set(hList(28),'Userdata',ones(NChan,1),'value',0); %ThetaCorrVec
	set(hList(29),'Userdata',ones(NChan,1),'value',0); %NoiseCorrVec

	KindEditMat=get(hList(26),'Userdata');
	set(hList(26),'Userdata','Absolute','Value',1);
	EstExt=['*.' int2str(NChan) 'est'];
	DefFilePath=[AEMPath,EstExt];
	[EStFile,EStPath,EStFilePath]=ReadFilePath([],DefFilePath,'Choose sensor status file (optional):');
	EstVec=[];
	if EStFile~=0;
		EstFid=fopen(EStFilePath,'r');
		if EstFid~=-1
			[EstVec,Count]=fread(EstFid,NChan,'int16');
			fclose(EstFid);
			if Count~=NChan
				EstVec=[];
			end
		end
	end
	set(hList(53),'Userdata',EstVec);

	EditAEM('firstcalculations');
	
elseif strcmp(action,'OpenTVMFile'),

	hList=get(hAllFig,'Userdata');
	AvgRefStatus=get(hList(51),'Userdata');
	if AvgRefStatus; 
		FileMask='*.TVM.AR'; 
		String='Choose the TVM.AR file:';
	else; 
		Mask='*.TVM'; 
		String='Choose the TVM file:';
	end
	[TVMFile,TVMPath,TVMFilePath]=ReadFilePath([],FileMask,String);
	if TVMFile==0; return; end
	set(hList(30),'Userdata','TVM');
	set(hList(24),'Userdata',TVMFilePath);
	fidTVM=fopen(TVMFilePath,'r');
	NChan=fread(fidTVM,1,'int16');
	set(hList(43),'Userdata',NChan);
	NTrials=fread(fidTVM,1,'int16');
	set(hList(44),'Userdata',NTrials);
	EditMat=fread(fidTVM,[NChan,NTrials],'float32');
	set(hList(7),'Userdata',EditMat);
	fseek(fidTVM,3.*4+3.*NChan.*NTrials.*4,'cof'); %2 * int16 NChan.*NTrials float32
	
	ThresVec=fread(fidTVM,NChan,'float32');
	set(hList(8),'Userdata',ThresVec);
	ChangedThStatusVec=fread(fidTVM,NChan,'int16');
	set(hList(9),'Userdata',ChangedThStatusVec);
	PlotChanStatusVec=fread(fidTVM,NChan,'int16');
	set(hList(10),'Userdata',PlotChanStatusVec);
	ThetaCorrVec=fread(fidTVM,NChan,'float32');
	set(hList(28),'Userdata',ThetaCorrVec);
	NoiseCorrVec=fread(fidTVM,NChan,'float32');
	set(hList(29),'Userdata',NoiseCorrVec);
	ch_ThetaCorr=fread(fidTVM,1,'int8');
	set(hList(28),'value',ch_ThetaCorr);
	ch_NoiseCorr=fread(fidTVM,1,'int8');
	set(hList(29),'value',ch_NoiseCorr);

	fclose(fidTVM);
	set(hList(26),'Userdata','Absolute','value',1); %KindEditMat
	
	EditAEM('firstcalculations');

elseif strcmp(action,'SaveTVMFile'),
	
	hList=get(hAllFig,'Userdata');
	KindEditFile=get(hList(30),'Userdata');
	ResultPath=get(hList(50),'Userdata');	
	AEMFilePath=get(hList(23),'Userdata');
	if ~strcmp(KindEditFile,'TVM')
		AvgRefStatus=get(hList(51),'Userdata');
		if isempty(ResultPath)
			TVMFilePath=AEMFilePath;
		else
			[AEMFile,AEMPath]=SepFilePath(AEMFilePath);
			TVMFilePath=[ResultPath,AEMFile];
		end
		LTVMFilePath=length(TVMFilePath);		
		if AvgRefStatus
			TVMFilePath(LTVMFilePath-5:LTVMFilePath-3)='TVM';
		else
			TVMFilePath(LTVMFilePath-2:LTVMFilePath)='TVM';
		end
		set(hList(24),'Userdata',TVMFilePath);
	else
		TVMFilePath=get(hList(24),'Userdata');
	end
	EditMat=get(hList(7),'Userdata');
	NChan=get(hList(43),'Userdata');
	NTrials=get(hList(44),'Userdata');
	ThresVec=get(hList(8),'Userdata');
	ChangedThStatusVec=get(hList(9),'Userdata');
	PlotChanStatusVec=get(hList(10),'Userdata');
	ch_ThetaCorr=get(hList(28),'value');
	ThetaCorrVec=get(hList(28),'Userdata');
	ch_NoiseCorr=get(hList(29),'value');
	NoiseCorrVec=get(hList(29),'Userdata');
	PlotChanStatusVec=get(hList(10),'Userdata');
	fidTVM=fopen(TVMFilePath,'r');
	NMat=4;
	if fidTVM==-1; 
		fidAEM=fopen(AEMFilePath,'r');
		fidTVM=fopen(TVMFilePath,'w');
		for MatInd=1:4	%NMAt
			NChan=fread(fidAEM,1,'int16');
			NTrials=fread(fidAEM,1,'int16');
			fwrite(fidTVM,NChan,'int16');
			fwrite(fidTVM,NTrials,'int16');
			EditMat=fread(fidAEM,[NChan NTrials],'float32');
			fwrite(fidTVM,EditMat,'float32');
		end	
		for MatInd=1:5	%NMat+minimumstd
			fwrite(fidTVM,zeros(NChan,1),'float32');
			fwrite(fidTVM,zeros(NChan,1),'int16');
			fwrite(fidTVM,ones(NChan,1),'int16');
			fwrite(fidTVM,ones(NChan,1),'float32');
			fwrite(fidTVM,ones(NChan,1),'float32');				%Alles NChan.*(4+2+2+4+4)+1+1
			fwrite(fidTVM,0,'int8');
			fwrite(fidTVM,0,'int8');
		end
		fclose(fidAEM);
	end
	fclose(fidTVM);
	fidTVM=fopen(TVMFilePath,'r+');
	
	fseek(fidTVM,NMat.*4+NMat.*4.*NChan.*NTrials,'bof');
		
	KindEditMat=get(hList(26),'Userdata');
	if strcmp(KindEditMat,'Absolute');			SeekFac=0;
	elseif strcmp(KindEditMat,'Minimum Std');	SeekFac=1;
	elseif strcmp(KindEditMat,'Maximum Std'); 	SeekFac=2;
	elseif strcmp(KindEditMat,'Transit'); 		SeekFac=3;
	elseif strcmp(KindEditMat,'Flat'); 			SeekFac=4;
	end

	fseek(fidTVM,SeekFac.*(NChan.*(4+2+2+4+4)+1+1),'cof');

	fwrite(fidTVM,ThresVec,'float32');
	fwrite(fidTVM,ChangedThStatusVec,'int16');
	fwrite(fidTVM,PlotChanStatusVec,'int16');
	fwrite(fidTVM,ThetaCorrVec,'float32');
	fwrite(fidTVM,NoiseCorrVec,'float32');				%Alles NChan.*(4+2+2+4+4)+1+1
	fwrite(fidTVM,ch_ThetaCorr,'int8');
	fwrite(fidTVM,ch_NoiseCorr,'int8');

	fclose(fidTVM);
	set(hList(30),'Userdata','TVM');

elseif strcmp(action,'SaveWEFile'),
	
	EditAEM('SaveTVMFile');
	EditAEM('CalcWEMat');
	
	hList=get(hAllFig,'Userdata');
	WeightEditMat=get(hList(32),'Userdata');
	NChan=get(hList(43),'Userdata');
	NTrials=get(hList(44),'Userdata');	
	ResultPath=get(hList(50),'Userdata');	
    hFigVec=get(hList(63),'Userdata');

%	hFigWeightEditMat=figure('Units','normal','Position',[0.66 0.66 0.33 .33], ...
%   'Name','Info WeightEditMat:', ...
%   'NumberTitle','off');
%	surf(WeightEditMat)
%	xlabel('Trial:')
%	ylabel('Channel:')

	ChanEditStatusMat=get(hList(33),'Userdata');
	
%	hFigChanEditStatusMat=figure('Units','normal','Position',[0.66 0.33 0.33 .33], ...
%   'Name','Info ChanEditStatusMat:', ...
%   'NumberTitle','off');
%	surf(ChanEditStatusMat)
%	xlabel('Trial:')
%	ylabel('Channel:')
	
	WeightTrialStatus=get(hList(34),'Userdata');
	ChanEditStatusMat=get(hList(33),'Userdata');
	hFigWeightTrialStatus=figure('Units','normal','Position',[0 0 1 .2], ...
      'Name','Info WeightTrialStatus:', ...
      'NumberTitle','off');
    hFigVec(1+5+2)=hFigWeightTrialStatus;
    set(hList(63),'Userdata',hFigVec);    

	GoodTrialVec=find(WeightTrialStatus);
	BadTrialVec=find(WeightTrialStatus==0);
	plot(GoodTrialVec,WeightTrialStatus(GoodTrialVec),'*g')
	hold on
	plot(BadTrialVec,WeightTrialStatus(BadTrialVec),'xr')
	axis([1 length(WeightTrialStatus) -.1 1.1])
	xlabel('Trial #')

	KindEditFile=get(hList(30),'Userdata');
	if strcmp(KindEditFile,'AEM')
		TmpFilePath=get(hList(23),'Userdata');
	elseif strcmp(KindEditFile,'TVM');
		TmpFilePath=get(hList(24),'Userdata');
	end
	AvgRefStatus=get(hList(51),'Userdata');
	if AvgRefStatus
		PutExt='.AR.WE';
		NGetExt=7;
	else
		PutExt='.WE';
		NGetExt=4;
	end
	if ~isempty(ResultPath)
		[TmpFile,TmpPath]=SepFilePath(TmpFilePath);
		TmpFilePath=[ResultPath,TmpFile];
	end
	[WEFilePath]=FileNameExt2Mat(TmpFilePath,PutExt,NGetExt);
	fidWE=fopen(WEFilePath,'w');
	if fidWE~=-1
		fprintf('\n\n')
		fprintf('Save Weight Edit Matrix to file:\n')
		fprintf(WEFilePath)
		fwrite(fidWE,NChan,'int16');
		fwrite(fidWE,NTrials,'int16');
		fwrite(fidWE,WeightEditMat,'int16');
		fwrite(fidWE,ChanEditStatusMat,'int16');
		fwrite(fidWE,WeightTrialStatus,'int16');
		fclose(fidWE);
	else
		fprintf('\n\n')
		fprintf('Problems to open WE file !\n')
	end

elseif strcmp(action,'CalcWEMat') | strcmp(action,'CalcWEMatShort') 

	hList=get(hAllFig,'Userdata');
	TVMFilePath=get(hList(24),'Userdata');
	fidTVM=fopen(TVMFilePath,'r');
	NChan=fread(fidTVM,1,'int16');
	NTrials=fread(fidTVM,1,'int16');
	MinSensorMaxStdStatus=get(hList(52),'Userdata');
	AllEPosSpher=get(hList(60),'Userdata');
    hFigVec=get(hList(63),'Userdata');

	WeightEditMat=ones(NChan,NTrials);		%Die weight Matrix ist per default eine Ones Matrix =>alle Kanaele in allen trials wuerden genutzt
	ChanEditStatusMat=zeros(NChan,NTrials);	%Dies ist die Status Matrix, um die farbliche Kennzeichnung der Kanaele im Edit Menue zu bstimmen
											%0 falls der Kanal o.k ist
											%1 falls der Kanal auf Grund einer flat line nicht gewertet wird. 
											%2 falls der Kanal in Bezug zur absoluten Groesse schlecht gewertet wird. 
											%3 falls der Kanal in Bezug zur transit Groesse schlecht gewertet wird. 
											%4 falls der Kanal in Bezug zur std Groesse schlecht gewertet wird. 
											%5 falls 2 und 3, 6 falls 2 und 4 etc.
	AbsEditMat=fread(fidTVM,[NChan,NTrials],'float32');
	fseek(fidTVM,4,'cof');
	StdEditMat=fread(fidTVM,[NChan,NTrials],'float32');
	fseek(fidTVM,4,'cof');
	TraEditMat=fread(fidTVM,[NChan,NTrials],'float32');
	fseek(fidTVM,4,'cof');
	FlaEditMat=fread(fidTVM,[NChan,NTrials],'float32');
	
	EditMatStatus=zeros(4,1);
	
	AbsThresVec=fread(fidTVM,NChan,'float32');
	AbsChangedThStatusVec=fread(fidTVM,NChan,'int16');
	if ~all(AbsChangedThStatusVec==0); EditMatStatus(1)=1; end
	AbsPlotChanStatusVec=fread(fidTVM,NChan,'int16');
	AbsThetaCorrVec=fread(fidTVM,NChan,'float32');
	AbsNoiseCorrVec=fread(fidTVM,NChan,'float32');
	Absch_ThetaCorr=fread(fidTVM,1,'int8');
	Absch_NoiseCorr=fread(fidTVM,1,'int8');
	
	MinStdThresVec=fread(fidTVM,NChan,'float32');
	MinStdChangedThStatusVec=fread(fidTVM,NChan,'int16');
	if ~all(MinStdChangedThStatusVec==0); EditMatStatus(2)=1; end
	MinStdPlotChanStatusVec=fread(fidTVM,NChan,'int16');
	MinStdThetaCorrVec=fread(fidTVM,NChan,'float32');
	MinStdNoiseCorrVec=fread(fidTVM,NChan,'float32');
	MinStdch_ThetaCorr=fread(fidTVM,1,'int8');
	MinStdch_NoiseCorr=fread(fidTVM,1,'int8');
	
	MaxStdThresVec=fread(fidTVM,NChan,'float32');
	MaxStdChangedThStatusVec=fread(fidTVM,NChan,'int16');
	if ~all(MaxStdChangedThStatusVec==0); EditMatStatus(2)=1; end
	MaxStdPlotChanStatusVec=fread(fidTVM,NChan,'int16');
	MaxStdThetaCorrVec=fread(fidTVM,NChan,'float32');
	MaxStdNoiseCorrVec=fread(fidTVM,NChan,'float32');
	MaxStdch_ThetaCorr=fread(fidTVM,1,'int8');
	MaxStdch_NoiseCorr=fread(fidTVM,1,'int8');
	
	TraThresVec=fread(fidTVM,NChan,'float32');
	TraChangedThStatusVec=fread(fidTVM,NChan,'int16');
	if ~all(TraChangedThStatusVec==0); EditMatStatus(3)=1; end
	TraPlotChanStatusVec=fread(fidTVM,NChan,'int16');
	TraThetaCorrVec=fread(fidTVM,NChan,'float32');
	TraNoiseCorrVec=fread(fidTVM,NChan,'float32');
	Trach_ThetaCorr=fread(fidTVM,1,'int8');
	Trach_NoiseCorr=fread(fidTVM,1,'int8');
	
	FlatThresVec=fread(fidTVM,NChan,'float32');
	FlatChangedThStatusVec=fread(fidTVM,NChan,'int16');
	if ~all(FlatChangedThStatusVec==0); EditMatStatus(4)=1; end
	FlatPlotChanStatusVec=fread(fidTVM,NChan,'int16');
	FlatThetaCorrVec=fread(fidTVM,NChan,'float32');
	FlatNoiseCorrVec=fread(fidTVM,NChan,'float32');
	Flatch_ThetaCorr=fread(fidTVM,1,'int8');
	Flatch_NoiseCorr=fread(fidTVM,1,'int8');

	fclose(fidTVM);
	
	if EditMatStatus(1)==1
		for TrialInd=1:NTrials
			BadChanVec=find(AbsEditMat(:,TrialInd)>AbsThresVec);
			if ~isempty(BadChanVec)
				WeightEditMat(BadChanVec,TrialInd)=zeros(length(BadChanVec),1);
				%	Wird fuer jeden einzelnen guten Kanal pro Trial um 1 groesser 
				ChanEditStatusMat(BadChanVec,TrialInd)=2.*ones(size(BadChanVec));
			end
		end
	end	
	if EditMatStatus(2)==1
		for TrialInd=1:NTrials
			BadChanVec=find(StdEditMat(:,TrialInd)>MaxStdThresVec | StdEditMat(:,TrialInd)<MinStdThresVec);
			if ~isempty(BadChanVec)
				WeightEditMat(BadChanVec,TrialInd)=zeros(length(BadChanVec),1);
				ChanEditStatusMat(BadChanVec,TrialInd)=3.*ones(size(BadChanVec))+ChanEditStatusMat(BadChanVec,TrialInd);
			end
		end
	end
	if EditMatStatus(3)==1
		for TrialInd=1:NTrials
			BadChanVec=find(TraEditMat(:,TrialInd)>TraThresVec);
			if ~isempty(BadChanVec)
				WeightEditMat(BadChanVec,TrialInd)=zeros(length(BadChanVec),1);
				ChanEditStatusMat(BadChanVec,TrialInd)=4.*ones(size(BadChanVec))+ChanEditStatusMat(BadChanVec,TrialInd);
			end
		end
	end
	if EditMatStatus(4)==1
		if any(EditMatStatus(1:3)==1)
			WeightEditMat=WeightEditMat.*FlaEditMat;
		else
			WeightEditMat=FlaEditMat;
		end
		[j,k]=find(FlaEditMat==0);
		for i=1:length(j)
			ChanEditStatusMat(j(i),k(i))=1;
		end
	end

	set(hList(32),'Userdata',WeightEditMat);
	set(hList(33),'Userdata',ChanEditStatusMat);

	if strcmp(action,'CalcWEMatShort'); return; end
	
	NMinGoodChan=round(2*NChan/3);
	SumWeightEditMat=sum(WeightEditMat);	%Dies ist die Summe ueber alle NChan und daher NTrials lang
	MaxSumWeightEditMat=max(SumWeightEditMat);
	GlobExtChanVal=NChan-MaxSumWeightEditMat;
	NBadChanVecVec=NChan.*ones(1,NTrials)-SumWeightEditMat;
	NNoBadChanVecIndVec=find(SumWeightEditMat==NChan);
	if MinSensorMaxStdStatus==0				%Min good sensors
		MedString=' ;  Median of good channels per trial: ';
		MeanString=' ;  Mean of good channels per trial:   ';
		MinString='Minimum number of good channels: ';
		GlobExtChanString='Number of globally extracted channels: ';
		MinWeightString=' ;  Actual threshold: ';
		MaxWeightString='Maximum number of channels to approximate with actual threshold:';
		HistFigName='Number of trials per number of good channels:';
		BadChanMaxStdFigName='Number of bad channels by trial #:';
		NNot2BadChanVecIndVec=[1:NTrials];
	elseif MinSensorMaxStdStatus==1			%Max. Std.
		LambdaApprox=get(hList(55),'Value');
		InvCoeff=get(hList(55),'Userdata');
		if isempty(InvCoeff) | isempty(AllEPosSpher);
			EditAEM('ReadCoeff');InvCoeff=get(hList(55),'Userdata');
		end
		[ENames]=SetENames([],NChan);
		ForCoeff=InvCoeff';
		InvCoeff=InvCoeff+eye(NChan).*LambdaApprox.*InvCoeff(1,1);
		SumWeightEditSplineMat=zeros(1,NTrials);
		NChan2=NChan.^2;
		AllChanOnes=ones(1,NChan);
		Message=char('');
		Message=char(Message,'Calculate standard deviation of');
		Message=char(Message,'spherical spline approximation');
		Message=char(Message,'for all given trials based on');
		Message=char(Message,'given sensor thresholds.');
		Message=char(Message,['(Lambda=' num2str(LambdaApprox) ')']);
		Message=char(Message,'');
		MessageTmp=char(Message,'');
		MessageTmp=char(MessageTmp,'');
		hmsgbox=msgbox(MessageTmp,'Info:','help');
        hChildMsgbox=get(hmsgbox,'children');
        hChild2Msgbox=get(hChildMsgbox(2),'children')
		set(hChildMsgbox(3),'Visible','off');
      	pause(.01);
		
		N2BadChanVecIndVec=find(NBadChanVecVec>NChan-NMinGoodChan)
		NNot2BadChanVecIndVec=find(NBadChanVecVec<=NChan-NMinGoodChan);
		SqrtSumSumForCoeff2=sqrt(sum(sum(ForCoeff.^2)));
		%===========================================================================
		%TrialInd==1
		GoodChanVec=find(WeightEditMat(:,1)==1); NGoodChan=length(GoodChanVec);
		TmpDataMat=ForCoeff(GoodChanVec,:);	
		c0Vec=mean(TmpDataMat);	
		TmpDataMat=TmpDataMat-(c0Vec'*ones(1,NGoodChan))';
		DipStrength = InvCoeff(GoodChanVec,GoodChanVec) \ TmpDataMat;
		TmpDataMat=(DipStrength' * ForCoeff(GoodChanVec,:))';
		TmpDataMat=TmpDataMat+(c0Vec'*AllChanOnes)';
		SumWeightEditSplineMat(1)=sqrt(sum(sum((TmpDataMat-ForCoeff).^2)))./SqrtSumSumForCoeff2;
		%TrialInd>1
		for TrialInd=2:NTrials
			GoodChanVec=find(WeightEditMat(:,TrialInd)==1); NGoodChan=length(GoodChanVec);
			if NGoodChan>=NMinGoodChan & NGoodChan<NChan
				Tmp=sum(abs(WeightEditMat(:,1:TrialInd-1)-diag(WeightEditMat(:,TrialInd))*ones(NChan,TrialInd-1)));
				Ind=find(Tmp==0)
				if ~isempty(Ind) %Is already calculated
					SumWeightEditSplineMat(TrialInd)=SumWeightEditSplineMat(Ind(1));
				else
					TmpDataMat=ForCoeff(GoodChanVec,:);	
					c0Vec=mean(TmpDataMat);	
					TmpDataMat=TmpDataMat-(c0Vec'*ones(1,NGoodChan))';
					DipStrength = InvCoeff(GoodChanVec,GoodChanVec) \ TmpDataMat;
					TmpDataMat=(DipStrength' * ForCoeff(GoodChanVec,:))';
					TmpDataMat=TmpDataMat+(c0Vec'*AllChanOnes)';
					SumWeightEditSplineMat(TrialInd)=sqrt(sum(sum((TmpDataMat-ForCoeff).^2)))./SqrtSumSumForCoeff2;
				end
			end	
			if round(TrialInd./25)==TrialInd./25
				fprintf('\n');
				fprintf('Trial %g of %g trials done ...  ',TrialInd,NTrials);
				MessageTmp=char(Message,'');
				MessageTmp=char(Message,['Trial ',sprintf('%g',TrialInd),' of ',sprintf('%g',NTrials),' trials done ...']);
				if strcmp(computer,'SOL2')
					set(hChild2Msgbox,'String',MessageTmp);
				else
					set(hChildMsgbox(2),'String',MessageTmp);
				end
                pause(.01)
			else
				fprintf('.');
			end
		end
		close(hmsgbox)
		Not2BadSumWeightEditSplineMat=SumWeightEditSplineMat(NNot2BadChanVecIndVec);
		MaxSumWeightEditSplineMat=max(SumWeightEditSplineMat);
		MinSumWeightEditSplineMat=min(Not2BadSumWeightEditSplineMat);
		SumWeightEditSplineMat(N2BadChanVecIndVec)=10^10.*ones(1,length(N2BadChanVecIndVec));
		%===========================================================================
		%===========================================================================
		SumWeightEditMat=SumWeightEditSplineMat;
		MedString=' ;  Median Std of approximation: ';
		MeanString=' ;  Mean Std of approximation:   ';
		GlobExtChanString='Number of globally extracted channels: ';
		MinWeightString=' ;  Actual Std. threshold: ';
		MaxWeightString=[];
		HistFigName='Number of trials per std of approximation:';
		BadChanMaxStdFigName='Std. of approximation by trial #:';
	end
	NNot2BadChanVecIndVec
	MinSumWeightEditMat=min(SumWeightEditMat(NNot2BadChanVecIndVec));
	MaxSumWeightEditMat=max(SumWeightEditMat(NNot2BadChanVecIndVec));
	MedSumWeightEditMat=median(SumWeightEditMat(NNot2BadChanVecIndVec));
	MeanSumWeightEditMat=mean(SumWeightEditMat(NNot2BadChanVecIndVec));
	again=1;FirstPlot=1;
	if MinSensorMaxStdStatus==0				%Min good channels
		MinWeightEdit=round(.95.*MaxSumWeightEditMat);
		GoodTrials=find(SumWeightEditMat>MinWeightEdit);
	elseif MinSensorMaxStdStatus==1			%Max. Std.
		MinWeightEdit=MedSumWeightEditMat;
		GoodTrials=find(SumWeightEditMat<MinWeightEdit);
	end
	NGoodTrials=length(GoodTrials);
	NBadTrials=NTrials-NGoodTrials;
	WeightTrialStatus=zeros(NTrials,1);
	WeightTrialStatus(GoodTrials)=ones(NGoodTrials,1);
	
	BadChanMaxStdFig=figure('Units','normal','NumberTitle','off','Position',[0,0,.75,.5],'Name',BadChanMaxStdFigName,'Color',[.9 .9 .9]);
	if MinSensorMaxStdStatus==0				%Min good Sensors
		plot(NBadChanVecVec,'r')
		ylabel('Number of bad channels')
		axis([1 NTrials 0 NMinGoodChan])
	elseif MinSensorMaxStdStatus==1			%Max. Std.
		plot(SumWeightEditSplineMat); 
		hold on
		plot(N2BadChanVecIndVec,zeros(size(N2BadChanVecIndVec)),'x')
		ylabel('Std. of approximation')	
		axis([1 NTrials 0 MaxSumWeightEditSplineMat])
	end
	
	xlabel('Trial #:')

	HistFig=figure('Units','normal','NumberTitle','off','Position',[0,.5,.75,.5],'Name',HistFigName,'Color',[.9 .9 .9]);
	hFigVec(1+5+1)=HistFig;
    set(hList(63),'Userdata',hFigVec);    

    HistFigVec(1)=HistFig;
	hAxes=axes('Position',[0 0 1 1]); 
	HistFigVec(2)=hAxes;
%  	btnPos=[.7 .01 .25 .05];
% 	callbackStr = 'Plot2d(''SetHistFigXAxis'')';
% 	hSetHistFigXAxis=uicontrol( ...
%         'Style','slider', ...
%         'Units','normalized', ...
%         'Position',btnPos, ...
%         'String','Cursor', ...
% 		'HorizontalAlignment','center',...
% 		'Userdata',[], ...
% 		'Min',0, ...
% 		'Max',.2, ...
% 		'SliderStep',[.01 .1], ...
% 		'Value',.06, ...
%         'Callback',callbackStr,...
% 		'Enable','on');
% 	HistFigVec(3)=hSetHistFigXAxis;
	
	axis('off');
	hText1_1=text('Units','normal','Position',[.02 .96],'String','Number of bad trials with actual threshold:','FontSize',[12],'Color','k','HorizontalAlignment','left');
	hText1_2=text('Units','normal','Position',[.43 .96],'String',[num2str(NBadTrials)],'FontSize',[12],'Color','r','HorizontalAlignment','left');
	hText2_1=text('Units','normal','Position',[.02 .92],'String','Number of good trials with actual threshold:','FontSize',[12],'Color','k','HorizontalAlignment','left');
	hText2_2=text('Units','normal','Position',[.43 .92],'String',[num2str(NGoodTrials)],'FontSize',[12],'Color','g','HorizontalAlignment','left');
	hText3=text('Units','normal','Position',[.475 .96],'String',[MedString,num2str(MedSumWeightEditMat)],'FontSize',[12],'Color','k','HorizontalAlignment','left');
	hText4=text('Units','normal','Position',[.475 .92],'String',[MeanString,num2str(MeanSumWeightEditMat)],'FontSize',[12],'Color','k','HorizontalAlignment','left');
	hText5_1=text('Units','normal','Position',[.02 .88],'String',GlobExtChanString,'FontSize',[12],'Color','k','HorizontalAlignment','left');
	hText5_2=text('Units','normal','Position',[.43 .88],'String',[num2str(GlobExtChanVal)],'FontSize',[12],'Color','k','HorizontalAlignment','left');
	hText6_1=text('Units','normal','Position',[.475 .88],'String',MinWeightString,'FontSize',[12],'Color','k','HorizontalAlignment','left');
	hText6_2=text('Units','normal','Position',[.66 .88],'String',[num2str(MinWeightEdit)],'FontSize',[12],'Color','k','HorizontalAlignment','left');
	hText7_1=text('Units','normal','Position',[.02 .84],'String',MaxWeightString,'FontSize',[12],'Color','k','HorizontalAlignment','left');
	hText7_2=text('Units','normal','Position',[.66 .84],'String',[num2str(NChan-MinWeightEdit)],'FontSize',[12],'Color','k','HorizontalAlignment','left');
	hTextOk=text('Units','normal','Position',[.5 .8],'String','Choose threshold and press "Return" !','FontSize',[16],'Color','k','HorizontalAlignment','Center');
	hIncAxesText=text('Units','normal','Position',[.925 .6],'String','>','FontSize',[30],'Color','k','HorizontalAlignment','Center','FontWeight','Bold');
	hDecAxesText=text('Units','normal','Position',[.925 .2],'String','<','FontSize',[30],'Color','k','HorizontalAlignment','Center','FontWeight','Bold');

	hHistFigAxes=axes('Units','normal','Color',[0 0 0],'Position',[.15 .075 .75 .70]);
	HistFigVec(4)=hHistFigAxes;
	set(hList(61),'Userdata',HistFigVec);

	if MinSensorMaxStdStatus==0				%Min good Sensors
		x=[MinSumWeightEditMat:MaxSumWeightEditMat];
	elseif MinSensorMaxStdStatus==1			%Max. Std.
		x=linspace(MinSumWeightEditMat,MaxSumWeightEditMat,1000);
		set(hText7_1,'Visible','off')
		set(hText7_2,'Visible','off')
	end
	[n,x]=hist(SumWeightEditMat(NNot2BadChanVecIndVec),x);
	hBar=bar(x,n);
 	xb=get(hBar,'XData');
   	[xb1,xb2]=size(xb);
   	xb=reshape(xb,1,xb1.*xb2);
	MaxXb=max(xb);
	MaxXbPlot=0.1;
	MinXbPlot=0;
   	yb=get(hBar,'YData');
   	[yb1,yb2]=size(yb);
   	yb=reshape(yb,1,yb1.*yb2);
% 	set(hSetHistFigXAxis,'Max',max(xb));
	plot(xb,yb)
	hold on
	plot([xb(1) xb(length(xb))],[0 0],'w--')
	if MinSensorMaxStdStatus==0				%Min good Sensors
		if x(1)<x(length(x)) & max(yb)>0
			axis([round(x(length(x)))./2 x(length(x)) 0 max(yb)])
		end
		xlabel('Minimum number of good channels:')
	elseif MinSensorMaxStdStatus==1			%Max. Std.
		axis([0 MaxXbPlot 0 max(yb)])
		MinWeightEdit=0.02;
		xlabel('Maximum std of approximation:')
	end
	ylabel('Number of trials:')
	hMinWeightEditLine=line('XData',[MinWeightEdit MinWeightEdit],'YData',[ 0 max(yb)],'Color','r','LineStyle','--');
	while again
		[XHoriz,YVert]=ginput(1);
		if isempty(XHoriz)
			again=0;
			close(HistFig);
		else
			if XHoriz>MaxXbPlot
				if YVert>.5
					MaxXbPlotTmp=MaxXbPlot+.01;
				else
					MaxXbPlotTmp=MaxXbPlot-.01;
				end
				if MaxXbPlotTmp>MinXbPlot
					MaxXbPlot=MaxXbPlotTmp;
					set(hHistFigAxes,'XLim',[MinXbPlot MaxXbPlot]);
				end
			else
				if MinSensorMaxStdStatus==0				%Min good Sensors
					MinWeightEdit=min([MaxSumWeightEditMat,round(XHoriz)]);
					MinWeightEdit=max([0 MinWeightEdit]);
					GoodTrials=find(SumWeightEditMat>MinWeightEdit);  
					BadTrials=find(SumWeightEditMat<=MinWeightEdit); 
				elseif MinSensorMaxStdStatus==1			%Max. Std.
					MinWeightEdit=XHoriz;
					GoodTrials=find(SumWeightEditMat<MinWeightEdit); 
					BadTrials=find(SumWeightEditMat>=MinWeightEdit); 
				end
				NGoodTrials=length(GoodTrials);
				if NGoodTrials==0
					Message=char('Warning,');
					Message=char(Message,'');
					Message=char(Message,'setting this limit results in no trials to average.');
					Message=char(Message,'');
					hmsgbox=msgbox(Message,'Info','help'); 
				else
					NBadTrials=length(BadTrials);
					WeightTrialStatus=zeros(NTrials,1);
					WeightTrialStatus(GoodTrials)=ones(NGoodTrials,1);
					set(hText1_2,'String',num2str(NBadTrials));	
					set(hText2_2,'String',num2str(NGoodTrials));
					if MinSensorMaxStdStatus==0				%Min good Sensors
						NChan2Approx=NChan-MinWeightEdit;
						if NChan2Approx>NChan./9
							set(hText6_2,'String',num2str(MinWeightEdit),'Color','r');
							set(hText7_2,'String',num2str(NChan2Approx),'Color','r');
						else
							set(hText6_2,'String',num2str(MinWeightEdit),'Color','k');
							set(hText7_2,'String',num2str(NChan2Approx),'Color','k');
						end
					elseif MinSensorMaxStdStatus==1			%Max. Std.
						set(hText6_2,'String',num2str(MinWeightEdit),'Color','k');
						NBadChanVec=[];				
						for i=1:length(GoodTrials)
							ChanStatusVec=WeightEditMat(:,GoodTrials(i));
							BadChanIndVec=find(ChanStatusVec==0);
							NBadChanVec(i)=length(BadChanIndVec);
						end
						[SortNBadChanVec,SortNBadChanIndVec]=sort(NBadChanVec);
						Worst5TrialIndVec=SortNBadChanIndVec(length(SortNBadChanIndVec)-4:length(SortNBadChanIndVec));
						hfigtmp=figure('Units','normal','NumberTitle','off','Position',[0,0,.666,1],'Color',[0 0 0]);
						hAxesTmp=axes('Position',[0.05 0.05 .9 .85],'Visible','off');
						NChan=NChan
						AllEPosSpher=AllEPosSpher
						[kTop,AxesTop,kFront,AxesFront,kBack,AxesBack,kLeft,...
	    				AxesLeft,kRight,AxesRight,kNorm,AxesNorm,kAll,AxesAll,...
						TopStatusVec,FrontStatusVec,BackStatusVec,LeftStatusVec,RightStatusVec,NormStatusVec,AllStatusVec]=Calc2dTimeAxes(AllEPosSpher,ones(NChan,1));	
						for i=1:min([5,NGoodTrials])
							set(hfigtmp,'Name',['Trial ' int2str(i) ' of ' int2str(min([5,NGoodTrials])) ' trials with highest number of bad channels; Trial # ', int2str(Worst5TrialIndVec(i))]);
							ChanStatusVec=WeightEditMat(:,GoodTrials(Worst5TrialIndVec(i)));
							BadChanIndVec=find(ChanStatusVec==0);
							NBadChanVec(i)=length(BadChanIndVec);
							for j=1:length(AllStatusVec)
								if ChanStatusVec(j)==0; ColorVal='r'; else; ColorVal='g'; end
								if i==1
									hTextVec(j)=text('Units','normal','Position',AxesAll(j,:),'HorizontalAlignment','Center','Color',ColorVal,'String',num2str(ENames(j,:)),'FontSize',18);
								else
									set(hTextVec(j),'Color',ColorVal);
								end
							end
							pause(1)
						end
						close(hfigtmp)
						set(hText7_2,'String',num2str(max(NBadChanVec)),'Color','k');
					end
				end
				set(hMinWeightEditLine,'XData',[MinWeightEdit MinWeightEdit]);
			end
		end
	end
	close(BadChanMaxStdFig)
	set(hList(34),'Userdata',WeightTrialStatus);

elseif strcmp(action,'SetHistFigXAxis'),
	
	hList=get(hAllFig,'Userdata');
	HistFigVec=get(hList(61),'Userdata');
	hSetHistFigXAxis=HistFigVec(3);
	hHistFigAxes=HistFigVec(4);
	get(hSetHistFigXAxis)
	get(hHistFigAxes)
	
elseif strcmp(action,'setKindEditMat'),
   
   	EditAEM('SaveTVMFile');
	hList=get(hAllFig,'Userdata');
    v = get(hList(26),'Value');
          
    % The Kind of thres fac Selection Menu
	if 		v==1; KindEditMat='Absolute';
	elseif 	v==2; KindEditMat='Minimum Std';
	elseif 	v==3; KindEditMat='Maximum Std';
	elseif 	v==4; KindEditMat='Transit';
	elseif 	v==5; KindEditMat='Flat';
	end
	set(hList(26),'Userdata',KindEditMat,'value',v);
	
	hList=get(hAllFig,'Userdata');
	NChan=get(hList(43),'Userdata');
	NTrials=get(hList(44),'Userdata');
	if strcmp(KindEditMat,'Minimum Std');
		set(hList(5),'Userdata',0.2,'String',num2str(0.2)); %ThresFac
	else
		set(hList(5),'Userdata',1.5,'String',num2str(1.5)); %ThresFac
	end
	KindEditFile=get(hList(30),'Userdata');
	if strcmp(KindEditFile,'AEM');
		FilePath=get(hList(23),'Userdata');
	elseif strcmp(KindEditFile,'TVM');
		FilePath=get(hList(24),'Userdata');
	end
	
	fid=fopen(FilePath,'r');
	
	NEditMat=4;
	
	if strcmp(KindEditMat,'Absolute') 
		SeekFac=0;
	elseif strcmp(KindEditMat,'Minimum Std') | strcmp(KindEditMat,'Maximum Std');
		SeekFac=1;
	elseif strcmp(KindEditMat,'Transit') 
		SeekFac=2;
	elseif strcmp(KindEditMat,'Flat') 
		SeekFac=3;
	end
	
	fseek(fid,(SeekFac+1).*4+SeekFac.*NChan.*NTrials.*4,'bof'); %NChan NTrials AbsEditMat 

	EditMat=fread(fid,[NChan,NTrials],'float32');
	
	fseek(fid,NEditMat.*4+NEditMat.*NChan.*NTrials.*4,'bof');
	
	if strcmp(KindEditFile,'TVM');
	
		if strcmp(KindEditMat,'Absolute') 
			SeekFac=0;
		elseif strcmp(KindEditMat,'Minimum Std') 
			SeekFac=1;
		elseif strcmp(KindEditMat,'Maximum Std');
			SeekFac=2;
		elseif strcmp(KindEditMat,'Transit') 
			SeekFac=3;
		elseif strcmp(KindEditMat,'Flat') 
			SeekFac=4;
		end
		
		fseek(fid,SeekFac.*(NChan.*(4+2+2+4+4)+1+1),'cof');

		ThresVec=fread(fid,NChan,'float32'); 
		ChangedThStatusVec=fread(fid,NChan,'int16');
		PlotChanStatusVec=fread(fid,NChan,'int16'); 
		ThetaCorrVec=fread(fid,NChan,'float32');
		NoiseCorrVec=fread(fid,NChan,'float32');
		ch_ThetaCorr=fread(fid,1,'int8');
		ch_NoiseCorr=fread(fid,1,'int8');

	else
		
		ThresVec=zeros(NChan,1);
		ChangedThStatusVec=zeros(NChan,1);
		PlotChanStatusVec=ones(NChan,1);
		ThetaCorrVec=ones(NChan,1);
		NoiseCorrVec=ones(NChan,1);
		ch_ThetaCorr=0;
		ch_NoiseCorr=0;
		
	end
	fclose(fid);
	set(hList(7),'Userdata',EditMat);
	set(hList(8),'Userdata',ThresVec); 
	set(hList(9),'Userdata',ChangedThStatusVec); 
	set(hList(10),'Userdata',PlotChanStatusVec); 
	set(hList(28),'Userdata',ThetaCorrVec,'value',ch_ThetaCorr); 
	set(hList(29),'Userdata',NoiseCorrVec,'value',ch_NoiseCorr); 

	set(hAllFig,'Name',['Choose ' KindEditMat ' Threshold']);
 	EditAEM('firstcalculations');
	EditAEM('AutoEdit');	

elseif strcmp(action,'ChoiceThetaCorr'),
   	
	v = get(gco,'value')
	hList=get(hAllFig,'Userdata');
	AvgRefStatus=get(hList(51),'Userdata');
	if v 
		if ~AvgRefStatus
			[File,Path,FilePath]=ReadFilePath([],'*.T','Choose the Theta file:');
			[CorrVec] = ReadData([FilePath],1);
			set(hList(28),'Userdata','CorrVec','value',1);
			EditAEM('firstcalculations');
		else
			fprintf('This does not make sense !!!');
		end
	else
		set(hList(28),'Userdata','0','value',0);
		EditAEM('firstcalculations');
	end	


elseif strcmp(action,'ChoiceNoiseCorr'),
	
	v = get(gco,'value')
	hList=get(hAllFig,'Userdata');
	AvgRefStatus=get(hList(51),'Userdata');
	if v 
		if ~AvgRefStatus
			[File,Path,FilePath]=ReadFilePath([],'*.F','Choose the Theta file:');
			[CorrVec] = ReadData([FilePath],1);
			set(hList(29),'Userdata','CorrVec','value',1);
			EditAEM('firstcalculations');
		else
			fprintf('This does not make sense !!!');
		end
	else
		set(hList(29),'Userdata','0','value',0);
		EditAEM('firstcalculations');
	end	

elseif strcmp(action,'UpdateDisplay'),

	hList=get(hAllFig,'Userdata');
	MinView=get(hList(3),'Userdata');
	MaxView=get(hList(4),'Userdata');
	EditMat=get(hList(7),'Userdata');
	NChan=get(hList(43),'Userdata');
	NTrials=get(hList(44),'Userdata');
	ThresVec=get(hList(8),'Userdata');
	ChangedThStatusVec=get(hList(9),'Userdata');
	hAxesVec=get(hList(11),'Userdata');
	hDataVec=get(hList(12),'Userdata');
	hBotLine=get(hList(13),'Userdata');
	hThresLine=get(hList(14),'Userdata');
	hThText1=get(hList(15),'Userdata');
	hThText2=get(hList(16),'Userdata');
	hThText3=get(hList(17),'Userdata');
	hThText4=get(hList(18),'Userdata');
	hMaxYbVec=get(hList(19),'Userdata');
	KindEditMat=get(hList(26),'Userdata');
	xbMat=get(hList(46),'Userdata');
	ybMat=get(hList(47),'Userdata');
	MaxYb=get(hList(48),'Userdata');
	MaxYbMedFac=get(hList(49),'Userdata');
    hTmp=axes('Position',[0 0 .001 .001],'Visible','off','Color',[0 0 0]);

    % Set up the special channel axes
	Nx=50;
	NxTmp=4.*Nx;
	x=linspace(MinView,MaxView,Nx); 
    hBarVec=zeros(NChan,1);
    xbMat=zeros(NChan,NxTmp);
    ybMat=zeros(NChan,NxTmp);
	for ChanInd=1:NChan
		[n,x]=hist(EditMat(ChanInd,:),x);
        hBar=bar(x,n);   
        xb=get(hBar,'XData');
        yb=get(hBar,'YData');
        xbMat(ChanInd,:)=reshape(xb,1,NxTmp);
        ybMat(ChanInd,:)=reshape(yb,1,NxTmp);
		MaxYbVec(ChanInd)=max(max(yb));
	end
    set(hTmp,'Visible','off');
	MaxYb=MaxYbMedFac.*median(MaxYbVec);
	set(hList(19),'Userdata',MaxYbVec);
	set(hList(46),'Userdata',xbMat);
	set(hList(47),'Userdata',ybMat);
	set(hList(48),'Userdata',MaxYb);
   
	for ChanInd=1:NChan
		SpecThres=ThresVec(ChanInd);	
		xb=xbMat(ChanInd,:);
		yb=ybMat(ChanInd,:);
		set(hAxesVec(ChanInd),'XLim',[MinView MaxView],'YLim',[0 MaxYb]);
		set(hDataVec(ChanInd),'XData',xb,'YData',yb);
		set(hBotLine(ChanInd),'XData',[xb(1) xb(length(xb))]);
		if ChangedThStatusVec(ChanInd); ThresLineColor='b'; else; ThresLineColor='r'; end
		set(hThresLine(ChanInd),'XData',[SpecThres SpecThres],'YData',[0 MaxYb],'Color',ThresLineColor);
		if strcmp(KindEditMat,'Absolute') | strcmp(KindEditMat,'Maximum Std') | strcmp(KindEditMat,'Transit') | strcmp(KindEditMat,'Flat')
			GoodTrials=find(EditMat(ChanInd,:)<SpecThres);
		else strcmp(KindEditMat,'Minimum Std')
			GoodTrials=find(EditMat(ChanInd,:)>SpecThres);
		end
		NGoodTrials=length(GoodTrials);
		NBadTrials=NTrials-NGoodTrials;
		GoodTrialsPH=round(NGoodTrials./NTrials.*100);
		set(hThText1(ChanInd),'Position',[SpecThres .5.*MaxYb],'String',num2str(GoodTrialsPH));
		set(hThText2(ChanInd),'Position',[SpecThres .66.*MaxYb],'String',num2str(NBadTrials));
		set(hThText3(ChanInd),'Position',[SpecThres .82.*MaxYb],'String',num2str(NGoodTrials));
		if ChangedThStatusVec(ChanInd); ChanTextColor='b'; else; ChanTextColor='m'; end
		set(hThText4(ChanInd),'Position',[SpecThres .34.*MaxYb],'String',[num2str(ChanInd)],'FontSize',[12],'Color',ChanTextColor);
	end
	set(hList(19),'Userdata',MaxYbVec);
	
elseif strcmp(action,'ResetThreshold'),
	
	hList=get(hAllFig,'Userdata');
	KindThresFac=get(hList(2),'Userdata');
	EditMat=get(hList(7),'Userdata');
	NChan=get(hList(43),'Userdata');
	NTrials=get(hList(44),'Userdata');
	set(hList(5),'Userdata',1.5); %ThFac
	set(hList(9),'Userdata',zeros(NChan,1)); %ChangedThStatusVec
	
	EditAEM('firstcalculations');

elseif strcmp(action,'SetThreshold'),
	
	hList=get(hAllFig,'Userdata');
	EditMat=get(hList(7),'Userdata');
	NChan=get(hList(43),'Userdata');
	NTrials=get(hList(44),'Userdata');
	set(hList(9),'Userdata',ones(NChan,1)); %ChangedThStatusVec

	EditAEM('UpdateDisplay');
	
elseif strcmp(action,'setKindThresFac'),
   
    v = get(gco,'value')
    % The Kind of thres fac Selection Menu
	if 		v==1; KindThresFac='MeanVec'; 
	elseif 	v==2; KindThresFac='MeanVal'; 
	elseif 	v==3; KindThresFac='MedianVec'; 
	elseif 	v==4; KindThresFac='MedianVal';
	elseif 	v==5; KindThresFac='SpecVal'; 
	end
	set(gco,'Userdata',KindThresFac,'value',v);
	
	EditAEM('firstcalculations');
	
elseif strcmp(action,'setStdFac') | ...
	strcmp(action,'setStdExp'),

	v = get(gco,'Value');
	hList=get(hAllFig,'Userdata');
    str = get(gco,'String');
    ind = find(abs(str)<32);
    str(ind) = 32*ones(size(ind));
    str = str';
    vv = eval(['[' str(:)' ']'],'-1')';
    if vv == -1
        vv = v;
    elseif vv<0 | length(vv)~=1
        vv = v;
    end
    set(gco,'Value',vv,'String',sprintf('%g',vv));

elseif strcmp(action,'setMinView'),
	
	v = get(gco,'Userdata');
	hList=get(hAllFig,'Userdata');
	MaxView=get(hList(4),'Userdata');
    str = get(gco,'String');
    ind = find(abs(str)<32);
    str(ind) = 32*ones(size(ind));
    str = str';
    vv = eval(['[' str(:)' ']'],'-1')';
    if vv == -1
        vv = v;
    elseif vv<0  | vv>=MaxView | length(vv)~=1
        vv = v;
    end
    vv = round(vv*1000)/1000;
    set(gco,'Userdata',vv,'String',sprintf('%g',vv));
	EditAEM('UpdateDisplay');

elseif strcmp(action,'setMaxView'),
	    
	v = get(gco,'Userdata');
	hList=get(hAllFig,'Userdata');
	MinView=get(hList(3),'Userdata');
	str = get(gco,'String');
    ind = find(abs(str)<32);
    str(ind) = 32*ones(size(ind));
    str = str';
    vv = eval(['[' str(:)' ']'],'-1')';
    if vv == -1
        vv = v;
    elseif vv<0  | vv<=MinView | length(vv)~=1
        vv = v;
    end
    vv = round(vv*1000)/1000;
    str = sprintf('%g',vv);
    set(gco,'Userdata',vv,'String',str);
	EditAEM('UpdateDisplay');
	
elseif strcmp(action,'setThresFac'),
	    
	v = get(gco,'Userdata');
	
	hList=get(hAllFig,'Userdata');
	KindThresFac=get(hList(2),'Userdata');
	SpecVal=get(hList(20),'Userdata');	
	
    str = get(gco,'String');
    ind = find(abs(str)<32);
    str(ind) = 32*ones(size(ind));
    str = str';
    vv = eval(['[' str(:)' ']'],'-1')';
    if vv == -1
        vv = v;
    elseif vv<0  | length(vv)~=1
        vv = v;
    end
    vv = round(vv*10)/10;
    str = sprintf('%g',vv);
    set(gco,'Userdata',vv,'String',str);
	
	if strcmp(KindThresFac,'MeanVal') | strcmp(KindThresFac,'MedianVal')
		SpecVal=vv./v.*SpecVal;
	else
		SpecVal=0;
	end
	set(hList(20),'Userdata',SpecVal,'String',sprintf('%g',SpecVal));	
	EditAEM('UpdateDisplay');
	
elseif strcmp(action,'setSpecVal')
	    
	v = get(gco,'Userdata');
    str = get(gco,'String');
    ind = find(abs(str)<32);
    str(ind) = 32*ones(size(ind));
    str = str';
    vv = eval(['[' str(:)' ']'],'-1')';
    if vv == -1
        vv = v;
    elseif vv<0  | length(vv)~=1
        vv = v;
    end
    vv = round(vv*10)/10;
    str = sprintf('%g',vv);
    set(gco,'Userdata',vv,'String',str);
	hList=get(hAllFig,'Userdata');
	set(hList(2),'Userdata','SpecVal','Value',5);
	ThresVec=get(hList(8),'Userdata');
	ThresVec=ones(size(ThresVec)).*vv;
	set(hList(8),'Userdata',ThresVec);
	EditAEM('UpdateDisplay');

elseif strcmp(action,'InfoEditMat'),

	EditMat = get(gco,'Userdata');
	hEditMatFig=figure('Units','normal','Position',[0.66 0.66 0.33 .33], ...
      'Name','Info Edit Mat', ...
      'NumberTitle','off');
	surf(EditMat)
	xlabel('Trial:')
	ylabel('Channel:')
	zlabel('Amplitude:')

elseif strcmp(action,'InfoThresVec'),
		
		ThresVec = get(gco,'Userdata');
		hEThresVecFig=figure('Units','normal','Position',[0.66 0.66 0.33 .33], ...
        'Name','Info Threshold Vector', ...
        'NumberTitle','off');
		plot(ThresVec)
		xlabel('Channel:')
		ylabel('Amplitude:')
		
elseif strcmp(action,'InfoChangedThStatusVec'),
		
		ChangedThStatusVec = get(gco,'Userdata');
		hInfoChangedThStatusVecFig=figure('Units','normal','Position',[0.66 0.66 0.33 .33], ...
        'Name','Info Changed Threshold Status Vector:', ...
        'NumberTitle','off');
		plot(ChangedThStatusVec)
		xlabel('Channel:')

elseif strcmp(action,'InfoPloChanStatusVec'),
		
		PlotChanStatusVec = get(gco,'Userdata');
		hInfoPlotChanStatusVecFig=figure('Units','normal','Position',[0.66 0.66 0.33 .33], ...
        'Name','Info Channel Status Vector:', ...
        'NumberTitle','off');
		plot(PlotChanStatusVec)
		xlabel('Channel:')

elseif strcmp(action,'AccChangeAllThresInter') | strcmp(action,'FastChangeAllThresInter'),
		
	hList=get(hAllFig,'Userdata');
	MinView=get(hList(3),'Userdata');
	MaxView=get(hList(4),'Userdata');
	EditMat=get(hList(7),'Userdata');
	NChan=get(hList(43),'Userdata')
	NTrials=get(hList(44),'Userdata')
	ThresVec=get(hList(8),'Userdata');
	ChangedThStatusVec=get(hList(9),'Userdata');
	KindEditMat=get(hList(26),'Userdata');
	xbMat=get(hList(46),'Userdata');
	ybMat=get(hList(47),'Userdata');
	MaxYb=get(hList(48),'Userdata');
	EditAEM('CalcWEMatShort');
	WeightEditMat=get(hList(32),'Userdata');
	hChangeAllFig=figure('Units','normal','NumberTitle','off','Position',[0 0 .5 1],'Name','Channel: 1');	
	axes('Units','normal','Position',[0 0 1 1]); axis('off');
    if strcmp(action,'AccChangeAllThresInter')
	   Message=char('Press "Return" to set actual threshold.');
	   Message=char(Message,'Press "Escape" to return to main menu.');
    else
       Message=char('Press "Escape" to return to main menu.');
    end

	text('Units','normal','Position',[.1 .95],'String',Message,'FontSize',[20],'Color','k','HorizontalAlignment','left');	
	
	hChangeAllAxes=axes('Units','normal','Color',[0 0 0],'Position',[.1 .1 .8 .8]);
	ChooseChanAgain=1;
	ChanInd=0;
	FirstPlot=1;
	XHoriz=0;
	while ChanInd<NChan & ChooseChanAgain
		GoodTrialsVec=[];
		while isempty(GoodTrialsVec)
			ChanInd=ChanInd+1;
			GoodTrialsVec=find(WeightEditMat(ChanInd,:)==1);
			if isempty(GoodTrialsVec)
				if strcmp(KindEditMat,'Minimum Std')
					ThresVec(ChanInd)=10^10;
				else
					ThresVec(ChanInd)=0;
				end
			end
		end
		set(hChangeAllFig,'Name',['Channel: ' int2str(ChanInd)]);
		ChooseLimAgain=1;
		Index=0;
		while ChooseLimAgain
			SpecThres=ThresVec(ChanInd);
			xb=xbMat(ChanInd,:);
			yb=ybMat(ChanInd,:);
	
			if strcmp(KindEditMat,'Absolute') | strcmp(KindEditMat,'Maximum Std') | strcmp(KindEditMat,'Transit') | strcmp(KindEditMat,'Flat')
				GoodTrials=find(EditMat(ChanInd,:)<SpecThres);
			else strcmp(KindEditMat,'Minimum Std')
				GoodTrials=find(EditMat(ChanInd,:)>SpecThres);
			end
			NGoodTrials=length(GoodTrials);
			NBadTrials=NTrials-NGoodTrials;
			GoodTrialsPH=round(NGoodTrials./NTrials.*100);
			if FirstPlot;
				FirstPlot=0;
				hData=line('XData',xb,'YData',yb,'Color','y');
				axis([MinView MaxView 0 MaxYb])
				xlabel('Amplitude [µV]')
				ylabel('Number of trials []')
				hThres=line('XData',[ThresVec(ChanInd) ThresVec(ChanInd)],'YData',[0 max(yb)],'Color','r','LineStyle','--');		
				hText1=text('Position',[SpecThres .85.*max(yb)],'String',num2str(GoodTrialsPH),'FontSize',[12],'Color','w','HorizontalAlignment','left');
				hText2=text('Position',[SpecThres .90.*max(yb)],'String',num2str(NBadTrials),'FontSize',[12],'Color','r','HorizontalAlignment','left');
				hText3=text('Position',[SpecThres .95.*max(yb)],'String',num2str(NGoodTrials),'FontSize',[12],'Color','g','HorizontalAlignment','left');			
			else
				axes(hChangeAllAxes);
				axis([MinView MaxView 0 MaxYb])
				set(hData,'XData',xb,'YData',yb);
				set(hThres,'XData',[SpecThres SpecThres],'YData',[0 MaxYb]);		
				set(hText1,'Position',[SpecThres .85.*MaxYb],'String',num2str(GoodTrialsPH));
				set(hText2,'Position',[SpecThres .90.*MaxYb],'String',num2str(NBadTrials));
				set(hText3,'Position',[SpecThres .95.*MaxYb],'String',num2str(NGoodTrials));			
			end
			
			[XHorizNew,YVert,Button]=ginput(1);
            if strcmp(action,'AccChangeAllThresInter')
			     if isempty(Button)
				    if Index==0;
					   ThresVec(ChanInd)=SpecThres;
				    else
					   ThresVec(ChanInd)=XHoriz;
				    end
				    Index=1;
				    ChooseLimAgain=0;
			     else
				    if Button==27
					   ChooseLimAgain=0;
					   ChooseChanAgain=0;
					   close(hChangeAllFig);
					   EditAEM('UpdateDisplay');
					   return;
                    end
				    ThresVec(ChanInd)=XHorizNew;
                end
                XHoriz=XHorizNew;
            else
                if Button==27
			         ChooseLimAgain=0;
					 ChooseChanAgain=0;
					 close(hChangeAllFig);
					 EditAEM('UpdateDisplay');
					 return;
                 end
                 ThresVec(ChanInd)=XHorizNew;
                 ChooseLimAgain=0;
            end
		end	%while
		ChangedThStatusVec(ChanInd)=1;
		set(hList(8),'Userdata',ThresVec);
		set(hList(9),'Userdata',ChangedThStatusVec);
		if ChanInd==NChan; close(hChangeAllFig); end
	end	%while NChan
	EditAEM('UpdateDisplay');

elseif strcmp(action,'ChangeSpecChanThres'),

	chChangeSpecThres = get(gco,'value');
	if chChangeSpecThres
		hList=get(hAllFig,'Userdata');
		MinView=get(hList(3),'Userdata');
		MaxView=get(hList(4),'Userdata');
		EditMat=get(hList(7),'Userdata');
		NChan=get(hList(43),'Userdata');
		NTrials=get(hList(44),'Userdata');
		ThresVec=get(hList(8),'Userdata');
		ChangedThStatusVec=get(hList(9),'Userdata');
		hAxesVec=get(hList(11),'Userdata');
		AxesPosMat=get(hList(22),'Userdata');
		KindEditMat=get(hList(26),'Userdata');

		axes('Units','normal','Position',[0 0 1 1],'Visible','off');
		% Set up the special channel axes
		Nx=50;
		NxTmp=5.*Nx+1;
		x=linspace(MinView,MaxView,Nx); 
	end
	
	while chChangeSpecThres
		ChooseChanAgain=1;
		while ChooseChanAgain
			[XHoriz,YVert]=ginput(1);
			ChanInd=0;
			while ChanInd<NChan & ChooseChanAgain
				ChanInd=ChanInd+1;
				Left=AxesPosMat(ChanInd,1);
				Bottom=AxesPosMat(ChanInd,2);
				Width=AxesPosMat(ChanInd,3);
				Hight=AxesPosMat(ChanInd,4);
				if XHoriz>Left & XHoriz<Left+Width & YVert>Bottom & YVert<Bottom+Hight
					ChooseChanAgain=0;
					SpecChan=ChanInd;
				end
			end		
		end
		[n,x]=hist(EditMat(SpecChan,:),x);
		[xb,yb]=bar(x,n);
		SpecThres=ThresVec(SpecChan);
		if strcmp(KindEditMat,'Absolute') | strcmp(KindEditMat,'Maximum Std') | strcmp(KindEditMat,'Transit') | strcmp(KindEditMat,'Flat')
			GoodTrials=find(EditMat(SpecChan,:)<SpecThres);
		else strcmp(KindEditMat,'Minimum Std')
			GoodTrials=find(EditMat(SpecChan,:)>SpecThres);
		end
		NGoodTrials=length(GoodTrials);
		NBadTrials=NTrials-NGoodTrials;
		GoodTrialsPH=round(NGoodTrials./NTrials.*100);
		ChangeThFigPos3=.33;
		ChangeThFigPos4=.33;
		ChangeThFigPos=[.66.*XHoriz-ChangeThFigPos3./2,YVert-ChangeThFigPos4./2,ChangeThFigPos3,ChangeThFigPos4];
		if ChangeThFigPos(1)<0; ChangeThFigPos(1)=0; end
		if ChangeThFigPos(2)+ChangeThFigPos(4)>1; ChangeThFigPos(2)=1-ChangeThFigPos(4); end
		hChangeThFig=figure('Units','normal','Color',[0 0 0],'NumberTitle','off','Position',ChangeThFigPos,'Name',['Channel: ',num2str(SpecChan)]);	
		hChangeThAllAxes=axes('Position',[0 0 1 1]);
		axis('off');
		text('Position',[.8 .015],'String','O.k.','FontSize',[20],'Color','g','HorizontalAlignment','left');	
		text('Position',[.8 .95],'String','Return:','FontSize',[20],'Color','r','HorizontalAlignment','left');	
		hChangeThPlotAxes=axes('Position',[.1 .1 .8 .8]);
		hChangeThLine=line('XData',xb,'YData',yb,'Color','y');
		line('XData',[MinView MaxView],'YData',[0 0],'LineStyle','--');
		axis([MinView MaxView 0 max(yb)])
		xlabel('Amplitude')
		ylabel('Number of trials')
		hSpecThLine=line('XData',[SpecThres SpecThres],'YData',[0 max(yb)],'Color','r','LineStyle','--');		
		hSpecThText1=text('Position',[SpecThres .85.*max(yb)],'String',num2str(GoodTrialsPH),'FontSize',[12],'Color','w','HorizontalAlignment','left');
		hSpecThText2=text('Position',[SpecThres .90.*max(yb)],'String',num2str(NBadTrials),'FontSize',[12],'Color','r','HorizontalAlignment','left');
		hSpecThText3=text('Position',[SpecThres .95.*max(yb)],'String',num2str(NGoodTrials),'FontSize',[12],'Color','g','HorizontalAlignment','left');			
		
		ChooseThresAgain=1;
		while ChooseThresAgain
			
			[XHoriz,YVert]=ginput(1);
			if YVert>max(yb) %Return
				ChooseThresAgain=0;
				chChangeSpecThres=0;
				close(hChangeThFig);
			elseif YVert<0  %Ok
				ChooseThresAgain=0;
				close(hChangeThFig);
			elseif XHoriz>=MinView & XHoriz<=MaxView
				SpecThres=XHoriz;
				if strcmp(KindEditMat,'Absolute') | strcmp(KindEditMat,'Maximum Std') | strcmp(KindEditMat,'Transit') | strcmp(KindEditMat,'Flat')
					GoodTrials=find(EditMat(SpecChan,:)<SpecThres);
				else strcmp(KindEditMat,'Minimum Std')
					GoodTrials=find(EditMat(SpecChan,:)>SpecThres);
				end
				NGoodTrials=length(GoodTrials);
				NBadTrials=NTrials-NGoodTrials;
				GoodTrialsPH=round(NGoodTrials./NTrials.*100);
				set(hSpecThLine,'XData',[SpecThres SpecThres],'YData',[0 max(yb)],'Color','r','LineStyle','--');		
				set(hSpecThText1,'Position',[SpecThres .85.*max(yb)],'String',num2str(GoodTrialsPH));
				set(hSpecThText2,'Position',[SpecThres .90.*max(yb)],'String',num2str(NBadTrials));
				set(hSpecThText3,'Position',[SpecThres .95.*max(yb)],'String',num2str(NGoodTrials));			
			end
			
		end	%while ChooseThresAgain
		if YVert<0 % Ok
			ThresVec(SpecChan)=SpecThres;
			set(hList(8),'Userdata',ThresVec);
			ChangedThStatusVec(SpecChan)=1;
			set(hList(9),'Userdata',ChangedThStatusVec);
		elseif YVert>max(yb)	%Return
		    set(hList(21),'Userdata',0,'value',0);
		end
	end	%while chChangeSpecThres

	EditAEM('UpdateDisplay');
		
end
