%% a4_ica_labeling

% required functions:
% - cm_label_ica_gui_20180116

currentFile = mfilename('fullpath');
[pathstr,~,~] = fileparts(currentFile);
cd(fullfile(pathstr,'..'))
rootpath = pwd;

% inputs
pn.eeg_BIDS = fullfile(rootpath, 'data', 'inputs', 'rawdata', 'eeg_BIDS');
pn.channel_locations = fullfile(rootpath, 'data', 'inputs', 'rawdata', 'channel_locations');
pn.events = fullfile(rootpath, 'data', 'inputs', 'rawdata', 'events');
pn.tools = fullfile(rootpath, 'tools');
% outputs
pn.eeg_ft = fullfile(rootpath, 'data', 'outputs', 'eeg');
pn.history = fullfile(rootpath, 'data', 'outputs', 'history');

addpath(fullfile(pn.tools, 'fieldtrip')); ft_defaults;
addpath(fullfile(pn.tools, 'helpers'));

%% define IDs for visual screening

ID = 'sub-033';

%% load data & start GUI

% load data (full data)
load(fullfile(pn.eeg_ft, [ID, '_task-xxxx_eeg_ica.mat']),'data');

if ~isfield(data.iclabels,'emg')
    data.iclabels.emg = [];
end

% load config (ICA version)
load(fullfile(pn.history, [ID, '_task-xxxx_config.mat']),'config');

% settings for ICA

% ica config
cfg.method           = config.ica1.cfg.method; %'runica';
cfg.trials           = 'all';
cfg.numcomponent     = 'all';
cfg.demean           = 'no';
cfg.runica.extended  = 1;

% ICA solution for segments
cfg.unmixing     = data.unmixing;
cfg.topolabel    = data.topolabel;

% ICA (from weights)

% components
comp = ft_componentanalysis(cfg,data);
    
% include electrode information
comp.elec = data.elec;

% include ICA labeling
comp.iclabels = data.iclabels;

% clear cfg
clear cfg

% label ICs

% settings
cfg.topoall  = 'yes';
cfg.chanlocs = data.chanlocs;

% label electrodes
data.iclabels = cm_label_ica_gui_20180116(cfg,comp);

% keep labels in config
config.ica1.iclabels.manual = data.iclabels;

% clear variables
clear cfg

% save data (full data)
save(fullfile(pn.eeg_ft, [ID, '_task-xxxx_eeg_ica.mat']),'data');

% save config (ICA version)
save(fullfile(pn.history, [ID, '_task-xxxx_config.mat']),'config');

% clear variables

clear BLOCK ID comp config data
