%==================================================================
%==================================================================
%
%	BatchTTx.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.                                                                      
%	Markus Junghoefer	[2000]
%
%
%	Function definition
%	
%
%
%
%
%=================================================================
%==================================================================
UnixStr=['lspdf -posted'];
[LsPdfStatus,LsPdfResult]=unix(UnixStr);
Tmp=findstr(LsPdfResult,'"');
if length(Tmp)>4
    LengthTmp=length(Tmp)
    LsPdfResult=LsPdfResult
end
HostName=[LsPdfResult(Tmp(3)+1:Tmp(4)-1)];
fprintf(1,['Data on host: ',HostName,'\n']);
HardDiskName=[LsPdfResult(Tmp(1)+1:Tmp(2)-1)];
fprintf(1,['Data on hard disk: ',HardDiskName,'\n']);
UnixStr=['get_pdfs -u -x'];
[GetPdfStatus,GetPdfResult]=unix(UnixStr);
TmpP=findstr(GetPdfResult,'-P');
TmpS=findstr(GetPdfResult,'-S');
Tmps=findstr(GetPdfResult,'-s');
Tmpr=findstr(GetPdfResult,'-r');
Tmpp=findstr(GetPdfResult,'-p');
NMsiFiles=length(TmpP);


SessionStr=char('00.00 00.00 00.00');           %Subject 1
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 2
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 3
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 4
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 5
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 6
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 7
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 8
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 9
SessionStr=char(SessionStr,'16.07 20.07 27.07');%Subject 10
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 11
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 12
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 13
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 14
SessionStr=char(SessionStr,'00.00 00.00 00.00');%Subject 15

DeleteOrigFileStatus=0
DeleteNoiseFileStatus=0
DeleteFilterFileStatus=0

for FileInd=1:NMsiFiles
    MsiPatient=[GetPdfResult(TmpP(FileInd)+3:TmpS(FileInd)-2)];
    fprintf(1,'\n')
    fprintf(1,['\n MsiPatient = ',MsiPatient])
    MsiScan=[GetPdfResult(TmpS(FileInd)+3:Tmps(FileInd)-2)] ;
    MsiSession=[GetPdfResult(Tmps(FileInd)+3:Tmpr(FileInd)-2)];
    MsiSessionTmp=[MsiSession(2:9),'@',MsiSession(11:15)];
    MsiRun=[GetPdfResult(Tmpr(FileInd)+3:Tmpp(FileInd)-2)];
    if FileInd<NMsiFiles
        MsiFile=deblank([GetPdfResult(Tmpp(FileInd)+3:TmpP(FileInd+1)-2)])
    else
        MsiFile=deblank([GetPdfResult(Tmpp(FileInd)+3:length(GetPdfResult)-2)])
    end
	SubjStr=MsiPatient(6:7);
    Subj=str2num(SubjStr);
    if ~isempty(findstr(MsiScan,'TTX'))
        Scan=2; %Finger Stimulation     
        PreTrigInt=136;
        PostTrigInt=271;
        SpecCondVec=[4098 4100 4102 4106 4110 4116 4118 4126];
        if strcmp(MsiRun,'1') | strcmp(MsiRun,'3') | strcmp(MsiRun,'5')
            NDefTrials=480;
        else
            NDefTrials=690;        
        end 
    else
        Scan=1; %Lip Stimulation
        PreTrigInt=136;
        PostTrigInt=271;
        SpecCondVec=[8192]; 
        NDefTrials=1023;
    end
    Scan=Scan
    %===========Session===============
    MsiSession=MsiSession
    SessionStr(Subj,:)
    MsiSession(2:6)
    Tmp=findstr(SessionStr(Subj,:),MsiSession(2:6))
    if isempty(Tmp)
        fprintf(1,'Unknown session of subject %g !',Subj);
        return;
    end
    Session=(Tmp-1)/6+1
    %===========Run===============
    Run=str2num(MsiRun)
    MsiPath=['/export/',HostName,filesep,HardDiskName,'/msi_data'];
    MsiPath=[MsiPath,filesep,MsiPatient,filesep,MsiScan,filesep,MsiSessionTmp,filesep,MsiRun];
    MsiFilePath=[MsiPath,filesep,MsiFile];
    NoiseFlag=1;
    if ~isempty(findstr(MsiFile,',n'))
        fprintf(1,'\n\n')
        fprintf(1,['MsiFile is allready noise reduced: Disable noise reducer; NoiseFlag=0']); 
        NoiseFlag=0;
    end 
    FilterFlag=1;
    if ~isempty(findstr(MsiFile,',f'))
        fprintf(1,'\n\n')
        fprintf(1,['MsiFile is allready filtered: Disable filterer; FilterFlag=0']); 
        FilterFlag=0;
    end
    fprintf(1,'\n\n')
    fprintf(1,['MsiFilePath: ',MsiFilePath]);

    MsiPathTmp='/export/jesse/data3/TTx'    
    SubDir=['TTx',SubjStr];
    [MkDirStatus,MkDirMessage]=mkdir(MsiPathTmp,SubDir);
    MsiPathTmp=[MsiPathTmp,filesep,SubDir];
    fprintf(1,'\n\n');
    fprintf(1,MkDirMessage);
    SubDir=['Scan',int2str(Scan)];
    [MkDirStatus,MkDirMessage]=mkdir(MsiPathTmp,SubDir);
    MsiPathTmp=[MsiPathTmp,filesep,SubDir];
    fprintf(1,'\n\n');
    fprintf(1,MkDirMessage);
    SubDir=['Session',int2str(Session)];
    [MkDirStatus,MkDirMessage]=mkdir(MsiPathTmp,SubDir);
    MsiPathTmp=[MsiPathTmp,filesep,SubDir];
    fprintf(1,'\n\n');
    fprintf(1,MkDirMessage);
    SubDir=['Run',int2str(Run)];
    [MkDirStatus,MkDirMessage]=mkdir(MsiPathTmp,SubDir);
    MsiPathTmp=[MsiPathTmp,filesep,SubDir];
    fprintf(1,'\n\n');
    fprintf(1,MkDirMessage);
    
    MsiFileTmp=['TTx',int2str(Subj),'.',int2str(Scan),'.',int2str(Session),'.',int2str(Run),'.f.msi'] ;
    MsiFilePathTmp=[MsiPathTmp,filesep,MsiFileTmp];
    
    %============NoiseReducer==================
    if NoiseFlag
        fprintf('\n\n');
        fprintf(1,'Reduce noise of file:\n');
        fprintf(1,MsiFilePath);
        fprintf('\n');
        fprintf(1,'Write noise reduced data to file:\n');
        fprintf(1,[MsiFilePath,',n']);
        fprintf('\n');
        if ~exist([MsiFilePath,',n'])
            UnixStr=['noisereducer -P ',MsiPatient,' -S ',MsiScan,' -s ',MsiSession,' -r ',MsiRun,' -p ',MsiFile,' -R MxaA,MyaA,MzaA,GxxA,GyyA,GzxA,GzyA -g -v']
            [UnixStatus,UnixResult]=unix(UnixStr);
            display(UnixResult)
        else
            fprintf(1,'\n\n')
            fprintf(1,'Do not do noisereducer since noise reduced file:\n')
            fprintf(1,[MsiFilePath,',n']); fprintf(1,'\n')
            fprintf(1,'allready exists.')
        end
        if exist([MsiFilePath,',n'])  & DeleteOrigFileStatus          
            UnixStr=['pdf_deleter -P ',MsiPatient,' -S ',MsiScan,' -s ',MsiSession,' -r ',MsiRun,' -p ',MsiFile];
            [UnixStatus,UnixResult]=unix(UnixStr);
            display(UnixResult)
        end
        MsiFile=[MsiFile,',n'];
        MsiFilePath=[MsiFilePath,',n'];
    end
    %============Filterer fbp1.5-50Hz,o==================
    if FilterFlag
        FilterStr1='bp1.5-50Hz';
        FilterExt1=[',f',FilterStr1,',o'];
    
        fprintf(1,'\n\n')
        fprintf(1,'Filter file:\n');
        fprintf(1,MsiFilePath);
        fprintf('\n');
        fprintf(1,['using filter: ',FilterStr1,'\n']);
        fprintf(1,'Write filtered data to file:\n');
        fprintf(1,[MsiFilePath,FilterExt1]);
        fprintf('\n');
    
        if ~exist([MsiFilePath,FilterExt1])
            UnixStr=['flt_help -P ',MsiPatient,' -S ',MsiScan,' -s ',MsiSession,' -r ',MsiRun,' -p ',MsiFile,' -f ',FilterStr1];
            [UnixStatus,UnixResult]=unix(UnixStr);
            fprintf(1,'\n\n')
            fprintf(1,UnixResult)
        else
            fprintf(1,'\n\n')
            fprintf(1,'Do not do filterer since filtered file:\n')
            fprintf(1,[MsiFilePath,FilterExt1]); fprintf(1,'\n')
            fprintf(1,'allready exists.')
        end       
        if exist([MsiFilePath,FilterExt1]) & DeleteNoiseFileStatus          
            UnixStr=['pdf_deleter -P ',MsiPatient,' -S ',MsiScan,' -s ',MsiSession,' -r ',MsiRun,' -p ',MsiFile];
            [UnixStatus,UnixResult]=unix(UnixStr);
            fprintf(1,'\n\n')
            fprintf(1,UnixResult)
        end  
        %============Filterer bp1-20Hz-678-2==================
        FilterStatus=0
        if FilterStatus
            FilterStr2='bp1-20Hz-678-2';
            FilterExt2=[',f',FilterStr2,',o'];
            fprintf(1,'\n\n')
            fprintf(1,'Filter file:\n');
            fprintf(1,MsiFilePath);
            fprintf('\n');
            fprintf(1,['using filter: ',FilterStr2,'\n']);
            fprintf(1,'Write filtered data to file:\n');
            fprintf(1,[MsiFilePath,FilterExt2]);
            fprintf('\n');
            if ~exist([MsiFilePath,FilterExt2])
                UnixStr=['flt_help -P ',MsiPatient,' -S ',MsiScan,' -s ',MsiSession,' -r ',MsiRun,' -p ',MsiFile,' -f ',FilterStr2];
               [UnixStatus,UnixResult]=unix(UnixStr);
                fprintf(1,'\n\n')
                fprintf(1,UnixResult)
            else
                fprintf(1,'\n\n')
                fprintf(1,'Do not do filterer since filtered file:\n')
                fprintf(1,[MsiFilePath,FilterExt2]); fprintf(1,'\n')
                fprintf(1,'allready exists.')
            end  
        end        
  
    end
    %========================================================
    MsiFile=[MsiFile,FilterExt1];
    MsiFilePath=[MsiPath,filesep,MsiFile];
    %============create_set==================
    MsiFilePathTmp=[MsiPathTmp,filesep,MsiFileTmp];
    
    fprintf(1,'\n\n')
    fprintf(1,'Create set of file %g:\n',FileInd)
    fprintf(1,'%s\n',MsiFile);
    fprintf(1,'and write set to file:\n')
    fprintf(1,'%s\n',[MsiFilePathTmp,'.set']);
    
    UnixStr=['create_set -P ',MsiPatient,' -S ',MsiScan,' -s ',MsiSession,' -r ',MsiRun,' -p ',MsiFile,' > ',MsiFilePathTmp,'.set'];
    [UnixStatus,UnixResult]=unix(UnixStr);
    fprintf(1,'\n\n')
    fprintf(1,UnixResult)
    %==============exp2besa===================
    fprintf(1,'\n\n')
    fprintf(1,'Exp2Besa of file %g:\n')
    fprintf(1,'%s\n',MsiFile);
    fprintf(1,'BaseFilePath:\n')
    fprintf(1,'%s\n',MsiFilePathTmp);
    UnixStr=['exp2besa -n -P ',MsiPatient,' -S ',MsiScan,' -s ',MsiSession,' -r ',MsiRun,' -p ',MsiFile,' ',MsiFilePathTmp];
    [UnixStatus,UnixResult]=unix(UnixStr);
    fprintf(1,'\n\n')
    fprintf(1,UnixResult)
    %==============TransMsiContSess=============
    fprintf(1,'\n\n')
    fprintf(1,'TransMsiContSessTTx of file %g:\n')
    fprintf(1,'%s\n',MsiFilePath);
	fprintf(1,'Write session and averaged files to base:\n')
    fprintf(1,'%s\n',[MsiFilePathTmp]);
    [NonUse,NonUse,TTxSesFilePath]=TransMsiContSessTTx(MsiFilePath,MsiFilePathTmp,PreTrigInt,PostTrigInt,1,SpecCondVec,[],NDefTrials,Session);
    CalcAutoEditMEGMat(TTxSesFilePath,[],1,1,408);
    if exist(MsiFilePath) & DeleteFilterFileStatus          
        UnixStr=['pdf_deleter -P ',MsiPatient,' -S ',MsiScan,' -s ',MsiSession,' -r ',MsiRun,' -p ',MsiFile];
        [UnixStatus,UnixResult]=unix(UnixStr);
        fprintf(1,'\n\n')
        fprintf(1,UnixResult)
    end  
end
