function[OutFilePath]=MergeEgisFiles(InFileMat,OutFilePath,MergeAddStatus)

%   MergeEgisFiles.m

%   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<3; MergeAddStatus=[]; end;
if nargin<2; OutFilePath=[]; end;
if nargin<1; InFileMat=[]; end;

%==================================================================
DefFilePath=SetDefPath('r','*.E*');
[NFiles,InFileMat,VersionString,BatchFilePath]=ReadFileNames(InFileMat,DefFilePath,'Choose Egis files:');
if NFiles<1; return; end
[BatchFile,BatchPath]=SepFilePath(BatchFilePath);
SetDefPath('w',BatchPath);

if isempty(OutFilePath)
	[OutFile,OutPath,OutFilePath]=WriteFilePath('Cat.E1');
end
if NFiles<2; 
	[NoUse,NoUse,OutFilePath]=GetFileNameOfMat(InFileMat,1);
	return; 
end
fprintf('\n');clc;
[MergeAddStatus]=IfEmptyInputSpecVal(MergeAddStatus,[1 2],1,...
	'Do you want to\n',...
	'Merge       [1]',...
	'or Add      [2]',...
	'the EGIS files ?');
	
LHeaderVec=[];
LDataVec=[];
LCellHdrVec=[];
NTrialsVec=[];
LSpecCellVec=[];

for FileIndex=1:NFiles
	[File,Path,FilePath]=GetFileNameOfMat(InFileMat,FileIndex);
	%=========Egis Header===============
	[Header,File,Path,FilePath]=ReadEGISHeader(FilePath);
	global BytOrd
	global HdrVer
	global LHeader
	LHeaderVec(FileIndex)=LHeader;
	global LData
	LDataVec(FileIndex)=LData;
	global ExptNam
	global RunDate
	global RunTime
	global SubjID
	global Handed
	global Sex
	global Age
	global ExperID
	global EdVer
	global CalFlag
	global NCells
	global NChan
	global LText
	global LComment
	global LPad
	global BrdGain
	global CellID
	global LCellHdr
	if FileIndex==1;
		LCellHdrMat=zeros(NFiles,NCells);
		NTrialsMat=zeros(NFiles,NCells);
		ChanZeroMat=zeros(NChan,NFiles);
		ChanGainMat=zeros(NChan,NFiles);
	end
	LCellHdrMat(FileIndex,:)=LCellHdr;
	global ChanZero
	ChanZeroMat(:,FileIndex)=ChanZero;
	global ChanGain
	ChanGainMat(:,FileIndex)=ChanGain;
	global CellID
	global CellName
	global NTrials
	NTrialsMat(FileIndex,:)=NTrials;
	global NPoints
	global SampRate
	global LSpec	
	for CellInd=1:NCells
		eval(['global LSpecCell',int2str(CellInd)])
		eval(['LSpecCellTmp',int2str(FileIndex),int2str(CellInd),'=LSpecCell' int2str(CellInd),';'])
	end
end
if MergeAddStatus==1	%Merge
	[mAll,nAll]=size(LSpecCellVec);
	[mTmp,nTmp]=size(LSpecCellTmp);
	LSpecCellVecTmp=zeros(mAll+mTmp,nAll);
	if ~isempty(LSpecCellVec)
		LSpecCellVecTmp(1:mAll,:)=LSpecCellVec;
	end
	LSpecCellVecTmp(mAll+1:mAll+mTmp,:)=LSpecCellTmp
	LSpecCellVec=[]; LSpecCellVec=LSpecCellVecTmp; LSpecCellVecTmp=[];
else					%Add
	for CellInd=1:NCells(1)
		for FileIndex=1:NFiles
			eval(['LSpecCellTmp=LSpecCellTmp' int2str(FileIndex),int2str(CellInd) ';'])
			[mAll,nAll]=size(LSpecCellVec);
			[mTmp,nTmp]=size(LSpecCellTmp);
			LSpecCellVecTmp=zeros(mAll+mTmp,nTmp);
			if FileIndex>1
				LSpecCellVecTmp(1:mAll,:)=LSpecCellVec;
			end
			LSpecCellVecTmp(mAll+1:mAll+mTmp,:)=LSpecCellTmp;
			LSpecCellVec=[]; LSpecCellVec=LSpecCellVecTmp; LSpecCellVecTmp=[];	
		end
		eval(['LSpecCell' int2str(CellInd) '=LSpecCellVec;'])
		LSpecCellVec=[];
	end
end

LData=sum(LDataVec);
NTrials=sum(NTrialsMat);
LCellHdr=90+NTrials.*LSpec./2.*2;
LHeader=[];
ChanZero=mean(ChanZeroMat');
ChanGain=mean(ChanGainMat');

[OutFile,OutPath,OutFilePath,LHeaderAll]=WriteEGISHeader(OutFilePath);

OutFid=fopen(OutFilePath,'r+','b');
fseek(OutFid,LHeaderAll,-1);
fprintf('\n\n')
if MergeAddStatus==1	%Merge
	for FileIndex=1:NFiles
		[InFile,InPath,InFilePath]=GetFileNameOfMat(InFileMat,FileIndex);
		InFid=fopen(InFilePath,'r','b');
		for CellIndex=1:NCells
			fseek(InFid,LHeaderVec(FileIndex),-1);
			fprintf('Write %g trials of file:\n',NTrialsMat(FileIndex,CellInd))
			disp(InFilePath); 
			fprintf('\n')
			fprintf('and Cell %g to file:\n',CellIndex)
			disp(OutFilePath); fprintf('\n\n')
			for TrialInd=1:NTrialsMat(FileIndex,CellInd)
				fprintf(1,'%g\n',TrialInd)
				Tmp=fread(InFid,[NChan,NPoints(FileIndex)],'int16');
				fwrite(OutFid,Tmp,'int16'); 
			end
		end
		fclose(InFid);
	end
	fclose(OutFid);
else		%Add
	for CellIndex=1:NCells
		for FileIndex=1:NFiles
			[InFile,InPath,InFilePath]=GetFileNameOfMat(InFileMat,FileIndex);
			InFid=fopen(InFilePath,'r','b');
			fseek(InFid,LHeaderVec(FileIndex)+sum(LCellHdrMat(FileIndex,1:CellIndex-1)),-1);
			fprintf('Write %g trials with %g channels and %g points of file:\n',NTrialsMat(FileIndex,CellInd),NChan,NPoints(CellIndex))
			disp(InFilePath); 
			fprintf('\n')
			fprintf('and Cell %g to file:\n',CellIndex)
			disp(OutFilePath); fprintf('\n\n')
			for TrialInd=1:NTrialsMat(FileIndex,CellInd)
				fprintf(1,'%g\n',TrialInd)
				Tmp=fread(InFid,[NChan,NPoints(CellIndex)],'int16');
				fwrite(OutFid,Tmp,'int16'); 
			end
			fclose(InFid);
		end	
	end
	fclose(OutFid);
end
return;
