%==================================================================
%
%	AvgAppTimePlot.m
%
%	Markus Junghoefer	[1996]
%   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.                                                                      
%
%
%	Function definition
	function[]=AvgAppTimePlot(DataFilePath);

%

%==================================================================
if nargin<1; clear all; DataFilePath=[]; end

%==================================================================
[DataFile,DataPath,DataFilePath]=ReadFilePath(DataFilePath,'*.ses*','Please choose the EGIS file to average:');
[PlotStatus]=IfEmptyInputBo('Do you want to display all calculations ?',[],[],1,1);
if PlotStatus
	[PauseStatus]=IfEmptyInputBo('Do you want to have breaks between trials ?',[],[],1,1);
else
	PauseStatus=0;
end


[Header,DataFile,DataPath,DataFilePath,SampRate,NCells,NTrials,NPoints,...
NChan,LHeader,LCellHdr,BrdGain,ChanZero,ChanGain,HdrVer,Bits,Range]=ReadEGISHeader(DataFilePath);

global PathResult
global PathUtil
global AvgNChan

[MaxChanGainDiff,MaxChanZeroDiff]=TestChanGain(ChanGain,ChanZero);

[ChanGainVec]=CalcGainVec(ChanGain,Bits,Range);

NBytesInTrial=(NPoints.*NChan).*2;

[ch_AvgRef]=IfEmptyInputBo('Do you want to calculate the average ref. ?',[],[],1,1);
if ch_AvgRef; NChanCalc=NChan+1; else; NChanCalc=NChan; end

[ENames]=SetENames([],NChanCalc);


AppVersion=1;
[AppScaleBins]=IfEmptyInputVal('Please insert the ScaleBin value:',[],[],200,1);

eval(['global LSpecCell1;'])
HEVec=LSpecCell1(:,1);
	
if ~all(HEVec==-1)
	NotEditVec=find(HEVec==-1);
	QuestVec=find(HEVec==0);
	GoodVec=find(HEVec==1);
	BadVec=find(HEVec>1);
				
	fprintf('Number of trials with status:\n\n')
	fprintf(1,'Not edit:  %g\n',length(NotEditVec))
	fprintf(1,'Quest:      %g\n',length(QuestVec))
	fprintf(1,'Good:       %g\n',length(GoodVec))
	fprintf(1,'Bad:         %g\n\n\n',length(BadVec))
		
	[ch_DispHeaderEdit]=IfEmptyInputBo(['Do you want to display the header edit values ? Y/N'],[],[],0,0);
	if ch_DispHeaderEdit; disp(HEVec'); end
	fprintf('\n\n');
	[ch_UseHEVec]=IfEmptyInputBo(['Do you want to use the header edit values ? Y/N'],[],[],1,0);
else
	ch_UseHEVec=0;
	fprintf(1,'All %g trials in this file are not hand edited !!!',length(HEVec)); pause(1);
end
	
if ch_UseHEVec
	%=========ACHTUNG===========
	%=========ACHTUNG===========
	% HEVec muss den Wert Eins haben damit der trial gewertet wird 
	if ~isempty(QuestVec);
		[UseQuestStatus]=IfEmptyInputBo('Do you want to use the trials with "???" status ?',[],[],0,0);
		if UseQuestStatus; 
			HEVec(QuestVec)=ones(size(QuestVec));
		end
	end
else
	HEVec=ones(size(HEVec));
end
	
	

%========================================
[ch_UseWEFile]=IfEmptyInputBo('Do you want to use the WeightEditMat ?',[],[],1,1);
if ch_UseWEFile
	[ch_UseWEVec]=IfEmptyInputBo(['Do you want to use the weight edit values ? Y/N'],[],[],1,1);
	if ch_AvgRef
		WEFilePath=[DataFilePath '.AR.WE'];
	else	
		WEFilePath=[DataFilePath '.WE'];
	end
	fidWE=fopen(WEFilePath,'r');
	if fidWE~=-1
		fprintf('Read Weight Edit Matrix from file:\n')
		fprintf(WEFilePath);
		NChanTmp=fread(fidWE,1,'int16');
		NTrialsTmp=fread(fidWE,1,'int16');
		WeightEditMat=fread(fidWE,[NChanTmp NTrialsTmp],'int16');
		ChanEditStatusMat=fread(fidWE,[NChanTmp NTrialsTmp],'int16');
		WEVec=fread(fidWE,NChanTmp,'int16');
		fclose(fidWE);
	else
		fprintf('Sorry, can not find file:\n');
		fprintf(WEFilePath)
		pause(2)
		WeightEditMat=ones(NChanCalc,NTrials);
		ChanEditStatusMat=zeros(NChanCalc,NTrials);
		WEVec=ones(NTrials,1);
	end
	if all(WeightEditMat==1)
		fprintf('All WeightEditMat ==ones => No use of WeightEditMat !!\n\n'); pause(1); 
		ch_UseWEFile=0;
	end
else
	WeightEditMat=ones(NChanCalc,NTrials);
	ChanEditStatusMat=zeros(NChanCalc,NTrials);
	WEVec=ones(NTrials,1);
	ch_UseWEVec=0;
end

%========================================
[ch_UseEstFile]=IfEmptyInputBo('Do you want to use the bad channel vec ?',[],[],1,1);

if ch_UseEstFile
	fprintf('\n\n')
	EstFilePath=[DataFilePath '.' int2str(NChanCalc) 'est'];
	EstFid=fopen(EstFilePath,'r');
	if EstFid~=-1
		fprintf('Read electrode status from file:\n');
		fprintf(EstFilePath);
		fprintf('\n\n\n');
		EstVec=fread(EstFid,NChanCalc,'int16'); 
		fclose(EstFid);
		BadChanVec=find(EstVec==0);
		if ~isempty(BadChanVec)
			NBadChan=length(BadChanVec);
			fprintf('Found the following %g bad channels in this file:\n\n',NBadChan);
			disp(BadChanVec)
			pause(3)
			WeightEditMat(BadChanVec,:)=zeros(NBadChan,NTrials);
		else
			fprintf('No bad channels found in this file.\n');
		end
	else
		fprintf('Sorry, can not find file:\n');
		fprintf(EstFilePath)
		fprintf('\n\n')
		[Ok]=IfEmptyInputBo('Continue ?',[],[],0,1);
		if ~Ok; return; end
		ch_UseEstFile=0;
		EstVec=ones(NChanCalc,1);
	end
end

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

NoiseVec=ones(NChanCalc,1);
if ~ch_UseWEVec  & ~ch_UseHEVec
	HWEditVec=ones(NTrials,1);
elseif ch_UseWEVec & ~ch_UseHEVec
	HWEditVec=WEVec;
elseif ~ch_UseWEVec & ch_UseHEVec
	HWEditVec=HEVec;
elseif ch_UseWEVec & ch_UseHEVec
	HWEditVec=HEVec.*WEVec;
end
	
EditVec=HWEditVec;
%========================================
fprintf('\n');clc;
[ch_SpecGrand]=IfEmptyInputSpecVal([],[1 2],2,...
'Do you want to read\n',...
'a condition text file       [1]',...
'or use Grand Avg            [2]');

if ch_SpecGrand==1
	CondFilePath=[DataFilePath '.CON'];
	[CondMat] = ReadData(CondFilePath,1,[],'ascii','ascii');
	[NRow,NCondVec]=size(CondMat);
	if NRow>2 & NCondVec<3
        CondMat=CondMat';
        [NRow,NCondVec]=size(CondMat);
    end
	if NRow==1; 
		CondFileFormat=1;
	elseif NRow==2; 
		CondFileFormat=2;
	end
	if CondFileFormat==1
		if NCondVec~=NTrials
			if NCondVec<NTrials
				fprintf('The number of trials in condition file is smaller than the number of trials in the EGIS file\n');
				fprintf('Take just the number of trials of the condition file.');
				NTrials=NCondVec;
				WeightEditMat=WeightEditMat(:,1:NTrials);
				ChanEditStatusMat=ChanEditStatusMat(:,1:NTrials);
				WEVec=WEVec(1:NTrials);
				HEVec=HEVec(1:NTrials);
			else
				fprintf('The number of trials in condition file is bigger than the number of trials in the EGIS file\n');
				fprintf('Take just the number of trials of the EGIS file.');
				CondVec=CondVec(1:NTrials);
			end
		end
		CondVec=CondMat;
		CondVecTmp=CondMat;
	else
		CondVec=-1.*ones(1,NTrials);
		for i=1:NTrials
			Index=find(CondMat(2,:)==i);
			if ~isempty(Index)
				if length(Index)>1; 
					fprintf('Sorry,\n');
					fprintf('the trial in row %g occurs more often than once !\n',i);
				end
					if Index>NTrials; 
						fprintf('The trial # %g in row # %g does not correspond to the given data set !\n',Index,i);
					end
					CondVec(i)=CondMat(1,Index);
				end
			end
			CondVecTmp=CondMat(1,:);
		end
		NCond=0;
		while ~isempty(CondVecTmp)
			NCond=NCond+1;
			CondCondVec(NCond)=CondVecTmp(1); %Welche Bedingungen wirklich vorkommen
			k=find(CondVecTmp~=CondVecTmp(1));
			CondVecTmp=CondVecTmp(k);
		end		
		if NCond>1; NCondString=['Found the following ' int2str(NCond) ' conditions in file:'];
		else;  		NCondString=['Found just one condition in file:'];
		end
		NEvents=NCond;
		fprintf('\n');clc;
		fprintf('Found the following %g conditions:',NCond);
		disp(CondCondVec)
		fprintf('in file:\n\n');
		fprintf(CondFilePath)
		fprintf('\n\n\n')
		pause(2)
		[SpecCond]=IfEmptyInputSpecVal([],CondCondVec,[],'Which specific condition do you want to avg ?');
		k=find(CondVec~=SpecCond);
		EditVec(k)=2.*ones(length(k),1);
	end
end
%========================================

%==================================================================================
MatlabVersionString=version;
MainMatlabVersion=str2num(MatlabVersionString(1));
cd ..; 
BasePath=pwd;
cd Geo

if MainMatlabVersion<5
	CoeffPath=[BasePath,':Plot2d3d:Plot3dCoeff40'];
	LegPath=[BasePath,':Plot2d3d:Plot3dLegCoeff'];
	ECfgPath=[BasePath,':Plot2d3d:Plot2dUtil:SensorCfg'];
	ECfgFile=[int2str(NChanCalc) '.ecfg'];
else
	CoeffPath=[BasePath,'Plot2d3d:Plot3dCoeff40'];
	LegPath=[BasePath,'Plot2d3d:Plot3dLegCoeff'];
	ECfgPath=[BasePath,'Plot2d3d:Plot2dUtil:SensorCfg'];
	ECfgFile=[int2str(NChanCalc) '.ecfg'];
end			

ECfgFilePath=[ECfgPath ':' ECfgFile];		
fid=fopen(ECfgFilePath,'r');
fprintf('Start reading of file...\n\n');
fprintf(ECfgFilePath)
fprintf('\n\n');
[NChanCalc,count] = fread(fid,1,'int16');	
[ScalpRadius,count] = fread(fid,1,'float32');
[TmpSpher,count]= fread(fid,[NChanCalc,2],'float32');
fclose(fid);
AllEPosSpher=zeros(NChanCalc,3);
AllEPosSpher(:,1:2)=TmpSpher(1:NChanCalc,:);
AllEPosSpher(:,3)=ScalpRadius.*ones(NChanCalc,1);
AllEPosCart = change_sphere_cart(AllEPosSpher,ScalpRadius,1);
[Coeff] = ReadOrCalcCoeff(1,AllEPosCart,AllEPosCart,LegPath,CoeffPath,ECfgFile,32,15, 0, 5001);
InvCoeff=Coeff;
ForCoeff=Coeff';
%========================================
ch_UseApprox=0;
ch_SaveApproxFile=0;
if ch_UseWEFile
	
	[ch_UseApprox]=IfEmptyInputBo('Do you want to approximate bad channels ?',[],[],1,1);
	if ch_UseApprox
		[LambdaApprox]=IfEmptyInputVal(['Please insert the wished Lambda value of Approximation:'],[],[],2,1);
		
		for i=1:NChanCalc; InvCoeff(i,i)=Coeff(i,i)+LambdaApprox; end
		
		TmpDataMat=zeros(NChanCalc,NPoints);
		
		OrigDataFid=fopen(DataFilePath,'r');
		Header=fread(OrigDataFid,LHeader,'int8');
		fclose(OrigDataFid);
		if PlotStatus
			%===================Plot==========================
			%[ ch_SubtractMean]=IfEmptyInputBo(['Do you want to subtract the mean ?'],[],[],1,1);
			ChanToPlot=NChanCalc;
			MaxDataDef=50;
			[MaxData]=IfEmptyInputVal(['Please insert the maximal plot value:'],[],[],MaxDataDef,1);
			[MinData]=IfEmptyInputVal(['Please insert the minimal plot value:'],[],[],-1.*MaxData,1);
			StartPoint=1;
			EndPoint=NPoints;
			StimPoint=99;
			DefFontSize=10;
		
			[kTop,AxesTop,kFront,AxesFront,kBack,AxesBack,kLeft,...
			AxesLeft,kRight,AxesRight,kNorm,AxesNorm,kAll,AxesAll,...
			TopStatusVec,FrontStatusVec,BackStatusVec,LeftStatusVec,RightStatusVec,NormStatusVec,AllStatusVec] = ...
			Calc2dTimeAxes(AllEPosSpher);

			hw=ceil(sqrt(NChanCalc));
			AxesPlot=AxesNorm.*hw./(hw+1);			
			AxesAll=AxesAll.*hw./(hw+1);			
			if ~isempty(StimPoint)
				x=linspace((StartPoint-StimPoint)*1000./SampRate,(EndPoint-StimPoint)*1000./SampRate,EndPoint-StartPoint+1);
			else
				x=linspace(StartPoint.*1000./SampRate,EndPoint*1000./SampRate,EndPoint-StartPoint+1);
			end		
			%=======Original Data================
			OrigFig=figure('Units','normal','NumberTitle','off','Position',[0,0,.485,1],'Name','Original data:','Color',[0 0 0]);
			hOrigAxesAll=axes('Units','normal','Position',[0,0,1,1]);
			text('Units','normal','Position',[.025,.9],'String','Original data:','FontSize',[18]);
			text('Units','normal','Position',[.025,.025],'String','Bad channels:','Color','w','FontSize',[14]);
		    text('Units','normal','Position',[.025,.05],'String','Trial:                             ','Color','w','FontSize',[14]);
			hBadChanOrigText=text('Units','normal','Position',[.2,.025],'String','0','Color','w','FontSize',[14]);
			hTrialOrigText=text('Units','normal','Position',[.2,.05],'String','0','Color','w','FontSize',[14]);
			axis('off')
			hold on
			hOrigAxesVec=[]; 
			hOrigAxesVec(ChanToPlot+1)=axes('Units','normal','Position',[0.965-1/hw,0.03,1/hw,1/(2*hw)]);
			
			AxisHight=round(abs(MaxData/2)+abs(MinData/2));
			set(hOrigAxesVec(ChanToPlot+1),'ytick',[0 AxisHight],'FontSize',[12]); 
			if ~isempty(StimPoint) & StartPoint<=StimPoint & EndPoint>=StimPoint 
				set(hOrigAxesVec(ChanToPlot+1),'xtick',[0 x(length(x))]);
				htmp=line('XData',[0 0],'YData',[0 AxisHight],'Color','yellow','LineStyle','--');
			else
				set(hOrigAxesVec(ChanToPlot+1),'xtick',[x(1) x(length(x))]);
			end
			xlabel('Points')
			ylabel('Pot.')	
			for ChanInd=1:ChanToPlot
				hOrigAxesVec(ChanInd)=axes('Units','normal','Position',[AxesPlot(ChanInd,1),AxesPlot(ChanInd,2),1/hw,1/hw],'Box','off');
				axis('off')
				hOrigDataVec(ChanInd)=line('XData',x,'YData',zeros(1,EndPoint-StartPoint+1),'Color','y','LineStyle','-');
				hOrigtmp1(ChanInd)=line('XData',[x(1) x(length(x))],'YData',[0 0],'Color','y','LineStyle','--');
				if ~isempty(StimPoint);
					if StimPoint>=StartPoint & StimPoint<=EndPoint
						hOrigtmp2=line('XData',[0 0],'YData',[MinData./2 MaxData./2],'Color','yellow','LineStyle','--');
					end
				end
				axis([x(1) x(length(x)) MinData MaxData])
				text('Units','normal','Position',[0,0.6],'Color','m','String',num2str(ChanInd),'FontSize',DefFontSize)
			end
			%=======Approx Data================
			AppFig=figure('Units','normal','NumberTitle','off','Position',[.5,0,.485,1],'Name','Approx data:','Color',[0 0 0]);
			hAppAxesAll=axes('Units','normal','Position',[0,0,1,1]);
			text('Units','normal','Position',[.025,.9],'String','Approx data:','FontSize',[18]);
			text('Units','normal','Position',[.025,.025],'String','Bad channels:','Color','w','FontSize',[14]);
		    text('Units','normal','Position',[.025,.05],'String','Trial:                             ','Color','w','FontSize',[14]);
			hBadChanAppText=text('Units','normal','Position',[.2,.025],'String','0','Color','w','FontSize',[14]);
			hTrialAppText=text('Units','normal','Position',[.2,.05],'String','0','Color','w','FontSize',[14]);
			axis('off')
			hold on
			hAppAxesAll=[]; 
			hAppAxesAll(ChanToPlot+1)=axes('Units','normal','Position',[0.965-1/hw,0.03,1/hw,1/(2*hw)]);
			
			AxisHight=round(abs(MaxData/2)+abs(MinData/2));
			set(hAppAxesAll(ChanToPlot+1),'ytick',[0 AxisHight],'FontSize',[12]); 
			if ~isempty(StimPoint) & StartPoint<=StimPoint & EndPoint>=StimPoint 
				set(hAppAxesAll(ChanToPlot+1),'xtick',[0 x(length(x))]);
				htmp=line('XData',[0 0],'YData',[0 AxisHight],'Color','yellow','LineStyle','--');
			else
				set(hAppAxesAll(ChanToPlot+1),'xtick',[x(1) x(length(x))]);
			end
			xlabel('Points')
			ylabel('Pot.')	
			for ChanInd=1:ChanToPlot
				hAppAxesVec(ChanInd)=axes('Units','normal','Position',[AxesPlot(ChanInd,1),AxesPlot(ChanInd,2),1/hw,1/hw],'Box','off');
				axis('off')
				hAppDataVec(ChanInd)=line('XData',x,'YData',zeros(1,EndPoint-StartPoint+1),'Color','y','LineStyle','-');
				hApptmp1(ChanInd)=line('XData',[x(1) x(length(x))],'YData',[0 0],'Color','y','LineStyle','--');
				if ~isempty(StimPoint);
					if StimPoint>=StartPoint & StimPoint<=EndPoint
						hApptmp2=line('XData',[0 0],'YData',[MinData./2 MaxData./2],'Color','yellow','LineStyle','--');
					end
				end
				axis([x(1) x(length(x)) MinData MaxData])
				text('Units','normal','Position',[0,0.6],'Color','m','String',num2str(ChanInd),'FontSize',DefFontSize)
			end
		end
		%===============================
	end
end

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

AvgMat=zeros(NChanCalc,NPoints);
DataMat=zeros(NChanCalc,NPoints);
TrialsToAvgVec=find(EditVec==1);
NTrialsToAvg=length(TrialsToAvgVec);
AvgIndex=0;

%======================================================
if ch_SpecGrand==1	
	AppFilePath=[DataFilePath '.app' int2str(SpecCond)];
else
	AppFilePath=[DataFilePath '.appg'];
end
LAppHeader=1000;
AppFilePath=[DataFilePath '.app'];
AppFid=fopen(AppFilePath,'w');
fwrite(AppFid,AppVersion,'int16');
fwrite(AppFid,LAppHeader,'int16');
fwrite(AppFid,AppScaleBins,'int16');
fwrite(AppFid,NChanCalc,'int16');
fwrite(AppFid,NPoints,'int16');
fwrite(AppFid,NTrialsToAvg,'int16');
fwrite(AppFid,SampRate,'int16');
fwrite(AppFid,ch_AvgRef,'int16');

AppTell=ftell(AppFid);
ZeroVec=zeros(LAppHeader-AppTell,1);
fwrite(AppFid,ZeroVec,'int8');

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

OrigDataFid=fopen(DataFilePath,'r');
fseek(OrigDataFid,LHeader,'bof');

%========================================
	
fprintf('\n');clc;
if ch_UseWEFile 
	if ~ch_UseApprox
		SumEditVec=(sum(WeightEditMat(:,TrialsToAvgVec)'))';
		NTrialAvgChanVec=SumEditVec;
	else
		SumEditVec=NTrialsToAvg.*ones(NChanCalc,1);
		NTrialAvgChanVec=sum(WeightEditMat(:,TrialsToAvgVec)');
	end
else
	SumEditVec=NTrialsToAvg.*ones(NChanCalc,1);
	NTrialAvgChanVec=SumEditVec;
end
NAvgTrials=0;
MedMedRawVec=zeros(NTrials,1);
MedMedAvgVec=zeros(NTrials,1);

for TrialInd=1:NTrials
	fprintf(1,'Read trial: %g ;\n',TrialInd);
	if EditVec(TrialInd)==1
		fprintf(1,'Trial: %g ;  ',TrialInd);
		NAvgTrials=NAvgTrials+1;
		fprintf(1,'Avg. trial: %g\n\n',NAvgTrials);
		if ch_UseWEFile
			GoodChanVec=find(WeightEditMat(:,TrialInd)==1);	
			BadChanVec=find(WeightEditMat(:,TrialInd)==0);	
			NGoodChan=length(GoodChanVec);
			NBadChan=NChanCalc-NGoodChan;
			fprintf('Number of good channels: %g\n',NGoodChan)
			fprintf('Number of bad channels:   %g\n',NBadChan)
		else
			GoodChanVec=[1:NChanCalc];
			NGoodChan=NChanCalc;
		end
		DataMat=fread(OrigDataFid,[NChan,NPoints],'int16');

		for TimeInd=1:NPoints
			DataMat(:,TimeInd)=(DataMat(:,TimeInd)-ChanZero).*ChanGainVec;
		end
	
		if ch_AvgRef
			AvgRefMat=zeros(NChanCalc,NPoints);
			AvgRefMat(1:NChan,:)=DataMat; DataMat=[];
			AvgRefVec=(sum(AvgRefMat(GoodChanVec,:)))./(length(GoodChanVec));
			for TimeInd=1:NPoints
				AvgRefMat(GoodChanVec,TimeInd)=AvgRefMat(GoodChanVec,TimeInd)-ones(NGoodChan,1).*AvgRefVec(TimeInd);
			end
			AvgRefMat(NChanCalc,:)=-1.*AvgRefVec;
			DataMat=AvgRefMat; AvgRefMat=[];
		end
		if PlotStatus
			for ChanInd=1:ChanToPlot
				if        any(GoodChanVec==ChanInd); PlotColor='w'; PlotLineStyle='-';
				else ; 								 PlotColor='r'; PlotLineStyle='-';
				end
				set(hOrigDataVec(ChanInd),'YData',DataMat(ChanInd,StartPoint:EndPoint),'Color',PlotColor,'LineStyle',PlotLineStyle);
			end
			set(hBadChanOrigText,'String',int2str(NBadChan));
			set(hTrialOrigText,'String',int2str(TrialInd));
			pause(.1);
		end
		if ch_UseApprox
			if ~isempty(BadChanVec)
				TmpDataMat=DataMat(GoodChanVec,:);
				c0=mean(TmpDataMat);
				[TmpDataMat]=CalcValOfVecToMat(TmpDataMat,c0,['-']);
				DipStrength = InvCoeff(GoodChanVec,GoodChanVec) \ TmpDataMat;
				TmpDataMat=(DipStrength' * ForCoeff(GoodChanVec,:))';
				[TmpDataMat]=CalcValOfVecToMat(TmpDataMat,c0,['+']);	
				DataMat(BadChanVec,:)=TmpDataMat(BadChanVec,:);
			end
			if PlotStatus
				for ChanInd=1:ChanToPlot
					if        any(GoodChanVec==ChanInd); PlotColor='w'; PlotLineStyle='-';
					else ; 								 PlotColor='r'; PlotLineStyle='-';
					end
					set(hAppDataVec(ChanInd),'YData',DataMat(ChanInd,StartPoint:EndPoint),'Color',PlotColor,'LineStyle',PlotLineStyle);
				end
				set(hBadChanAppText,'String',int2str(NBadChan));
				set(hTrialAppText,'String',int2str(TrialInd));
				if PauseStatus; 
					pause; 
				else
					pause(.1)
				end	
			end
			MedMedRawVec(TrialInd)=median(median(abs(DataMat)));
			AvgMat=AvgMat+DataMat;
			MaxAbsDataMat=max(max(abs(DataMat)));
		else	
			MedMedRawVec(TrialInd)=median(median(abs(DataMat(GoodChanVec,:))));
			AvgMat(GoodChanVec,:)=AvgMat(GoodChanVec,:)+DataMat(GoodChanVec,:);
			MaxAbsDataMat=max(max(abs(DataMat(GoodChanVec,:))));
		end
		MedMedAvgVec(TrialInd)=median(median(abs(AvgMat(GoodChanVec,:))));
		%==========================================================
		
		if MaxAbsDataMat.*AppScaleBins>32768; fprintf('WARNING: Bad scaling in SaveAppData !!!!!'); end
		fwrite(AppFid,DataMat'.*AppScaleBins,'int16');
		%==========================================================			
	else			%	if EditVec(TrialInd)==1
		fprintf(1,'Trial: %g  xxx\n\n\n',TrialInd);
		fseek(OrigDataFid,NBytesInTrial,'cof');
	end			%	if EditVec(TrialInd)==1
end	%for TrialInd
NotZeroIndexVec=find(SumEditVec~=0);
for TimeInd=1:NPoints
	AvgMat(NotZeroIndexVec,TimeInd)=AvgMat(NotZeroIndexVec,TimeInd)./SumEditVec(NotZeroIndexVec);
end

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

if PlotStatus
	close(OrigFig);close(AppFig);
end
fclose(OrigDataFid); 
fclose(AppFid); 	

if PlotStatus
	hStdFig=figure('Units','normal','NumberTitle','off','Position',[0,0,.666,1],'Name','Std:','Color',[0 0 0]);
	hStdAxesAll=axes('Units','normal','Position',[0,0,1,1]);
	axis('off');
	[StdAxesPos]=CalcAxesPos(NTrialsToAvg+1,[.05 .05 0 0 .05],2);
	x=[1:NPoints];
	MinData=-15;
	MaxData=15;
end
for TrialInd=1:NTrialsToAvg
	if PlotStatus
		hStdAxesVec(TrialInd)=axes('Units','normal','Position',StdAxesPos(TrialInd,:));
		axis('off')
		hStdDataVec(TrialInd)=line('XData',x,'YData',zeros(1,NPoints),'Color','y','LineStyle','-');
		hOrigDataVec(TrialInd)=line('XData',x,'YData',zeros(1,NPoints),'Color','y','LineStyle','-');
		axis([1 NPoints MinData MaxData])
		line('XData',[x(1) x(length(x))],'YData',[0 0],'Color','y','LineStyle','--');
		text('Units','normal','Position',[0,.9],'String','Trial:','FontSize',[12],'Color','w');
		text('Units','normal','Position',[0,.9],'String','Trial:','FontSize',[12],'Color','w');
		text('Units','normal','Position',[.15,.9],'String',num2str(TrialsToAvgVec(TrialInd)),'FontSize',[12],'Color','w');
		text('Units','normal','Position',[.3,.9],'String','Mean Time Std:','FontSize',[12],'Color','w');
		hTrialStdVec(TrialInd)=text('Units','normal','Position',[.8,.9],'String','0','FontSize',[12],'Color','w');
	end
end
if PlotStatus
	hStdAxesVec(NTrialsToAvg+1)=axes('Units','normal','Position',StdAxesPos(NTrialsToAvg+1,:));
	axis('off')
	text('Units','normal','Position',[.1,.33],'String','Channel:','FontSize',[18]);
	text('Units','normal','Position',[.1,.66],'String','Mean Trial Std:','Color','w','FontSize',[18]);
	hChanText=text('Units','normal','Position',[.75,.33],'String','0','Color','w','FontSize',[18]);
	hMeanStdText=text('Units','normal','Position',[.75,.66],'String','0','Color','w','FontSize',[18]);
end

StdTrialTimeMat=zeros(NTrialsToAvg,NPoints);
StdChanTimeMat=zeros(NChanCalc,NPoints);
AppFid=fopen(AppFilePath,'r');

if NTrialsToAvg>1
	for ChanInd=1:NChanCalc
		AvgTmp=AvgMat(ChanInd,:);
		SeekStatus=fseek(AppFid,LAppHeader+(ChanInd-1).*NPoints.*2,-1);
		for TrialInd=1:NTrialsToAvg
			if TrialInd>1
				SeekStatus=fseek(AppFid,(NChanCalc-1).*NPoints.*2,0);
				if SeekStatus==-1; error('fseek error'); end		
			end		
			DataTmp=(fread(AppFid,NPoints,'int16'))';
			DataTmp=DataTmp./AppScaleBins;
			StdTrialTimeMat(TrialInd,:)=DataTmp;
			DiffTmp=DataTmp-AvgTmp;	
			StdTmp=std(DiffTmp);
			if PlotStatus
				if WeightEditMat(ChanInd,TrialsToAvgVec(TrialInd)); PlotColor='w'; else; PlotColor='r'; end
				set(hStdDataVec(TrialInd),'YData',DataTmp-ones(1,NPoints).*mean(DataTmp),'Color',PlotColor);
				set(hOrigDataVec(TrialInd),'YData',AvgTmp-ones(1,NPoints).*mean(AvgTmp),'Color','y');
				set(hTrialStdVec(TrialInd),'String',num2str(StdTmp));
			end
		end
		%===============================================
		StdChanTimeMat(ChanInd,:)=std(StdTrialTimeMat); %std over trials
		%===============================================
		MeanStdChanVec(ChanInd)=mean(StdChanTimeMat(ChanInd,:));
		if PlotStatus
			set(hChanText,'String',num2str(ChanInd));
			set(hMeanStdText,'String',num2str(MeanStdChanVec(ChanInd)));	
			if PauseStatus; 
				pause;
			else
				pause(.5);
			end		
		else
			fprintf('Channel: %g  ; Trial Std: %g !\n',ChanInd,(round(MeanStdChanVec(ChanInd).*1000)./1000))
		end
	end
end

fclose(AppFid); 	

if PlotStatus
	pause(1);
	close(hStdFig);
end
%==============================================
%=======Plot MeanStdChanVec  ===================
if PlotStatus
	ChanToPlot=NChanCalc;
	MinData=min(min(StdChanTimeMat));
	MaxData=max(max(StdChanTimeMat));
	if MinData==MaxData
		fprintf(' min(min(StdChanTimeMat))==max(max(StdChanTimeMat))');
		MinData=MinData-1;
		MaxData=MaxData+1;
	end
	
	StartPoint=76;
	EndPoint=200;
	NPlotPoints=EndPoint-StartPoint+1;
	%EndPoint=NPoints;
	StimPoint=300;
	DefFontSize=9;
		
	[kTop,AxesTop,kFront,AxesFront,kBack,AxesBack,kLeft,...
	AxesLeft,kRight,AxesRight,kNorm,AxesNorm,kAll,AxesAll,...
	TopStatusVec,FrontStatusVec,BackStatusVec,LeftStatusVec,RightStatusVec,NormStatusVec,AllStatusVec] = ...
	Calc2dTimeAxes(AllEPosSpher);
	hw=ceil(sqrt(NChanCalc));
	AxesPlot=AxesNorm.*hw./(hw+1);			
	AxesAll=AxesAll.*hw./(hw+1);			
	if ~isempty(StimPoint)
		x=linspace((StartPoint-StimPoint)*1000./SampRate,(EndPoint-StimPoint)*1000./SampRate,EndPoint-StartPoint+1);
	else
		x=linspace(StartPoint.*1000./SampRate,EndPoint*1000./SampRate,EndPoint-StartPoint+1);
	end		
	hStdMatFig=figure('Units','normal','NumberTitle','off','Position',[0,0,.666,1],'Name','Std:','Color',[0 0 0]);
	hStdMatAllAxes=axes('Units','normal','Position',[0,0,1,1]);
	text('Units','normal','Position',[.025,.9],'String','Std:','FontSize',[18]);
	axis('off')
	hold on
	hStdMatAxesVec=[]; 		
	hStdMatAxesVec(ChanToPlot+1)=axes('Units','normal','Position',[0.965-1/hw,0.03,1/hw,1/(2*hw)]);	
	AxisHight=round(abs(MaxData/2)+abs(MinData/2));
	set(hStdMatAxesVec(ChanToPlot+1),'ytick',[0 AxisHight],'FontSize',[12]); 
	if ~isempty(StimPoint) & StartPoint<=StimPoint & EndPoint>=StimPoint 
		set(hStdMatAxesVec(ChanToPlot+1),'xtick',[0 x(length(x))]);
		line('XData',[0 0],'YData',[0 AxisHight],'Color','y','LineStyle','--');
	else
		set(hStdMatAxesVec(ChanToPlot+1),'xtick',[x(1) x(length(x))]);
	end
	xlabel('Points')
	ylabel('Pot.')	
	for ChanInd=1:ChanToPlot
		hStdMatAxesVec(ChanInd)=axes('Units','normal','Position',[AxesPlot(ChanInd,1),AxesPlot(ChanInd,2),1/hw,1/hw],'Box','off');
		axis('off')
		line('XData',x,'YData',StdChanTimeMat(ChanInd,:),'Color','w','LineStyle','-');
		line('XData',[x(1) x(length(x))],'YData',[0 0],'Color','y','LineStyle','--');
		if ~isempty(StimPoint);
			if StimPoint>=StartPoint & StimPoint<=EndPoint
				line('XData',[0 0],'YData',[MinData./2 MaxData./2],'Color','y','LineStyle','--');
			end
		end
		axis([x(1) x(length(x)) MinData MaxData])
		text('Units','normal','Position',[0,0.5],'Color','m','String',num2str(ChanInd),'FontSize',DefFontSize)
		text('Units','normal','Position',[0,0.65],'Color','w','String',num2str(MeanStdChanVec(ChanInd)),'FontSize',DefFontSize)
		text('Units','normal','Position',[0,0.8],'Color','y','String',num2str(NTrialAvgChanVec(ChanInd)),'FontSize',DefFontSize)
	end
	%==============================================
	pause
	close(hStdMatFig);
end
%========================================
if ~ch_AvgRef
	AvgNChan=NChan+1;
	%Der NChan+1 Kanal wird fuer die gemittelte Referenz reserviert
	AvgMatTmp=zeros(AvgNChan,NPoints);
	AvgMatTmp(1:AvgNChan-1,:)=AvgMat; AvgMat=[]; AvgMat=AvgMatTmp; AvgMatTmp=[];
		
	%SumEditVec beinhaltet die gemittelten trials pro Kanal
	%Der AvgNChan Wert des SumEditVec beinhaltet den Median Wert des Vektors SumEditVec(1:AvgNChan-1)
	SumEditVecTmp=zeros(AvgNChan,1);
	SumEditVecTmp(1:AvgNChan-1)=SumEditVec;
	SumEditVecTmp(AvgNChan)=median(SumEditVec);
	SumEditVec=[]; SumEditVec=SumEditVecTmp; SumEditVecTmp=[];
	NoiseVecTmp=zeros(AvgNChan,1);
	NoiseVecTmp(1:AvgNChan-1)=NoiseVec;
	NoiseVecTmp(AvgNChan)=median(NoiseVecTmp);
	NoiseVec=[]; NoiseVec=NoiseVecTmp; NoiseVecTmp=[];
else
	AvgNChan=NChanCalc;
end

[ch_SumEditVec]=IfEmptyInputBo(['Do you want to display the SumEditVec ?'],[],[],0,1);
if ch_SumEditVec; disp(SumEditVec'); end

SumNoiseVec=(1./NoiseVec).*SumEditVec;
[ch_SumNoiseVec]=IfEmptyInputBo(['Do you want to display the SumNoiseVec ?'],[],[],0,1);
if ch_SumNoiseVec; disp(SumNoiseVec'); end

if ch_UseApprox
	[ch_NTrialAvgChanVec]=IfEmptyInputBo(['Do you want to display the NTrialAvgChanVec ?'],[],[],0,1);
	if ch_NTrialAvgChanVec; disp(NTrialAvgChanVec); end
end
if ~ch_AvgRef
	SaveStdChanTimeMat=zeros(AvgNChan,NPoints);
	SaveStdChanTimeMat(1:NChanCalc,:)=StdChanTimeMat;
	SaveNTrialAvgChanVec=zeros(AvgNChan,1);
	SaveNTrialAvgChanVec(1:NChan)=NTrialAvgChanVec; 
else
	SaveStdChanTimeMat=StdChanTimeMat;
	SaveNTrialAvgChanVec=NTrialAvgChanVec;
end
%=================================Save this averaged data to file=================================

if isempty(PathResult); PathResult=DataPath; end;
if ch_SpecGrand==2
	AvgFilePath=[PathResult,DataFile,'.atg'];
	AvgTrialIndFilePath=[DataFilePath '.AvgIndg'];
elseif ch_SpecGrand==1
	AvgFilePath=[PathResult,DataFile,'.at',int2str(SpecCond)];
	AvgTrialIndFilePath=[DataFilePath '.AvgInd' int2str(SpecCond)];
end
if isempty(TrialsToAvgVec); 
	TrialsToAvgVec=0; 
	IsTrialInFile=0;
else
	IsTrialInFile=1;
end
SaveData(TrialsToAvgVec,AvgTrialIndFilePath,1,[],'ascii','ascii',[],[],[],1,1,0);

if IsTrialInFile
	if ch_AvgRef
		AvgFilePath=[AvgFilePath,'.ar'];
	end
	fprintf('\n');clc; fprintf('Save this averaged data to file:\n\n'); fprintf(AvgFilePath); fprintf('\n\n'); 
	[ch_UseDefFileName]=IfEmptyInputBo(['Do you want to take this default file name ? Y/N'],[],[],1);
	if ~ch_UseDefFileName; AvgFilePath=[]; end
	SaveAvgFile(AvgFilePath,AvgMat,SaveNTrialAvgChanVec,SaveStdChanTimeMat,SampRate,MedMedRawVec,MedMedAvgVec);

	if ~ch_AvgRef	
		%===================Calculate the average reference====================================================
		AvgRefMat=zeros(size(AvgMat));

		AvgRefMat(NChanCalc+1,:)=-1.*sum(AvgMat)./NChanCalc;
		for TimeInd=1:NPoints
			AvgRefMat(1:NChan,TimeInd)=AvgMat(1:NChan,TimeInd)+AvgRefMat(NChan+1,TimeInd).*ones(NChan,1);
		end

		AvgFilePath=[AvgFilePath,'.ar'];
		fprintf('\n');clc; fprintf('Save this averaged data to file:\n\n'); fprintf(AvgFilePath); fprintf('\n\n'); 
		[ch_UseDefFileName]=IfEmptyInputBo(['Do you want to take this default file name ? Y/N'],[],[],1);
		if ~ch_UseDefFileName; SaveFilePath=[]; end
		SaveAvgFile(AvgFilePath,AvgRefMat,SaveNTrialAvgChanVec,SaveStdChanTimeMat,SampRate,MedMedRawVec,MedMedAvgVec);
	end %if ~ch_AvgRef	
end


return;
