function []=Batch2ndLevel(ConStart,ConEnd,SubVec,SubgroupDir,StatsDesign)

%   Batch2ndLevel

%   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<1; ConStart=[]; end
if nargin<2; ConEnd=[]; end
if nargin<3; SubVec=[]; end
if nargin<4; SubgroupDir=[]; end
if nargin<5; StatsDesign=[]; end
global BATCHMJ FullConDir ConNames ConTypes ConVals 

%Changes in (search for BATCHMJ):
%spm_spm_ui
%spm_result_ui
%spm_getSPM
%spm_conman
%spm_render
StudyStr='Giessen'
if isempty(ConStart); ConStart=21; end %Starts with Con+1
if isempty(ConEnd);   ConEnd=[21];  end %Ends with Con+1; if isempty(ConEnd); ConEnd=size(F.names,2); end
if isempty(SubgroupDir); SubgroupDir='FlipFemale'; end

BATCHMJ.QTMP=1; %1=None,  (Threshold Masking)
BATCHMJ.c=2; %1=Stop; 2=Continue calculation if result files are already in folder => Overwrite existing files
BaseStr='0'
SmoothStr='08'
FlipStatus=0
if isempty(SubVec)
    if strcmp(StudyStr,'GV')
        SubVec=[1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 21]
        FemaleVec=[7 9 10 11 13 14 16 17 18 20 22]
        MaleVec  =[2 3 4  5  6  12 15 21 23 24 25]
        %SexVec=[MaleVec,FemaleVec]
    elseif strcmp(StudyStr,'Giessen')
        SubVec=[3 4 5 6 7 9 10 11 12 13 14 15 16 17 18 20 21 22 23 24 25]
        MaleVec=[3 4 5 6 12 15 21 23 24 25]
        FemaleVec=[7 9 10 11 13 14 16 17 18 20 22]
        FemaleVec10=[9 10 11 13 14 16 17 18 20 22]
        SexVec=[MaleVec,FemaleVec]
    end
    IndVec1=MaleVec
    NIndVec1=length(IndVec1);
    IndVec2=FemaleVec
    NIndVec2=length(IndVec2);
    IndVec=[ones(size(IndVec1)),2.*ones(size(IndVec2))]
    if strcmp(SubgroupDir,'Female')
        SubVec=FemaleVec;
        StatsDesign='One sample t-test'
    elseif strcmp(SubgroupDir,'Male')
        SubVec=MaleVec;
        StatsDesign='One sample t-test'
    elseif strcmp(SubgroupDir,'All')
        SubVec=SexVec;
        StatsDesign='One sample t-test'
    elseif strcmp(SubgroupDir,'Gender')
        SubVec=SexVec;
        StatsDesign='Two sample t-test'
    elseif strcmp(SubgroupDir,'Flip')
        StatsDesign='Paired t-test'
    elseif strcmp(SubgroupDir,'FlipFemale')
        SubVec=FemaleVec;
        StatsDesign='Paired t-test'
    elseif strcmp(SubgroupDir,'FlipMale')
        SubVec=MaleVec;
        StatsDesign='Paired t-test'
    end
end
NSub=length(SubVec);

GrandParentDir=['D:\ValAro\00_Stats_NoScaling\RandStatsSmooth',SmoothStr];
RendFilePath='C:\toolbox\spm99\rend\render_smooth_average.mat';

%======================Create ParentDir==================
ParentDir=[GrandParentDir,filesep,SubgroupDir];
[MkDirStatus,MkDirMsg]=mkdir(GrandParentDir,SubgroupDir);
if MkDirStatus==1;
    fprintf(['Make directory: ',SubgroupDir,' !\n\n'])
elseif MkDirStatus==2;
    fprintf(['Directory: ',SubgroupDir,' already exists !\n\n'])
elseif MkDirStatus==0;
    MkDirStatus=MkDirStatus
    MkDirMsg=MkDirMsg
    pause;
end
%======================Create ContrastDir==================
ContrastDir='XContrasts';
FullContrastDir=[ParentDir,filesep,ContrastDir];
[MkDirStatus,MkDirMsg]=mkdir(ParentDir,ContrastDir);
if MkDirStatus==1;
    fprintf(['Make directory: ',ContrastDir,' !\n\n'])
elseif MkDirStatus==2;
    fprintf(['Directory: ',ContrastDir,' already exists !\n\n'])
elseif MkDirStatus==0;
    MkDirStatus=MkDirStatus
    MkDirMsg=MkDirMsg
    pause;
end
%============================================================
if strcmp(StudyStr,'GV')
    
elseif strcmp(StudyStr,'Giessen')
    F = struct( ...
        'names',  {{...
                'CPosHiGTNeutAll','CPosHiLTNeutAll','CNegHiGTNeutAll','CNegHiLTNeutAll','CPosLoGTNeutAll',...
                'CPosLoLTNeutAll','CNegLoGTNeutAll','CNegLoLTNeutAll','CPosHiGTNegHiAll','CPosHiLTNegHiAll',...                 %10
                'CPosLoGTNegLoAll','CPosLoLTNegLoAll','CAroHiGTLoAll','CAroHiLTLoAll','CAroLinHiGTLoAll',...
                'CAroLinHiLTLoAll','CAroExp1HiGTLoAll','CAroExp1HiLTLoAll','CAroExp2HiGTLoAll','CAroExp2HiLTLoAll',...           %20
                'CValPosGTNegAll','CValPosLTNegAll','CPosHiGTNeutSlow','CPosHiLTNeutSlow','CNegHiGTNeutSlow',...
                'CNegHiLTNeutSlow','CPosLoGTNeutSlow','CPosLoLTNeutSlow','CNegLoGTNeutSlow','CNegLoLTNeutSlow',...               %30
                'CPosHiGTNegHiSlow','CPosHiLTNegHiSlow','CPosLoGTNegLoSlow','CPosLoLTNegLoSlow','CAroHiGTLoSlow',...
                'CAroHiLTLoSlow','CAroLinHiGTLoSlow','CAroLinHiLTLoSlow','CAroExp1HiGTLoSlow','CAroExp1HiLTLoSlow',...           %40
                'CAroExp2HiGTLoSlow','CAroExp2HiLTLoSlow','CValPosGTNegSlow','CValPosLTNegSlow','CPosHiGTNeutFast',...
                'CPosHiLTNeutFast','CNegHiGTNeutFast','CNegHiLTNeutFast','CPosLoGTNeutFast','CPosLoLTNeutFast',...               %50
                'CNegLoGTNeutFast','CNegLoLTNeutFast','CPosHiGTNegHiFast','CPosHiLTNegHiFast','CPosLoGTNegLoFast',...             
                'CPosLoLTNegLoFast','CAroHiGTLoFast','CAroHiLTLoFast','CAroLinHiGTLoFast','CAroLinHiLTLoFast',...                 %60
                'CAroExp1HiGTLoFast','CAroExp1HiLTLoFast','CAroExp2HiGTLoFast','CAroExp2HiLTLoFast','CValPosGTNegFast',...
                'CValPosLTNegFast','CFastGTSlow','CFastLTSlow','CFastGTSlowNegHi','CFastLTSlowNegHi',...                            %70
                'CFastGTSlowNegLo','CFastLTSlowNegLo','CFastGTSlowNeut','CFastLTSlowNeut','CFastGTSlowPosLo',...
                'CFastLTSlowPosLo','CFastGTSlowPosHi','CFastLTSlowPosHi','CFastGTSlowHiAro','CFastLTSlowHiAro',...                  %80
                'CFastGTSlowLoAro','CFastLTSlowLoAro','CFastGTSlowNegVal','CFastLTSlowNegVal','CFastGTSlowPosVal', ...
                'CFastLTSlowPosVal','CPosHiLTPosLoAll','CPosHiGTPosLoAll','CPosHiLTPosLoSlow','CPosHiGTPosLoSlow', ...              %90
                'CPosHiLTPosLoFast','CPosHiGTPosLoFast','CNegHiLTNegLoAll','CNegHiGTNegLoAll','CNegHiLTNegLoSlow', ...
                'CNegHiGTNegLoSlow','CNegHiLTNegLoFast','CNegHiGTNegLoFast','CPosHiLTNegLoAll','CPosHiGTNegLoAll', ...             %100
                'CPosHiLTNegLoSlow','CPosHiGTNegLoSlow','CPosHiLTNegLoFast','CPosHiGTNegLoFast','CNegHiLTPosLoAll', ...
                'CNegHiGTPosLoAll', 'CNegHiLTPosLoSlow','CNegHiGTPosLoSlow','CNegHiLTPosLoFast','CNegHiGTPosLoFast', ...            %110
                'CAroHiGTLoNoNeutralAll','CAroHiLTLoNoNeutralAll','CAroHiGTLoNoNeutralSlow','CAroHiLTLoNoNeutralSlow','CAroHiGTLoNoNeutralFast',...
                'CAroHiLTLoNoNeutralFast','CAroLoGTNeutralAll','CAroLoLTNeutralAll','CAroLoGTNeutralSlow','CAroLoLTNeutralSlow',... %120
                'CAroLoGTNeutralFast','CAroLoLTNeutralFast','CAroHiGTNeutralAll','CAroHiLTNeutralAll','CAroHiGTNeutralSlow',...
                'CAroHiLTNeutralSlow','CAroHiGTNeutralFast','CAroHiLTNeutralFast',...
            }})
end
if isempty(ConEnd)
    ConEnd=size(F.names,2);
end
for i=ConStart:2:ConEnd   
    Con=i+1;
    if Con<10
        PreConStr=['00',int2str(Con)];
    elseif Con>9 & Con<100
        PreConStr=['0',int2str(Con)];
    else
        PreConStr=[int2str(Con)];
    end
    if Con==1
        ConStr='EffectsOfInterest'
        ConDir=[PreConStr,'_EffectsOfInterest'];
        File=['ess_0',PreConStr,'.img'];
    else
        ConStr=char(F.names(Con-1));
        ConName=[PreConStr,'_',ConStr];
        ConDir=[PreConStr,'_',ConStr(2:length(ConStr))]
        File=['con_0',PreConStr,'.img'];
    end

    if ~isempty(findstr(SubgroupDir,'Flip'))
        FlipFile=['con_f',PreConStr,'.img'];
    end
    FullConDir=[FullContrastDir,filesep,ConDir]; 
    [MkDirStatus,MkDirMsg]=mkdir(FullContrastDir,ConDir);
    if MkDirStatus==2
        fprintf(1,'Directory\n')
        fprintf(1,ConDir); fprintf(1,'\n'); 
        fprintf(1,'already exists in\n')
        fprintf(1,ParentDir)
    elseif MkDirStatus==1
        fprintf(1,'Create directory\n')
        fprintf(1,ConDir)
        fprintf(1,'\n')
        fprintf(1,'in\n')
        fprintf(1,ParentDir)
    elseif MkDirStatus==0
        fprintf(1,'Can not create directory:\n')
        fprintf(1,ConDir)
        fprintf(1,'in\n')
        fprintf(1,ParentDir)
        fprintf(1,'\n\n')
        fprintf(1,'Error message:\n')
        fprintf(1,MkDirMsg)
    end
    FullConDir
    cd(FullConDir)
    
    NFilesExist=0;
    NFilesNotExist=0;
    ExistFilePathMat=[];
    NotExistFilePathMat=[];
    for SubInd=1:NSub
        ActSub=SubVec(SubInd);
        ActSubStr=int2str(ActSub);
        if ActSub<10
            ActSubStr=['0',ActSubStr];
        end
        BasePath=['D:\ValAro\',ActSubStr,'\snraS',ActSubStr,'Base',BaseStr,'Smooth',SmoothStr,'\'];
        FilePath=[BasePath,File];
        
        FileExist=exist(FilePath,'file');
        if FileExist==2
            NFilesExist=NFilesExist+1;
            if NFilesExist==1
                ExistFilePathMat=char(FilePath);
            else
                ExistFilePathMat=char(ExistFilePathMat,FilePath);
            end
        else
            NFilesNotExist=NFilesNotExist+1;
            if NFilesNotExist==1
                NotExistFilePathMat=char(FilePath);
            else
                NotExistFilePathMat=char(NotExistFilePathMat,FilePath);
            end   
        end
        if ~isempty(findstr(SubgroupDir,'Flip'))
            FlipFilePath=[BasePath,FlipFile];
            FileExist=exist(FlipFilePath,'file');
            if FileExist==2
                NFilesExist=NFilesExist+1;
                if NFilesExist==1
                    ExistFilePathMat=char(FlipFilePath);
                else
                    ExistFilePathMat=char(ExistFilePathMat,FlipFilePath);
                end
            else
                NFilesNotExist=NFilesNotExist+1;
                if NFilesNotExist==1
                    NotExistFilePathMat=char(FlipFilePath);
                else
                    NotExistFilePathMat=char(NotExistFilePathMat,FlipFilePath);
                end   
            end
        end
    end
    fprintf(1,'%g existing files chosen:\n\n',NFilesExist)
    disp(ExistFilePathMat)
    fprintf(1,'\n\n')
    if NFilesNotExist>0
        fprintf(1,'%g not existing files chosen:\n\n',NFilesNotExist)
        disp(NotExistFilePathMat)
        pause
    end
    D=spm_spm_ui('DesDefs_Stats');
    if strcmp(StatsDesign,'One sample t-test')   
        D=D(1);
        BatchI=ones(NSub,4);
        BatchI(:,1)=[1:NSub]';   
    elseif strcmp(StatsDesign,'Two sample t-test')
        D=D(2);
        BatchI=ones(NSub,4);
        BatchI(1:NIndVec1,1)=[1:NIndVec1]'; 
        BatchI(NIndVec1+1:NSub,1)=[1:NIndVec2]'; 
        BatchI(:,2)=IndVec';
        BatchI
    elseif strcmp(StatsDesign,'Paired t-test')
        D=D(3);
        BatchI=ones(NSub.*2,4);
        BatchI(1:2:NSub.*2,2)=ones(NSub,1); 
        BatchI(2:2:NSub.*2,2)=2.*ones(NSub,1); 
        BatchI(1:2:NSub.*2,3)=[1:NSub]'; 
        BatchI(2:2:NSub.*2,3)=[1:NSub]';
        BatchI
    else
        error('Unknown StatsDesign')
    end
    BATCHMJ.P=cellstr(ExistFilePathMat);
    BATCHMJ.I=BatchI;
     
    D.iGMsca=9;
    D.M_.X=0;
    D.iGXcalc=1;
    spm_spm_ui('cfg',D)
    %==========================Calculate Contrasts==============================
    if strcmp(StatsDesign,'One sample t-test')
        ConNames={{ConName}};
        ConTypes={{'T'}};
        ConVals={{1}};
    elseif strcmp(StatsDesign,'Two sample t-test')
        ConTypes={{'T'}}
        ConVals={{[-1 1 0]}}; 
        GTInd=findstr(ConName,'GT')
        LTInd=findstr(ConName,'LT')
        ConNames=ConName;
        if ~isempty(GTInd)
            ConNames={{[,'Female > Male; ',ConNames]}}
        elseif ~isempty(LTInd)
            ConNames(LTInd)='G';
            ConNames={{[,'Male > ´Female; ',ConNames]}}
        else
            error('Unknown Contrast')
        end
    elseif strcmp(StatsDesign,'Paired t-test')
        ConTypes={{'T'}}
        ConVals={{[1,-1,zeros(1,NSub)]}}; 
        ConNames=ConName;
        ConNames={{[,'Right vs. Left; ',ConNames]}}
    end
    spm_bch('BatchAna2ndLevelCon')
    pause(1)
end
