function GroupCorr(Group1Dir,Group2Dir)
% FORMAT GroupCorr(Group1Dir,Group2Dir)
%   Input:
%     Group1Dir - directory of the the first group
%     Group2Dir - directory of the the second group
%   Output:
%     rGroup.img - image with Pearson's Correlation Coefficient
%     pGroup.img - image with significance of Pearson's Correlation Coefficient
%___________________________________________________________________________
% Written by YAN Chao-Gan 090302.
% State Key Laboratory of Cognitive Neuroscience and Learning, Beijing Normal University, China, 100875
% ycg.yan@gmail.com

olddir=pwd;
cd(Group1Dir);
DirList=dir('*.img');
[Outdata,Vox,Head] = rest_readfile(DirList(1).name);
Group1Series=zeros(length(DirList),size(Outdata,1),size(Outdata,2),size(Outdata,3));
for i=1:length(DirList)
    [Outdata,Head] = rest_readfile(DirList(i).name);
    Group1Series(i,:,:,:)=Outdata;
end

cd(Group2Dir);
DirList=dir('*.img');
[Outdata,Vox,Head] = rest_readfile(DirList(1).name);
Group2ConSeries=zeros(length(DirList),size(Outdata,1),size(Outdata,2),size(Outdata,3));
for i=1:length(DirList)
    [Outdata,Head] = rest_readfile(DirList(i).name);
    Group2ConSeries(i,:,:,:)=Outdata;
end

cd(olddir);
rGroup=zeros(size(Outdata,1),size(Outdata,2),size(Outdata,3));
pGroup=zeros(size(Outdata,1),size(Outdata,2),size(Outdata,3));
for i=1:size(Outdata,1)
    for j=1:size(Outdata,2)
        for k=1:size(Outdata,3)
            [r p]=corrcoef(squeeze(Group1Series(:,i,j,k)),squeeze(Group2Series(:,i,j,k)));
            rGroup(i,j,k)=r(1,2);
            pGroup(i,j,k)=p(1,2);
        end
    end
end
rGroup(isnan(rGroup))=0;
pGroup(isnan(pGroup))=1;
rest_WriteNiftiImage(rGroup,Head,'rGroup.img');
rest_WriteNiftiImage(pGroup,Head,'pGroup.img');

