function [EgisFileMat,ConFileMat] = Neuroscan2Egis(NsFileMat,PreTrig,PostTrig,CellStatus,DownSample,LowFiltStatus,...
    LowFrequ,LowN,HighFiltStatus,HighFrequ,HighN,StopFiltStatus,StopFrequ,StopN,OldStatus,SkipStepStatus)
    
%   Neuroscan2Egis

%   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<16; SkipStepStatus = 0;end
if nargin<15; OldStatus = 0;end
if nargin<14; StopN=6; end
if nargin<13; StopFrequ=[49 51]; end %[LineFrequ-1 LineFrequ+1];
if nargin<12; StopFiltStatus=1; end
if nargin<11; HighN=6; end
if nargin<10; HighFrequ=2; end
if nargin<9; HighFiltStatus=1; end
if nargin<8; LowN=6; end
if nargin<7; LowFrequ=40; end
if nargin<6; LowFiltStatus=1; end
if nargin<5; DownSample=1; end
if nargin<4; CellStatus=0; end
if nargin<3; PostTrig=[]; end
if nargin<2; PreTrig=[]; end
if nargin<1;NsFileMat=[]; end


% Nyquist=SampRate./2;
% LineFrequ=50;
% StopFrequ=[LineFrequ-1 LineFrequ+1];
% LowFiltStatus=1;
% HighFiltStatus=0;
% StopFiltStatus=0;
% LowFrequ=40;
% LowN=6;
% StopN=6;

DefFilePath=SetDefPath('r','*.cnt',[],0);
[NFiles,NsFileMat,VersionString,BatchFilePath]=ReadFileNames(NsFileMat,DefFilePath,'Choose cnt file(s) or a batch file:');
if NFiles==0; return; end
[BatchFile,BatchPath]=SepFilePath(BatchFilePath);
SetDefPath('w',BatchPath,[],0);
[EgisFileMat]=FileNameExt2Mat(NsFileMat,'ses',3);
[ConFileMat]=FileNameExt2Mat(EgisFileMat,'.con');

for FileInd=1:NFiles
    [NsFile,NsPath,NsFilePath]=GetFileNameOfMat(NsFileMat,FileInd);
    [EgisFile,EgisPath,EgisFilePath]=GetFileNameOfMat(EgisFileMat,FileInd);
    [ConFile,ConPath,ConFilePath]=GetFileNameOfMat(ConFileMat,FileInd);
    
    if exist(ConFilePath) & exist(EgisFilePath) & SkipStepStatus
        fprintf(1,'session file already exists: skipping segmentation.\n');
        pause(1);
        continue;
    end
        
    % 	if strcmp(NsFile(5),'C')
    % 		PreTrig=49;
    % 		PostTrig=350;	
    % 	elseif strcmp(NsFile(5),'R')
    % 		PreTrig=49;
    % 		PostTrig=350;
    % 	else
    % 		error('Unknown file format')
    % 	end
    % 	if strcmp(NsFile(7),'1')
    % 		PreTrig=0;
    % 		PostTrig=168;	
    % 	else
    %  		PreTrig=49;
    %  		PostTrig=100;
    % 	end
    
    if isempty(PreTrig)
        PreTrig=199;
    end
    if isempty(PostTrig)
        PostTrig=800;
    end
    
    if OldStatus
        f=ReadNeuroScanStructPOld(NsFilePath);
    else
        f=ReadNeuroScanStruct(NsFilePath);
    end
    %==========================================
    NTotTrials=f.header.numevents;
    NNsChan=f.header.nchannels;
    ChanVec=1:NNsChan;
    EtChan=[];
    NEtChan=length(EtChan);
    for i=1:NEtChan
        Tmp=find(ChanVec~=EtChan(i));
        ChanVec=ChanVec(Tmp);
    end

    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;
    Range=366;		
    LPad=Range;
    BrdGain=1;
    ChanGain=ones(NChan,1);
    ChanZero=zeros(NChan,1);
    CellVec=[1 2 3 4 5 6];
    NBadStimtype=0;
    NOKStimtype=0;
    TrialStatusVec=zeros(NTotTrials,1);
    for i=1:NTotTrials
        StimtypeTmp=f.events(i).stimtype;
        if StimtypeTmp>0 & StimtypeTmp<7
            TrialStatusVec(i)=1;
        end
        StimTypeVec(i)=f.events(i).stimtype;
        StimOffsetvec(i)=f.events(i).offset;	
    end
    UseTrialIndVec=find(TrialStatusVec);
    StimTypeVec=StimTypeVec(UseTrialIndVec);
    StimOffsetvec=StimOffsetvec(UseTrialIndVec);
    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
    %============Save condition vector to file==========================		
    SaveData(StimTypeVec',ConFilePath,1,[],'ascii','ascii',[],[],[],0,0,0);
    %=========EGIS Header======================
    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;
    %===============================
    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,'Total cells:%g ',NCells);
    fprintf(1,'Total trials:%g ',NTotTrials);
    fprintf(1,'Number of sensors:%g ',NChan);
    %==========================================
    
    if HighFiltStatus
        [BHigh,AHigh]=butter(HighN,HighFrequ./Nyquist,'high');
    end
    if LowFiltStatus
        [BLow,ALow]=butter(LowN,LowFrequ./Nyquist,'low');
    end
    if StopFiltStatus
        [BLow,ALow]=butter(StopN,StopFrequ./Nyquist,'stop');
    end
    for CellInd=1:NCells
        if CellStatus
            TrialIndVec=find(StimTypeVec==CellVec(CellInd));
        else
            TrialIndVec=UseTrialIndVec;
        end
        NTrialsInCell=NTrials(CellInd);
        if DownSample>1
            x=[1:NPoints(CellInd)];
            xi=[1:DownSample:NPoints(CellInd)];
            DataTmp=zeros(NChan,NPoints/DownSample);
        end
        for TrialInd=1:NTrialsInCell;
            ActTrial=TrialIndVec(TrialInd);
            if mod(TrialInd,50)==0 
                fprintf(1,'\nWrite trial of %g of %g in Cell %g of %g to file...',TrialInd,NTrialsInCell,CellInd,NCells);
            end
            if TrialInd==NTrialsInCell
                fprintf(1,'\n');
            end
            if OldStatus
                Data=ReadNeuroscanTrialPOld(NsFilePath,ActTrial,f,PreTrig,PostTrig);
            else
                Data=ReadNeuroscanTrial(NsFilePath,ActTrial,f,PreTrig,PostTrig);
            end
            Data=Data(ChanVec,:);
            if NEtChan>0
                fprintf(1,'Extract sensor %g ...\n',EtChan)
            end
            if DownSample>1
                for ChanInd=1:NChan
                    DataTmp(Chan,:)=interp1(x,Data(ChanVec,:),xi);
                end
                Data=DataTmp;
            end
            if LowFiltStatus
                for ChanInd=1:NChan
                    Data(ChanInd,:)=filtfilt(BLow,ALow,Data(ChanInd,:));
                    if mod(ChanInd,10)==0
                        fprintf(1,'filter lowpass ... Frequ: %g Hz; Order: %g; Sensor: %g\n',LowFrequ,LowN,i)
                    end
                end
            end
            if HighFiltStatus
                for ChanInd=1:NChan
                    Data(ChanInd,:)=filtfilt(BHigh,AHigh,Data(ChanInd,:));
                    if mod(ChanInd,10)==0
                        fprintf(1,'filter highpass ... Frequ: %g Hz; Order: %g; Sensor: %g\n',HighFrequ,HighN,i)
                    end
                end
            end
            if StopFiltStatus
                for ChanInd=1:NChan
                    Data(ChanInd,:)=filtfilt(BStop,AStop,Data(ChanInd,:));
                    if mod(ChanInd,10)==0
                        fprintf(1,'filter stopband ... Frequ: %g Hz; Order: %g; Sensor: %g\n',StopFrequ,StopN,i);
                    end
                end
            end
            fwrite(EgisFid,Data.*2.^Bits./Range,'int16'); 
        end		
    end
    fclose(EgisFid);
end
return;
