function[OutFileMat]=ExtEgisCells(InFileMat,SepFileStatus)
%	ExtEgisCells.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<2; SepFileStatus=[]; end;
if nargin<1; InFileMat=[]; end;

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

SepFileStatusStr=questdlg('Extract cells in one single or seperate files ?', ...
    'Single or seperate files ?', ...
    'Single','Seperate','Single');

LHeaderVec=[];
LDataVec=[];
LCellHdrVec=[];
NTrialsVec=[];
LSpecCellVec=[];
OutFileMat=[];
for FileIndex=1:NFiles
    [InFile,InPath,InFilePath]=GetFileNameOfMat(InFileMat,FileIndex);
    %=========Egis Header===============
    Header=ReadEGISHeader(InFilePath);
    global BytOrd
    global HdrVer
    global LHeader
    global 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 LCellHdr
    global ChanZero
    global ChanGain
    global CellID
    global CellName
    global NTrials
    global NPoints
    global SampRate
    global LSpec	
    
    LDataTmp=LData;
    NCellsTmp=NCells;
    LCellHdrVec=LCellHdr;
    CellIDVec=CellID; 
    CellNameVec=CellName;
    NTrialsVec=NTrials;
    NPointsVec=NPoints;
    SampRateVec=SampRate;
    LSpecVec=LSpec;
    InLHeader=LHeader;
    
    InFid=fopen(InFilePath,'r','b');  
    if strcmp(SepFileStatusStr,'Seperate')   
        for CellInd=1:NCellsTmp  
            OutFilePath=[InFilePath,'.',int2str(CellInd)];
            [OutFileMat,NFileMatOut]=AddFileName2Mat(OutFileMat,OutFilePath,1);  
            
            NCells=1;
            LCellHdr=LCellHdrVec(CellInd);
            CellID=1;
            CellName=CellNameVec(:,CellInd);
            NTrials=NTrialsVec(CellInd);
            NPoints=NPointsVec(CellInd);
            SampRate=SampRateVec(CellInd);
            LSpec=LSpecVec(CellInd);
            LData=NTrials.*NChan.*NPoints.*2;
            
            [OutFile,OutPath,OutFilePath,LHeader]=WriteEGISHeader(OutFilePath,0,1);      
            OutFid=fopen(OutFilePath,'a','b');
            InSeekStatus=fseek(InFid,InLHeader+sum(NTrialsVec(1:CellInd-1)).*NChan.*NPoints.*2,-1);
            if InSeekStatus==-1; error('InSeekStatus error'); end
            OutSeekStatus=fseek(OutFid,LHeader,-1);
            if OutSeekStatus==-1; error('OutSeekStatus error'); end
            fprintf('Write %g trials of cell %g to file:\n',NTrialsVec(CellInd),CellInd)
            disp(OutFilePath); 
            fprintf('\n')
            for TrialInd=1:NTrialsVec(CellInd)
                fprintf(1,'%g\n',TrialInd)
                Tmp=fread(InFid,[NChan,NPointsVec(CellInd)],'int16');
                fwrite(OutFid,Tmp,'int16'); 
            end
            fclose(OutFid);
        end      
    elseif strcmp(SepFileStatusStr,'Single')  
        NCells=1;
        LCellHdr=LCellHdrVec(1);
        CellID=1;
        CellName=CellNameVec(:,1);
        NTrials=sum(NTrialsVec);
        NPoints=NPointsVec(1);
        SampRate=SampRateVec(1);
        LSpec=LSpecVec(1);
        LData=NTrials.*NChan.*NPoints.*2;
        OutFilePath=[InFilePath,'.ext'];
        [OutFileMat,NFileMatOut]=AddFileName2Mat(OutFileMat,OutFilePath,1);  
        LSpecCellTmp=[];
        for CellInd=1:NCellsTmp
            eval(['global LSpecCell',int2str(CellInd),';'])
            eval(['LSpecCellTmp=[LSpecCellTmp;LSpecCell',int2str(CellInd),'];'])
        end
        LSpecCell1=LSpecCellTmp;
        [OutFile,OutPath,OutFilePath,LHeader]=WriteEGISHeader(OutFilePath,0,1);      
        OutFid=fopen(OutFilePath,'a','b');
        OutSeekStatus=fseek(OutFid,LHeader,-1);
        if OutSeekStatus==-1; error('OutSeekStatus error'); end
        for CellInd=1:NCellsTmp  
            InSeekStatus=fseek(InFid,InLHeader+sum(NTrialsVec(1:CellInd-1)).*NChan.*NPoints.*2,-1);
            if InSeekStatus==-1; error('InSeekStatus error'); end    
            fprintf('Extract file:\n')
            disp(InFilePath); 
            fprintf('\n')
            fprintf('Actual cell:      %g\n',CellInd)
            fprintf('Total cells:      %g\n',NCellsTmp)
            fprintf('Number of trials: %g\n',NTrialsVec(CellInd))
            fprintf('\n')
            fprintf('Write to file:\n')
            disp(OutFilePath); 
            fprintf('\n')
            for TrialInd=1:NTrialsVec(CellInd)
                fprintf(1,'%g\n',TrialInd)
                Tmp=fread(InFid,[NChan,NPointsVec(CellInd)],'int16');
                fwrite(OutFid,Tmp,'int16'); 
            end  
        end
        fclose(OutFid);
    end 
    fclose(InFid); 
end
return;
