function [RMat,PMat,BatchFilePath,NChanExtra]=CalcScadsCorrCoef(InFileMat,Weights,MinPoint,MaxPoint,...
    CalcBaseStatus,MinBase,MaxBase,TempFiltStruc,SpatFiltStruc,CalcGradStatus,CalcAbsStatus,Domain)
%	CalcScadsCorrCoeff.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<12; Domain=1;end
if nargin<10; CalcAbsStatus=[];end
if nargin<10; CalcGradStatus=[];end
if nargin<9; SpatFiltStruc=[];end
if nargin<8; TempFiltStruc=[];end
if nargin<7; MaxBase=[]; end
if nargin<6; MinBase=[]; end
if nargin<5; CalcBaseStatus=[]; end
if nargin<4; MaxPoint=[]; end
if nargin<3; MinPoint=[]; end
if nargin<2; Weights=[]; end
if nargin<1; InFileMat=[]; end

RMat=[];PMat=[];BatchFilePath=[];NChanExtra=[];
if isempty(TempFiltStruc); TempFiltStatus=0; else; TempFiltStatus=1; end
if isempty(SpatFiltStruc); SpatFiltStatus=0; else; SpatFiltStatus=1; end
if isempty(CalcGradStatus); CalcGradStatus=0; end
if isempty(CalcAbsStatus); CalcAbsStatus=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);

[NFilesIn,InFileMat,NonUse,BatchFilePath]=ReadFileNames(InFileMat,DefFilePath,'Choose avg files or batch file:');
if NFilesIn==0; return; end
[BatchFile,BatchPath]=SepFilePath(BatchFilePath);
SetDefPath(2,BatchPath);
Message=char(' ');
Message=char(Message,' ');
Message=char(Message,'Read data from files:');
NFilesIn=size(InFileMat,1);
SetNumber=[];
[InFile,InPath,InFilePath]=GetFileNameOfMat(InFileMat,1);
   
Message=char(Message,' ');
MessageTmp=char(Message,InFilePath);
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(.01);

if Domain==8
    
	for FileInd=1:NFilesIn
		[InFile,InPath,InFilePath]=GetFileNameOfMat(InFileMat,FileInd);	
        [AvgMat,FilePath,SizeDataMat,NDim,Version,SampRate,AvgRef,...
        StartF0,EndF0,DeltaF0,NTap,SigmaM,EegMegStatus,NChanExtra,AmpPhaseStatus,NTrials]=ReadWaveletData(InFilePath);
        MedMedRawVec = [];
        MedMedAvgVec = [];
        StdMat = [];   
        [File,Path]=SepFilePath(FilePath);
        [NChan,NPoints,NFrequ]=size(AvgMat);
        if FileInd==1
            DiffMat=zeros(NFilesIn,NChan,NPoints,NFrequ);
        end
        CalcBaseStatus = 0;
        dfStr='No baseline subtraction ...';
	    fprintf('No baseline subtraction ...\n');
        AbsMsg='No absolute values ...';
		fprintf('No absolute values ...\n');
		TempFiltMsg='No temporal filtering ...';
        fprintf('No temporal filtering ...\n');
        SpatFiltMsg='No spatial filtering ...';
        fprintf('No spatial filtering ...\n');
        MessageTmp=char(Message,InFilePath);
		MessageTmp=char(MessageTmp,' ');
		MessageTmp=char(MessageTmp,['File ', int2str(FileInd),' of ',int2str(NFilesIn),' ...']);
		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:NFilesIn
		[InFile,InPath,InFilePath]=GetFileNameOfMat(InFileMat,FileInd);
		[AvgMat,File,Path,FilePath,NTrialAvgVec,StdMat,...
		SampRate,AvgRef,Version,MedMedRawVec,MedMedAvgVec,...
		EegMegStatus,NChanExtra]=ReadAvgFile(InFilePath);
        [NChan,NPoints]=size(AvgMat);
		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);
			AvgMat=CalcBaseline(AvgMat,MinBase,MaxBase,CalcBaseStatus);
		else
            BaseMsg='No baseline subtraction ...';
			fprintf('No baseline subtraction ...\n');
		end
		if CalcAbsStatus; 
            AvgMat=abs(AvgMat); 
            AbsMsg='Absolute values ...';
			fprintf('Absolute values ...\n');
        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:NChan
				    AvgMat(i,:)=(filtfilt(LowFiltCoeff(1,:),LowFiltCoeff(2,:),AvgMat(i,:)'))';
			    end
            end
            if ~isempty(HighFiltCoeff)
                fprintf('Temporal highpass filtering ...\n');
                for i=1:NChan
				    AvgMat(i,:)=(filtfilt(HighFiltCoeff(1,:),HighFiltCoeff(2,:),AvgMat(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);
            AvgMat(1:NChan-NChanExtra,:)=SpatFilt(AvgMat(1:NChan-NChanExtra,:),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');
            AvgMat=gradient(AvgMat);
        else
            CalcGradMsg='No gradient ...';
            fprintf('No gradient ...\n');
        end
		if FileInd==1; 
        	AllAvgMat=zeros(NFilesIn,NChan,NPoints);
			AllStdMat=zeros(NFilesIn,NChan,NPoints);
			AllNTrialAvgVec=zeros(NFilesIn,length(NTrialAvgVec));
			AllMedMedRawVec=zeros(NFilesIn,length(MedMedRawVec));
			AllMedMedAvgVec=zeros(NFilesIn,length(MedMedAvgVec));
		end
        AllAvgMat(FileInd,:,:)=AvgMat;
		AllStdMat(FileInd,:,:)=StdMat;
		AllNTrialAvgVec(FileInd,1:length(NTrialAvgVec))=NTrialAvgVec';
		AllMedMedRawVec(FileInd,1:length(MedMedRawVec))=MedMedRawVec';
        AllMedMedAvgVec(FileInd,1:length(MedMedAvgVec))=MedMedAvgVec';
        MessageTmp=char(Message,InFilePath);
		MessageTmp=char(MessageTmp,' ');
		MessageTmp=char(MessageTmp,['File ', int2str(FileInd),' of ',int2str(NFilesIn),' ...']);
		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)
        MeanAllAvgMat=mean(AllAvgMat(:,:,AvgIntMat(i,1):AvgIntMat(i,2)),3); 
        for j=AvgIntMat(i,1):AvgIntMat(i,2)
            AllAvgMat(:,:,j)=MeanAllAvgMat; 
        end
    end
end
fprintf('\n\n');
if size(Weights,2)>1
    Weights=Weights';
end

Message=char('');
Message=char(Message,'Calculate correlation coefficients:');
Message=char(Message,['(Interval: ',int2str(MinPoint),' - ',int2str(MaxPoint),')']);
Message=char(Message,'');
Message=char(Message,'Points done ...');
Message=char(Message,'');
Message=char(Message,'');

if Domain==8
    break;  
else  
    RMat=zeros(NChan,NPoints);
    PMat=zeros(NChan,NPoints);
    for PointInd=MinPoint:MaxPoint
        Tmp=[squeeze(AllAvgMat(:,:,PointInd)),Weights];
        [r,p]=corrcoef(Tmp);           
        RMat(:,MinPoint+PointInd-1)=r(1:NChan,NChan+1);
        PMat(:,MinPoint+PointInd-1)=p(1:NChan,NChan+1);

        if floor(PointInd./10)==PointInd./10
            fprintf(1,'%g of %g points done ...\n',PointInd-MinPoint+1,MaxPoint-MinPoint+1)
            MessageTmp=char(Message,[int2str(PointInd-MinPoint+1),' of ',int2str(MaxPoint-MinPoint+1)]);
            if strcmp(computer,'MAC2')
                set(hChildMsgbox(2),'String',MessageTmp);
            else
                set(hChild2Msgbox,'String',MessageTmp);
            end
            pause(.1);
        end
    end  
end
PMat(RMat>0)=1-PMat(RMat>0);
PMat(RMat<0)=-1+PMat(RMat<0);
close(hmsgbox);
return;
