function [OutFileMat1,OutFileMat2]=CalcAvgDiffDiff(InFileMat)

%	CalcAvgDiffDiff

%   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<1; InFileMat=[]; end
[NFilesIn,InFileMat]=ReadFileNames(InFileMat,'*.at*','Choose avg files or batch file:');
if NFilesIn==0; return; end
[OutFileMat1]=PutFileExt2Mat(InFileMat,'d0');
[OutFileMat2]=PutFileExt2Mat(InFileMat,'d2');

for FileInd=1:NFilesIn
	[InFile,InPath,InFilePath]=GetFileNameOfMat(InFileMat,FileInd);
	
	[AvgMat,File,Path,FilePath,NTrialAvgVec,StdChanTimeMat,...
	SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec]=ReadAvgFile(InFilePath);
	[NChan,NPoints]=size(AvgMat);NPoints2=NPoints./2;
	%=====================
 	AvgMatOut=zeros(NChan,NPoints);
	for ChanInd=1:NChan
		for TimeInd=1:NPoints2
			if ~((AvgMat(ChanInd,TimeInd)>0 & AvgMat(ChanInd,TimeInd+NPoints2)>0) | (AvgMat(ChanInd,TimeInd)<0 & AvgMat(ChanInd,TimeInd+NPoints2)<0))
				AvgMatOut(ChanInd,TimeInd)=AvgMat(ChanInd,TimeInd)-AvgMat(ChanInd,TimeInd+NPoints2);
			end
		end
	end
	[OutFile,OutPath,OutFilePath]=GetFileNameOfMat(OutFileMat1,FileInd);
	SaveAvgFile(OutFilePath,AvgMatOut,NTrialAvgVec,StdChanTimeMat,SampRate,MedMedRawVec,MedMedAvgVec);
	%=====================
	AvgMatOut(:,1:NPoints2)=AvgMat(:,1:NPoints2)-AvgMat(:,NPoints2+1:NPoints);
	[OutFile,OutPath,OutFilePath]=GetFileNameOfMat(OutFileMat2,FileInd);
	SaveAvgFile(OutFilePath,AvgMatOut,NTrialAvgVec,StdChanTimeMat,SampRate,MedMedRawVec,MedMedAvgVec);
end
											
return;
