function[OutFilePath]=CalcGrad(InFileMat,Ext,DefFileMask,FilterStatus)
%   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.                                                                      
%==================================================================
%
%	CalcGrad.m
%
%	Markus Junghoefer	[2002]
%
%
%	Function definition
%
%
%
%==================================================================
if nargin<4; 
	FilterStatus=0;
end
if nargin<3; 
	DefFileMask='*at*'; 
end;
if nargin<2; 
	Ext=[]; 
end;
if nargin<1; 
	InFileMat=[]; 
end;

%==================================================================
SampRate=250;

[DefFilePath] = SetDefPath(1,DefFileMask);
[NFiles,InFileMat,NonUse,BatchFilePath]=ReadFileNames(InFileMat,DefFilePath,'Choose Avg files:');
if NFiles==0; OutFilePath=[]; return; end
[BatchFile,BatchPath]=SepFilePath(BatchFilePath);
SetDefPath(2,BatchPath);
if FilterStatus
	FilePath=which('20HzPass25HzStopButter250.lf');
    [File,FullPath]=SepFilePath(FilePath);
	if FullPath(end)==filesep
		FullPath=FullPath(1:end-1);
	end
	if ~isempty(FullPath); eval(['cd ',FullPath]); end
	[LowFiltFile,LowFiltPath,LowFiltFilePath]=ReadFilePath([],['*',int2str(SampRate),'.lf'],'Open lowpass file:');
	if LowFiltFile==0; return; end
	[LowFiltCoeff] = ReadBem(LowFiltFilePath,1,'Matrix','Ascii');
	if isempty(LowFiltCoeff); return; end
	SizeLowFiltCoeff=size(LowFiltCoeff);
	if SizeLowFiltCoeff(1)~=2 & SizeLowFiltCoeff(2)==2; LowFiltCoeff=LowFiltCoeff'; end
else
	LowFiltCoeff=[];
end
if isempty(Ext); 
    if FilterStatus
        Ext='.lf.grad'; 
    else
        Ext='.nf.grad'; 
    end
end
for FileIndex=1:NFiles
	[File,Path,FilePath]=GetFileNameOfMat(InFileMat,FileIndex);
	[AvgMat,File,Path,FilePath,NTrialAvgVec,StdMat,SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra]=ReadAvgFile(FilePath);
	[NChan,NPoints]=size(AvgMat);
	if length(LowFiltCoeff)~=0
		for i=1:NChan
			AvgMat(i,:)=(filtfilt(LowFiltCoeff(1,:),LowFiltCoeff(2,:),AvgMat(i,:)'))';
		end
	end
	SaveAvgFile([FilePath,Ext],gradient(AvgMat),NTrialAvgVec,gradient(StdMat),SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra);
end
return;
