%==================================================================
%
%	CalcThetaNoise.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 [SaveFilePath]=CalcThetaNoise(FileMat,EConfigFilePath,ENames,BatchStatus)
	
%=================================================================
%=================================================================
if nargin<4; BatchStatus=0; end;
if nargin<3; ENames=[]; end;
if nargin<2; EConfigFilePath=[]; ch_TakeDefEFile=[]; end;
if nargin<1; FileMat=[]; end

[NFiles,FileMat]=ReadFileNames([],'*.AEM*','Choose EditMat files:');

for OverAllFileIndex=1:NFiles
	
	FilePath=FileMat(OverAllFileIndex,2:FileMat(OverAllFileIndex,1)+1);
	[File,Path]=SepFilePath(FilePath);
	[AbsMat,NoUse,NoUse,NoUse,EndPos] = ReadData(FilePath,1);
	[StdMat,NoUse,NoUse,NoUse,EndPos] = ReadData(FilePath,1,[],'int16','float32',EndPos);
	[TraMat]= ReadData(FilePath,1,[],'int16','float32',EndPos);

%==================================================================
	[NChan,NTrials]=size(AbsMat);

	[ENames]=SetENames(ENames,NChan);

	%===================How to Plot Data======================================================
	if isempty(EConfigFilePath)
	
		fprintf('\n');clc;
		[ch_TakeDefEFile]=IfEmptyInputBo(['Do you want to take the 128 electrode default file ?'],ch_TakeDefEFile,1,1,1);
		if ch_TakeDefEFile
			cd ..;eval(['cd GeoUtil']);
			DefEFilePath=[pwd ':' int2str(NChan) '.ecfg'];
			cd ..; eval(['cd GeoAnalysis1.0']);
			ExEConfigFilePath=exist(DefEFilePath);
			if ExEConfigFilePath~=2
				fprintf('Sorry, but this file does not exist any more !');pause(2);fprintf('\n');clc		
			else
				EConfigFilePath=DefEFilePath;
			end
		end
		if ~ch_TakeDefEFile | (ch_TakeDefEFile & ExEConfigFilePath~=2)
			EConfigFilePath=[];
			fprintf('Please choose the electrode config file:')
			pause(1)
		end
	end
	[NChanTmp,SpherRadius,EPosSpher,ENames,EConfigFile,EConfigPath,EConfigFilePath]=ReadEConfig(EConfigFilePath);
	%==================================================================
	ChanAllVec=[1:NChan];
	ChanMatStatusVec=ones(NChan,1);
	
	for MatInd=1:3
		if MatInd==1
			Mat=AbsMat;
			StatusStr='Absolut';
		elseif MatInd==2
			Mat=StdMat;
			StatusStr='Std';
		elseif MatInd==3
			Mat=TraMat;
			StatusStr='Transit';
		end
		ThresVec=ones(NChan,1);

		MaxMat=(max(Mat'))';
		MaxMaxMat=max(MaxMat);
		MinMat=(min(Mat'))';
		MinMinMat=min(MinMat);
		MeanMat=(mean(Mat'))';
		MeanMeanMat=mean(MeanMat);
		MedMat=(median(Mat'))';
		MedMedMat=median(MedMat);
		
		Again=1;
		AgainInd=0;
		
		while Again
			
			if AgainInd==0
				NoiseFig=figure('Units','normal','NumberTitle','off','Position',[0,0,.66,1],'Name',[StatusStr ' noise of theta in ' File]);
				XAllVec=EPosSpher(:,1);
				[XAllVecSort,XAllIVecSort]=sort(XAllVec);
				YAllVec=MedMat;
				YAllVecSort=YAllVec(XAllIVecSort);
				ChanAllVecSort=ChanAllVec(XAllIVecSort);
				ChanVecSort=ChanAllVecSort;
				AgainInd=1;
			else
				clf;
			end
		
			XVecSort=XAllVec(ChanVecSort);
			YVecSort=YAllVec(ChanVecSort);
					
			p=polyfit(XVecSort,YVecSort,2);
			f=polyval(p,XVecSort);
				
			subplot(3,1,1)
			plot(XVecSort,YVecSort,'ko')
			hold on
			plot(XVecSort,f,'--')
			for i=1:length(XVecSort)
				text('Position',[XVecSort(i),YVecSort(i)],'String',int2str(ChanVecSort(i)),'FontSize',[10]);
			end
			title('YVecSort of special channels')
			
			subplot(3,1,2)
			plot(XVecSort,YVecSort-f,'ko')
			hold on
			plot(XVecSort,zeros(size(f)),'--')
			for i=1:length(XVecSort)
				text('Position',[XVecSort(i),YVecSort(i)-f(i)],'String',int2str(ChanVecSort(i)),'FontSize',[10]);
			end
			title('YVecSort-f of special channels')
			
			subplot(3,1,3)
			fAll=interp1(XVecSort,f,XAllVecSort,'spline');
			fAllReSort(XAllIVecSort)=fAll;
			AmplFacVec(XAllIVecSort)=1./(fAll./min(fAll));
			NAllVecSort=(YAllVecSort-fAll);
			NAllVecReSort(XAllIVecSort)=NAllVecSort;
			
			plot(XAllVecSort,NAllVecSort,'ko')
			hold on
			plot(XAllVecSort,ones(size(fAll)),'--')
			for i=1:NChan
				text('Position',[XAllVecSort(i),NAllVecSort(i)],'String',int2str(XAllIVecSort(i)),'FontSize',[10]);	
			end
			title('NAllVecSort of all channels')
			[Again]=IfEmptyInputBo('Again ?',[],[],1,1); 
			fprintf('\n\n')
			%SaveFig=figure('Units','normal','NumberTitle','off','Position',[0,.33,.66,.66],'Name','Data to save:');
			%subplot(2,1,1)
			%plot(fAllReSort)
			%title('fAllReSort')
			%subplot(2,1,2)
			%plot(NAllVecReSort)
			%title('NAllVecReSort')
			%close(SaveFig)
			
			if Again
				[ChanVecIndSort,NoChanVecIndSort,ChanStatusVec,ch_ChooseChannelInd]=ChooseChanInd(NChan,[],1,[],[],[],EPosSpher,ENames);;		
				if ~ch_ChooseChannelInd
					[MaxNoiseFac]=IfEmptyInputValInt('Please insert the maximum noise factor:',[],[],2,1);
					ChanVecIndSort=find(YAllVecSort-fAll<MaxNoiseFac);
					NoChanVecIndSort=find(YAllVecSort-fAll>MaxNoiseFac);
				end
				ChanVecSort=ChanAllVecSort(ChanVecIndSort);
			else
				if ~isempty(NoChanVecIndSort)
					NoChanVecSort=ChanAllVecSort(NoChanVecIndSort);
					ChanStatusVec=ones(NChan,1);
					ChanStatusVec(NoChanVecSort)=zeros(length(NoChanVecSort),1);
					ChanMatStatusVec(NoChanVecSort)=zeros(length(NoChanVecSort),1);
					[ch_SaveSpecEStatus]=IfEmptyInputBo('Do you want to save this special channel status vector ?',[],[],0,1);
					[SaveFile,SavePath,SaveFilePath]=SaveEStatus(ChanStatusVec,[],[],[],ch_SaveSpecEStatus);
				end
			end
		end
		
		if MatInd==1	
			[NoUse,TEndPos]=SaveData(fAllReSort,[FilePath '.T'],1);
			[NoUse,FEndPos]=SaveData(NAllVecReSort,[FilePath '.F'],1);
		else
			[NoUse,TEndPos]=SaveData(fAllReSort,[FilePath '.T'],1,[],'int16','float32',1,TEndPos);
			[NoUse,FEndPos]=SaveData(NAllVecReSort,[FilePath '.F'],1,[],'int16','float32',1,FEndPos);
		end	
		close(NoiseFig);
	end
	[ch_SaveMatEStatus]=IfEmptyInputBo('Do you want to save the combined ','abs, std and transit channel status vector ?',[],1,1);
	[SaveFile,SavePath,SaveFilePath]=SaveEStatus(ChanMatStatusVec,[],[],[],ch_SaveMatEStatus);
end
return;
