function [CsdFileMat] = App2Csd(FileMat)


%   App2Csd


%   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<2; Lambda=[]; end
if nargin<1; FileMat=[]; end

[NFiles,FileMat]=ReadFileNames(FileMat,'*.app*','Choose app. file(s) or batch file:');
if NFiles==0; CsdFileMat=[]; return; end
CsdFileMat=FileNameExt2Mat(FileMat,'.csd');
%==================================================================================
CoeffPathTmp=what('Plot3dCoeff40');
CoeffPath=getfield(CoeffPathTmp,'path');
if strcmp(CoeffPath(length(CoeffPath)),FileSep);CoeffPath=CoeffPath(1:length(CoeffPath)-1); end
LegPathTmp=what('Plot3dLegCoeff');
LegPath=getfield(LegPathTmp,'path');
if strcmp(LegPath(length(LegPath)),FileSep); LegPath=LegPath(1:length(LegPath)-1); end
ECfgPathTmp=what('SensorCfg');
ECfgPath=getfield(ECfgPathTmp,'path');
if strcmp(ECfgPath(length(ECfgPath)),FileSep); ECfgPath=ECfgPath(1:length(ECfgPath)-1); end
NChanOld=0;
for FileIndex=1:NFiles
	[File,Path,FilePath]=GetFileNameOfMat(FileMat,FileIndex);
	[CsdFile,CsdPath,CsdFilePath]=GetFileNameOfMat(CsdFileMat,FileIndex);
	[DataMat,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,AvgRefStatus]=ReadAppData(FilePath,0);
	%===========================================================================
	if NChan~=NChanOld
		ECfgFile=[int2str(NChan) '.ecfg'];
		ECfgFilePath=[ECfgPath,FileSep,ECfgFile];
		fid=fopen(ECfgFilePath,'r','b');
		fprintf('Start reading sensor configuration...\n\n');
		fprintf(ECfgFilePath)
		fprintf('\n\n');
		NChan=fread(fid,1,'int16');	
		ScalpRadius=fread(fid,1,'float32');
		TmpSpher=fread(fid,[NChan,2],'float32');
		fclose(fid);
		AllEPosSpher=zeros(NChan,3);
		AllEPosSpher(:,1:2)=TmpSpher(1:NChan,:);
		AllEPosSpher(:,3)=ScalpRadius.*ones(NChan,1);
		AllEPosCart = change_sphere_cart(AllEPosSpher,ScalpRadius,1);
		[InvCoeff] = ReadOrCalcCoeff(1,AllEPosCart,AllEPosCart,LegPath,CoeffPath,ECfgFile,32,15, 0, 5001);	
		[CsdCoeff] = ReadOrCalcCoeff(3,AllEPosCart,AllEPosCart,LegPath,CoeffPath,ECfgFile,NChan,15, 0, 5001);
		[Lambda]=IfEmptyInputValInt('Insert lambda value of approximation:','(zero ~ no approximation)',Lambda,2,0,100,1);
		InvCoeff=InvCoeff+Lambda.*InvCoeff(1,1).*eye(NChan);
		AllChanOnes=ones(1,NChan);
		NChanOld=NChan;
	end	
	%===========================================================================
	CsdFid=fopen(CsdFilePath,'w','b');
	fwrite(CsdFid,Version,'int16');
	fwrite(CsdFid,LHeader,'int16');
	fwrite(CsdFid,ScaleBins,'int16');
	fwrite(CsdFid,NChan,'int16');
	fwrite(CsdFid,NPoints,'int16');
	fwrite(CsdFid,NTrials,'int16');
	fwrite(CsdFid,SampRate,'int16');
	fwrite(CsdFid,AvgRefStatus,'int16');	
	ZeroVec=zeros(LHeader-16,1);
	fwrite(CsdFid,ZeroVec,'int8');	
	for TrialInd=1:NTrials
		fprintf('File %g of %g; Trial %g of %g;\n',FileIndex,NFiles,TrialInd,NTrials);
		[DataMat,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,AvgRefStatus]=ReadAppData(FilePath,TrialInd);
		c0=mean(DataMat);
		DataMat=DataMat-(c0'*AllChanOnes)';
		DipStrength = InvCoeff \ DataMat;
		DataMat=(DipStrength' * CsdCoeff)';
		DataMat=DataMat+(c0'*AllChanOnes)';	
		fwrite(CsdFid,DataMat'.*ScaleBins,'int16');	
	end
	fclose(CsdFid);
end
