function [AWEFileMat,WeightMat]=FindBadChanTrial(AEMFileMat,LimesFac,BatchStatus,SkipStepStatus,PrintStatus)

%	FindBadChanTrial.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.

if nargin<5; SkipStepStatus = 0;end
if nargin<4; PrintStatus = 0;end
if nargin<3; BatchStatus=[]; end
if nargin<2; LimesFac=[]; end
if nargin<1; AEMFileMat=[]; end

if isempty(BatchStatus); BatchStatus=0; end
[NFiles,AEMFileMat]=ReadFileNames(AEMFileMat,'*.AEM*','Choose EditMat files:');

[LimesFac]=IfEmptyInputVal('Please insert the limes:',[],LimesFac,2.5,0);
[AWEFileMat]=FileNameExt2Mat(AEMFileMat,['.AWE']);

if ~BatchStatus
	[PlotStatus]=IfEmptyInputBo('Do you want to plot all calculations ?',[],[],1,1);
else
	PlotStatus=0;
end

fprintf(1,'Finding bad channels in trials...\n');
for FileIndex=1:NFiles
	
	[File,Path,FilePath]=GetFileNameOfMat(AEMFileMat,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,[],[],[],[],[],[],[],[],0,0);
	[StdMat,NoUse,NoUse,NoUse,EndPos] = ReadData(FilePath,1,[],'int16','float32',EndPos,[],[],[],[],0,0);
	[TraMat]= ReadData(FilePath,1,[],'int16','float32',EndPos,[],[],[],[],0,0);

%==================================================================
	[NChan,NTrials]=size(AbsMat);
	WeightMat=ones(NChan,NTrials);
	[ENames]=SetENames([],NChan);
	
	if PlotStatus
		MatlabVersionString=version;						
		MainMatlabVersion=str2num(MatlabVersionString(1));	

		%===================How to Plot Data======================================================
		ECfgFile=GetDefEcfgFile(NChan);	
        ECfgFilePath=which(ECfgFile);
		[NChanTmp,ScalpRadius,AllEPosSpher,ENames,EConfigFile,EConfigPath,EConfigFilePath]=ReadEConfig(ECfgFilePath,0);
		AllEPosCart = change_sphere_cart(AllEPosSpher,ScalpRadius,1);
		%===================Plot==========================
		
		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(NChanTmp));
		AxesPlot=AxesNorm.*hw./(hw+1);			
		AxesAll=AxesAll.*hw./(hw+1);					
		x=[1:NTrials];
		hAllFig=figure('Units','normal','NumberTitle','off','Position',[0,0,.475,1],'Name','Find bad electrode-trials:');
		hStdAxesAll=axes('Units','normal','Position',[0,0,1,1]);
		hStatusText=text('Units','normal','Position',[.05,.9],'String','Hallo','Color','w','FontSize',[18]);
		axis('off')
		hold on
		hOrigAxesVec=[]; 
		hOrigAxesVec(NChan+1)=axes('Units','normal','Position',[0.965-1/hw,0.03,1/hw,1/(2*hw)]);		
		set(hOrigAxesVec(NChan+1),'xtick',[1 NTrials],'FontSize',[12]); 
		xlabel('Trials')
		ylabel('Pot.')	
		hOrigDataMat=zeros(NChan,NTrials);
		for ChanInd=1:NChan
			hOrigAxesVec(ChanInd)=axes('Units','normal','Position',[AxesPlot(ChanInd,1),AxesPlot(ChanInd,2),1/hw,.5/hw],'Box','off');
			axis('off')
		end
	end
	%==================================================================
	WeightMatTmp=ones(NChan,NTrials);
	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
		if PlotStatus
			set(hStatusText,'String',StatusStr);
		end
		StdVec=(std(Mat'))';
		MedVec=(median(Mat'))';
		for ChanInd=1:NChan
			UpperLimesVec(ChanInd)=MedVec(ChanInd)+StdVec(ChanInd).*LimesFac;
			LowerLimesVec(ChanInd)=MedVec(ChanInd)-StdVec(ChanInd).*LimesFac;
			BadTrialVec=find(Mat(ChanInd,:)>UpperLimesVec(ChanInd) | Mat(ChanInd,:)<LowerLimesVec(ChanInd));
			GoodTrialVec=find(Mat(ChanInd,:)<=UpperLimesVec(ChanInd) | Mat(ChanInd,:)>=LowerLimesVec(ChanInd));
			NBadTrial=length(BadTrialVec);
			NGoodTrial=length(GoodTrialVec);
			WeightMatTmp(ChanInd,BadTrialVec)=zeros(1,NBadTrial);
			if PlotStatus
				axes(hOrigAxesVec(ChanInd));
				plot(GoodTrialVec,Mat(ChanInd,GoodTrialVec),'.');
				hold on
				plot(BadTrialVec,Mat(ChanInd,BadTrialVec),'r.');
				line('XData',[1 NTrials],'YData',[MedVec(ChanInd) MedVec(ChanInd)],'Color','w','LineStyle','-');
				line('XData',[1 NTrials],'YData',[UpperLimesVec(ChanInd) UpperLimesVec(ChanInd)],'Color','r','LineStyle','--');
				line('XData',[1 NTrials],'YData',[LowerLimesVec(ChanInd) LowerLimesVec(ChanInd)],'Color','r','LineStyle','--');
				axis([1 NTrials min(Mat(ChanInd,:)) max(Mat(ChanInd,:))])
				axis('off')
				hold off
			end
		end
		WeightMat=WeightMat.*WeightMatTmp;
		if PlotStatus; pause; end
	end
	if PlotStatus
		set(hStatusText,'String','All');
		for ChanInd=1:NChan	
			axes(hOrigAxesVec(ChanInd));
			BadTrialVec=find(WeightMat(ChanInd,:)==0);
			GoodTrialVec=find(WeightMat(ChanInd,:)==1);
			NBadTrial=length(BadTrialVec);
			NGoodTrial=length(GoodTrialVec);
			plot(GoodTrialVec,zeros(NGoodTrial,1),'wx');
			hold on
			plot(BadTrialVec,ones(NBadTrial,1),'rx');
			axis([1 NTrials -1 2])
			axis('off')
		end
		if PlotStatus; pause; end
	end
	if PlotStatus; close(hAllFig); end
	[AWEFile,AWEPath,AWEFilePath]=GetFileNameOfMat(AWEFileMat,FileIndex);
	SaveData(WeightMat,AWEFilePath,1,[],'int16','int16',[],[],[],0,0);
end


return;
