function []=BatchResultsGV(ConStart,ConEnd,SubVec,SubgroupDir)

%   BatchResultsGV.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.  

if nargin<1; ConStart=[]; end
if nargin<2; ConEnd=[]; end
if nargin<3; SubVec=[]; end
if nargin<4; SubgroupDir=[]; end

global BATCHMJ BATCHMJSPM BATCHMJVOL hReg PRINTSTR AllMeanZ AllStdZ aMat

%Changes in (search for BATCHMJ):
%spm_spm_ui
%spm_result_ui
%spm_getSPM
%spm_conman
%spm_render

if isempty(ConStart); ConStart=1; end %Starts with Con+1
if isempty(ConEnd);   ConEnd=[1];  end %Ends with Con+1; if isempty(ConEnd); ConEnd=size(F.names,2); end
if isempty(SubgroupDir); SubgroupDir='All'; end

ucStr='u' % 'u'=>uncorrected; 'c'=>corrected
uu=0.01
uuStr=uu.*1000;
if uuStr<10
    uuStr=['00',num2str(uuStr)] 
elseif uuStr<100
    uuStr=['0',num2str(uuStr)]
else
    uuStr=num2str(uuStr)
end
k=20
kStr=int2str(k);
AdjustStatus=0
BATCHMJ.ucStr=ucStr
BATCHMJ.uu=uu;
BATCHMJ.k=k
BATCHMJ.Rname='Global-Maximum'
BATCHMJ.R=20 %mm

BaseStr='0';
SmoothStr='08';
SubVec=[3:10,12:21] %Low18 and High18 does not exist in subject 1
%SubVec=[1:3,5:9,12:21]
FlipStatus=0;
if isempty(SubVec)   
    FemaleVec=[7 9 10 11 13 14 16 17 18 20 22]
    MaleVec  =[2 3 4  5  6  12 15 21 23 24 25]
    if strcmp(SubgroupDir,'All') | strcmp(SubgroupDir,'Gender')
        SubVec=[MaleVec,FemaleVec]
    elseif strcmp(SubgroupDir,'Female')
        SubVec=FemaleVec
    elseif strcmp(SubgroupDir,'Male')
        SubVec=MaleVec
    end
end
NSub=length(SubVec);

GrandParentDir=['K:\fMRIData\fMRIDataGV'];
RendFilePath='C:\Programme\Matlab12\toolbox\spm99\rend\render_smooth_average.mat';
hXYFig=figure('Units','normal','Position',[0 .45 .5 .5], ...  
	'Name','XY','Color',[1 1 1],'NumberTitle','off');
hMeanXYFig=figure('Units','normal','Position',[0 .05 .5 .5], ...
	'Name','Mean-XY','Color',[1 1 1],'NumberTitle','off');
hZFig=figure('Units','normal','Position',[.5 .45 .5 .5], ...
	'Name','Z','Color',[1 1 1],'NumberTitle','off');
hMeanZFig=figure('Units','normal','Position',[.5 .05 .5 .5], ...
	'Name','Mean-Z','Color',[1 1 1],'NumberTitle','off');

NCond=1
Vox=[-42 -76 6]%[0 -90 -4]%%[0 -72 12] %[40 -72 -8]%[0 -90 -8] %[40 -72 -8] %[-52 -64 38] %[40 -72 -8] % %[0 -90 -8] %[-36 -79 -3] %[46 -66 6] [-48 -80 6]
SubPlotVec=[4 5];
AllZ=zeros(NSub,NCond,70);
AllMeanZ=zeros(NSub,NCond,10);
AllStdZ=zeros(NSub,NCond,10);
MaxMeanZOld=-inf;
MinMeanZOld=inf;
for SubInd=1:NSub
    ActSub=SubVec(SubInd);
    SubIndDir=int2str(ActSub);
    if ActSub<10
        SubIndDir=['0',SubIndDir]
    end
    %======================ParentDir = ContrastDir==================
   %StatsStr='Para';
   %StatsStr='HiOff';
   %StatsStr='LoOff';
   %StatsStr='LoHi';
   StatsStr='LoHi72';
    ContrastDir=['snraS',SubIndDir,StatsStr];
    FullContrastDir=[GrandParentDir,filesep,SubIndDir,filesep,ContrastDir];
    if strcmp(StatsStr,'Para')
        F0 = struct('names',{{'Low09','Low18','Low36','Low72','High09','High18',...
                    'High36','High72','AllLow','AllHigh','LowLin','HighLin'}})
        F1 = struct('names',{{'Low09','Low36','Low72','High09','High36','High72',...
                 'AllLow','AllHigh','LowLin','HighLin'}}) %Just Subject 1
        Sub1ConVec=[1 0 2 3 4 0 5 6 7 8 9 10];
    elseif strcmp(StatsStr,'HiOff')
        F0 = struct( 'names',{{'HighHighOff','LowHighOff'}}) 
        F1 = F0;
        Sub1ConVec=[1 2];
   elseif strcmp(StatsStr,'LoOff')
        F0 = struct( 'names',{{'HighLowOff','LowLowOff'}}) 
        F1 = F0;
        Sub1ConVec=[1 2];
   elseif strcmp(StatsStr,'LoHi09')
        F0 = struct( 'names',{{'High09','Low09'}}) 
        F1 = F0;
        Sub1ConVec=[1 2];
   elseif strcmp(StatsStr,'LoHi18')
        F0 = struct( 'names',{{'High18','Low18'}}) 
        F1 = F0;
        Sub1ConVec=[1 2];
   elseif strcmp(StatsStr,'LoHi36')
        F0 = struct( 'names',{{'High36','Low36'}}) 
        F1 = F0;
        Sub1ConVec=[1 2];
   elseif strcmp(StatsStr,'LoHi72')
        F0 = struct( 'names',{{'High72','Low72'}}) 
        F1 = F0;
        Sub1ConVec=[1 2];
   elseif strcmp(StatsStr,'LoHi')
        F0 = struct( 'names',{{'HighLow','LowLow','HighHigh','LowHigh','HighBTLow','LowBTHigh'}}) 
        F1 = F0;
        Sub1ConVec=[1:6];
    elseif strcmp(StatsStr,'LoHi')
        F0 = struct( 'names',{{'HighLow','LowLow','HighHigh','LowHigh','HighBTLow','LowBTHigh'}}) 
        F1 = F0;
        Sub1ConVec=[1:6];
    end
    
    ParentDir=FullContrastDir
    %======================Create StatsDir==================
    StatsDir=[ucStr,uuStr,'k',kStr]
    FullStatsDir=[ParentDir,filesep,StatsDir]
    [MkDirStatus,MkDirMsg]=mkdir(ParentDir,StatsDir);
    if MkDirStatus==1;
        fprintf(['Make directory: ',StatsDir,' !\n\n'])
    elseif MkDirStatus==2;
        fprintf(['Directory: ',StatsDir,' already exists !\n\n'])
    elseif MkDirStatus==0;
        MkDirStatus=MkDirStatus
        MkDirMsg=MkDirMsg
        pause;
    end
    %======================Create FullGlassStatsDir==================
    GlassStatsDir='GlassStatsJpg'
    FullGlassStatsDir=[FullStatsDir,filesep,GlassStatsDir]
    [MkDirStatus,MkDirMsg]=mkdir(FullStatsDir,GlassStatsDir);
    if MkDirStatus==1;
        fprintf(['Make directory: ',GlassStatsDir,' !\n\n'])
    elseif MkDirStatus==2;
        fprintf(['Directory: ',GlassStatsDir,' already exists !\n\n'])
    elseif MkDirStatus==0;
        MkDirStatus=MkDirStatus
        MkDirMsg=MkDirMsg
        pause;
    end
    %======================Create FullGlassRenderDir==================
    GlassRenderDir='GlassRenderJpg'
    FullGlassRenderDir=[FullStatsDir,filesep,GlassRenderDir]
    [MkDirStatus,MkDirMsg]=mkdir(FullStatsDir,GlassRenderDir);
    if MkDirStatus==1;
        fprintf(['Make directory: ',GlassRenderDir,' !\n\n'])
    elseif MkDirStatus==2;
        fprintf(['Directory: ',GlassRenderDir,' already exists !\n\n'])
    elseif MkDirStatus==0;
        MkDirStatus=MkDirStatus
        MkDirMsg=MkDirMsg
        pause;
    end
    %======================Create FilteredDir==================
    FilteredDir='Filtered'
    FullFilteredDir=[FullStatsDir,filesep,FilteredDir]
    [MkDirStatus,MkDirMsg]=mkdir(FullStatsDir,FilteredDir);
    if MkDirStatus==1;
        fprintf(['Make directory: ',FilteredDir,' !\n\n'])
    elseif MkDirStatus==2;
        fprintf(['Directory: ',FilteredDir,' already exists !\n\n'])
    elseif MkDirStatus==0;
        MkDirStatus=MkDirStatus
        MkDirMsg=MkDirMsg
        pause;
    end
    %======================Create VOIDir==================
    VOIDir='VOI'
    FullVOIDir=[FullStatsDir,filesep,VOIDir]
    [MkDirStatus,MkDirMsg]=mkdir(FullStatsDir,VOIDir);
    if MkDirStatus==1;
        fprintf(['Make directory: ',VOIDir,' !\n\n'])
    elseif MkDirStatus==2;
        fprintf(['Directory: ',VOIDir,' already exists !\n\n'])
    elseif MkDirStatus==0;
        MkDirStatus=MkDirStatus
        MkDirMsg=MkDirMsg
        pause;
    end
    %=================================================================

    if isempty(ConEnd)
        ConEnd=size(F.names,2);
    end
    for i=ConStart:ConEnd
        if ActSub==1
            F=F1
            Con=Sub1ConVec(i)+1;
        else
            F=F0
            Con=i+1
        end 
        BATCHMJ.Ic=Con
        if AdjustStatus
            BATCHMJ.Ic2=Con
        else
            BATCHMJ.Ic2=0
        end
        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(1:length(ConStr))]
            File=['con_0',PreConStr,'.img']
        end    
        FullConDir=FullContrastDir
        BATCHMJ.SWD=FullConDir
        %========================================================
        [hReg,SPM,VOL,xX,xCon,xSDM]=spm_results_ui; %vargout(1){hReg,SPM,VOL,xX,xCon,xSDM};
        spm_list('List',SPM,VOL,[],[],'',hReg);
        eval(['cd ',FullGlassStatsDir])
        %PRINTSTR=['print -djpeg100 -painters -append -noui ',ConDir,'.jpg'];
        %spm_figure('Print')
        %pause(2)
        %===================Jump to global maxima======================
        h=get(0,'CurrentFigure');
        h = spm_mip_ui('FindMIPax',h);
        [xyz,d] = spm_mip_ui('Jump',h,'glmax');
        %[xyz,d] = spm_mip_ui('SetCoords',Vox,h);
        [Y,xY]=spm_regions(SPM,VOL,xX,xCon,xSDM,hReg)
        eval(['cd ',FullVOIDir])
        PRINTSTR=['print -djpeg100 -painters -append -noui ',ConDir,'.jpg']
        spm_figure('Print')
        pause(1)
        [MeanZ,StdZ,z]=CalcXY(xY);
        MaxMeanZVec(SubInd)=max(MeanZ(1,:))
        if SubInd==1 & NCond==4 & size(MeanZ,1)==3
            MeanZTmp=zeros(4,10);
            MeanZTmp([1 3 4],:)=MeanZ;
            MeanZTmp(2,:)=MeanZ(1,:);
            MeanZ=MeanZTmp;
            
            StdZTmp=zeros(4,10);
            StdZTmp([1 3 4],:)=StdZ;
            StdZTmp(2,:)=StdZ(1,:);
            StdZ=StdZTmp;
            
            zTmp=zeros(4,70);
            zTmp([1 3 4],:)=z;
            zTmp(2,:)=z(1,:);
            z=zTmp;
        end
        
        MeanZBase=mean(MeanZ(:,1:2),2);
        MaxMeanZBaseVec(SubInd)=MeanZBase(1);
        zBase=mean(z(:,1:2),2);
        for i=1:NCond
            MeanZ(i,:)=((MeanZ(i,:)-MeanZBase(i))./MeanZBase(i)).*100;
            StdZ(i,:)=(StdZ(i,:)./MeanZBase(i)).*100;
            z(i,:)=((z(i,:)-zBase(i))./zBase(i)).*100;
        end;

        MinMeanZNew=min(min(MeanZ));
        if MinMeanZNew<MinMeanZOld;
            MinMeanZOld=MinMeanZNew;
        end
        MaxMeanZNew=max(max(MeanZ))
        if MaxMeanZNew>MaxMeanZOld
            MaxMeanZOld=MaxMeanZNew;
        end
        
        AllZ(SubInd,:,:)=z;
        AllMeanZ(SubInd,:,:)=MeanZ;
        AllStdZ(SubInd,:,:)=StdZ;
        
        figure(hXYFig);
        subplot(SubPlotVec(1),SubPlotVec(2),SubInd);
        errorbar([1:10],AllMeanZ(SubInd,1,:),AllStdZ(SubInd,1,:),'k')
        if NCond>1
            hold on
            errorbar([1:10],AllMeanZ(SubInd,2,:),AllStdZ(SubInd,2,:),'r')
            if NCond>2
                errorbar([1:10],AllMeanZ(SubInd,3,:),AllStdZ(SubInd,3,:),'b')
                if NCond>3
                    errorbar([1:10],AllMeanZ(SubInd,4,:),AllStdZ(SubInd,4,:),'g')
                end
            end
        end
        %axis([1 10 .9.*MinMeanZNew 1.1.*MaxMeanZNew])
        axis([1 10 -.5 2])
        title([int2str(ActSub)])
        
        figure(hZFig);
        subplot(SubPlotVec(1),SubPlotVec(2),SubInd);
        plot([1:70],squeeze(AllZ(SubInd,1,:)),'k')
        if NCond>1
            hold on
            plot([1:70],squeeze(AllZ(SubInd,2,:)),'r')
            if NCond>2
                plot([1:70],squeeze(AllZ(SubInd,1,:)),'b')
                if NCond>3
                    plot([1:70],squeeze(AllZ(SubInd,1,:)),'g')
                end
            end
        end
        axis([1 70 MinMeanZNew MaxMeanZNew])
        title([int2str(ActSub)])
        
        BaseVec=[];
        if SubInd>1
            MeanAllZ1=squeeze(mean(AllZ(1:SubInd,1,:),1));
            StdAllZ1=squeeze(std(AllZ(1:SubInd,1,:),1));
            MeanAllMeanZ1=squeeze(mean(AllMeanZ(1:SubInd,1,:),1));
            MeanAllStdZ1=squeeze(mean(AllStdZ(1:SubInd,1,:),1));
            if ~isempty(BaseVec)
                MeanAllMeanZ1=MeanAllMeanZ1-mean(MeanAllMeanZ1(BaseVec));
            end
            if NCond>1
                MeanAllZ2=squeeze(mean(AllZ(1:SubInd,2,:),1));
                StdAllZ2=squeeze(std(AllZ(1:SubInd,2,:),1));
                MeanAllMeanZ2=squeeze(mean(AllMeanZ(1:SubInd,2,:),1)); %Subject 1 missing 0> 2:SubInd
                MeanAllStdZ2=squeeze(mean(AllStdZ(1:SubInd,2,:),1));    %Subject 1 missing
                if ~isempty(BaseVec)
                    MeanAllMeanZ2=MeanAllMeanZ2-mean(MeanAllMeanZ2(BaseVec));
                end
                if NCond>2
                    MeanAllZ3=squeeze(mean(AllZ(1:SubInd,3,:),1));
                    StdAllZ3=squeeze(std(AllZ(1:SubInd,3,:),1));
                    MeanAllMeanZ3=squeeze(mean(AllMeanZ(1:SubInd,3,:),1));
                    MeanAllStdZ3=squeeze(mean(AllStdZ(1:SubInd,3,:),1));
                    if ~isempty(BaseVec)
                        MeanAllMeanZ3=MeanAllMeanZ3-mean(MeanAllMeanZ3(BaseVec));
                    end
                    if NCond>3
                        MeanAllZ4=squeeze(mean(AllZ(1:SubInd,4,:),1));
                        StdAllZ4=squeeze(std(AllZ(1:SubInd,4,:),1));
                        MeanAllMeanZ4=squeeze(mean(AllMeanZ(1:SubInd,4,:),1));
                        MeanAllStdZ4=squeeze(mean(AllStdZ(1:SubInd,4,:),1));
                        if ~isempty(BaseVec)
                            MeanAllMeanZ4=MeanAllMeanZ4-mean(MeanAllMeanZ4(BaseVec));
                        end
                    end
                end
            end
            figure(hMeanZFig);
            errorbar([1:70],MeanAllZ1,StdAllZ1,'k')
            hold on
            if NCond>1
                errorbar([1:70],MeanAllZ2,StdAllZ2,'r')
                if NCond>2
                    errorbar([1:70],MeanAllZ3,StdAllZ3,'b')
                    if NCond>3
                        errorbar([1:70],MeanAllZ4,StdAllZ4,'g')
                    end
                end
            end
            %axis([1 70 MinMeanZOld MaxMeanZOld]) 
            %axis([1 70 -3 3]) 
            hold off
            title('Mean Z')
            
            figure(hMeanXYFig);
            errorbar([1:10],MeanAllMeanZ1,sqrt(MeanAllStdZ1.^2./(2.*SubInd)),'k')
            hold on
           %plot([1:10],squeeze(AllMeanZ(1:SubInd,1,:)))
            if NCond>1
                errorbar([1:10],MeanAllMeanZ2,sqrt(MeanAllStdZ2.^2./(2.*SubInd)),'r')
                if NCond>2
                    errorbar([1:10],MeanAllMeanZ3,sqrt(MeanAllStdZ3.^2./(2.*SubInd)),'b')
                    if NCond>3
                        errorbar([1:10],MeanAllMeanZ4,sqrt(MeanAllStdZ4.^2./(2.*SubInd)),'g')
                    end
                end
            end
            %axis([1 70 min(min(MeanAllMeanZ1)) max(max(MeanAllMeanZ1))]) 
            %axis([1 10 -0.25 4.5]) %4.5 1.75]
            hold off
            title('Mean XY')
        end
        FilterPath=[FullFilteredDir,filesep,ConDir];
        [MkDirStatus,MkDirMsg]=mkdir(FullFilteredDir,ConDir);
        if MkDirStatus==1;
            fprintf(['Make directory: ',ConDir,' !\n\n'])
        elseif MkDirStatus==2;
            fprintf(['Directory: ',ConDir,' already exists !\n\n'])
        elseif MkDirStatus==0;
            MkDirStatus=MkDirStatus
            MkDirMsg=MkDirMsg
            pause;
        end
        eval(['cd ',FilterPath])
        spm_write_filtered(BATCHMJSPM.Z,BATCHMJSPM.XYZ,BATCHMJVOL.DIM,BATCHMJVOL.M,...
            sprintf('SPM{%c}-filtered: u = %5.3f, k = %d',BATCHMJSPM.STAT,BATCHMJSPM.u,BATCHMJSPM.k),ConDir);
        FilterFilePathImg=[FilterPath,filesep,ConDir,'.img'];
        [TValVec,BMat,MMat,MniMat,ValFilePath,BTalFilePath,MTalFilePath,MniFilePath]=Vox2Tal(FilterFilePathImg);
        TDStrFilePath=['H:\TD\TDStrSort.txt'];
        TDCoorFilePath=['H:\TD\TDCoorSort.txt'];
        [BTalFile,BTalPath]=SepFilePath(BTalFilePath)
        TdFilePath=[BTalPath,'TD_',BTalFile];
        %FindTD([],BTalFilePath,TDStrFilePath,TDCoorFilePath,TdFilePath)
        %CalcTalStat(240,TdFilePath,ValFilePath);
        if ~isempty(TValVec)
            spm_render(struct('XYZ',BATCHMJSPM.XYZ,'t',BATCHMJSPM.Z,'mat',BATCHMJVOL.M,'dim',BATCHMJVOL.DIM),NaN,RendFilePath);
        end
        eval(['cd ',FullGlassRenderDir])
        PRINTSTR=['print -djpeg100 -painters -append -noui ',ConDir,'.jpg']
        spm_figure('Print')
        pause(1)
    end
end
a=mean(AllMeanZ,3);
figure(hZFig);
clf;
aMat(:,4)=a;
boxplot(aMat)
return;

