function appConfig=nic_rsdd_calcICA(appConfig,datareductionOutDir,ICAOutDir,randorderType)
% Do ICA
% Input: appConfig - structure containing all parameters 
% datareductionOutDir: the folder of pca 
% ICAOutDir: output dir of ICA
%-----------------------------------------------------------
%   Copyright (C) 2009 Neuroimage Computing Group, State Key Laboratory of
%   Cognitive Neuroscience and Learning, Beijing normal university
%	Written by Gwen Chen
%	Version=1.0;
%	Release=20090728;
%-----------------------------------------------------------
%

if(~exist('datareductionOutDir','var'))
    datareductionOutDir='mat';
end

if(~exist('ICAOutDir','var'))
    ICAOutDir='mat';
end

numOfIC = appConfig.compNum;% the number of IC
mask_ind=appConfig.maskInd; % the mask


outPrefix=appConfig.outPrefix; % the prefix
outDir=appConfig.outDir; % the output directory


disp(' ');
disp('---------------------------------------------------------------------');
disp('STARTING GROUP ICA STEP');
disp('---------------------------------------------------------------------');




if(~isfield(appConfig,'ICA_Options'))
    appConfig.ICA_Options=icatb_icaOptions([numOfIC length(mask_ind)],appConfig.icaAlgorithmNo,'off'); % obtrain the ICA options
else 
    if(isfield(appConfig,'isAutomaticEstimate')) % if the user set the mode of 'autoestimate', then set the compNum with the number of autoestimation
        if(appConfig.isAutomaticEstimate==1)
            switch(appConfig.icaAlgorithmNo)
                case 1
                    appConfig.ICA_Options(20)={numOfIC};
                case 2
                    appConfig.ICA_Options(10)={numOfIC};
            end
        end
    end
end


selected_ica_algorithm=appConfig.icaAlgorithm;

ICA_Options=appConfig.ICA_Options;

% pInfo = appConfig.HInfo;

% pca result of the last step 

load(fullfile(outDir,datareductionOutDir,sprintf('%s_pca_r%d-%d.mat',outPrefix,appConfig.reductionPara.numOfReductionSteps,1))); % load the data

isFine=0;
tryTimes=0;
Max_Try_Times=3;
while isFine==0 && tryTimes<Max_Try_Times
    [icaAlgo, W, A, icasig_tmp,isFine] = icatb_icaAlgorithm(selected_ica_algorithm, dataPCA', ICA_Options); % call the algorithm
    tryTimes=tryTimes+1;
end
if(isFine==0)
    error('It can''t be converged, please reduce the error tolerance');
end
clear dataPCA;

icasig = icasig_tmp;

clear icasig_tmp;

numOfIC=size(icasig,1);

% adjust the sign of component
 for compNum=1:numOfIC
        changeSign = 0;
        [Y I] =max(abs(icasig(compNum,:)));
        highestVal = icasig(compNum,I);
        sumICA = sum(icasig(compNum,find(abs(icasig(compNum,:))>mean(abs(icasig(compNum,:))))));
        moreNeg = sumICA < 0;
        % use a better criteria to change the sign
        if sign(highestVal) == -1
            disp(['Changing sign of component ',num2str(compNum)]);
            icasig(compNum,:) = icasig(compNum,:)*-1;
        end

 end



icaout=fullfile(outDir,ICAOutDir,sprintf('%s_ica.mat',outPrefix));

save(icaout, 'A', 'W', 'icasig', 'mask_ind');
% load(icaout);


if(~isfield(appConfig,'HInfo'))
    [da pInfo]=nic_rsdd_loadData(appConfig.AppFileList{1,3}.name(1,:),[]);
    clear da;
else
    pInfo=appConfig.HInfo;
end
complexInfoRead = struct('complex_file_naming',{'R_'  'I_'},'complexType','real&imaginary');
    
outfile = [outPrefix,'_agg__component_ica_'];

outDir=fullfile(outDir,ICAOutDir);


disp('---------------------------------------------------------------------');
disp('DONE CALCULATING GROUP ICA');
disp('---------------------------------------------------------------------');
disp('');


return;

function deleteFiles(files_in_zip)
% delete files extracted from zip

for i=1:length(files_in_zip)
    delete(files_in_zip{i});
end





