function[AEMFilePathMat,AlternPath]=CalcAutoEditMat(FileMat,TimeStatusVec,AvgRefStatus,UseSpecChanStatus,...
    CalcBaseStatus,BaseStartPoint,BaseEndPoint,ChooseTimeIndStatus,LFlatWin,CalcFlaMatStatus,UseAWEStatus,MinGoodChan,AlternPath,FreStart,FreEnd);
%   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<15; FreEnd=[]; end
if nargin<14; FreStart=[]; end
if nargin<13; AlternPath=[]; end
if nargin<12; MinGoodChan=[]; end
if nargin<11; UseAWEStatus=[]; end
if nargin<10; CalcFlaMatStatus=0; end
if nargin<9; LFlatWin=[]; end
if nargin<8; ChooseTimeIndStatus=[]; end
if nargin<7; BaseEndPoint=[]; end
if nargin<6; BaseStartPoint=[]; end
if nargin<5; CalcBaseStatus=[]; end
if nargin<4; UseSpecChanStatus=[]; end
if nargin<3; AvgRefStatus=[]; end
if nargin<2; TimeStatusVec=[]; end
if nargin<1; FileMat=[]; end

BitsRangeStatus=0;
[NFiles,FileMat]=ReadFileNames(FileMat,'*.E*','Choose Egis file:');
[NoUse,LFileMat]=size(FileMat);

if NFiles==0; return; end

[AvgRefStatus]=IfEmptyInputBo('Do you want to calculate the average ref. ?',[],AvgRefStatus,0,1);
if AvgRefStatus
    [UseSpecChanStatus]=IfEmptyInputBo('Do you want to choose special channels ?',[],UseSpecChanStatus,1,1);
    [UseAWEStatus]=IfEmptyInputBo('Do you want to use AWE ?',[],UseAWEStatus,1,1);
    if UseAWEStatus; [AWEFileMat]=FileNameExt2Mat(FileMat,['.AEM.AWE']); end
else
    UseAWEStatus=0; UseSpecChanStatus=0;
end

if AvgRefStatus
    PutExt='.AEM.AR';
else
    PutExt='.AEM';
end

[AEMFilePathMat]=FileNameExt2Mat(FileMat,PutExt);
[AEMFilePathMat,AlternPath]=TestFileMatWrite(AEMFilePathMat,AlternPath);
if isempty(FreStart) | isempty(FreEnd); 
    CalcFreMatStatus=0; 
else
    CalcFreMatStatus=1; 
end

for FileIndex=1:NFiles	
    AbsMatCell=[];  %New
    StdMatCell=[];  %New
    TraMatCell=[];  %New
    FlaMatCell=[];  %New
    FreMatCell=[];  %New
    
    NAwe=0; % New Counter for AEM.AWE MAT	der über die zellen aggregriert
    [EGISFile,EGISPath,EGISFilePath]=GetFileNameOfMat(FileMat,FileIndex);
    [Header,EGISFile,EGISPath,EGISFilePath,SampRate,NCells,NTrials,NPoints,...
            NChan,LHeader,LCellHdr,BrdGain,ChanZero,ChanGain,HdrVer,Bits,Range]=ReadEGISHeader(EGISFilePath,[],[],[],[],BitsRangeStatus);
    if isempty(MinGoodChan); 
        MinGoodChan=floor(NChan.*.8); 
    end
    [ChanGainVec]=CalcGainVec(ChanGain,Bits,Range);
    if AvgRefStatus; 
        NChanCalc=NChan+1; 
    else
        NChanCalc=NChan;
    end
    %==================================================================
    if AvgRefStatus 
        if UseSpecChanStatus
            EStatusFilePath=[EGISFilePath '.' int2str(NChan) 'est'];
            fprintf('Read electrode status from file:\n');
            disp(EStatusFilePath);
            fprintf('\n');
            fid=fopen(EStatusFilePath,'r','b');
            AvgRefChanStatus=fread(fid,NChan,'int16');
            fclose(fid);
            AvgRefChanInd=find(AvgRefChanStatus==1);
            NoAvgRefChanInd=find(AvgRefChanStatus==0);
        else
            AvgRefChanInd=[1:NChan];
            NoAvgRefChanInd=[];
        end
        if UseAWEStatus
            [AWEFile,AWEPath,AWEFilePath]=GetFileNameOfMat(AWEFileMat,FileIndex);
            AWEMat=ReadData(AWEFilePath,1,[],'int16','int16');
            if ~isempty(NoAvgRefChanInd)
                AWEMat(NoAvgRefChanInd,:)=zeros(length(NoAvgRefChanInd),sum(NTrials)); %Changed to the sum of trials
            end
        end
    else
        UseAWEStatus=0;
    end
    NPointsInCell=NPoints.*NTrials.*NChan;
    NoPointsInAllCells=sum(NPointsInCell);
    NoPointsInFile=NoPointsInAllCells+LHeader;
    
    fprintf('\n')
    clc;
    fprintf('Start reading data file...\n\n');
    disp(EGISFilePath);
    fprintf('\n\n');
    EgisFid=fopen(EGISFilePath,'r','b');
    FidStatus=fseek(EgisFid,LHeader,-1);
    if FidStatus~=0; 
        error('Fseek error in CalcAutoEditMat !!'); 
    end
    fprintf('Number of cells in file: %g \n\n',NCells);
    
    for CellIndex=1:NCells	
        if isempty(TimeStatusVec)
            TimeStatusVec=ones(NPoints(CellIndex),1);
        else
            if length(TimeStatusVec)>NPoints(CellIndex)
                TimeStatusVec=ones(NPoints(CellIndex),1);
                fprintf(1,'Set length of TimeStatusVec to %g (NPoints)\n',NPoints(CellIndex))
            end
        end
        [TimeIndVec,NoTimeIndVec,TimeStatusVec,NInt,IntStartVec]=ChooseTimeIndTmp(ChooseTimeIndStatus,[],[],TimeStatusVec,NPoints(CellIndex));		
        if isempty(TimeIndVec); 
            error('TimeIndVec is empty in CalcAutoEditMat !'); 
        end
        NPointsCalc=length(TimeIndVec);
        for NIntIndex=1:NInt
            NoTransVec(NIntIndex)=find(TimeIndVec==IntStartVec(NIntIndex));
        end
        TransStatusVec=ones(size(TimeIndVec));
        if NInt>1
            TransStatusVec(NoTransVec)=zeros(length(NoTransVec),1);
        end
        if CalcFlaMatStatus
            [LFlatWin]=IfEmptyInputValInt('Please insert the length of flat test window:',[],LFlatWin,5,1,NPoints(CellIndex),1);
        end
        %=======================================================
        
        AbsMat=ones(NTrials(CellIndex),NChanCalc);
        TraMat=ones(NTrials(CellIndex),NChanCalc);
        StdMat=ones(NTrials(CellIndex),NChanCalc);
        FlaMat=ones(NTrials(CellIndex),NChanCalc);
        FreMat=ones(NTrials(CellIndex),NChanCalc);
        
        if AvgRefStatus
            AvgRefMat=zeros(NChanCalc,NPointsCalc);
        end
        for TrialIndex=1:NTrials(CellIndex)
            NAwe=NAwe+1;
            CalcStatus=1;
            DataMat=fread(EgisFid,[NChan,NPoints(CellIndex)],'int16');
            DataMat=DataMat(:,TimeIndVec);
            for TimeInd=1:length(TimeIndVec)
                DataMat(:,TimeInd)=DataMat(:,TimeInd).*ChanGainVec;
            end
            if CalcFlaMatStatus
                %==========Calculate the FlaMat=================
                for ChanIndex=1:NChan
                    TmpVec=DataMat(ChanIndex,:);
                    TimeIndex=1;
                    while TimeIndex<=NPointsCalc-LFlatWin+1
                        TmpTmpVec=TmpVec(TimeIndex:TimeIndex+LFlatWin-1);
                        if any(TmpTmpVec~=TmpTmpVec(1))
                            TimeIndex=TimeIndex+LFlatWin;
                        else
                            FlaMat(TrialIndex,ChanIndex)=0;	
                            TimeIndex=NPointsCalc+1;
                        end
                    end
                end
            end	
            %===========================
            if AvgRefStatus
                if UseAWEStatus; 
                    AvgRefChanInd=find(AWEMat(:,NAwe)==1);
                end  % hier wird NAwe counter eingesetzt
                Tmp=find(AvgRefChanInd~=NChanCalc);
                if ~isempty(Tmp); 
                    NTmp=length(Tmp);
                else; 
                    NTmp=0; 
                end
                if NTmp>=MinGoodChan				
                    AvgRefVec=(sum(DataMat(AvgRefChanInd(Tmp),:)))./(length(Tmp));
                    AvgRefMat(NChanCalc,:)=AvgRefVec;
                    for TimeIndex=1:NPointsCalc
                        AvgRefMat(1:NChanCalc-1,TimeIndex)=DataMat(:,TimeIndex)-AvgRefVec(TimeIndex);
                    end
                    DataMat=AvgRefMat;
                else
                    CalcStatus=0;
                    fprintf(1,'\n%g (res. sensors) < %g (min. sensors) in trial %g of cell %g\n',NTmp,MinGoodChan,TrialIndex,CellIndex);
                end
            end
            if CalcStatus
                %==========Subtract the baseline=================
                if CalcBaseStatus
                    if isempty(BaseStartPoint); 
                        BaseStartPoint=1; 					
                    end
                    if isempty(BaseEndPoint) | BaseEndPoint>NPoints(CellIndex); 	
                        BaseEndPoint=min(length(TimeIndVec),NPoints(CellIndex)); 	
                    end
                end
                [DataMat,BaseStartPoint,BaseEndPoint,CalcBaseStatus]=CalcBaseline(DataMat,BaseStartPoint,BaseEndPoint,CalcBaseStatus);		
                DataMat=DataMat';	%Da std, abs etc ueber Kanaele rechnen wuerden
                %==========Calculate the StdMat=================
                StdMat(TrialIndex,:)=std(DataMat);
                %==========Calculate the AbsMat=================
                AbsMat(TrialIndex,:)=max(abs(DataMat));
                %==========Calculate the TraMat=================
                MaxAbsVec=zeros(1,NChanCalc);
                AbsVecTmp=zeros(1,NChanCalc);
                for TimeIndex=2:NPointsCalc	
                    if TransStatusVec(TimeIndex)	
                        AbsVecTmp=abs(DataMat(TimeIndex,:)-DataMat(TimeIndex-1,:));
                        HigherChan=find(AbsVecTmp>MaxAbsVec);
                        MaxAbsVec(HigherChan)=AbsVecTmp(HigherChan);
                    end
                end
                TraMat(TrialIndex,:)=MaxAbsVec;
                %==========Calculate the FreMat=================
                if CalcFreMatStatus
                    FftDataMat=fft(DataMat);
                    PFftDataMat=abs(FftDataMat.*conj(FftDataMat))./NPoints;
                    FreMat(TrialIndex,:)=sqrt(mean(PFftDataMat(FreStart:FreEnd,:)));
                end
            else
                AbsMat(TrialIndex,:)=1000000.*ones(1,NChanCalc);
                StdMat(TrialIndex,:)=1000000.*ones(1,NChanCalc);
                TraMat(TrialIndex,:)=1000000.*ones(1,NChanCalc);
                FreMat(TrialIndex,:)=1000000.*ones(1,NChanCalc);
            end
            if round(TrialIndex./10)==TrialIndex./10
                fprintf(1,'\n');
                fprintf(1,'Cell %g of %g; Trial in cell %g of %g; Total trials %g of %g      ',CellIndex,NCells,TrialIndex,NTrials(CellIndex),sum(NTrials(1:CellIndex-1))+TrialIndex,sum(NTrials));
            else
                fprintf(1,'.');
            end
        end
        MaxMaxAbsMat=max(max(AbsMat));
        MaxMaxStdMat=max(max(StdMat));
        MaxMaxTraMat=max(max(TraMat));
        MaxMaxFreMat=max(max(FreMat));
        MaxMaxFlatMat=length(find(~FlaMat));
        fprintf(1,'\n\n');
        fprintf(1,'Maximum of abs value: %g \n',MaxMaxAbsMat);
        fprintf(1,'Maximum of std value: %g \n',MaxMaxStdMat);
        fprintf(1,'Maximum of tra value: %g \n',MaxMaxTraMat);
        fprintf(1,'Maximum of fre value: %g \n',MaxMaxFreMat);
        fprintf(1,'Maximum of fla value: %g \n',MaxMaxFlatMat);
        fprintf(1,'\n\n');
        AbsMatCell=[AbsMatCell AbsMat']; % hier werden die trials für abs std tra aneinandergehängt um zusammenhängend weggeschrieben zu werden
        StdMatCell=[StdMatCell StdMat']; 
        TraMatCell=[TraMatCell TraMat'];
        FlaMatCell=[FlaMatCell FlaMat'];
        FreMatCell=[FreMatCell FreMat'];
    end	%CellIndex
    fclose(EgisFid);
    %=============================Save EditMat to file================================================================
    [AEMFile,AEMPath,AEMFilePath]=GetFileNameOfMat(AEMFilePathMat,FileIndex);
    [NoUse,EndPos]=SaveData(AbsMatCell,AEMFilePath,1,[],'int16','float32');
    [NoUse,EndPos]=SaveData(StdMatCell,AEMFilePath,1,[],'int16','float32',1,EndPos);
    [NoUse,EndPos]=SaveData(TraMatCell,AEMFilePath,1,[],'int16','float32',1,EndPos);
    [NoUse,EndPos]=SaveData(FlaMatCell,AEMFilePath,1,[],'int16','float32',1,EndPos);
    [NoUse,EndPos]=SaveData(FreMatCell,AEMFilePath,1,[],'int16','float32',1,EndPos);
end	%FileIndex
return;
