function nic_rsdd_calibration(appConfig)
% Calibration of components (all): Z-score /calibration
% Input: appConfig - structure containing all parameters necessary for
% group
% filein: the components back reconstructed
% fileout: the components after calibration before statistics
%-----------------------------------------------------------
%   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=20090729;
%  Last Revised by Gwen Chen
%-----------------------------------------------------------


numOfIC = appConfig.compNum;
mask_ind=appConfig.maskInd;


outPrefix=appConfig.outPrefix;
outDir=appConfig.outDir;
outputDir=outDir;

disp(' ');
disp('---------------------------------------------------------------------');
disp('STARTING TO SCALE COMPONENT SETS');
disp('---------------------------------------------------------------------');


inputPrefix = outPrefix;


%--load reference image
%---------------------------------------------------------
icain=[outPrefix '_ica'];
ref = load(fullfile(fullfile(outDir,'mat'), [icain, '.mat']));
refImage = ref.icasig;
refImage = refImage';
clear ref;

if(~isfield(appConfig,'HInfo'))
    [da appConfig.HInfo]=nic_rsdd_loadData(appConfig.AppFileList{1,3}.name(1,:),[]);
    clear da;
end

if size(refImage, 1) == prod(appConfig.HInfo.dim(1:3))
    refImage = refImage(mask_ind, :);
end


%--scale components
%------------------------------------------------------------
fileCount =1;
subFile = [outPrefix,'_ica_br',num2str(fileCount), '.mat'];
load(fullfile(fullfile(outputDir,'mat'), subFile));
%load(subFile);
numSets = length(appConfig.AppSubjectLabels);
ses = 1;

compSetFields={'ic','tc'};

nic_waitbar(0,sprintf('Calibration components...'), 'Multiple-runs ICA (Post processing)','Child');
for i=1:numSets

    %keep track of subject
    subjectNumber = ceil(i/ ses);

    disp(['--Subject ',num2str(subjectNumber),' Session ',num2str(ses),'''s Component Set']);

    % IC
    tempIC = getfield(compSet, compSetFields{1});
    % TC
    tempTC = getfield(compSet, compSetFields{2});

    clear compSet;

    % put components in proper orientation
    if (size(tempTC, 1) > size(tempTC, 2))
        tempTC = tempTC';
    end

    if (size(tempIC, 1) > size(tempIC, 2))
        tempIC = tempIC';
    end

    numOfIC=size(tempIC,1);
    % get sign of correlation between subject components and reference
    % component
    for compNum = 1:numOfIC
        subjectImage = detrend(tempIC(compNum, :),0);
        if length(subjectImage) ~= size(refImage, 1)
            subjectImage = subjectImage(mask_ind);
        end
        corSign = sign(refImage(:, compNum)'*subjectImage');
        % check the sign function
        if sign(corSign) == -1
            string = ['  Difference in Sign Between Reference Image and Subject ', num2str(subjectNumber), ' Session ', num2str(ses), ...
                ' Component ', num2str(compNum)];
            disp([string,' -> Changing Sign of component and timecourse']);
            tempIC(compNum, :) = tempIC(compNum, :) * -1;
            tempTC(compNum, :) = tempTC(compNum, :) * -1;
        end
    end
    clear subjectImage;


    clear compSet;
    
%     [sesInfo, complexInfoRead] = icatb_name_complex_images(sesInfo, 'read');

    if size(tempIC, 2) == prod(appConfig.HInfo.dim(1:3))
        tempIC = tempIC(:, mask_ind);
    end

    %scale timecourses and components
    complexInfoRead = struct('complex_file_naming',{'R_'  'I_'},'complexType','real&imaginary');

    [tempIC, tempTC] = nic_icatb_scaleICA(tempIC, tempTC, appConfig.AppFileList{i,3}.name, ...
        appConfig.scaleType, 'real', complexInfoRead, mask_ind);%ÐÞ¸Ä

    % Get var names from compSetfields to store in calibration MAT files
    eval([compSetFields{1}, ' = tempIC;']);
    eval([compSetFields{2}, ' = tempTC;']);
     
    dispStr = ['...saving scaled ica data for subject ', num2str(subjectNumber), ' session ', num2str(ses),...
                ' in nifti format and as matlab file'];

    disp(dispStr);

    % save data in matlab file
    subFileOut = [outPrefix '_ica_c', num2str(subjectNumber), '-', num2str(ses), '.mat'];
    subFileOut = fullfile(fullfile(outputDir,'mat'), subFileOut);
    
    save(subFileOut, compSetFields{:});

    eval(['clear ', compSetFields{1}, ' ', compSetFields{2}]);

    subIndex = sprintf('%03d',subjectNumber);
    sessIndex = num2str(ses);

    %save individual images in analyze file

    outfile = [inputPrefix, '_sub', subIndex, '_component_ica', '_s', sessIndex, '_'];

    % global variable necessary for defining the real&imag or magnitude&phase
    HInfo=appConfig.HInfo;
    [fileNames, zipFileName, files_in_zip] = nic_icatb_saveICAData(outfile, tempIC, tempTC, mask_ind, numOfIC, ...
            HInfo, 'real', complexInfoRead, outputDir);

    clear tempTC tempIC;

    %load next subject's file
    if(i ~= numSets)
        fileCount = fileCount + 1;
        subFile = [outPrefix '_ica_br',num2str(fileCount), '.mat'];
        
        load(fullfile(fullfile(outputDir,'mat'), subFile));
    end

    %increment session number
%     ses = ses + 1;
    nic_waitbar(i/numSets,sprintf('Calibration components...'), 'Multiple-runs ICA (Post processing)','Child');
end


disp('---------------------------------------------------------------------');
disp('DONE SCALING COMPONENTS');
disp('---------------------------------------------------------------------');
disp(' ');


