function [SaveFilePath,ChanStatusVec]=FindBadChan(FileMat,LimesFac,BatchStatus)

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

if nargin<3; BatchStatus=[]; end
if nargin<2; LimesFac=[]; end
if nargin<1; FileMat=[]; end

MatlabVersionString=version;
MainMatlabVersion=str2num(MatlabVersionString(1));

[NFiles,FileMat]=ReadFileNames(FileMat,'*.AEM*','Choose EditMat files:');
[LimesFac]=IfEmptyInputVal('Please insert the limes:',[],LimesFac,2,1);
if isempty(BatchStatus); BatchStatus=0; end

for FileIndex=1:NFiles
	
	[File,Path,FilePath]=GetFileNameOfMat(FileMat,FileIndex);
	if strcmp(FilePath(length(FilePath)-2:length(FilePath)),'.AR');
		ch_CalcAvfRef=1;
	else
		ch_CalcAvfRef=0;
	end

	[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([],NChan);

	%===================How to Plot Data===============================
    ECfgFile=GetDefEcfgFile(NChan);
    ECfgFilePath=which(ECfgFile);

	[NChanTmp,SpherRadius,EPosSpher,ENames,EConfigFile,EConfigPath,EConfigFilePath]=ReadEConfig(ECfgFilePath);
	
	%==================================================================
	ChanAllVec=[1:NChan];
	ChanStatusVec=ones(NChan,1);
	XAllVec=EPosSpher(:,1);
	[XAllVecSort,XAllIVecSort]=sort(XAllVec);
	

	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);
		if ~BatchStatus
			NoiseFig=figure('Units','normal','NumberTitle','off','Position',[0,0,.66,1],'Name',[StatusStr ' noise of theta in ' File]);
		end
		YAllVec=MedMat;
		YAllVecSort=YAllVec(XAllIVecSort);
		ChanAllVecSort=ChanAllVec(XAllIVecSort);
		ChanVecSort=ChanAllVecSort;
		XVecSort=XAllVec(ChanVecSort);
		YVecSort=YAllVec(ChanVecSort);
		p=polyfit(XVecSort,YVecSort,2);
		f=polyval(p,XVecSort);
		NVecSort=YVecSort-f;
		
		MedVecSort=median(NVecSort);
		StdVecSort=std(NVecSort);
		HiLimes=MedVecSort+StdVecSort.*LimesFac;
		LoLimes=MedVecSort-StdVecSort.*LimesFac;
		GoodChanVecIndSort=find(NVecSort<=HiLimes | NVecSort>=LoLimes);
		BadChanVecIndSort=find(NVecSort>HiLimes | NVecSort<LoLimes);
		
		GoodChanVecSort=ChanAllVecSort(GoodChanVecIndSort);
		BadChanVecSort=ChanVecSort(BadChanVecIndSort);
		if ~isempty(BadChanVecSort)
			ChanStatusVec(BadChanVecSort)=zeros(size(BadChanVecSort));
		end
		if ~BatchStatus
			
			subplot(2,1,1)
			plot(XVecSort,YVecSort,'ko')
			hold on
			plot(XVecSort,f,'--')
			for i=1:NChan
				if any(BadChanVecIndSort==i)
					PlotColor='r';
				else
					PlotColor='w';
				end
				text('Position',[XVecSort(i),YVecSort(i)],'String',int2str(ChanVecSort(i)),'FontSize',[10],'Color',PlotColor);
			end
			title('YVecSort')
			
			axis([min(XVecSort) max(XVecSort) 0 max(YVecSort)])


			subplot(2,1,2)
			plot(XVecSort,NVecSort,'ko')
			hold on
			plot(XVecSort,zeros(size(XVecSort)),'--')
			plot(XVecSort,HiLimes.*ones(size(XVecSort)),'r--')
			plot(XVecSort,LoLimes.*ones(size(XVecSort)),'r--')
			for i=1:NChan
				if any(BadChanVecIndSort==i)
					PlotColor='r';
				else
					PlotColor='w';
				end
				text('Position',[XVecSort(i),YVecSort(i)-f(i)],'String',int2str(ChanVecSort(i)),'FontSize',[10],'Color',PlotColor);
			end
			title('YVecSort-f')	
			axis([min(XVecSort) max(XVecSort) min(YVecSort-f) max(YVecSort-f)])
			pause
			close(NoiseFig);
		end
	end	
	SaveFilePath=[FilePath(1:length(FilePath)-3),int2str(NChan) 'est'];
	fprintf('Save electrode status to disk in file:\n');
	fprintf(SaveFilePath);
	fprintf('\n');
	fid=fopen(SaveFilePath,'w','b');
	fwrite(fid,ChanStatusVec,'int16'); 
	fclose(fid);
	SaveFilePath=[FilePath(1:length(FilePath)-3),int2str(NChan+1) 'est'];
	fprintf('Save electrode status to disk in file:\n');
	fprintf(SaveFilePath);
	fprintf('\n');
	fid=fopen(SaveFilePath,'w','b');
	fwrite(fid,ChanStatusVec,'int16'); 
	fwrite(fid,1,'int16'); 
	fclose(fid);
end


return;
