function Et2Egis(FileMat,PreTrig,PostTrig,CellStatus)
%   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.                                                                      
%==================================================================
%
%	Et2Egis
%
%
%	Markus Junghoefer	[2002]
%
%
%	Function definition
%
%	function NsStruct=Et2Egis(NsFilePath)
% 
% 	if nargin<1; FilePath=[]; end
%

%=================================================================
if nargin<4; CellStatus=0; end
if nargin<3; PostTrig=[]; end	
if nargin<2; PreTrig=[]; end 
if nargin<1;FileMat=[]; end

DefFilePath=SetDefPath('r','*.cnt');
[NFiles,FileMat,VersionString,BatchFilePath]=ReadFileNames(FileMat,DefFilePath,'Choose cnt file(s) or a batch file:');
if NFiles==0; return; end
[BatchFile,BatchPath]=SepFilePath(BatchFilePath)
SetDefPath('w',BatchPath);
for FileInd=1:NFiles
	[NsFile,NsPath,NsFilePath]=GetFileNameOfMat(FileMat,FileInd);
	if strcmp(NsFile(5),'C')
		PostTrig=450;
		PreTrig=49;
	elseif strcmp(NsFile(5),'R')
		PostTrig=1500;
		PreTrig=99;
	else
		error('Unknown file format')
	end
	
	f=ReadNeuroScanStruct(NsFilePath);
	%==========================================
	NTotTrials=f.header.numevents;
	NNsChan=f.header.nchannels;
	ChanVec=[54,60];
	NChan=length(ChanVec);
	BytOrd=[0 0 0 0];
	HdrVer=2;	
	LHeader=0;
	ExptNam=zeros(80,1);
	Date=setstr(f.header.date)';
	Date=[str2num(Date(1:2)),str2num(Date(4:5)),str2num(Date(7:8))];
	Time=setstr(f.header.time)';
	Time=[str2num(Time(1:2)),str2num(Time(4:5)),str2num(Time(7:8))];
	SubjID=1; %f.header.id;
	Handed=f.header.hand;
	Sex=f.header.sex;
	Age=f.header.age;
	ExperID=0;
	EdVer=2;
	CalFlag=0;
	LComment=0;
	Bits=10;   		LText=Bits;		%Muss noch geaendert werden	
	Range=366;		LPad=Range;		%Muss noch geaendert werden
	BrdGain=1;
	for i = 1:NChan
		% 	ChanGain(i)=f.electloc(i).gain;
		% 	ChanZero(i)=f.electloc(i).calib;
		ChanGain(i)=1;
		ChanZero(i)=0;
	end
	CellVec=[1 2 3 4];
	NBadStimtype=0;
	NOKStimtype=0;
	TrialStatusVec=zeros(NTotTrials,1);
	for i=1:NTotTrials
		StimtypeTmp=f.events(i).stimtype;
		if StimtypeTmp>0 & StimtypeTmp<6
			TrialStatusVec(i)=1;
		end
		StimTypeVec(i)=f.events(i).stimtype;
		StimOffsetvec(i)=f.events(i).offset;	
	end
	UseTrialIndVec=find(TrialStatusVec);
	NonUseTrialIndVec=find(~TrialStatusVec)
	NTotTrials=length(UseTrialIndVec);
	NCells=length(CellVec);
	for i=1:NCells
		NTrials(i)=length(find(StimTypeVec==CellVec(i)));
	end
	if ~CellStatus
		NCells=1;
		NTrials=NTotTrials;
	end
	CellID=zeros(NCells,1);  
	CellName=zeros(NCells,80);
	%NPoints=f.header.pnts.*ones(1,NCells);
	NPoints=(PreTrig+PostTrig+1).*ones(1,NCells)
	SampRate=f.header.rate.*ones(1,NCells);
	LSpec=4.*ones(1,NCells)	
	LCellHdr=90+NTrials.*LSpec;
	LData=sum(NTrials.*NPoints).*NChan.*NPoints.*2;
	%=========EGIS Header======================
	EgisFilePath=[NsFilePath(1:length(NsFilePath)-4),'.Et.ses'];
	EgisFid=fopen(EgisFilePath,'w','b');
	CountBytOrd=fwrite(EgisFid,BytOrd,'uint8');
	CountHdrVer=fwrite(EgisFid,HdrVer,'int16');
	Tell1LHeader=ftell(EgisFid);
	CountLHeader=fwrite(EgisFid,LHeader,'int16');
	LData=sum(NTrials.*NPoints).*NChan.*2;
	CountLData=fwrite(EgisFid,LData,'int32');
	CountExptNam=fwrite(EgisFid,ExptNam,'uchar');
	CountRunDate=fwrite(EgisFid,Date,'int16');
	CountRunTime=fwrite(EgisFid,Time,'int16');
	CountSubjID=fwrite(EgisFid,SubjID,'int16');
	CountHanded=fwrite(EgisFid,Handed,'int16');
	CountSex=fwrite(EgisFid,Sex,'int16');
	CountAge=fwrite(EgisFid,Age,'int16');
	CountExperID=fwrite(EgisFid,ExperID,'int16');
	CountEdVer=fwrite(EgisFid,EdVer,'int16');
	CountCalFlag=fwrite(EgisFid,CalFlag,'int16');
	CountNCells=fwrite(EgisFid,NCells,'int16');
	CountNChan=fwrite(EgisFid,NChan,'int16')
	CountLComment=fwrite(EgisFid,LComment,'int16');
	CountLText=fwrite(EgisFid,LText,'int16');
	CountLPad=fwrite(EgisFid,LPad,'int16');
	CountBrdGain=fwrite(EgisFid,BrdGain,'int16');
	CountLCellHdr=fwrite(EgisFid,LCellHdr,'int16');
	CountChanZero=fwrite(EgisFid,ChanZero,'int16');
	CountChanGain=fwrite(EgisFid,ChanGain,'int16');
	Tell1=ftell(EgisFid);
	index=0;
	Offset=0;
	for i=1:NCells
		CountCellID(i)=fwrite(EgisFid,CellID(i),'int16');
		CountCellName(i)=fwrite(EgisFid,CellName(i,:),'char');
		CountNTrials(i)=fwrite(EgisFid,NTrials(i),'int16');
		CountNPoints(i)=fwrite(EgisFid,NPoints(i),'int16');
		CountSampRate(i)=fwrite(EgisFid,SampRate(i),'int16');
		CountLSpec(i)=fwrite(EgisFid,LSpec(i),'int16');
		for j=1:NTrials(i)
			LSpecCell=zeros(LSpec(i)./2,1);
			CountTmpToWrite=fwrite(EgisFid,LSpecCell,'int16');
		end
	end
	Tell2LHeader=ftell(EgisFid);
	if  LHeader<Tell2LHeader
		LHeader=Tell2LHeader;
		fseek(EgisFid,Tell1LHeader,'bof');
		CountLHeader=fwrite(EgisFid,LHeader,'int16');
	end
	if Tell2LHeader<LHeader
		EmptyZeros=zeros(1,LHeader-Tell2LHeader);
		CountEmpty=fwrite(EgisFid,EmptyZeros,'int8');
	end
	%==========================================
	fseek(EgisFid,LHeader,'bof');
	
	fprintf(1,'\n\n\n');
	fprintf(1,'Total cells:          %g\n',NCells);
	fprintf(1,'Total trials:         %g\n',NTotTrials);
	fprintf(1,'Number of sensors:    %g\n\n',NChan);
	%==========================================
	Nyquist=SampRate./2;
	LineFrequ=50;
	StopFrequ=[LineFrequ-1 LineFrequ+1];
	LowFrequ=20;
	LowN=6;
	StopN=6;
	[BLow,ALow]=butter(LowN,LowFrequ./Nyquist,'low');
	[BStop,AStop]=butter(StopN,StopFrequ./Nyquist,'stop');
	
	for CellInd=1:NCells
		if CellStatus
			TrialIndVec=find(StimTypeVec==CellVec(CellInd));
		else
			TrialIndVec=UseTrialIndVec;
		end
		NTrialsInCell=NTrials(CellInd);
		DataMat=zeros(NTrialsInCell,NChan,NPoints(CellInd));
		fprintf(1,'\n');
		fprintf(1,'Cell:    %g\n',CellInd);
		fprintf(1,'NTrials: %g\n',NTrialsInCell);
		fprintf(1,'NPoints: %g\n\n',NPoints(CellInd));
		for TrialInd=1:NTrialsInCell;
			ActTrial=TrialIndVec(TrialInd);
			fprintf(1,'Cell: %g; Trial: %g\n',CellInd,TrialInd);
			Data=ReadNeuroscanTrial(NsFilePath,ActTrial,f,PreTrig,PostTrig);
			Data=Data(ChanVec,:);
			for ChanInd=1:NChan
% 				Data(ChanInd,:)=filtfilt(BStop,AStop,Data(ChanInd,:));
				Data(ChanInd,:)=filtfilt(BLow,ALow,Data(ChanInd,:));
			end
			fprintf(1,'Filter data stopband ...\n')
			fprintf(1,'Save sensor %g ...\n',ChanVec)
			fwrite(EgisFid,Data,'int16'); 
			DataMat(TrialInd,:,:)=Data;
		end		
	end
	fclose(EgisFid);
	Tmp=findstr(NsFile,'.cnt')
	if ~strcmp(NsPath(end),filesep); NsPath=[NsPath,filesep]; end
	if isempty(Tmp)
		SaveFilePath=[];
	else
		SaveFilePath=[NsPath,NsFile(1:Tmp),'et.mat'];
	end
	SaveNDimData(DataMat,SaveFilePath);
end
return
