function [EgisFileMat,ConFileMat] = Labview2Egis(NsFileMat,PreTrig,PostTrig,CellStatus,DownSample,LowFiltStatus,LowFrequ,LowN,HighFiltStatus,HighFrequ,HighN,StopFiltStatus,StopFrequ,StopN)

%    Labview2Egis

%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Andrea De Cesarei , 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<14; StopN=6; end
if nargin<13; StopFrequ=[49 51]; end %[LineFrequ-1 LineFrequ+1];
if nargin<12; StopFiltStatus=0; end
if nargin<11; HighN=6; end
if nargin<10; HighFrequ=2; end
if nargin<9; HighFiltStatus=0; end
if nargin<8; LowN=6; end
if nargin<7; LowFrequ=30; 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

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

DefFilePath=SetDefPath('r','*.sng');
[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);
[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 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=499;
    end
    if isempty(PostTrig)
        PostTrig=1000;
    end
    
    
    % f=ReadNeuroScanStruct(NsFilePath);
    %==========================================    
    NTotTrials=450 %f.header.numevents;
    NNsChan=64 %f.header.nchannels;
    EtChan=[60 61 62 63 64]
    % 	EtChan=[54,60];
    NEtChan=length(EtChan);
    ChanVec=1:NNsChan;
    for i=1:NEtChan
        Tmp=find(ChanVec~=EtChan(i));
        ChanVec=ChanVec(Tmp);
    end
    NChan=length(ChanVec);
    
    
    % info for the conversion from A/D to microvolt
    EegResolution=0.1121;
    EogResolution=0.2241;
    EogChan=[63 64];
    EegVec=1:NNsChan;
    for i=1:length(EogChan)
        Tmp=find(EegVec~=EogChan(i));
        EegVec=EegVec(Tmp);
    end
    BytOrd=[0 0 0 0];
    HdrVer=2;	
    LHeader=0;
    ExptNam=zeros(80,1);
    Date=[12,12,12];; % setstr(f.header.date)';
    % Date=[str2num(Date(1:2)),str2num(Date(4:5)),str2num(Date(7:8))];
    Time=[34,34,34]; % setstr(f.header.time)';
    % Time=[str2num(Time(1:2)),str2num(Time(4:5)),str2num(Time(7:8))];
    SubjID=1; %f.header.id;
    Handed=0; %f.header.hand;
    Sex=0; %f.header.sex;
    Age=0; %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;
    
    
%     % copies the correct sequence file according to the subject code
%     SeqCode=NsFileMat(length(NsFileMat)-5);
%     SesFile=strcat('seq', num2str(SeqCode), '.txt')
%     SesCodeFile=strcat( NsFileMat(1:length(NsFileMat)-4), '.ses.con')
%     copyfile(SesFile, SesCodeFile);

     % copies the correct sequence file according to the subject code
     cd(BatchPath);
     SeqCode=NsFile(length(NsFile)-5);
     SesFile=strcat('seq', num2str(SeqCode), '.txt')
     SesCodeFile=strcat( NsFile(1:(length(NsFile)-4)), '.ses.con') 
  %   copyfile(SesFile, SesCodeFile);
    
    % determines conditions.. not really useful at this point.
    
    TrialStatusVec=zeros(NTotTrials,1);
    for i=1:NTotTrials
        StimtypeTmp=1; %f.events(i).stimtype;
        if StimtypeTmp>0 & StimtypeTmp<7
            TrialStatusVec(i)=1;
        end
        StimTypeVec(i)=1; %f.events(i).stimtype;
        StimOffsetvec(i)=0; %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',[],[],[],1,1,0);  %see how this works
    %=========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=RecSampRate.*ones(1,NCells); % 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,0,'bof');
        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,0,'bof')
    fseek(EgisFid,LHeader,'bof')
    ftell(EgisFid)
    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);
    %==========================================
    
    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);
        fprintf(1,'\n');
        fprintf(1,'Cell:    %g\n',CellInd);
        fprintf(1,'NTrials: %g\n',NTrialsInCell);
        fprintf(1,'NPoints: %g\n\n',NPoints(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);
            
            fprintf(1,'Cell %g of %g; Trial %g of %g ...\n',CellInd,NCells,TrialInd,NTrialsInCell);
            
           
            %[Data,NChan,NPoint,NTrial]=ReadStoneData(NsFilePath);
            Data=ReadBinTrial(NsFilePath, ActTrial);
            % Data=ReadNeuroscanTrial(NsFilePath,ActTrial,f,PreTrig,PostTrig);
            
            
            
            % here transforms from A/D units into microvolt...
            Data(EegVec, :)=Data(EegVec, :).*EegResolution;
            %Data(EogChan, :)=Data(EogChan, :).*EogResolution; 
            Data=Data(ChanVec,:);
            if NEtChan>0
                fprintf(1,'Extract sensor %g ...\n',EtChan)
            else
                fprintf(1,'No sensor extraction ...\n')
            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,:));
                end
                fprintf(1,'filter lowpass ... Frequ: %g Hz; Order: %g; Sensor: %g\n',LowFrequ,LowN,i)
            end
            if HighFiltStatus
                for ChanInd=1:NChan
                    Data(ChanInd,:)=filtfilt(BHigh,AHigh,Data(ChanInd,:));
                end
                fprintf(1,'filter highpass ... Frequ: %g Hz; Order: %g; Sensor: %g\n',HighFrequ,HighN,i)
            end
            if StopFiltStatus
                for ChanInd=1:NChan
                    Data(ChanInd,:)=filtfilt(BStop,AStop,Data(ChanInd,:));
                end
                fprintf(1,'filter stopband ... Frequ: %g Hz; Order: %g; Sensor: %g\n',StopFrequ,StopN,i)
            end
            if TrialInd==1 
                Tmpa=Data;
            end
            fwrite(EgisFid,Data.*2.^Bits./Range,'int16'); 
        end		% for TrialInd=1:NTrialsInCell;
    end         % for CellInd=1:NCells
    fclose(EgisFid);
end             %for FileInd=1:NFiles
return;
