function GIG_calculateIC(calcuIC)

sublist=calcuIC.sub;
PCnum=calcuIC.PCnum;
ICnum=calcuIC.ICnum;
workpath=calcuIC.workpath;
outpath=calcuIC.outpath;
mask=calcuIC.mask;
subnum=size(sublist,1);
maskpath=fullfile(outpath,'BrainMask');

if ~exist(maskpath,'dir')
    mkdir(maskpath);
end
currentPath=calcuIC.currentPath;
mini_corr_top=str2num(calcuIC.mini_corr_top);
mini_corr_all=str2num(calcuIC.mini_corr_all);
mini_corr_but=str2num(calcuIC.mini_corr_but);
%% parameters
perc_thres=0.9; % for group mask, > perc_thres of subjects with 1 then set to 1, otherwise set to 0   
multiplier=0.9;% for individual mask, > multiplier x mean is set to 1, otherwise set to 0


top_slice = [43:52];  % examine the top x slice
but_slice = [6:15];   % examine the buttom x slice

if isempty(mini_corr_all) ||isempty(mini_corr_top)||isempty(mini_corr_but)
    mini_corr_all = 0.8;  % if the individual mask with smaller correlation < mini_corr_all with the compared mask, discard this subject
    mini_corr_top = 0.75;  % if the individual mask with smaller correlation < mini_corr_top with the compared mask, discard this subject
    mini_corr_but = 0.55;  % if the individual mask with smaller correlation < mini_corr_but with the compared mask, discard this subject

end


%read mask
if ~isempty(mask)
    v0=spm_vol(mask);
    MaskData=spm_read_vols(v0);
    MaskData=round(MaskData);
    Mask_Vec=reshape(MaskData,1,[]);
    mask_final=Mask_Vec;
    VoxNum=size(find(Mask_Vec~=0),2);
    use_final_idx=1:size(sublist,1);
end 
if isempty(mask)
    for i=1:subnum
        fprintf('\n\tstart reading the subject''s : %s NFITI image ...\n',sublist(i,:));
        subFolder=deblank(sublist(i,:));
        subpath=strcat(workpath,filesep,subFolder);
        subFile=dir([subpath,filesep,'*.nii']);
        v=spm_vol(strcat(subFile.folder,filesep,subFile.name));
        mask_hdr=v(1);
        Dimension=v.dim;% 
        dat=spm_read_vols(v); 
        timepoints=size(v,1); 
        FmriMatr=[];
        for j=1:timepoints
            FmriVec=reshape(dat(:,:,:,j),1,[]);
            FmriMatr(j,:) = FmriVec;
        end
        firstFmriVec=reshape(dat(:,:,:,1),1,[]);  
       %generate individual mask
         temp_thres = mean(firstFmriVec) .* multiplier;
         SubMask_Vec = (firstFmriVec(:)>= temp_thres);
         allSubMask(i,:) = SubMask_Vec;
    end
     %% reslice mask by spm to consisitent mask and subject spm->subject
     
        temp=dat(:,:,:,1);% the dimension of subject
        defaultMask=strcat(currentPath,filesep,'template',filesep,'mask',filesep,'mask.nii');%
        maskHdr=spm_vol(defaultMask);
        if ~isequal(size(temp),maskHdr.dim)
            % need reslice
            InputFile=defaultMask; 
            OutputFile=strcat(currentPath,filesep,'template',filesep,'mask',filesep,'rmask.nii');
            hld=0;
            TargetSpace=strcat(subFile.folder,filesep,subFile.name);
            neuromark_resliceImage(InputFile,OutputFile,hld, TargetSpace);
             v1=spm_vol(OutputFile);%
        else
            % not need reslice
             v1=spm_vol(defaultMask);%
        end
       
        data=spm_read_vols(v1);
        DataVec(1,:)=data(:);
        % Generating spm mask
    spm_TemMask_Vec=zeros(1,size(DataVec,2));
    for j=1:size(DataVec,2)
        if DataVec(1,j)~=0
            spm_TemMask_Vec(j)=1;
        end
    end
end
 
%% group mask
% calculate common mask
if isempty(mask)
    mask_comm_temp = zeros(Dimension(1)*Dimension(2)*Dimension(3),1);
    for i = 1:size(allSubMask,2)
        if (sum(allSubMask(:,i))/subnum) >= perc_thres
            mask_comm_temp(i) = 1;
        end
    end
    mask_comm_temp = reshape(mask_comm_temp,Dimension(1),Dimension(2),Dimension(3));
    [corr_mask_all] = GIG_corr_with_mask(mask_comm_temp, reshape(allSubMask, subnum,Dimension(1),Dimension(2),Dimension(3)) , 1:Dimension(3));
    [corr_mask_but] = GIG_corr_with_mask(mask_comm_temp, reshape(allSubMask, subnum, Dimension(1),Dimension(2),Dimension(3)), but_slice);
    [corr_mask_top] = GIG_corr_with_mask(mask_comm_temp, reshape(allSubMask, subnum, Dimension(1),Dimension(2),Dimension(3)), top_slice);


    % choose subject larger than thres
    use_all_idx     = find(corr_mask_all >= mini_corr_all);
    use_top_idx     = find(corr_mask_top >= mini_corr_top);
    use_but_idx     = find(corr_mask_but >= mini_corr_but);


    % overlap idx
    use_final_idx     = intersect(use_top_idx, use_but_idx);
    use_final_idx     = intersect(use_final_idx, use_all_idx);
    % use_discard_idx   = setdiff([1:length(corr_mask_all)], use_final_idx);

    % calculate final mask
    mask_comm_final = zeros(Dimension(1)*Dimension(2)*Dimension(3),1);
    for i = 1:size(allSubMask,2)
        if (sum(allSubMask(use_final_idx,i))/(length(use_final_idx))) >= perc_thres
            mask_comm_final(i) = 1;
        end
    end
end  
%% overlap group mask and template 
if isempty(mask)
    spm_TemMask_Vec=spm_TemMask_Vec';
    mask_overlap=zeros(length(mask_comm_final),1);
    for i=1:length(mask_comm_final)
        if mask_comm_final(i)==1&&spm_TemMask_Vec(i)==1
            mask_overlap(i)=1;
        else
            mask_overlap(i)=0;
        end
    end
    mask_final  = reshape(mask_overlap,  Dimension(1), Dimension(2), Dimension(3));
    hdr_final = mask_hdr;
    maskpath=fullfile(outpath,'BrainMask');

    if ~exist(maskpath,'dir')
        mkdir(maskpath);
    end

    hdr_final.fname= fullfile(maskpath,'comm_mask.nii');
    spm_write_vol(hdr_final, mask_final);

    VoxNum=size(find(mask_final==1),1);
end

%% Write qualified subjects
fid=fopen(strcat(maskpath,filesep,'SubjectInfo.txt'),'a');
if isempty(mask)
   fprintf(fid,'You use brain mask generated by the toolbox...\n');
%    fprintf(fid,'------Below are the subjects retained according to the thresholds------\n');
   fprintf(fid,'The following includes the subject IDs after the subject selection according to the setting.');
   fprintf(fid,'Thresholds are %.2f for whole brain,%.2f for the top slices,and %.2f for the bottom slices\n',mini_corr_all,mini_corr_top,mini_corr_but);
   
else
     fprintf(fid,'You use brain mask provided by yourself...\n');
     fprintf(fid,'The following includes the subject IDs you use to estimate whose brain functional network and time series\n');
end
 
 
for i=1:length(use_final_idx)
    fprintf(fid,'%s\n',sublist(use_final_idx(i),:));   
end
%% grouplevel ics
    for i=1:length(use_final_idx)
        fprintf('\n\tstart reading the subject''s : %s NFITI image ...\n',sublist(use_final_idx(i),:));
        subFolder=deblank(sublist(use_final_idx(i),:));
        subpath=strcat(workpath,filesep,subFolder);
        subFile=dir([subpath,filesep,'*.nii']);
        v=spm_vol(strcat(subFile.folder,filesep,subFile.name));
        Dimension=v.dim;% 
        dat=spm_read_vols(v);
        timepoints=size(v,1);
        
        FmriMatr=[];
        for j=1:timepoints
            FmriVec=reshape(dat(:,:,:,j),1,[]);
            FmriMatr(j,:) = FmriVec;
        end
        
         FmriMatMask=zeros(timepoints,VoxNum);
         
          h=1;
        for k=1:Dimension(1)*Dimension(2)*Dimension(3)
            if mask_final(k)~=0
                FmriMatMask(:,h)=FmriMatr(:,k);
                h=h+1;
            end
        end
        allsubFmriMatr(i).FmriMatMask=FmriMatMask;
        GIGSubPCnum =PCnum;
        GIGGroupPCnum =ICnum;
        IndiPCAData= GIG_CalPCA( FmriMatMask',GIGSubPCnum); %subject level PCA
        SubPCAOut(:,GIGSubPCnum*(i-1)+1:GIGSubPCnum*i)=IndiPCAData;%
    end
     GroupPCAOut = GIG_CalPCA(SubPCAOut,GIGGroupPCnum); 
    
    disp('Start group level ICA for geting group components......................................');
    %ICA
    algorithmName='Infomax';
    [A2, GICs2] = useICASSO(GroupPCAOut',algorithmName);%GICs are group ICs

    % Reshaping the estimated ICs 
    GIGICMatPlMask=zeros(size(GICs2,1),Dimension(1)*Dimension(2)*Dimension(3));
    h=1;
    for K=1:Dimension(1)*Dimension(2)*Dimension(3)
        if mask_final(K)==0
            GIGICMatPlMask(:,K)=0;
        else
            GIGICMatPlMask(:,K)=GICs2(:,h);
            h=h+1;
        end
    end
   Components_Output=strcat(outpath,filesep,'ComponentsOutput');
    GIC_outpath = strcat(outpath,filesep,'GrouplevelICA');
    if ~exist(GIC_outpath,'dir')
        mkdir(GIC_outpath);
    end
    for i=1:size(GIGICMatPlMask,1)
        File_path=strcat(GIC_outpath,filesep,'Group-level Component',32,num2str(i),'.nii');
        GIGICMatPlMask_3D=reshape(GIGICMatPlMask(i,:),Dimension(1),Dimension(2),[]);
        if ~isempty(mask)
            v0.fname = File_path; % v0 is mask
            v0.dt=[16,0];
            spm_write_vol(v0,GIGICMatPlMask_3D);
        else
             v(1).fname=File_path; 
             spm_write_vol(v(1),GIGICMatPlMask_3D); 
        end
        fprintf('\n\tGenerate Group Level Component Image %d...\n',i);
        currentPath=strrep(which('GIGICA.m'),strcat('GIGICA.m'),'');
        structFile = strcat(currentPath,'template\ch2better_aligned2EPI.nii');
        image_values='positive and negative';
       [dd, FileName, extn] = fileparts(deblank(File_path));
        fig_title=FileName;
        load coldhot coldhot ;
        cmap = coldhot(1:4:end, :);
         gH = ica_plot_orth(File_path, 'structfile', structFile, 'image_values', image_values, 'convert_to_zscores', 'yes', 'threshold', 3, 'set_to_max_voxel', 1, ...
                'labels', '', 'fig_title', fig_title, 'cmap', cmap);
         h0=gH;
         cd(GIC_outpath);
         saveas(h0,strcat('Group-level Component',32,num2str(i),'.tif'));
         close gcf;
         %save as matrix
         File_ICname=strcat(GIC_outpath,filesep,'Group-level Component',32,num2str(i),'.mat');
         save(File_ICname,'GIGICMatPlMask_3D');
    end 
    %% remove noise
    str='';
    for i=1:size(GIGICMatPlMask,1)
        str=strcat(str,num2str(i),',');
    end
    str(end)='';
%      string=getappdata(hObject,'compid');
     [h,compid]=Removenoise('compid',str);% h is str 
     %split the string
     remain=strtrim(compid);
     num=0;
     ICNID=[];
     while remain
        [token,remain]=strtok(remain,',');
        ICNID(num+1,:)=str2num(token);
        num=num+1;
     end
     close(h);
     GICs2=GICs2(ICNID,:);
%      set(h,'visible','on');
%% individual ics
for i=1:length(use_final_idx)
        FmriMatMask=allsubFmriMatr(i).FmriMatMask;
        fprintf('\n\tStart estimating ICs and TCs for subject %s...\n',sublist(use_final_idx(i),:));
        [GIGICMat1,GIGTCMatB1]=GIG_GIGICA(FmriMatMask,GICs2);
%         GIGTCMat1=FmriMatMask*pinv(GIGICMat1);

%% calculate FNC
   out_path_FNC = strcat(Components_Output,filesep,sublist(use_final_idx(i),:),filesep,'FNC');%estimate component NIFTI image
   if ~exist(out_path_FNC,'dir')
        mkdir(out_path_FNC);
   end
     corrmatrix=[];
    connecMatrix=corr(GIGTCMatB1);
    connecMatrix=connecMatrix+diag(nan+zeros(1,length(connecMatrix)));
    
     fncmap=figure;
     imagesc(connecMatrix);
     colorbar;
%      colorbar('ticks',)
%      caxis([]);
     set(gca,'fontsize',12);
     xlabel('Component ID');
     ylabel('Component ID');
     title(strcat('Functional Network Connectivity Of Subject',32,sublist(use_final_idx(i),:)));
     set(gcf,'name',strcat('Functional Network Connectivity',32,sublist(use_final_idx(i),:)));
     set(gca,'titlefontweight','bold');
     axis square;
%      set(gca,'xtick',ICNID,'ytick',ICNID);
     set(gca,'xtick',[1:length(ICNID)],'xticklabel',ICNID,'ytick',[1:length(ICNID)],'yticklabel',ICNID);
     
    cd(out_path_FNC);

    saveas(fncmap,[sublist(use_final_idx(i),:),'_FNC','.tif']);
    save(strcat(sublist(use_final_idx(i),:),'_FNC.mat'),'connecMatrix');
    save(strcat(sublist(use_final_idx(i),:),'_TC.mat'),'GIGTCMatB1');
    close gcf;
%         close all force;
        GIGICMatPlMask=zeros(size(GIGICMat1,1),Dimension(1)*Dimension(2)*Dimension(3));
        h=1;
        for K=1:Dimension(1)*Dimension(2)*Dimension(3)
            if mask_final(K)==0
                GIGICMatPlMask(:,K)=0;
            else
                GIGICMatPlMask(:,K)=GIGICMat1(:,h);
                h=h+1;
            end
        end
        outpath_corr= strcat(Components_Output,filesep,sublist(use_final_idx(i),:));
        out_path_fig_IC = strcat(Components_Output,filesep,sublist(use_final_idx(i),:),filesep,'IC');%.tif image and matrix
        out_path_fig_TC = strcat(Components_Output,filesep,sublist(use_final_idx(i),:),filesep,'TC');%time series image and matrix
        if ~exist(out_path_fig_IC,'dir')
            mkdir(out_path_fig_IC);
        end
        if ~exist(out_path_fig_TC,'dir')
            mkdir(out_path_fig_TC);
        end
        
        
        corrMatrix=corr(GIGICMat1',GICs2');
        coeff_Vec=diag(corrMatrix) ;
        fid=fopen(strcat(outpath_corr,filesep,'coefficient.txt'),'a');
        for jj=1:length(coeff_Vec)
            fprintf(fid,'%d %.4f\r\n',ICNID(jj,:),coeff_Vec(jj,:));   
        end
        
%           id=1;
          for t=1:size(GIGICMatPlMask,1)
            File_path = strcat(out_path_fig_IC,filesep,sublist(use_final_idx(i),:),'_IC_',num2str(ICNID(t,:)),'.nii');
            
            GIGICMatPlMask_3D=reshape(GIGICMatPlMask(t,:),Dimension(1),Dimension(2),[]);
            if isempty(mask)
                v(1).fname = File_path; % v0 is mask
                spm_write_vol(v(1),GIGICMatPlMask_3D); %save component
            else
                v0.fname=File_path; 
                spm_write_vol(v0,GIGICMatPlMask_3D); 
            end
            % Generate component image
            fprintf('\n\tGenerate Subject Level Component Image %d...\n',ICNID(t,:));
            currentPath=strrep(which('GIGICA'),strcat('GIGICA','.m'),'');
            structFile = strcat(currentPath,'template\ch2better_aligned2EPI.nii');
            image_values='positive and negative';
             [dd, FileName, extn] = fileparts(deblank(File_path));
             fig_title=FileName;
            load coldhot coldhot ;
            cmap = coldhot(1:4:end, :);
            gH = ica_plot_orth(File_path, 'structfile', structFile, 'image_values', image_values, 'convert_to_zscores', 'yes', 'threshold', 3, 'set_to_max_voxel', 1, ...
                'labels', '', 'fig_title', fig_title, 'cmap', cmap);

    
            h0=gH;
            cd(out_path_fig_IC);
            saveas(h0,[sublist(use_final_idx(i),:),'_IC_',num2str(ICNID(t,:)),'.tif']);
            close gcf;
            %save as matrix
            File_ICname=strcat(out_path_fig_IC,filesep,sublist(use_final_idx(i),:),'_IC_',num2str(ICNID(t,:)),'.mat');
            save(File_ICname,'GIGICMatPlMask_3D');
%             id=id+1;
          end
     
            % Generating and saving TC ;
%          id2=1;
        fprintf('\n\tGenerating and saving TCs...\n')
        for t=1:size(GIGTCMatB1,2)
            h1=figure;
            x=1:timepoints;
            a=GIGTCMatB1(:,t);
            plot(x,a','-ob');
            title('Time Course');
            cd(out_path_fig_TC);
            saveas(h1,[sublist(use_final_idx(i),:),'_TC_',num2str(ICNID(t,:)),'.jpg']);
            File_TCname=strcat(out_path_fig_TC,filesep,sublist(use_final_idx(i),:),'_TC_',num2str(ICNID(t,:)),'.mat');

            save(File_TCname,'a');
            close gcf; 
        end

        
end
disp('Complete all process!')
cd(currentPath);
fclose all;
% close all force;
    

 
   