function [OutFileMat]=Ctf2Scads(InFileMat,EegMegStatus)
%   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.                                                                      
%==================================================================
%
%	Ctf2Scads
%
%	Markus Junghoefer	[2001]
%
%
%	Function definition
%	
%	[OutFileMat]=Ctf2Scads(InFileMat)
%
%
%
%=================================================================
if nargin<2; EegMegStatus=[]; end
if nargin<1; InFileMat=[]; end

if isempty(EegMegStatus); EegMegStatus=2; end %2=MEG; 1=EEG

[DefFilePath] = SetDefPath(1,'*.mat*');
[NFilesIn,InFileMat,NonUse,BatchFilePath]=ReadFileNames(InFileMat,DefFilePath,'Choose CTF .mat files or batch file:');
[BatchFile,BatchPath]=SepFilePath(BatchFilePath);
SetDefPath(2,BatchPath);

if NFilesIn==0; return; end
if EegMegStatus==1 %EEG
    SensorType=9;
elseif EegMegStatus==2 %MEG
    SensorType=5;
end
for FileInd=1:NFilesIn
	[InFile,InPath,InFilePath]=GetFileNameOfMat(InFileMat,FileInd);
	Nat=findstr(InFile,'.mat');
	if Nat(1)<length(InFile)-3
		OutFile=[InFile(1:Nat(1)-1),InFile(Nat+3:length(InFile)),'.at'];
	else
		OutFile=[InFile(1:Nat(1)-1),'.at'];
	end
	OutFilePath=[InPath,OutFile];
	Struc=load(InFilePath);
    NChan=Struc.d.Nchannels;
    NChanTmp=0;
    for ChanInd=1:NChan
        if Struc.ch(ChanInd).SensorType==SensorType
            NChanTmp=NChanTmp+1;
            ChanIndVec(NChanTmp)=ChanInd;
        end
    end   
    Data=Struc.d.Data;
    AvgMat=squeeze(Data(:,ChanIndVec,1))';
    StdMat=squeeze(Data(:,ChanIndVec,2))';
    SampRate=Struc.fh.Srate;
	NChan=NChanTmp
	NTrialAvgVec=ones(NChan,1);
	MedMedRawVec=[];
	MedMedAvgVec=[];
	NChanExtra=0;
	SaveAvgFile(OutFilePath,AvgMat,NTrialAvgVec,StdMat,SampRate,MedMedRawVec,MedMedAvgVec,EegMegStatus,NChanExtra)
end
return;
