function [sesInfo] = icatb_parameterInitialization(sesInfo, statusHandle)
%% Initializes the variables from the user input and perfoms error checking
% Inputs: sesInfo - structure containing all parameters for analysis

if ~exist('sesInfo','var')
    [P] = icatb_selectEntry('typeEntity', 'file', 'title', 'Select Parameter File', 'filter', '*param*.mat');
    if isempty(P)
        error('Parameter file is not selected for analysis');
    end
    [pathstr, fileName] = fileparts(P);
    outputDir = pathstr;
    % Make sure parameter file exists
    load(P);
    if ~exist('sesInfo', 'var')
        %         infoCell{1} = P;
        %         icatb_error('The selected file does not contain sesInfo variable', infoCell);
        error(['The selected file ', P, ' does not contain the sesInfo variable']);
    end
else
    outputDir = sesInfo.outputDir; % get the output directory information
end

if ~exist('statusHandle', 'var')
    statusHandle = [];
end

[modalityType, dataTitle] = icatb_get_modality;

% Load defaults
icatb_defaults;

global PARAMETER_INFO_MAT_FILE; % parameter file
global DATA_REDUCTION_MAT_FILE; %A file for each subject's principal components
global ICA_MAT_FILE;
global BACK_RECONSTRUCTION_MAT_FILE;
global CALIBRATE_MAT_FILE;
global AGGREGATE_AN3_FILE;
global FUNCTIONAL_DATA_FILTER;
global FLIP_ANALYZE_IMAGES;

functional_data_extn = FUNCTIONAL_DATA_FILTER(2:end);

if ~strcmpi(modalityType, 'eeg')
    if ~strcmpi(functional_data_extn, '.nii') & ~strcmpi(functional_data_extn, '.img')
        error(['Functional data filter used for writing images is neither nifti nor analyze format.' ...
            ' Check FUNCTIONAL_DATA_FILTER variable in icatb_defaults.m']);
    end
end


sesInfo.flip_analyze_images = FLIP_ANALYZE_IMAGES;
sesInfo.numComp = sesInfo.userInput.numComp;

%get number of subjects and sessions
sesInfo.numOfSub = sesInfo.userInput.numOfSub;
sesInfo.numOfSess = sesInfo.userInput.numOfSess;
sesInfo.numOfDataSets = sesInfo.userInput.numOfSub*sesInfo.userInput.numOfSess;
if isfield(sesInfo.userInput, 'dataType')
    sesInfo.dataType = sesInfo.userInput.dataType;
else
    sesInfo.dataType = 'real';
end

%naming convention for matlab output files
sesInfo.param_file = [sesInfo.userInput.prefix, PARAMETER_INFO_MAT_FILE];
sesInfo.data_reduction_mat_file = [sesInfo.userInput.prefix,DATA_REDUCTION_MAT_FILE];
sesInfo.ica_mat_file = [sesInfo.userInput.prefix,ICA_MAT_FILE];
sesInfo.back_reconstruction_mat_file = [sesInfo.userInput.prefix,BACK_RECONSTRUCTION_MAT_FILE];
sesInfo.calibrate_components_mat_file = [sesInfo.userInput.prefix,CALIBRATE_MAT_FILE];
sesInfo.aggregate_components_an3_file = [sesInfo.userInput.prefix,AGGREGATE_AN3_FILE];

% get the count for time points
if isfield(sesInfo.userInput, 'diffTimePoints')
    countFiles = sesInfo.userInput.diffTimePoints; % different time points
else
    % get the count of the files
    [countFiles] = icatb_get_countTimePoints(sesInfo.userInput.files);
end
% end for checking the time points

checkTimePoints = find(countFiles ~= countFiles(1));

if ~isempty(checkTimePoints)
    flagTimePoints = 'different_time_points';
else
    flagTimePoints = 'same_time_points';
end

% store these two parameters
sesInfo.flagTimePoints = flagTimePoints;
sesInfo.diffTimePoints = countFiles;

[sesInfo.icaOutputFiles] = icatb_getOutputFileNames(sesInfo.userInput.prefix, sesInfo.numComp, sesInfo.numOfSub, ...
    sesInfo.numOfSess, flagTimePoints);

if~isempty(statusHandle)
    % Display Waitbar

    % get the status handles
    statusData = get(statusHandle, 'userdata');
    statusData.perCompleted = statusData.perCompleted + statusData.unitPerCompleted;
    set(statusHandle, 'name', [num2str(round(statusData.perCompleted*100)), '% analysis done']);
    set(statusHandle, 'userdata', statusData);
    waitbar(statusData.perCompleted, statusHandle);

end

%input files
sesInfo.inputFiles = sesInfo.userInput.files;
sesInfo.numOfScans = sesInfo.diffTimePoints(1);

% get the naming of the complex images
[sesInfo, complexInfo] = icatb_name_complex_images(sesInfo, 'read');

if ~strcmpi(modalityType, 'eeg')
    % return HInfo
    [V, sesInfo.HInfo] = icatb_returnHInfo(sesInfo.userInput.files(1).name(1, :));
    clear V;

    % Check HInfo
    [sesInfo.HInfo] = icatb_checkHInfo(sesInfo.HInfo, sesInfo.userInput.files(1).name(1, :), functional_data_extn);
else
    sesInfo.HInfo = sesInfo.userInput.HInfo;
end

if ~isempty(statusHandle)

    % get the status handles
    statusData = get(statusHandle, 'userdata');
    statusData.perCompleted = statusData.perCompleted + statusData.unitPerCompleted;
    set(statusHandle, 'userdata', statusData);
    set(statusHandle, 'name', [num2str(round(statusData.perCompleted*100)), '% analysis done']); waitbar(statusData.perCompleted, statusHandle);

end

%--algorithm
sesInfo.algorithm = sesInfo.userInput.algorithm;

%--scaleType
sesInfo.scaleType = sesInfo.userInput.scaleType;

%--Convert To Z
if isfield(sesInfo.userInput, 'convertToZ')
    convertToZ = sesInfo.userInput.convertToZ;
    if convertToZ
        sesInfo.scaleType = 2;
    end
    sesInfo.userInput = rmfield(sesInfo.userInput, 'convertToZ');
    if isfield(sesInfo, 'convertToZ')
        sesInfo = rmfield(sesInfo, 'convertToZ');
    end
end


if isfield(sesInfo.userInput, 'mask_ind')
    % get the mask indices
    sesInfo.mask_ind = sesInfo.userInput.mask_ind;
else


    if ~strcmpi(modalityType, 'eeg')
        %--get mask
        if(isempty(sesInfo.userInput.maskFile))
            sesInfo.mask_ind  = icatb_createMask(sesInfo.inputFiles, sesInfo.HInfo, ...
                sesInfo.dataType, 'default', complexInfo);
        else
            files(1).name = sesInfo.userInput.maskFile;
            sesInfo.mask_ind = icatb_createMask(files, sesInfo.HInfo, 'real', 'user_specified', ...
                complexInfo);
            clear files;
        end

    else

        % Handle EEG data here
        [origData, HInfo] = icatb_loadData(deblank(sesInfo.inputFiles(1).name(1, :)));
        sesInfo.HInfo = HInfo;
        % Data dimensions
        dims = [size(origData, 1), size(origData, 2), size(origData, 4)];

        if (isempty(sesInfo.userInput.maskFile))

            % Use all indices
            temp = ones(prod(dims(1:2)), 1);

        else

            files(1).name = sesInfo.userInput.maskFile;

            temp = icatb_loadData(files(1).name);

            if length(find(size(temp) == dims(1:2))) ~= 2
                error(['Mask ', files(1).name, ' doesn''t match data dimensions ']);
            end

        end

        % Mask indices
        sesInfo.mask_ind = find(temp(:) ~= 0);
    end

end
% end for checking mask indices

%setup rest of reduction step values
sesInfo.numReductionSteps = sesInfo.userInput.numReductionSteps;
[sesInfo]=icatb_dataReductionSetup(sesInfo);


%check to make sure valid parameters
icatb_parameterErrorCheck(sesInfo);


% Store flip parameter
sesInfo.flip_analyze_images = FLIP_ANALYZE_IMAGES;

%parameters are now initialized and ready for analysis
sesInfo.isInitialized = 1;

%save group information in matlab file
[pp, fileName] = fileparts(sesInfo.userInput.param_file);

icatb_save(fullfile(outputDir, [fileName, '.mat']), 'sesInfo');

if ~isempty(statusHandle)
    % get the status handles
    statusData = get(statusHandle, 'userdata');
    statusData.perCompleted = statusData.perCompleted + statusData.unitPerCompleted;
    set(statusHandle, 'userdata', statusData);
    set(statusHandle, 'name', [num2str(round(statusData.perCompleted*100)), '% analysis done']); waitbar(statusData.perCompleted, statusHandle);
end
