function [OutFilePath,MiCsAvgMatOut,NTrialAvgVec1,MiCsStdMatOut,SampRate1,AvgRef1,Version1,MedMedRawVec1,MedMedAvgVec1,EegMegStatus1,NChanExtra1]= ...
CalcAvgScadsTStat(InFileMat,CalcBaseStatus,MinBase,MaxBase,SaveStatus,OutFilePath,AddFileExt,TStatus,CalcAbsStatus,FlipMat,restrictedstatus,displaymode, ...
TempFiltStruc,SpatFiltStruc,Domain,CalcGradStatus,FileOrder)

%	CalcScadsTStat.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<17; FileOrder=[];end
if nargin<16; CalcGradStatus=[];end
if nargin<15; Domain=1;end
if nargin<14; SpatFiltStruc=[];end
if nargin<13; TempFiltStruc=[];end
if nargin<12; displaymode=0;end
if nargin<11; restrictedstatus=1; end
if nargin<10; FlipMat=[]; end
if nargin<9; CalcAbsStatus=[]; end
if nargin<8; TStatus=[]; end
if nargin<7; AddFileExt=[]; end
if nargin<6; OutFilePath=[]; end
if nargin<5; SaveStatus=[]; end
if nargin<4; MaxBase=[]; end
if nargin<3; MinBase=[]; end
if nargin<2; CalcBaseStatus=[]; end
if nargin<1; InFileMat=[]; end


if isempty(CalcGradStatus); CalcGradStatus=0; end
if isempty(TempFiltStruc); TempFiltStatus=0; else; TempFiltStatus=1; end
if isempty(SpatFiltStruc); SpatFiltStatus=0; else; SpatFiltStatus=1; end
if isempty(SaveStatus); SaveStatus=1; end
if isempty(CalcAbsStatus); CalcAbsStatus=0; end
if isempty(TStatus); TStatus=0; end

[CalcBaseStatus]=IfEmptyInputBo('Do you want to subtract a baseline ?',[],CalcBaseStatus,1,1);
if CalcBaseStatus & (isempty(MinBase) | isempty(MaxBase))
	fprintf('\n')
	[NPointsBaseStatus]=IfEmptyInputBo('Do you want to use','the whole interval as baseline ?',[],1,0);
	if NPointsBaseStatus; 
		MinBase=[]; MaxBase=[]; 
	else
		[MinBase]=IfEmptyInputVal('Please insert the baseline start point:',[],MinBase,1,0);
		[MaxBase]=IfEmptyInputVal('Please insert the baseline start point:',[],MaxBase,1,0);
	end
end
[DefFilePath]=SetDefPath('r','*.at*');
[DefFilePath]=SwitchGrandBatch(DefFilePath,'Grand2Batch',1);
if TStatus==3
	StrTmp='Choose pairs of avg files or batch file:'
else
	StrTmp='Choose avg files or batch file:'
end
[NFilesIn,InFileMat,NonUse,BatchFilePath]=ReadFileNames(InFileMat,DefFilePath,StrTmp);
if NFilesIn==0; return; end
[BatchFile,BatchPath]=SepFilePath(BatchFilePath);
SetDefPath(2,BatchPath);
if TStatus==2 | TStatus==3
    if isempty(FileOrder)
        FileOrderStr=questdlg('File order ?','Please identify the file order ?','Paired (1 2, 1 2, ...)','Block (1 1 ..., 2 2 ...)','Cancel','Block (1 1 ..., 2 2 ...)');
        switch FileOrderStr
            case 'Paired (1 2, 1 2, ...)', 
                FileOrder=1;
            case 'Block (1 1 ..., 2 2 ...)', 
                FileOrder=2;
            case 'Cancel'
                return;
        end %Switch
    end
    if FileOrder==1
        SampleVec1=[1:2:NFilesIn-1];
        SampleVec2=[2:2:NFilesIn];
    elseif FileOrder==2
        SampleVec1=[1:NFilesIn./2];
        SampleVec2=[NFilesIn./2+1:NFilesIn];
    end
end

InFileMat1=[];
InFileMat2=[];
Message=char(' ');

if TStatus==1
    Message=char(Message,'Calculate one sample t-test:');
	FileExt='.ott'; %One sample t-test
    InFileMat1=InFileMat;
    InFileMat2=[];
elseif TStatus==2
    Message=char(Message,'Calculate two sample t-test:');
    FileExt='.ttt'; %Two sample t-test
    InFileMat1=InFileMat(SampleVec1,:);
    InFileMat2=InFileMat(SampleVec2,:);
elseif TStatus==3
    Message=char(Message,'Calculate paired t-test:');
    FileExt='.ptt'; %Paired t-test
    InFileMat1=InFileMat(SampleVec1,:);
    InFileMat2=InFileMat(SampleVec2,:);
elseif TStatus==4
    Message=char(Message,'Calculate symmetry t-test:');
    FileExt='.stt'; %Symmetry t-test
    InFileMat1=InFileMat;
    InFileMat2=InFileMat;
end
if CalcBaseStatus
	FileExt=[FileExt,'b'];
end
if ~isempty(AddFileExt)
	FileExt=[FileExt,AddFileExt];
end
NFilesIn1=size(InFileMat1,1);
NFilesIn2=size(InFileMat2,1);
SetNumber1=[];
[InFile1,InPath1,InFilePath1]=GetFileNameOfMat(InFileMat,1);
   
Message=char(Message,' ');
MessageTmp=char(Message,InFilePath1);
MessageTmp=char(MessageTmp,' ');
MessageTmp=char(MessageTmp,' ');
MessageTmp=char(MessageTmp,' ');
MessageTmp=char(MessageTmp,' ');
MessageTmp=char(MessageTmp,' ');
MessageTmp=char(MessageTmp,' ');
MessageTmp=char(MessageTmp,' ');
hmsgbox=msgbox(MessageTmp,'Info:','help'); 
hChildMsgbox=get(hmsgbox,'Children');
hChild2Msgbox=get(hChildMsgbox(2),'Children');
set(hChildMsgbox(end),'Visible','off');
pause(.1)
if Domain==8
    
	for FileInd=1:NFilesIn1
		[InFile1,InPath1,InFilePath1]=GetFileNameOfMat(InFileMat1,FileInd);
		[InFile2,InPath2,InFilePath2]=GetFileNameOfMat(InFileMat2,FileInd);
        [AvgMat1,FilePath1,SizeDataMat1,NDim1,Version1,SampRate1,AvgRef1,...
        StartF01,EndF01,DeltaF01,NTap1,SigmaM1,EegMegStatus1,NChanExtra1,AmpPhaseStatus1,NTrials1]=...
        ReadWaveletData(InFilePath1);
        MedMedRawVec1 = [];
        MedMedAvgVec1 = [];
        StdMat1 = [];
        [AvgMat2,FilePath2,SizeDataMat2,NDim2,Version2,SampRate2,AvgRef2,...
        StartF02,EndF02,DeltaF02,NTap2,SigmaM2,EegMegStatus2,NChanExtra2,AmpPhaseStatus2,NTrials2]=...
        ReadWaveletData(InFilePath2);
        MedMedRawVec2 = [];
        MedMedAvgVec2 = [];
        StdMat2 = [];
        [File1,Path1]=SepFilePath(FilePath1);
        [File2,Path2]=SepFilePath(FilePath2);
        [NChan1,NPoints1,NFrequ1]=size(AvgMat1);
        [NChan2,NPoints2,NFrequ2]=size(AvgMat2);
        if FileInd==1
            DiffMat=zeros(NFilesIn1,NChan1,NPoints1,NFrequ1);
        end
        DiffMat(FileInd,:,:,:)=AvgMat1-AvgMat2;
        CalcBaseStatus = 0;
        dfStr='No baseline subtraction ...';
	    fprintf('No baseline subtraction ...\n');
		TempFiltMsg='No temporal filtering ...';
        fprintf('No temporal filtering ...\n');
        SpatFiltMsg='No spatial filtering ...';
        fprintf('No spatial filtering ...\n');
        MessageTmp=char(Message,InFilePath1);
		MessageTmp=char(MessageTmp,' ');
		MessageTmp=char(MessageTmp,['File ', int2str(FileInd),' of ',int2str(NFilesIn1),' ...']);
		MessageTmp=char(MessageTmp,' ');
        MessageTmp=char(MessageTmp,BaseMsg);
        MessageTmp=char(MessageTmp,TempFiltMsg);
        MessageTmp=char(MessageTmp,SpatFiltMsg);
		if strcmp(computer,'MAC2')
			set(hChildMsgbox(2),'String',MessageTmp);
		else
			set(hChild2Msgbox,'String',MessageTmp);
		end
        pause(.01)
	end
   
else   
    
	for FileInd=1:NFilesIn1
        FileIndStr=int2str(FileInd);
        if FileInd<10; FileIndStr=['0',FileIndStr]; end
		[InFile1,InPath1,InFilePath1]=GetFileNameOfMat(InFileMat1,FileInd);
		[AvgMat1,File1,Path1,FilePath1,NTrialAvgVec1,StdMat1,...
		SampRate1,AvgRef1,Version1,MedMedRawVec1,MedMedAvgVec1,...
		EegMegStatus1,NChanExtra1]=ReadAvgFile(InFilePath1);
        [NChan1,NPoints1]=size(AvgMat1);
		if CalcBaseStatus
            BaseMsg='Baseline subtraction ...';
			if isempty(MinBase); MinBase=1; end
			if isempty(MaxBase); MaxBase=NPoints1; end
			fprintf('Subtract baseline interval of points %g - %g\n',MinBase,MaxBase);
			[AvgMat1]=CalcBaseline(AvgMat1,MinBase,MaxBase,CalcBaseStatus);
		else
            BaseMsg='No baseline subtraction ...';
			fprintf('No baseline subtraction ...\n');
		end
        if CalcAbsStatus
            AbsMsg='Absolute values ...';
            fprintf('Calculate absolute values ...\n')          
            AvgMat1=abs(AvgMat1); 
            StdMat1=abs(StdMat1);
        else
            AbsMsg='No absolute values ...'
            fprintf('No absolute values ...\n');
        end
        if TempFiltStatus 
            TempFiltMsg='Temporal filtering ...';
            LowFiltCoeff=TempFiltStruc.LowFiltCoeff;
            HighFiltCoeff=TempFiltStruc.HighFiltCoeff;
            if ~isempty(LowFiltCoeff)
                fprintf('Temporal lowpass filtering ...\n');
                for i=1:NChan1
				    AvgMat1(i,:)=(filtfilt(LowFiltCoeff(1,:),LowFiltCoeff(2,:),AvgMat1(i,:)'))';
                    StdMat1(i,:)=(filtfilt(LowFiltCoeff(1,:),LowFiltCoeff(2,:),StdMat1(i,:)'))';
			    end
            end
            if ~isempty(HighFiltCoeff)
                fprintf('Temporal highpass filtering ...\n');
                for i=1:NChan1
				    AvgMat1(i,:)=(filtfilt(HighFiltCoeff(1,:),HighFiltCoeff(2,:),AvgMat1(i,:)'))';
                    StdMat1(i,:)=(filtfilt(HighFiltCoeff(1,:),HighFiltCoeff(2,:),StdMat1(i,:)'))';
			    end
            end
        else
            TempFiltMsg='No temporal filtering ...';
            fprintf('No temporal filtering ...\n');
        end
        if SpatFiltStatus
            SpatFiltMsg='Spatial filtering ...';
            fprintf('Apply spatial lowpass filter. Sigma: %g\n',SpatFiltStruc.Sigma./pi.*180);
            AvgMat1(1:NChan1-NChanExtra1,:)=SpatFilt(AvgMat1(1:NChan1-NChanExtra1,:),SpatFiltStruc.PhiMat,SpatFiltStruc.Sigma,1);
            StdMat1(1:NChan1-NChanExtra1,:)=SpatFilt(StdMat1(1:NChan1-NChanExtra1,:),SpatFiltStruc.PhiMat,SpatFiltStruc.Sigma,1);
        else
            SpatFiltMsg='No spatial filtering ...';
            fprintf('No spatial filtering ...\n');
        end
        if CalcGradStatus
            CalcGradMsg='Calculate gradient ...';
            fprintf('Calculate gradient\n');
            AvgMat1=gradient(AvgMat1);
            StdMat1=gradient(StdMat1);
        else
            CalcGradMsg='No gradient ...';
            fprintf('No gradient ...\n');
        end
		if FileInd==1; 
        	AllAvgMat1=zeros(NFilesIn1,NChan1,NPoints1);
			AllStdMat1=zeros(NFilesIn1,NChan1,NPoints1);
			AllNTrialAvgVec1=zeros(NFilesIn1,length(NTrialAvgVec1));
			AllMedMedRawVec1=zeros(NFilesIn1,length(MedMedRawVec1));
			AllMedMedAvgVec1=zeros(NFilesIn1,length(MedMedAvgVec1));
		end
        AllAvgMat1(FileInd,:,:)=AvgMat1;
		AllStdMat1(FileInd,:,:)=StdMat1;
		AllNTrialAvgVec1(FileInd,1:length(NTrialAvgVec1))=NTrialAvgVec1';
		AllMedMedRawVec1(FileInd,1:length(MedMedRawVec1))=MedMedRawVec1';
        AllMedMedAvgVec1(FileInd,1:length(MedMedAvgVec1))=MedMedAvgVec1';
        MessageTmp=char(Message,InFilePath1);
		MessageTmp=char(MessageTmp,' ');
		MessageTmp=char(MessageTmp,['File ', int2str(FileInd),' of ',int2str(NFilesIn1),' ...']);
		MessageTmp=char(MessageTmp,' ');
        MessageTmp=char(MessageTmp,BaseMsg);
        MessageTmp=char(MessageTmp,AbsMsg);
        MessageTmp=char(MessageTmp,TempFiltMsg);
        MessageTmp=char(MessageTmp,SpatFiltMsg);
        MessageTmp=char(MessageTmp,CalcGradMsg);
		if strcmp(computer,'MAC2')
			set(hChildMsgbox(2),'String',MessageTmp);
		else
			set(hChild2Msgbox,'String',MessageTmp);
		end
        pause(.01)
	end

	for FileInd=1:NFilesIn2
        FileIndStr=int2str(FileInd);
        if FileInd<10; FileIndStr=['0',FileIndStr]; end
        [InFile2,InPath2,InFilePath2]=GetFileNameOfMat(InFileMat2,FileInd);
        [AvgMat2,File2,Path2,FilePath2,NTrialAvgVec2,StdMat2,...
        SampRate2,AvgRef2,Version2,MedMedRawVec2,MedMedAvgVec2,...
        EegMegStatus2,NChanExtra2]=ReadAvgFile(InFilePath2);
        [NChan2,NPoints2]=size(AvgMat2);
        if CalcBaseStatus
            BaseMsg='Baseline subtraction ...';
            if isempty(MinBase); MinBase=1; end
            if isempty(MaxBase); MaxBase=NPoints1; end
            fprintf('Subtract baseline interval of points %g - %g\n',MinBase,MaxBase);
            [AvgMat2]=CalcBaseline(AvgMat2,MinBase,MaxBase,CalcBaseStatus);
        else
            BaseMsg='No baseline subtraction ...';
		    fprintf('No baseline subtraction ...\n');
        end
        if CalcAbsStatus
            AbsMsg='Absolute values ...';
            fprintf('Calculate absolute values ...\n')          
            AvgMat2=abs(AvgMat2); 
            StdMat2=abs(StdMat2);
        else
            AbsMsg='No absolute values ...'
            fprintf('No absolute values ...\n');
        end
        if TempFiltStatus
            TempFiltMsg='Temporal filtering ...';
            LowFiltCoeff=TempFiltStruc.LowFiltCoeff;
            HighFiltCoeff=TempFiltStruc.HighFiltCoeff;
            if ~isempty(LowFiltCoeff)
                 fprintf('Temporal lowpass filtering ...\n');
                for i=1:NChan1
				    AvgMat2(i,:)=(filtfilt(LowFiltCoeff(1,:),LowFiltCoeff(2,:),AvgMat2(i,:)'))';
                    StdMat2(i,:)=(filtfilt(LowFiltCoeff(1,:),LowFiltCoeff(2,:),StdMat2(i,:)'))';
			    end
            end
            if ~isempty(HighFiltCoeff)
                fprintf('Temporal highpass filtering ...\n');
                for i=1:NChan1
				    AvgMat2(i,:)=(filtfilt(HighFiltCoeff(1,:),HighFiltCoeff(2,:),AvgMat2(i,:)'))';
                    StdMat2(i,:)=(filtfilt(HighFiltCoeff(1,:),HighFiltCoeff(2,:),StdMat2(i,:)'))';
			    end
            end
        else
            TempFiltMsg='No temporal filtering ...';
            fprintf('No temporal filter applied ...\n');
        end
        if SpatFiltStatus
            SpatFiltMsg='Spatial filtering ...';
            fprintf('Apply spatial lowpass filter. Sigma: %g\n',SpatFiltStruc.Sigma./pi.*180);
            AvgMat2(1:NChan2-NChanExtra2,:)=SpatFilt(AvgMat2(1:NChan2-NChanExtra2,:),SpatFiltStruc.PhiMat,SpatFiltStruc.Sigma,1);
            StdMat2(1:NChan2-NChanExtra2,:)=SpatFilt(StdMat2(1:NChan2-NChanExtra2,:),SpatFiltStruc.PhiMat,SpatFiltStruc.Sigma,1);
        else
            SpatFiltMsg='No spatial filtering ...';
            fprintf('No spatial filter applied ...\n');
        end
        if CalcGradStatus
            CalcGradMsg='Calculate gradient ...';
            fprintf('Calculate gradient\n');
            AvgMat2=gradient(AvgMat2);
            StdMat2=gradient(StdMat2);
        else
            CalcGradMsg='No gradient ...';
            fprintf('No gradient ...\n');
        end
        if FileInd==1; 
            AllAvgMat2=zeros(NFilesIn2,NChan2,NPoints2);
            AllStdMat2=zeros(NFilesIn2,NChan2,NPoints2);
            AllNTrialAvgVec2=zeros(NFilesIn2,length(NTrialAvgVec2));
            AllMedMedRawVec2=zeros(NFilesIn2,length(MedMedRawVec2));
            AllMedMedAvgVec2=zeros(NFilesIn2,length(MedMedAvgVec2));
        end
        if TStatus==4 %Symmetry
            AvgMat2Tmp=AvgMat2;
            StdMat2Tmp=StdMat2;
            for i=1:size(FlipMat,1)  
				AvgMat2Tmp(FlipMat(i,1),:)=AvgMat2(FlipMat(i,2),:);
                AvgMat2Tmp(FlipMat(i,2),:)=AvgMat2(FlipMat(i,1),:);
				StdMat2Tmp(FlipMat(i,1),:)=StdMat2(FlipMat(i,2),:);
                StdMat2Tmp(FlipMat(i,2),:)=StdMat2(FlipMat(i,1),:);
			end
            AvgMat2=AvgMat2Tmp;
            StdMat2=StdMat2Tmp;
        end
        
        AllAvgMat2(FileInd,:,:)=AvgMat2;
        AllStdMat2(FileInd,:,:)=StdMat2;
        AllNTrialAvgVec2(FileInd,1:length(NTrialAvgVec2))=NTrialAvgVec2';
        AllMedMedRawVec2(FileInd,1:length(MedMedRawVec2))=MedMedRawVec2';
        AllMedMedAvgVec2(FileInd,1:length(MedMedAvgVec2))=MedMedAvgVec2';
        MessageTmp=char(Message,InFilePath2);
		MessageTmp=char(MessageTmp,' ');
		MessageTmp=char(MessageTmp,['File ', int2str(FileInd),' of ',int2str(NFilesIn2),' ...']);
		MessageTmp=char(MessageTmp,' ');
        MessageTmp=char(MessageTmp,BaseMsg);
        MessageTmp=char(MessageTmp,AbsMsg);
        MessageTmp=char(MessageTmp,TempFiltMsg);
        MessageTmp=char(MessageTmp,SpatFiltMsg);
        MessageTmp=char(MessageTmp,CalcGradMsg);
		if strcmp(computer,'MAC2')
			set(hChildMsgbox(2),'String',MessageTmp);
		else
			set(hChild2Msgbox,'String',MessageTmp);
		end
        pause(.01)
	end
end
AvgIntervalStatus=0;
AvgIntMat=[39 59; 89 126];
if AvgIntervalStatus
    for i=1:size(AvgIntMat,1)
        MeanAllAvgMat1=mean(AllAvgMat1(:,:,AvgIntMat(i,1):AvgIntMat(i,2)),3);
        if NFilesIn2>0
            MeanAllAvgMat2=mean(AllAvgMat2(:,:,AvgIntMat(i,1):AvgIntMat(i,2)),3);
        end
        for j=AvgIntMat(i,1):AvgIntMat(i,2)
            AllAvgMat1(:,:,j)=MeanAllAvgMat1;
            if NFilesIn2>0
                AllAvgMat2(:,:,j)=MeanAllAvgMat2;
            end
        end
    end
end
fprintf('\n\n');

for i=1:2   
    if Domain==8
         if TStatus==3 
            SumDiffMat=sum(DiffMat,1);
            SumSquareDiffMat=sum(DiffMat.^2,1);
            SigmaDiff=sqrt((SumSquareDiffMat-SumDiffMat.^2./NFilesIn)./(NFilesIn-1));
            ZeroSigmaDiff=SigmaDiff==0;
            SigmaDiff=SigmaDiff+ZeroSigmaDiff;		                %Set SigmaDiff=1 if SigmaDiff=0
            MiCsAvgMat=(SumDiffMat./NFilesIn)./(SigmaDiff./sqrt(NFilesIn));
            MiCsAvgMat=MiCsAvgMat-MiCsAvgMat.*ZeroSigmaDiff;		%Set SigmaDiff=0 if SigmaDiff=0
            MiCsAvgMatOut=squeeze(MiCsAvgMat);
            break;
        end
    else
        if TStatus==1 %One Sample
            if i==1
                MeanAvgMat1=mean(AllAvgMat1,1);
                StdAvgMat1=std(AllAvgMat1,0,1);
            else
                MeanAvgMat1=mean(AllStdMat1,1);
                StdAvgMat1=std(AllStdMat1,0,1);
            end
            Vari=sqrt((StdAvgMat1.^2)./NFilesIn1);
            ZeroVari=Vari==0;
            Vari=Vari+ZeroVari;									%Set Vari=1 if Vari=0
            MiCsAvgMat=(MeanAvgMat1)./Vari;
            MiCsAvgMat=MiCsAvgMat-MiCsAvgMat.*ZeroVari;			%Set Vari=0 if Vari=0
        elseif TStatus==3 %Paired
            if i==1
                DiffMat=AllAvgMat1-AllAvgMat2;
            else
                DiffMat=AllStdMat1-AllStdMat2;
            end
            SumDiffMat=sum(DiffMat,1);
            SumSquareDiffMat=sum(DiffMat.^2,1);
            SigmaDiff=sqrt((SumSquareDiffMat-SumDiffMat.^2./NFilesIn)./(NFilesIn-1));
            ZeroSigmaDiff=SigmaDiff==0;
            SigmaDiff=SigmaDiff+ZeroSigmaDiff;		                %Set SigmaDiff=1 if SigmaDiff=0
            MiCsAvgMat=(SumDiffMat./NFilesIn)./(SigmaDiff./sqrt(NFilesIn));
            MiCsAvgMat=MiCsAvgMat-MiCsAvgMat.*ZeroSigmaDiff;		%Set SigmaDiff=0 if SigmaDiff=0        
        else
            if i==1
                MeanAvgMat1=mean(AllAvgMat1,1);
                MeanAvgMat2=mean(AllAvgMat2,1);
                StdAvgMat1=std(AllAvgMat1,0,1);
                StdAvgMat2=std(AllAvgMat2,0,1);
            else
                MeanAvgMat1=mean(AllStdMat1,1);
                MeanAvgMat2=mean(AllStdMat2,1);
                StdAvgMat1=std(AllStdMat1,0,1);
                StdAvgMat2=std(AllStdMat2,0,1);
            end
            Vari=sqrt((StdAvgMat1.^2+StdAvgMat2.^2)./NFilesIn2);
            ZeroVari=Vari==0;
            Vari=Vari+ZeroVari;									%Set Vari=1 if Vari=0
            MiCsAvgMat=(MeanAvgMat1-MeanAvgMat2)./Vari;
            MiCsAvgMat=MiCsAvgMat-MiCsAvgMat.*ZeroVari;			%Set Vari=0 if Vari=0     
        end
        if i==1
            MiCsAvgMatOut=squeeze(MiCsAvgMat);
        else
            MiCsStdMatOut=squeeze(MiCsAvgMat);
        end
    end
end
close(hmsgbox);

if restrictedstatus == 0
   df = ones(size(MiCsAvgMatOut))*(size(InFileMat,1)/2) -1;
   if displaymode == 1 %bin
        %MiCsAvgMatOut = ((tcdf(MiCsAvgMatOut,df))>0.975) | ((tcdf(MiCsAvgMatOut,df))<0.025);
        MiCsAvgMatOut = (tcdf(abs(MiCsAvgMatOut,df)))<0.025; 
   elseif displaymode == 2 %p
         MiCsAvgMatOut = 1- tcdf(abs(MiCsAvgMatOut),df);
   end
end

if restrictedstatus > 0
    [InFile1,InPath1,InFilePath1]=GetFileNameOfMat(InFileMat1,1);
	[AvgMat1,File1,Path1,FilePath1,NTrialAvgVec1,StdMat1,SampRate1,AvgRef1,Version1,MedMedRawVec1,MedMedAvgVec1,EegMegStatus1,NChanExtra1]=ReadAvgFile(InFilePath1);
    [NChan1,NPoints1]=size(AvgMat1);
    EConfigFilePath=strrep(which('129.ecfg'),'129.ecfg',[num2str(NChan1),'.ecfg']);
    [NChan_ttest,SpherRadius_ttest,EPosSpher_ttest,ENames_ttest,EConfigFile_ttest,EConfigPath_ttest,EConfigFilePath_ttest]=ReadEConfig(EConfigFilePath);
    hCalcTTestPairesMenu = findobj('tag','hCalcTTestPairesMenu');
    userdatacell = get(hCalcTTestPairesMenu,'Userdata');
    minneighbours = userdatacell{1};
    minpointsinrow = userdatacell{2};
    alphavalue = userdatacell{3};
    neighbourspherdist = userdatacell{4};

    if isempty(findobj('tag','plot3dmenufig'))
        plot3d;
        plot3dmenufig = findobj('tag','plot3dmenufig');
        set(plot3dmenufig,'visible','off');
        pause(0.000001);
        neighbourcell=findchanneighbours(EPosSpher_ttest,SpherRadius_ttest,neighbourspherdist);
        close(plot3dmenufig);
    else
        neighbourcell=findchanneighbours(EPosSpher_ttest,SpherRadius_ttest,neighbourspherdist);
    end
    
    %t-Value
    df = (size(InFileMat,1)/2) -1;
    if df < 1
        errordlg('It is not possible to calculate paired t-test with less than 4 files!');
        return
    end
    significancelevelb = tinv(alphavalue/2,df);%top quantil
    significancelevelt = tinv(1-alphavalue/2,df);%bottom quantil
    message={'testing restrictions... '};
	infdlg1 = infdlg('Testing...',message,[],[],[]);
	
	infdlgtext1 = findobj('tag','infdlgtext1');
	infdlgtext2 = findobj('tag','infdlgtext2');
    infdlg1 = findobj('tag','infdlg');
	fprintf(1,'Testing restriction....\n');
    MiCsAvgMatOutcpy = zeros(size(MiCsAvgMatOut));
    pmat = ones(size(MiCsAvgMatOut));
        
    for r=1:NPoints1-minpointsinrow
        set(infdlgtext1,'String',[num2str(r),' of ']);
        set(infdlgtext2,'String',num2str(NPoints1-minpointsinrow));
        pause(0.001);
        for s=1:NChan1
            g=0;
            minneighbourscriterium = 1;
            minpointscriterium = 1;
            while g<minpointsinrow
                    %fprintf(1,'Channel %i...\n',s);
                if  MiCsAvgMatOut(s,r+g)>significancelevelt | MiCsAvgMatOut(s,r+g)<significancelevelb
                    nrsigneighbours = 0;
                    for z=1:length(neighbourcell{s})
                        if MiCsAvgMatOut(neighbourcell{s},r+g)>significancelevelt | MiCsAvgMatOut(s,r+g)<significancelevelb
                           nrsigneighbours = nrsigneighbours+1;
                       end
                    end
                    if nrsigneighbours < minneighbours + 1
                       minneighbourscriterium = 0;
                    end
                else 
                    minpointscriterium = 0;
                    break;
                end
                g=g+1;
             end
             if minpointscriterium & minneighbourscriterium
                 MiCsAvgMatOutcpy(s,r) = 1;
                 pmat(s,r) = 1-tcdf(MiCsAvgMatOut(s,r),df);
             end 
        end
    end
    MiCsAvgMatOut(find(MiCsAvgMatOutcpy==0))=0;
    pmat(find(MiCsAvgMatOutcpy == 0))= 0.5;
    
	if min(min(MiCsAvgMatOut))==0 & max(max(MiCsAvgMatOut))==0
	    MiCsAvgMatOut(1,1)=0.001;
	end
    
    if displaymode == 2 
        MiCsAvgMatOut = pmat;
    elseif displaymode == 1
        MiCsAvgMatOut = MiCsAvgMatOutcpy;
    end
    
    close (infdlg1);

end

if SaveStatus
	[OutFile,OutPath,OutFilePath]=SaveAvgFile([BatchFilePath,FileExt],MiCsAvgMat,NTrialAvgVec1,MiCsStdMat,SampRate1,MedMedRawVec1,MedMedAvgVec1,EegMegStatus1,NChanExtra1);
end



return;
