% eeg_checkset()   - check the consistency of the fields of an EEG dataset
%                    Also: See EEG dataset structure field descriptions below.
%
% Usage: >> [EEGOUT,changes] = eeg_checkset(EEG); % perform all checks
%                                                  except 'makeur'
%        >> [EEGOUT,changes] = eeg_checkset(EEG, 'keyword'); % perform 'keyword' check(s)
%
% Inputs:
%       EEG        - EEGLAB dataset structure or (ALLEEG) array of EEG structures
%
% Optional keywords:
%   'icaconsist'   - if EEG contains several datasets, check whether they have
%                    the same ICA decomposition
%   'epochconsist' - if EEG contains several datasets, check whether they have
%                    identical epoch lengths and time limits.
%   'chanconsist'  - if EEG contains several datasets, check whether they have
%                    the same number of channels and channel labels.
%   'data'         - check whether EEG contains data (EEG.data)
%   'loaddata'     - load data array (if necessary)
%   'savedata'     - save data array (if necessary - see EEG.saved below)
%   'contdata'     - check whether EEG contains continuous data
%   'epoch'        - check whether EEG contains epoched or continuous data
%   'ica'          - check whether EEG contains an ICA decomposition
%   'besa'         - check whether EEG contains component dipole locations
%   'event'        - check whether EEG contains an event array
%   'makeur'       - remake the EEG.urevent structure
%   'checkur'      - check whether the EEG.urevent structure is consistent
%                    with the EEG.event structure
%   'chanlocsize'  - check the EEG.chanlocs structure length; show warning if
%                    necessary.
%   'chanlocs_homogeneous' - check whether EEG contains consistent channel
%                            information; if not, correct it.This option
%                            calls eeg_checkchanlocs.
%   'eventconsistency'     - check whether EEG.event information are consistent;
%                            rebuild event* subfields of the 'EEG.epoch' structure
%                            (can be time consuming).
% Outputs:
%       EEGOUT     - output EEGLAB dataset or dataset array
%       changes    - change code: 'no' = no changes; 'yes' = the EEG
%                    structure was modified
%
% ===========================================================
% The structure of an EEG dataset under EEGLAB (as of v5.03):
%
% Basic dataset information:
%   EEG.setname      - descriptive name|title for the dataset
%   EEG.filename     - filename of the dataset file on disk
%   EEG.filepath     - filepath (directory/folder) of the dataset file(s)
%   EEG.trials       - number of epochs (or trials) in the dataset.
%                      If data are continuous, this number is 1.
%   EEG.pnts         - number of time points (or data frames) per trial (epoch).
%                      If data are continuous (trials=1), the total number
%                      of time points (frames) in the dataset
%   EEG.nbchan       - number of channels
%   EEG.srate        - data sampling rate (in Hz)
%   EEG.xmin         - epoch start latency|time (in sec. relative to the
%                      time-locking event at time 0)
%   EEG.xmax         - epoch end latency|time (in seconds)
%   EEG.times        - vector of latencies|times in miliseconds (one per time point)
%   EEG.ref          - ['common'|'averef'|integer] reference channel type or number
%   EEG.history      - cell array of ascii pop-window commands that created
%                      or modified the dataset
%   EEG.comments     - comments about the nature of the dataset (edit this via
%                      menu selection Edit > About this dataset)
%   EEG.etc          - miscellaneous (technical or temporary) dataset information
%   EEG.saved        - ['yes'|'no'] 'no' flags need to save dataset changes before exit
%
% The data:
%   EEG.data         - two-dimensional continuous data array (chans, frames)
%                      ELSE, three-dim. epoched data array (chans, frames, epochs)
%
% The channel locations sub-structures:
%   EEG.chanlocs     - structure array containing names and locations
%                      of the channels on the scalp
%   EEG.urchanlocs   - original (ur) dataset chanlocs structure containing
%                      all channels originally collected with these data
%                      (before channel rejection)
%   EEG.chaninfo     - structure containing additional channel info
%   EEG.ref          - type of channel reference ('common'|'averef'|+/-int]
%   EEG.splinefile   - location of the spline file used by headplot() to plot
%                      data scalp maps in 3-D
%
% The event and epoch sub-structures:
%   EEG.event        - event structure containing times and nature of experimental
%                      events recorded as occurring at data time points
%   EEG.urevent      - original (ur) event structure containing all experimental
%                      events recorded as occurring at the original data time points
%                      (before data rejection)
%   EEG.epoch        - epoch event information and epoch-associated data structure array (one per epoch)
%   EEG.eventdescription - cell array of strings describing event fields.
%   EEG.epochdescription - cell array of strings describing epoch fields.
%   --> See the http://sccn.ucsd.edu/eeglab/maintut/eeglabscript.html for details
%
% ICA (or other linear) data components:
%   EEG.icasphere   - sphering array returned by linear (ICA) decomposition
%   EEG.icaweights  - unmixing weights array returned by linear (ICA) decomposition
%   EEG.icawinv     - inverse (ICA) weight matrix. Columns gives the projected
%                     topographies of the components to the electrodes.
%   EEG.icaact      - ICA activations matrix (components, frames, epochs)
%                     Note: [] here means that 'compute_ica' option has been set
%                     to 0 under 'File > Memory options' In this case,
%                     component activations are computed only as needed.
%   EEG.icasplinefile - location of the spline file used by headplot() to plot
%                     component scalp maps in 3-D
%   EEG.chaninfo.icachansind  - indices of channels used in the ICA decomposition
%   EEG.dipfit      - array of structures containing component map dipole models
%
% Variables indicating membership of the dataset in a studyset:
%   EEG.subject     - studyset subject code
%   EEG.group       - studyset group code
%   EEG.condition   - studyset experimental condition code
%   EEG.run         - studyset run number
%   EEG.session     - studyset session number
%
% Variables used for manual and semi-automatic data rejection:
%   EEG.specdata           - data spectrum for every single trial
%   EEG.specica            - data spectrum for every single trial
%   EEG.stats              - statistics used for data rejection
%       EEG.stats.kurtc    - component kurtosis values
%       EEG.stats.kurtg    - global kurtosis of components
%       EEG.stats.kurta    - kurtosis of accepted epochs
%       EEG.stats.kurtr    - kurtosis of rejected epochs
%       EEG.stats.kurtd    - kurtosis of spatial distribution
%   EEG.reject            - statistics used for data rejection
%       EEG.reject.entropy - entropy of epochs
%       EEG.reject.entropyc  - entropy of components
%       EEG.reject.threshold - rejection thresholds
%       EEG.reject.icareject - epochs rejected by ICA criteria
%       EEG.reject.gcompreject - rejected ICA components
%       EEG.reject.sigreject  - epochs rejected by single-channel criteria
%       EEG.reject.elecreject - epochs rejected by raw data criteria
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab()

% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

% 01-25-02 reformated help & license -ad
% 01-26-02 chandeg events and trial condition format -ad
% 01-27-02 debug when trial condition is empty -ad
% 02-15-02 remove icawinv recompute for pop_epoch -ad & ja
% 02-16-02 remove last modification and test icawinv separatelly -ad
% 02-16-02 empty event and epoch check -ad
% 03-07-02 add the eeglab options -ad
% 03-07-02 corrected typos and rate/point calculation -ad & ja
% 03-15-02 add channel location reading & checking -ad
% 03-15-02 add checking of ICA and epochs with pop_up windows -ad
% 03-27-02 recorrected rate/point calculation -ad & sm

function [EEG, res] = eeg_checkset( EEG, varargin );
msg = '';
res = 'no';
com = sprintf('EEG = eeg_checkset( EEG );');

if nargin < 1
    help eeg_checkset;
    return;
end

if isempty(EEG), return; end
if ~isfield(EEG, 'data'), return; end

% checking multiple datasets
% --------------------------
if length(EEG) > 1

    if nargin > 1
        switch varargin{1}
            case 'epochconsist', % test epoch consistency
                % ----------------------
                res = 'no';
                datasettype = unique_bc( [ EEG.trials ] );
                if datasettype(1) == 1 && length(datasettype) == 1, return; % continuous data
                elseif datasettype(1) == 1,                        return; % continuous and epoch data
                end

                allpnts = unique_bc( [ EEG.pnts ] );
                allxmin = unique_bc( [ EEG.xmin ] );
                if length(allpnts) == 1 && length(allxmin) == 1, res = 'yes'; end
                return;

            case 'chanconsist'  % test channel number and name consistency
                % ----------------------------------------
                res = 'yes';
                chanlen    = unique_bc( [ EEG.nbchan ] );
                anyempty    = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) );
                if length(chanlen) == 1 && all(anyempty == 0)
                    tmpchanlocs = EEG(1).chanlocs;
                    channame1 = { tmpchanlocs.labels };
                    for i = 2:length(EEG)
                        tmpchanlocs = EEG(i).chanlocs;
                        channame2 = { tmpchanlocs.labels };
                        if length(intersect(channame1, channame2)) ~= length(channame1), res = 'no'; end
                    end
                else res = 'no';
                end

                % Field 'datachan in 'urchanlocs' is removed, if exist
                if isfield(EEG, 'urchanlocs') && ~all(cellfun(@isempty,{EEG.urchanlocs})) && isfield([EEG.urchanlocs], 'datachan')
                        [EEG.urchanlocs] = deal(rmfield([EEG.urchanlocs], 'datachan'));
                end
                return;

            case 'icaconsist'  % test ICA decomposition consistency
                % ----------------------------------
                res = 'yes';
                anyempty    = unique_bc( cellfun( 'isempty', { EEG.icaweights }) );
                if length(anyempty) == 1 && anyempty(1) == 0
                    ica1 = EEG(1).icawinv;
                    for i = 2:length(EEG)
                        if ~isequal(EEG(1).icawinv, EEG(i).icawinv)
                            res = 'no';
                        end
                    end
                else res = 'no';
                end
                return;

        end
    end

end

% reading these option take time because
% of disk access
% --------------
eeglab_options;

% standard checking
% -----------------
ALLEEG = EEG;
for inddataset = 1:length(ALLEEG)

    EEG = ALLEEG(inddataset);

    % additional checks
    % -----------------
    res = -1; % error code
    if ~isempty( varargin)
        for index = 1:length( varargin )
            switch varargin{ index }
                case 'data',; % already done at the top
                case 'contdata',;
                    if EEG.trials > 1
                        errordlg2(strvcat('Error: function only works on continuous data'), 'Error');
                        return;
                    end
                case 'ica',
                    if isempty(EEG.icaweights)
                        errordlg2(strvcat('Error: no ICA decomposition. use menu "Tools > Run ICA" first.'), 'Error');
                        return;
                    end
                case 'epoch',
                    if EEG.trials == 1
                        errordlg2(strvcat('Extract epochs before running that function', 'Use Tools > Extract epochs'), 'Error');
                        return
                    end
                case 'besa',
                    if ~isfield(EEG, 'sources')
                        errordlg2(strvcat('No dipole information', '1) Export component maps: Tools > Localize ... BESA > Export ...' ...
                            , '2) Run BESA to localize the equivalent dipoles', ...
                            '3) Import the BESA dipoles: Tools > Localize ... BESA > Import ...'), 'Error');
                        return
                    end
                case 'event',
                    if isempty(EEG.event)
                        errordlg2(strvcat('Requires events. You need to add events first.', ...
                            'Use "File > Import event info" or "File > Import epoch info"', ...
                            'Install plugin VidEd to manually add events as you scroll the data.' ), 'Error');
                        return;
                    end
                case 'chanloc',
                    tmplocs = EEG.chanlocs;
                    if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
                        errordlg2( strvcat('This functionality requires channel location information.', ...
                            'Enter the channel file name via "Edit > Edit dataset info".', ...
                            'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
                        return;
                    end
                case 'chanlocs_homogeneous',
                    tmplocs = EEG.chanlocs;
	                if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
                        errordlg2( strvcat('This functionality requires channel location information.', ...
                            'Enter the channel file name via "Edit > Edit dataset info".', ...
                            'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
                        return;
                    end
                    if ~isfield(EEG.chanlocs, 'X') || isempty(EEG.chanlocs(1).X)
                        EEG = eeg_checkchanlocs(EEG);
                        % EEG.chanlocs = convertlocs(EEG.chanlocs, 'topo2all');
                        res = ['EEG = eeg_checkset(EEG, ''chanlocs_homogeneous''); ' ];
                    end
                case 'chanlocsize',
                    if ~isempty(EEG.chanlocs)
                        if length(EEG.chanlocs) > EEG.nbchan
                            questdlg2(strvcat('Warning: there is one more electrode location than', ...
                                'data channels. EEGLAB will consider the last electrode to be the', ...
                                'common reference channel. If this is not the case, remove the', ...
                                'extra channel'), 'Warning', 'Ok', 'Ok');
                        end
                    end
                case 'makeur',
                    if ~isempty(EEG.event)
                        if isfield(EEG.event, 'urevent'),
                            EEG.event = rmfield(EEG.event, 'urevent');
                            disp('eeg_checkset note: re-creating the original event table (EEG.urevent)');
                        else
                            disp('eeg_checkset note: creating the original event table (EEG.urevent)');
                        end
                        EEG.urevent = EEG.event;
                        for index = 1:length(EEG.event)
                            EEG.event(index).urevent = index;
                        end
                    end
                case 'checkur',
                    if ~isempty(EEG.event)
                        if isfield(EEG.event, 'urevent') && ~isempty(EEG.urevent)
                            urlatencies = [ EEG.urevent.latency ];
                            [newlat tmpind] = sort(urlatencies);
                            if ~isequal(newlat, urlatencies)
                                EEG.urevent   = EEG.urevent(tmpind);
                                [tmp tmpind2] = sort(tmpind);
                                for index = 1:length(EEG.event)
                                    EEG.event(index).urevent = tmpind2(EEG.event(index).urevent);
                                end
                            end
                        end
                    end
                case 'eventconsistency',
                    [EEG res] = eeg_checkset(EEG);
                    if isempty(EEG.event), return; end

                    % check events (slow)
                    % ------------
                    if isfield(EEG.event, 'type')
                        eventInds = arrayfun(@(x)isempty(x.type), EEG.event);
                        if any(eventInds)
                            if all(arrayfun(@(x)isnumeric(x.type), EEG.event))
                                 for ind = find(eventInds), EEG.event(ind).type = NaN; end
                            else for ind = find(eventInds), EEG.event(ind).type = 'empty'; end
                            end
                        end
                        if ~all(arrayfun(@(x)ischar(x.type), EEG.event)) && ~all(arrayfun(@(x)isnumeric(x.type), EEG.event))
                            disp('Warning: converting all event types to strings');
                            for ind = 1:length(EEG.event)
                                EEG.event(ind).type = num2str(EEG.event(ind).type);
                            end
                            EEG = eeg_checkset(EEG, 'eventconsistency');
                        end

                    end

                    % Removing events with NaN latency
                    % --------------------------------
                    if isfield(EEG.event, 'latency')
                        nanindex = find(isnan([ EEG.event.latency ]));
                        if ~isempty(nanindex)
                            EEG.event(nanindex) = [];
                            trialtext = '';
                             for inan = 1:length(nanindex)
                                 trialstext = [trialtext ' ' num2str(nanindex(inan))];
                             end
                            disp(sprintf(['eeg_checkset: Event(s) with NaN latency were deleted \nDeleted event index(es):[' trialstext ']']));
                        end
                    end

                    % remove the events which latency are out of boundary
                    % ---------------------------------------------------
                    if isfield(EEG.event, 'latency')
                        if isfield(EEG.event, 'type') && ischar(EEG.event(1).type)
                            if strcmpi(EEG.event(1).type, 'boundary') && isfield(EEG.event, 'duration')
                                if EEG.event(1).duration < 1
                                    EEG.event(1) = [];
                                elseif EEG.event(1).latency > 0 && EEG.event(1).latency < 1
                                    EEG.event(1).latency = 0.5;
                                end
                            end
                        end

                        try, tmpevent = EEG.event; alllatencies = [ tmpevent.latency ];
                        catch, error('Checkset: error empty latency entry for new events added by user');
                        end
                        I1 = find(alllatencies < 0.5);
                        I2 = find(alllatencies > EEG.pnts*EEG.trials+1); % The addition of 1 was included
                        % because, if data epochs are extracted from -1 to
                        % time 0, this allow to include the last event in
                        % the last epoch (otherwise all epochs have an
                        % event except the last one
                        if (length(I1) + length(I2)) > 0
                            fprintf('eeg_checkset warning: %d/%d events had out-of-bounds latencies and were removed\n', ...
                                length(I1) + length(I2), length(EEG.event));
                            EEG.event(union(I1, I2)) = [];
                        end
                    end
                    if isempty(EEG.event), return; end

                    % save information for non latency fields updates
                    % -----------------------------------------------
                    difffield = [];
                    if ~isempty(EEG.event) && isfield(EEG.event, 'epoch')
                        % remove fields with empty epochs
                        % -------------------------------
                        removeevent = [];
                        try
                            tmpevent = EEG.event;
                            allepochs = [ tmpevent.epoch ];
                            removeevent = find( allepochs < 1 || allepochs > EEG.trials);
                            if ~isempty(removeevent)
                                disp([ 'eeg_checkset warning: ' int2str(length(removeevent)) ' event had invalid epoch numbers and were removed']);
                            end
                        catch
                            for indexevent = 1:length(EEG.event)
                                if isempty( EEG.event(indexevent).epoch ) || ~isnumeric(EEG.event(indexevent).epoch) ...
                                        || EEG.event(indexevent).epoch < 1 || EEG.event(indexevent).epoch > EEG.trials
                                    removeevent = [removeevent indexevent];
                                    disp([ 'eeg_checkset warning: event ' int2str(indexevent) ' has an invalid epoch number: removed']);
                                end
                            end
                        end
                        EEG.event(removeevent) = [];
                    end
                    if isempty(EEG.event), return; end

                    % Duration set to 0 if empty
                    % --------------------------
                    if isfield(EEG.event, 'duration')
                        emptyDur = cellfun(@isempty, { EEG.event.duration });
                        if any(emptyDur)
                            for indexevent = find(emptyDur)
                                EEG.event(indexevent).duration = 0;
                            end
                        end
                    end

                    % uniformize fields (str or int) if necessary
                    % -------------------------------------------
                    fnames = fieldnames(EEG.event);
                    for fidx = 1:length(fnames)
                        fname = fnames{fidx};
                        if ~strcmpi(fname, 'mffkeys') && ~strcmpi(fname, 'mffkeysbackup')
                            tmpevent  = EEG.event;
                            allvalues = { tmpevent.(fname) };
                            try
                                % find indices of numeric values among values of this event property
                                valreal = ~cellfun('isclass', allvalues, 'char');
                            catch
                                valreal = mycellfun('isclass', allvalues, 'double');
                            end

                            format = 'ok';
                            if ~all(valreal) % all valreal ok
                                format = 'str';
                                if all(valreal == 0) % all valreal=0 ok
                                    format = 'ok';
                                end
                            end
                            if strcmp(format, 'str')
                                fprintf('eeg_checkset note: event field format ''%s'' made uniform\n', fname);
                                allvalues = cellfun(@num2str, allvalues, 'uniformoutput', false);
                                [EEG.event(valreal).(fname)] = deal(allvalues{find(valreal)});
                            end
                        end
                    end

                    % check boundary events
                    % ---------------------
                    tmpevent = EEG.event;
                    if isfield(tmpevent, 'type') && ~isnumeric(tmpevent(1).type)
                        allEventTypes = { tmpevent.type };
                        boundsInd = strmatch('boundary', allEventTypes);
                        if ~isempty(boundsInd),
                            bounds = [ tmpevent(boundsInd).latency ];
                            % remove last event if necessary
                            if EEG.trials==1;%this if block added by James Desjardins (Jan 13th, 2014)
                                if round(bounds(end)-0.5+1) >= size(EEG.data,2), EEG.event(boundsInd(end)) = []; bounds(end) = []; end; % remove final boundary if any
                            end
                            % The first boundary below need to be kept for
                            % urevent latency calculation
                            % if bounds(1) < 0, EEG.event(bounds(1))   = []; end; % remove initial boundary if any
                            indDoublet = find(bounds(2:end)-bounds(1:end-1)==0);
                            if ~isempty(indDoublet)
                                disp('Warning: duplicate boundary event removed');
                                if isfield(EEG.event, 'duration')
                                    for indBound = 1:length(indDoublet)
                                        EEG.event(boundsInd(indDoublet(indBound)+1)).duration = EEG.event(boundsInd(indDoublet(indBound)+1)).duration+EEG.event(boundsInd(indDoublet(indBound))).duration;
                                    end
                                end
                                EEG.event(boundsInd(indDoublet)) = [];
                            end
                        end
                    end
                    if isempty(EEG.event), return; end

                    % check that numeric format is double (Matlab 7)
                    % -----------------------------------
                    allfields = fieldnames(EEG.event);
                    if ~isempty(EEG.event)
                        for index = 1:length(allfields)
                            tmpval = EEG.event(1).(allfields{index});
                            if isnumeric(tmpval) && ~isa(tmpval, 'double')
                                for indexevent = 1:length(EEG.event)
                                    tmpval  =   getfield(EEG.event, { indexevent }, allfields{index} );
                                    EEG.event = setfield(EEG.event, { indexevent }, allfields{index}, double(tmpval));
                                end
                            end
                        end
                    end

                    % check duration field, replace empty by 0
                    % ----------------------------------------
                    if isfield(EEG.event, 'duration')
                        tmpevent = EEG.event;
                        try,   valempt = cellfun('isempty'  , { tmpevent.duration });
                        catch, valempt = mycellfun('isempty', { tmpevent.duration });
                        end
                        if any(valempt),
                            for index = find(valempt)
                                EEG.event(index).duration = 0;
                            end
                        end
                    end

                    % resort events
                    % -------------
                    if isfield(EEG.event, 'latency')
                        try,
                            if isfield(EEG.event, 'epoch')
                                TMPEEG = pop_editeventvals(EEG, 'sort', { 'epoch' 0 'latency' 0 });
                            else
                                TMPEEG = pop_editeventvals(EEG, 'sort', { 'latency' 0 });
                            end
                            if ~isequal(TMPEEG.event, EEG.event)
                                EEG = TMPEEG;
                                disp('Event resorted by increasing latencies.');
                            end
                        catch,
                            disp('eeg_checkset: problem when attempting to resort event latencies.');
                        end
                    end

                    % check latency of first event
                    % ----------------------------
                    if ~isempty(EEG.event)
                        if isfield(EEG.event, 'latency')
                            if EEG.event(1).latency < 0.5
                                EEG.event(1).latency = 0.5;
                            end
                        end
                    end

                    % build epoch structure
                    % ---------------------
                    try,
                        if EEG.trials > 1 && ~isempty(EEG.event)
                            % erase existing event-related fields
                            % ------------------------------
                            if ~isfield(EEG,'epoch')
                                EEG.epoch = [];
                            end
                            if ~isempty(EEG.epoch)
                                if length(EEG.epoch) ~= EEG.trials
                                    disp('Warning: number of epoch entries does not match number of dataset trials;');
                                    disp('         user-defined epoch entries will be erased.');
                                    EEG.epoch = [];
                                else
                                    fn = fieldnames(EEG.epoch);
                                    EEG.epoch = rmfield(EEG.epoch,fn(strncmp('event',fn,5)));
                                end
                            end

                            % set event field
                            % ---------------
                            tmpevent   = EEG.event;
                            eventepoch = [tmpevent.epoch];
                            epochevent = cell(1,EEG.trials);
                            destdata = epochevent;
                            EEG.epoch(length(epochevent)).event = [];
                            for k=1:length(epochevent)
                                epochevent{k} = find(eventepoch==k);
                            end
                            tmpepoch = EEG.epoch;
                            [tmpepoch.event] = epochevent{:};
                            EEG.epoch = tmpepoch;
                            maxlen = max(cellfun(@length,epochevent));

                            % copy event information into the epoch array
                            % -------------------------------------------
                            eventfields = fieldnames(EEG.event)';
                            eventfields = eventfields(~strcmp(eventfields,'epoch'));
                            tmpevent    = EEG.event;
                            for k = 1:length(eventfields)
                                fname = eventfields{k};
                                switch fname
                                    case 'latency'
                                        sourcedata = round(eeg_point2lat([tmpevent.(fname)],[tmpevent.epoch],EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3) * 10^8 )/10^8;
                                        sourcedata = num2cell(sourcedata);
                                    case 'duration'
                                        sourcedata = num2cell([tmpevent.(fname)]/EEG.srate*1000);
                                    otherwise
                                        sourcedata = {tmpevent.(fname)};
                                end
                                if maxlen == 1
                                    destdata = cell(1,length(epochevent));
                                    destdata(~cellfun('isempty',epochevent)) = sourcedata([epochevent{:}]);
                                else
                                    for l=1:length(epochevent)
                                        destdata{l} = sourcedata(epochevent{l});
                                    end
                                end
                                tmpepoch = EEG.epoch;
                                [tmpepoch.(['event' fname])] = destdata{:};
                                EEG.epoch = tmpepoch;
                            end
                        end
                    catch,
                        errordlg2(['Warning: minor problem encountered when generating' 10 ...
                            'the EEG.epoch structure (used only in user scripts)']); return;
                    end
                case { 'loaddata' 'savedata' 'chanconsist' 'icaconsist' 'epochconsist' }, res = '';
                otherwise, error('eeg_checkset: unknown option');
            end
        end
    end

    res = [];

    % check name consistency
    % ----------------------
    if ~isempty(EEG.setname)
        if ~ischar(EEG.setname)
            EEG.setname = '';
        else
            if size(EEG.setname,1) > 1
                disp('eeg_checkset warning: invalid dataset name, removed');
                EEG.setname = '';
            end
        end
    else
        EEG.setname = '';
    end

    % checking history and convert if necessary
    % -----------------------------------------
    if isfield(EEG, 'history') && size(EEG.history,1) > 1
        allcoms = cellstr(EEG.history);
        EEG.history = deblank(allcoms{1});
        for index = 2:length(allcoms)
            EEG.history = [ EEG.history 10 deblank(allcoms{index}) ];
        end
    end

    % read data if necessary
    % ----------------------
    if ischar(EEG.data) && nargin > 1
        if strcmpi(varargin{1}, 'loaddata')

            EEG.data = eeg_getdatact(EEG);

        end
    end

    % save data if necessary
    % ----------------------
    if nargin > 1

        % datfile available?
        % ------------------
        datfile = 0;
        if isfield(EEG, 'datfile')
            if ~isempty(EEG.datfile)
                datfile = 1;
            end
        end

        % save data
        % ---------
        if strcmpi(varargin{1}, 'savedata') && option_storedisk
            error('eeg_checkset: cannot call savedata any more');

            % the code below is deprecated
            if ~ischar(EEG.data) % not already saved
                disp('Writing previous dataset to disk...');

                if datfile
                    tmpdata = reshape(EEG.data, EEG.nbchan,  EEG.pnts*EEG.trials);
                    floatwrite( tmpdata', fullfile(EEG.filepath, EEG.datfile), 'ieee-le');
                    EEG.data   = EEG.datfile;
                end
                EEG.icaact = [];

                % saving dataset
                % --------------
                filename = fullfile(EEG(1).filepath, EEG(1).filename);
                if ~ischar(EEG.data) && option_single, EEG.data = single(EEG.data); end
                v = version;
                if str2num(v(1)) >= 7, save( filename, '-v6', '-mat', 'EEG'); % Matlab 7
                else                   save( filename, '-mat', 'EEG');
                end
                if ~ischar(EEG.data), EEG.data = 'in set file'; end

                % res = sprintf('%s = eeg_checkset( %s, ''savedata'');', inputname(1), inputname(1));
                res = ['EEG = eeg_checkset( EEG, ''savedata'');'];
            end
        end
    end

    % numerical format
    % ----------------
    if isnumeric(EEG.data)
        v = version;
        EEG.icawinv    = double(EEG.icawinv); % required for dipole fitting, otherwise it crashes
        EEG.icaweights = double(EEG.icaweights);
        EEG.icasphere  = double(EEG.icasphere);
        if ~isempty(findstr(v, 'R11')) || ~isempty(findstr(v, 'R12')) || ~isempty(findstr(v, 'R13'))
            EEG.data       = double(EEG.data);
            EEG.icaact     = double(EEG.icaact);
        else
            try,
                if isa(EEG.data, 'double') && option_single
                    EEG.data       = single(EEG.data);
                    EEG.icaact     = single(EEG.icaact);
                end
            catch,
                disp('WARNING: EEGLAB ran out of memory while converting dataset to single precision.');
                disp('         Save dataset (preferably saving data to a separate file; see File > Memory options).');
                disp('         Then reload it.');
            end
        end
    end

    % verify the type of the variables
    % --------------------------------
    % data dimensions -------------------------
    if isnumeric(EEG.data) && ~isempty(EEG.data)
        if ~isequal(size(EEG.data,1), EEG.nbchan)
            disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,1)) ...
                ') does not match the number of channels (' int2str(EEG.nbchan) '): corrected' ]);
            res = com;
            EEG.nbchan = size(EEG.data,1);
        end

        if (ndims(EEG.data)) < 3 && (EEG.pnts > 1)
            if mod(size(EEG.data,2), EEG.pnts) ~= 0
                if popask( [ 'eeg_checkset error: the number of frames does not divide the number of columns in the data.'  10 ...
                        'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the command line)'])
                    error('eeg_checkset error: user abort');
                    %res = com;
                    %EEG.pnts = size(EEG.data,2);
                    %EEG = eeg_checkset(EEG);
                    %return;
                else
                    res = com;
                    return;
                    %error( 'eeg_checkset error: number of points does not divide the number of columns in data');
                end
            else
                if EEG.trials > 1
                    disp( 'eeg_checkset note: data array made 3-D');
                    res = com;
                end
                if size(EEG.data,2) ~= EEG.pnts
                    EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, size(EEG.data,2)/EEG.pnts);
                end
            end
        end

        % size of data -----------
        if size(EEG.data,3) ~= EEG.trials
            disp( ['eeg_checkset warning: 3rd dimension size of data (' int2str(size(EEG.data,3)) ...
                ') does not match the number of epochs (' int2str(EEG.trials) '), corrected' ]);
            res = com;
            EEG.trials = size(EEG.data,3);
        end
        if size(EEG.data,2) ~= EEG.pnts
            disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,2)) ...
                ') does not match the number of points (' int2str(EEG.pnts) '): corrected' ]);
            res = com;
            EEG.pnts = size(EEG.data,2);
        end
    end

    % parameters consistency
    % -------------------------
    if round(EEG.srate*(EEG.xmax-EEG.xmin)+1) ~= EEG.pnts
        fprintf( 'eeg_checkset note: upper time limit (xmax) adjusted so (xmax-xmin)*srate+1 = number of frames\n');
        if EEG.srate == 0
            EEG.srate = 1;
        end
        EEG.xmax = (EEG.pnts-1)/EEG.srate+EEG.xmin;
        res = com;
    end

    % deal with event arrays
    % ----------------------
    if ~isfield(EEG, 'event'), EEG.event = []; res = com; end
    if ~isempty(EEG.event)
        if EEG.trials > 1 && ~isfield(EEG.event, 'epoch')
            if popask( [ 'eeg_checkset error: the event info structure does not contain an ''epoch'' field.'  ...
                    'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
                error('eeg_checkset error(): user abort');
                %res = com;
                %EEG.event = [];
                %EEG = eeg_checkset(EEG);
                %return;
            else
                res = com;
                return;
                %error('eeg_checkset error: no epoch field in event structure');
            end
        end
    else
        EEG.event = [];
    end
    if isempty(EEG.event)
        EEG.eventdescription = {};
    end
    if ~isfield(EEG, 'eventdescription') || ~iscell(EEG.eventdescription)
        EEG.eventdescription = cell(1, length(fieldnames(EEG.event)));
        res = com;
    else
        if ~isempty(EEG.event)
            if length(EEG.eventdescription) > length( fieldnames(EEG.event))
                EEG.eventdescription = EEG.eventdescription(1:length( fieldnames(EEG.event)));
            elseif length(EEG.eventdescription) < length( fieldnames(EEG.event))
                EEG.eventdescription(end+1:length( fieldnames(EEG.event))) = {''};
            end
        end
    end
    % create urevent if continuous data
    % ---------------------------------
    %if ~isempty(EEG.event) && ~isfield(EEG, 'urevent')
    %    EEG.urevent = EEG.event;
    %   disp('eeg_checkset note: creating the original event table (EEG.urevent)');
    %    for index = 1:length(EEG.event)
    %        EEG.event(index).urevent = index;
    %    end
    %end
    if isfield(EEG, 'urevent') && isfield(EEG.urevent, 'urevent')
        EEG.urevent = rmfield(EEG.urevent, 'urevent');
    end

    % deal with epoch arrays
    % ----------------------
    if ~isfield(EEG, 'epoch'), EEG.epoch = []; res = com; end

    % check if only one epoch
    % -----------------------
    if EEG.trials == 1
        if isfield(EEG.event, 'epoch')
            EEG.event = rmfield(EEG.event, 'epoch'); res = com;
        end
        if ~isempty(EEG.epoch)
            EEG.epoch = []; res = com;
        end
    end

    if ~isfield(EEG, 'epochdescription'), EEG.epochdescription = {}; res = com; end
    if ~isempty(EEG.epoch)
        if isstruct(EEG.epoch),  l = length( EEG.epoch);
        else                     l = size( EEG.epoch, 2);
        end
        if l ~= EEG.trials
            if popask( [ 'eeg_checkset error: the number of epoch indices in the epoch array/struct (' ...
                    int2str(l) ') is different from the number of epochs in the data (' int2str(EEG.trials) ').' 10 ...
                    'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
                error('eeg_checkset error: user abort');
                %res = com;
                %EEG.epoch = [];
                %EEG = eeg_checkset(EEG);
                %return;
            else
                res = com;
                return;
                %error('eeg_checkset error: epoch structure size invalid');
            end
        end
    else
        EEG.epoch = [];
    end

    % check ica
    % ---------
    if ~isfield(EEG, 'icachansind')
        if isempty(EEG.icaweights)
            EEG.icachansind = []; res = com;
        else
            EEG.icachansind = [1:EEG.nbchan]; res = com;
        end
    elseif isempty(EEG.icachansind)
        if isempty(EEG.icaweights)
            EEG.icachansind = []; res = com;
        else
            EEG.icachansind = [1:EEG.nbchan]; res = com;
        end
    end
    if ~isempty(EEG.icasphere)
        if ~isempty(EEG.icaweights)
            if size(EEG.icaweights,2) ~= size(EEG.icasphere,1)
                if popask( [ 'eeg_checkset error: number of columns in weights array (' int2str(size(EEG.icaweights,2)) ')' 10 ...
                        'does not match the number of rows in the sphere array (' int2str(size(EEG.icasphere,1)) ')' 10 ...
                        'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
                    res = com;
                    EEG.icasphere = [];
                    EEG.icaweights = [];
                    EEG = eeg_checkset(EEG);
                    return;
                else
                    error('eeg_checkset error: user abort');
                    res = com;
                    return;
                    %error('eeg_checkset error: invalid weight and sphere array sizes');
                end
            end
            if isnumeric(EEG.data)
                if length(EEG.icachansind) ~= size(EEG.icasphere,2)
                    if popask( [ 'eeg_checkset error: number of elements in ''icachansind'' (' int2str(length(EEG.icachansind)) ')' 10 ...
                            'does not match the number of columns in the sphere array (' int2str(size(EEG.icasphere,2)) ')' 10 ...
                            'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
                        res = com;
                        EEG.icasphere = [];
                        EEG.icaweights = [];
                        EEG = eeg_checkset(EEG);
                        return;
                    else
                        error('eeg_checkset error: user abort');
                        res = com;
                        return;
                        %error('eeg_checkset error: invalid weight and sphere array sizes');
                    end
                end
                if isempty(EEG.icaact) || (size(EEG.icaact,1) ~= size(EEG.icaweights,1)) || (size(EEG.icaact,2) ~= size(EEG.data,2))
                    EEG.icaweights = double(EEG.icaweights);
                    EEG.icawinv = double(EEG.icawinv);

                    % scale ICA components to RMS microvolt
                    if option_scaleicarms
                        if ~isempty(EEG.icawinv)
                            if mean(mean(abs(pinv(EEG.icaweights * EEG.icasphere)-EEG.icawinv))) < 0.0001
                                disp('Scaling components to RMS microvolt');
                                scaling = repmat(sqrt(mean(EEG(1).icawinv(:,:).^2))', [1 size(EEG.icaweights,2)]);
                                EEG.etc.icaweights_beforerms = EEG.icaweights;
                                EEG.etc.icasphere_beforerms = EEG.icasphere;

                                EEG.icaweights = EEG.icaweights .* scaling;
                                EEG.icawinv = pinv(EEG.icaweights * EEG.icasphere);
                            end
                        end
                    end

                    if ~isempty(EEG.data) && option_computeica
                        fprintf('eeg_checkset: recomputing the ICA activation matrix ...\n');
                        res = com;
                        % Make compatible with Matlab 7
                        if any(isnan(EEG.data(:)))
                            tmpdata = EEG.data(EEG.icachansind,:);
                            fprintf('eeg_checkset: recomputing ICA ignoring NaN indices ...\n');
                            tmpindices = find(~sum(isnan(tmpdata))); % was: tmpindices = find(~isnan(EEG.data(1,:)));
                            EEG.icaact = zeros(size(EEG.icaweights,1), size(tmpdata,2)); EEG.icaact(:) = NaN;
                            EEG.icaact(:,tmpindices) = (EEG.icaweights*EEG.icasphere)*tmpdata(:,tmpindices);
                        else
                            EEG.icaact = (EEG.icaweights*EEG.icasphere)*EEG.data(EEG.icachansind,:); % automatically does single or double
                        end
                        EEG.icaact    = reshape( EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);
                    end
                end
            end
            if isempty(EEG.icawinv)
                EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere); % a priori same result as inv
                res         = com;
            end
        else
            disp( [ 'eeg_checkset warning: weights matrix cannot be empty if sphere matrix is not, correcting ...' ]);
            res = com;
            EEG.icasphere = [];
        end
        if option_computeica
            if ~isempty(EEG.icaact) && ndims(EEG.icaact) < 3 && (EEG.trials > 1)
                disp( [ 'eeg_checkset note: independent component made 3-D' ]);
                res = com;
                EEG.icaact = reshape(EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);
            end
        else
            if ~isempty(EEG.icaact)
                fprintf('eeg_checkset: removing ICA activation matrix (as per edit options) ...\n');
            end
            EEG.icaact     = [];
        end
    else
        if ~isempty( EEG.icaweights ), EEG.icaweights = []; res = com; end
        if ~isempty( EEG.icawinv ),    EEG.icawinv = []; res = com; end
        if ~isempty( EEG.icaact ),     EEG.icaact = []; res = com; end
    end
    if isempty(EEG.icaact)
        EEG.icaact = [];
    end

    % -------------
    % check chanlocs
    % -------------
    if ~isfield(EEG, 'chaninfo')
        EEG.chaninfo = [];
    end
    if ~isempty( EEG.chanlocs )

        % reference (use EEG structure)
        % ---------
        if ~isfield(EEG, 'ref'), EEG.ref = ''; end
        if strcmpi(EEG.ref, 'averef')
            ref = 'average';
        else ref = '';
        end
        if ~isfield( EEG.chanlocs, 'ref')
            EEG.chanlocs(1).ref = ref;
        end
        charrefs = cellfun('isclass',{EEG.chanlocs.ref},'char');
        if any(charrefs) ref = ''; end
        for tmpind = find(~charrefs)
            EEG.chanlocs(tmpind).ref = ref;
        end
        if ~isstruct( EEG.chanlocs)
            if exist( EEG.chanlocs ) ~= 2
                disp( [ 'eeg_checkset warning: channel file does not exist or is not in Matlab path: filename removed from EEG struct' ]);
                EEG.chanlocs = [];
                res = com;
            else
                res = com;
                try, EEG.chanlocs = readlocs( EEG.chanlocs );
                    disp( [ 'eeg_checkset: channel file read' ]);
                catch, EEG.chanlocs = []; end
            end
        else
            if ~isfield(EEG.chanlocs,'labels')
                disp('eeg_checkset warning: no field label in channel location structure, removing it');
                EEG.chanlocs = [];
                res = com;
            end
        end
        if isstruct( EEG.chanlocs)
            if length( EEG.chanlocs) ~= EEG.nbchan && length( EEG.chanlocs) ~= EEG.nbchan+1 && ~isempty(EEG.data)
                disp( [ 'eeg_checkset warning: number of channels different in data and channel file/struct: channel file/struct removed' ]);
                EEG.chanlocs = [];
                res = com;
            end
        end

        % force Nosedir to +X (done here because of DIPFIT)
        % -------------------
        if isfield(EEG.chaninfo, 'nosedir')
            if ~strcmpi(EEG.chaninfo.nosedir, '+x') && all(isfield(EEG.chanlocs,{'X','Y','theta','sph_theta'}))
                disp(['Note for expert users: Nose direction is now set from ''' upper(EEG.chaninfo.nosedir)  ''' to default +X in EEG.chanlocs']);
                [tmp chaninfo chans] = eeg_checkchanlocs(EEG.chanlocs, EEG.chaninfo); % Merge all channels for rotation (FID and data channels)
                if strcmpi(chaninfo.nosedir, '+y')
                    rotate = 270;
                elseif strcmpi(chaninfo.nosedir, '-x')
                    rotate = 180;
                else
                    rotate = 90;
                end
                for index = 1:length(chans)
                    rotategrad = rotate/180*pi;
                    coord = (chans(index).Y + chans(index).X*sqrt(-1))*exp(sqrt(-1)*-rotategrad);
                    chans(index).Y = real(coord);
                    chans(index).X = imag(coord);

                    if ~isempty(chans(index).theta)
                        chans(index).theta     = chans(index).theta    -rotate;
                        chans(index).sph_theta = chans(index).sph_theta+rotate;
                        if chans(index).theta    <-180, chans(index).theta    =chans(index).theta    +360; end
                        if chans(index).sph_theta>180 , chans(index).sph_theta=chans(index).sph_theta-360; end
                    end
                end

                if isfield(EEG, 'dipfit')
                    if isfield(EEG.dipfit, 'coord_transform')
                        if isempty(EEG.dipfit.coord_transform)
                            EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
                        end
                        EEG.dipfit.coord_transform(6) = EEG.dipfit.coord_transform(6)+rotategrad;
                    end
                end

                chaninfo.nosedir = '+X';
                [EEG.chanlocs EEG.chaninfo] = eeg_checkchanlocs(chans, chaninfo); % Update FID in chaninfo and remove them from chanlocs
            end;
        end

        % general checking of channels
        % ----------------------------
        EEG = eeg_checkchanlocs(EEG);
        if EEG.nbchan ~= length(EEG.chanlocs)
            EEG.chanlocs = [];
            EEG.chaninfo = [];
            disp('Warning: the size of the channel location structure does not match with');
            disp('         number of channels. Channel information have been removed.');
        end
    end
    EEG.chaninfo.icachansind = EEG.icachansind; % just a copy for programming convinience

    %if ~isfield(EEG, 'urchanlocs')
    %    EEG.urchanlocs = EEG.chanlocs;
    %    for index = 1:length(EEG.chanlocs)
    %        EEG.chanlocs(index).urchan = index;
    %    end
    %    disp('eeg_checkset note: creating backup chanlocs structure (urchanlocs)');
    %end

    % Field 'datachan in 'urchanlocs' is removed, if exist
    if isfield(EEG, 'urchanlocs') && ~isempty(EEG.urchanlocs) && isfield(EEG.urchanlocs, 'datachan')
        EEG.urchanlocs = rmfield(EEG.urchanlocs, 'datachan');
    end

    % check reference
    % ---------------
    if ~isfield(EEG, 'ref')
        EEG.ref = 'common';
    end
    if ischar(EEG.ref) && strcmpi(EEG.ref, 'common')
        if length(EEG.chanlocs) > EEG.nbchan
            disp('Extra common reference electrode location detected');
            EEG.ref = EEG.nbchan+1;
        end
    end

    % DIPFIT structure
    % ----------------
    if ~isfield(EEG,'dipfit') || isempty(EEG.dipfit)
        EEG.dipfit = []; res = com;
    else
        try
            % check if dipfitdefs is present
            dipfitdefs;
	        if isfield(EEG.dipfit, 'vol') && ~isfield(EEG.dipfit, 'hdmfile')
		        if exist('pop_dipfit_settings')
		            disp('Old DIPFIT structure detected: converting to DIPFIT 2 format');
		            EEG.dipfit.hdmfile     = template_models(1).hdmfile;
		            EEG.dipfit.coordformat = template_models(1).coordformat;
		            EEG.dipfit.mrifile     = template_models(1).mrifile;
		            EEG.dipfit.chanfile    = template_models(1).chanfile;
		            EEG.dipfit.coord_transform = [];
		            EEG.saved = 'no';
		            res = com;
		        end
		    end
		    if isfield(EEG.dipfit, 'hdmfile')
		        if length(EEG.dipfit.hdmfile) > 8
		            if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(1).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(1).hdmfile; end
		            if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(2).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(2).hdmfile; end
		        end
		        if length(EEG.dipfit.mrifile) > 8
		            if strcmpi(EEG.dipfit.mrifile(end-8), template_models(1).mrifile(end-8)), EEG.dipfit.mrifile = template_models(1).mrifile; end
		            if strcmpi(EEG.dipfit.mrifile(end-8), template_models(2).mrifile(end-8)), EEG.dipfit.mrifile = template_models(2).mrifile; end
		        end
		        if length(EEG.dipfit.chanfile) > 8
		            if strcmpi(EEG.dipfit.chanfile(end-8), template_models(1).chanfile(end-8)), EEG.dipfit.chanfile = template_models(1).chanfile; end
		            if strcmpi(EEG.dipfit.chanfile(end-8), template_models(2).chanfile(end-8)), EEG.dipfit.chanfile = template_models(2).chanfile; end
		        end
		    end

		    if isfield(EEG.dipfit, 'coord_transform')
		        if isempty(EEG.dipfit.coord_transform)
		            EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
		        end
	    	elseif ~isempty(EEG.dipfit)
	    	    EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
		    end
        catch
            e = lasterror;
            if ~strcmp(e.identifier,'MATLAB:UndefinedFunction')
                % if we got some error aside from dipfitdefs not being present, rethrow it
                rethrow(e);
            end
        end
    end

    % check events (fast)
    % ------------
    if isfield(EEG.event, 'type')
        tmpevent = EEG.event(1:min(length(EEG.event), 100));
        if ~all(cellfun(@ischar, { tmpevent.type })) && ~all(cellfun(@isnumeric, { tmpevent.type }))
            disp('Warning: converting all event types to strings');
            for ind = 1:length(EEG.event)
                EEG.event(ind).type = num2str(EEG.event(ind).type);
            end
            EEG = eeg_checkset(EEG, 'eventconsistency');
        end
    end

    % EEG.times (only for epoched datasets)
    % ---------
    if ~isfield(EEG, 'times') || isempty(EEG.times) || length(EEG.times) ~= EEG.pnts
        EEG.times = linspace(EEG.xmin*1000, EEG.xmax*1000, EEG.pnts);
    end

    if ~isfield(EEG, 'history')    EEG.history    = ''; res = com; end
    if ~isfield(EEG, 'splinefile') EEG.splinefile = ''; res = com; end
    if ~isfield(EEG, 'icasplinefile') EEG.icasplinefile = ''; res = com; end
    if ~isfield(EEG, 'saved')      EEG.saved      = 'no'; res = com; end
    if ~isfield(EEG, 'subject')    EEG.subject    = ''; res = com; end
    if ~isfield(EEG, 'condition')  EEG.condition  = ''; res = com; end
    if ~isfield(EEG, 'group')      EEG.group      = ''; res = com; end
    if ~isfield(EEG, 'run')        EEG.run        = []; res = com; end
    if ~isfield(EEG, 'session')    EEG.session    = []; res = com; end
    if ~isfield(EEG, 'urchanlocs') EEG.urchanlocs = []; res = com; end
    if ~isfield(EEG, 'specdata')   EEG.specdata   = []; res = com; end
    if ~isfield(EEG, 'specicaact') EEG.specicaact = []; res = com; end
    if ~isfield(EEG, 'comments')   EEG.comments   = ''; res = com; end
    if ~isfield(EEG, 'etc'     )   EEG.etc        = []; res = com; end
    if ~isfield(EEG, 'urevent' )   EEG.urevent    = []; res = com; end
    if ~isfield(EEG, 'ref') || isempty(EEG.ref) EEG.ref = 'common'; res = com; end

    % create fields if absent
    % -----------------------
    if ~isfield(EEG, 'reject')                    EEG.reject.rejjp = []; res = com; end

    listf = { 'rejjp' 'rejkurt' 'rejmanual' 'rejthresh' 'rejconst', 'rejfreq' ...
        'icarejjp' 'icarejkurt' 'icarejmanual' 'icarejthresh' 'icarejconst', 'icarejfreq'};
    for index = 1:length(listf)
        name = listf{index};
        elecfield = [name 'E'];
        if ~isfield(EEG.reject, elecfield),     EEG.reject.(elecfield) = []; res = com; end
        if ~isfield(EEG.reject, name)
            EEG.reject.(name) = [];
            res = com;
        elseif ~isempty(EEG.reject.(name)) && isempty(EEG.reject.(elecfield))
            % check if electrode array is empty with rejection array is not
            nbchan = fastif(strcmp(name, 'ica'), size(EEG.icaweights,1), EEG.nbchan);
            EEG.reject = setfield(EEG.reject, elecfield, zeros(nbchan, length(getfield(EEG.reject, name)))); res = com;
        end
    end
    if ~isfield(EEG.reject, 'rejglobal')        EEG.reject.rejglobal  = []; res = com; end
    if ~isfield(EEG.reject, 'rejglobalE')       EEG.reject.rejglobalE = []; res = com; end

    % track version of EEGLAB
    % -----------------------
    tmpvers = eeg_getversion;
    if ~isfield(EEG.etc, 'eeglabvers') || ~isequal(EEG.etc.eeglabvers, tmpvers)
        EEG.etc.eeglabvers = tmpvers;
        EEG = eeg_hist( EEG, ['EEG.etc.eeglabvers = ''' tmpvers '''; % this tracks which version of EEGLAB is being used, you may ignore it'] );
        res = com;
    end

    % default colors for rejection
    % ----------------------------
    if ~isfield(EEG.reject, 'rejmanualcol')   EEG.reject.rejmanualcol = [1.0000    1     0.783]; res = com; end
    if ~isfield(EEG.reject, 'rejthreshcol')   EEG.reject.rejthreshcol = [0.8487    1.0000    0.5008]; res = com; end
    if ~isfield(EEG.reject, 'rejconstcol')    EEG.reject.rejconstcol  = [0.6940    1.0000    0.7008]; res = com; end
    if ~isfield(EEG.reject, 'rejjpcol')       EEG.reject.rejjpcol     = [1.0000    0.6991    0.7537]; res = com; end
    if ~isfield(EEG.reject, 'rejkurtcol')     EEG.reject.rejkurtcol   = [0.6880    0.7042    1.0000]; res = com; end
    if ~isfield(EEG.reject, 'rejfreqcol')     EEG.reject.rejfreqcol   = [0.9596    0.7193    1.0000]; res = com; end
    if ~isfield(EEG.reject, 'disprej')        EEG.reject.disprej      = { }; end

    if ~isfield(EEG, 'stats')           EEG.stats.jp = []; res = com; end
    if ~isfield(EEG.stats, 'jp')        EEG.stats.jp = []; res = com; end
    if ~isfield(EEG.stats, 'jpE')       EEG.stats.jpE = []; res = com; end
    if ~isfield(EEG.stats, 'icajp')     EEG.stats.icajp = []; res = com; end
    if ~isfield(EEG.stats, 'icajpE')    EEG.stats.icajpE = []; res = com; end
    if ~isfield(EEG.stats, 'kurt')      EEG.stats.kurt = []; res = com; end
    if ~isfield(EEG.stats, 'kurtE')     EEG.stats.kurtE = []; res = com; end
    if ~isfield(EEG.stats, 'icakurt')   EEG.stats.icakurt = []; res = com; end
    if ~isfield(EEG.stats, 'icakurtE')  EEG.stats.icakurtE = []; res = com; end

    % component rejection
    % -------------------
    if ~isfield(EEG.stats, 'compenta')        EEG.stats.compenta = []; res = com; end
    if ~isfield(EEG.stats, 'compentr')        EEG.stats.compentr = []; res = com; end
    if ~isfield(EEG.stats, 'compkurta')       EEG.stats.compkurta = []; res = com; end
    if ~isfield(EEG.stats, 'compkurtr')       EEG.stats.compkurtr = []; res = com; end
    if ~isfield(EEG.stats, 'compkurtdist')    EEG.stats.compkurtdist = []; res = com; end
    if ~isfield(EEG.reject, 'threshold')      EEG.reject.threshold = [0.8 0.8 0.8]; res = com; end
    if ~isfield(EEG.reject, 'threshentropy')  EEG.reject.threshentropy = 600; res = com; end
    if ~isfield(EEG.reject, 'threshkurtact')  EEG.reject.threshkurtact = 600; res = com; end
    if ~isfield(EEG.reject, 'threshkurtdist') EEG.reject.threshkurtdist = 600; res = com; end
    if ~isfield(EEG.reject, 'gcompreject')    EEG.reject.gcompreject = []; res = com; end
    if length(EEG.reject.gcompreject) ~= size(EEG.icaweights,1)
        EEG.reject.gcompreject = zeros(1, size(EEG.icaweights,1));
    end

    % remove old fields
    % -----------------
    if isfield(EEG, 'averef'), EEG = rmfield(EEG, 'averef'); end
    if isfield(EEG, 'rt'    ), EEG = rmfield(EEG, 'rt');     end

    % store in new structure
    % ----------------------
    if isstruct(EEG)
        if ~exist('ALLEEGNEW','var')
            ALLEEGNEW = EEG;
        else
            ALLEEGNEW(inddataset) = EEG;
        end
    end
end

% recorder fields
% ---------------
fieldorder = { 'setname' ...
    'filename' ...
    'filepath' ...
    'subject' ...
    'group' ...
    'condition' ...
    'session' ...
    'comments' ...
    'nbchan' ...
    'trials' ...
    'pnts' ...
    'srate' ...
    'xmin' ...
    'xmax' ...
    'times' ...
    'data' ...
    'icaact' ...
    'icawinv' ...
    'icasphere' ...
    'icaweights' ...
    'icachansind' ...
    'chanlocs' ...
    'urchanlocs' ...
    'chaninfo' ...
    'ref' ...
    'event' ...
    'urevent' ...
    'eventdescription' ...
    'epoch' ...
    'epochdescription' ...
    'reject' ...
    'stats' ...
    'specdata' ...
    'specicaact' ...
    'splinefile' ...
    'icasplinefile' ...
    'dipfit' ...
    'history' ...
    'saved' ...
    'etc' };

for fcell = fieldnames(EEG)'
    fname = fcell{1};
    if ~any(strcmp(fieldorder,fname))
        fieldorder{end+1} = fname;
    end
end

try
    ALLEEGNEW = orderfields(ALLEEGNEW, fieldorder);
    EEG = ALLEEGNEW;
catch
    disp('Couldn''t order data set fields properly.');
end

if exist('ALLEEGNEW','var')
    EEG = ALLEEGNEW;
end

if ~isa(EEG, 'eegobj') && option_eegobject
    EEG = eegobj(EEG);
end

return;

function num = popask( text )
ButtonName=questdlg2( text, ...
    'Confirmation', 'Cancel', 'Yes','Yes');
switch lower(ButtonName),
    case 'cancel', num = 0;
    case 'yes',    num = 1;
end

function res = mycellfun(com, vals, classtype);
res = zeros(1, length(vals));
switch com
    case 'isempty',
        for index = 1:length(vals), res(index) = isempty(vals{index}); end
    case 'isclass'
        if strcmp(classtype, 'double')
            for index = 1:length(vals), res(index) = isnumeric(vals{index}); end
        else
            error('unknown cellfun command');
        end
    otherwise error('unknown cellfun command');
end


function outstr = GE_dumpImageHeader(img)
%
% outstr = GE_dumpImageHeader(img)
%
% Writes the image header to the string outstr
%
% Souheil J. Inati
% Dartmouth College
% May 2000
% souheil.inati@dartmouth.edu
%

outstr = sprintf('im_suid: %s\n',         char(img.im_suid));
outstr  = strcat(outstr, sprintf('im_uniq: %d\n',         img.im_uniq));
outstr  = strcat(outstr, sprintf('im_diskid: %s\n',       char(img.im_diskid)));
outstr  = strcat(outstr, sprintf('im_exno: %d\n',         img.im_exno));
outstr  = strcat(outstr, sprintf('im_seno: %d\n',         img.im_seno));
outstr  = strcat(outstr, sprintf('im_no: %d\n',           img.im_no));
outstr  = strcat(outstr, sprintf('im_datetime: %d\n',     img.im_datetime));
outstr  = strcat(outstr, sprintf('im_actual_dt: %d\n',    img.im_actual_dt));
outstr  = strcat(outstr, sprintf('sctime: %f\n',          img.sctime));
outstr  = strcat(outstr, sprintf('slthick: %f\n',         img.slthick));
outstr  = strcat(outstr, sprintf('imatrix_X: %d\n',       img.imatrix_X));
outstr  = strcat(outstr, sprintf('imatrix_Y: %d\n',       img.imatrix_Y));
outstr  = strcat(outstr, sprintf('dfov: %f\n',            img.dfov));
outstr  = strcat(outstr, sprintf('dfov_rect: %f\n',       img.dfov_rect));
outstr  = strcat(outstr, sprintf('dim_X: %f\n',           img.dim_X));
outstr  = strcat(outstr, sprintf('dim_Y: %f\n',           img.dim_Y));
outstr  = strcat(outstr, sprintf('pixsize_X: %f\n',       img.pixsize_X));
outstr  = strcat(outstr, sprintf('pixsize_Y: %f\n',       img.pixsize_Y));
outstr  = strcat(outstr, sprintf('pdid: %s\n',            sprintf('%s',img.pdid)));
outstr  = strcat(outstr, sprintf('contrastIV: %s\n',      cstring(img.contrastIV)));
outstr  = strcat(outstr, sprintf('contrastOral: %s\n',    cstring(img.contrastOral)));
outstr  = strcat(outstr, sprintf('contmode: %d\n',        img.contmode));
outstr  = strcat(outstr, sprintf('serrx: %d\n',           img.serrx));
outstr  = strcat(outstr, sprintf('imgrx: %d\n',           img.imgrx));
outstr  = strcat(outstr, sprintf('screenformat: %d\n',    img.screenformat));
outstr  = strcat(outstr, sprintf('plane: %d\n',           img.plane));
outstr  = strcat(outstr, sprintf('scanspacing: %f\n',     img.scanspacing));
outstr  = strcat(outstr, sprintf('im_compress: %d\n',     img.im_compress));
outstr  = strcat(outstr, sprintf('im_scouttype: %d\n',    img.im_scouttype));
outstr  = strcat(outstr, sprintf('loc_ras: %s\n',         char(img.loc_ras)));
outstr  = strcat(outstr, sprintf('loc: %f\n',          img.loc));
outstr  = strcat(outstr, sprintf('ctr_R: %f\n',        img.ctr_R));
outstr  = strcat(outstr, sprintf('ctr_A: %f\n',        img.ctr_A));
outstr  = strcat(outstr, sprintf('ctr_S: %f\n',        img.ctr_S));
outstr  = strcat(outstr, sprintf('norm_R: %f\n',       img.norm_R));
outstr  = strcat(outstr, sprintf('norm_A: %f\n',       img.norm_A));
outstr  = strcat(outstr, sprintf('norm_S: %f\n',       img.norm_S));
outstr  = strcat(outstr, sprintf('tlhc_R: %f\n',       img.tlhc_R));
outstr  = strcat(outstr, sprintf('tlhc_A: %f\n',       img.tlhc_A));
outstr  = strcat(outstr, sprintf('tlhc_S: %f\n',       img.tlhc_S));
outstr  = strcat(outstr, sprintf('trhc_R: %f\n',       img.trhc_R));
outstr  = strcat(outstr, sprintf('trhc_A: %f\n',       img.trhc_A));
outstr  = strcat(outstr, sprintf('trhc_S: %f\n',       img.trhc_S));
outstr  = strcat(outstr, sprintf('brhc_R: %f\n',       img.brhc_R));
outstr  = strcat(outstr, sprintf('brhc_A: %f\n',       img.brhc_A));
outstr  = strcat(outstr, sprintf('brhc_S: %f\n',       img.brhc_S));
outstr  = strcat(outstr, sprintf('forimgrev: %s\n',    char(img.forimgrev)));
outstr  = strcat(outstr, sprintf('tr: %d\n',           img.tr));
outstr  = strcat(outstr, sprintf('ti: %d\n',           img.ti));
outstr  = strcat(outstr, sprintf('te: %d\n',           img.te));
outstr  = strcat(outstr, sprintf('te2: %d\n',          img.te2));
outstr  = strcat(outstr, sprintf('numecho: %d\n',      img.numecho));
outstr  = strcat(outstr, sprintf('echonum: %d\n',      img.echonum));
outstr  = strcat(outstr, sprintf('tbldlta: %f\n',      img.tbldlta));
outstr  = strcat(outstr, sprintf('nex: %f\n',          img.nex));
outstr  = strcat(outstr, sprintf('contig: %d\n',       img.contig));
outstr  = strcat(outstr, sprintf('hrtrate: %d\n',      img.hrtrate));
outstr  = strcat(outstr, sprintf('tdel: %d\n',         img.tdel));
outstr  = strcat(outstr, sprintf('saravg: %f\n',       img.saravg));
outstr  = strcat(outstr, sprintf('sarpeak: %f\n',      img.sarpeak));
outstr  = strcat(outstr, sprintf('monsar: %d\n',          img.monsar));
outstr  = strcat(outstr, sprintf('trgwindow: %d\n',       img.trgwindow));
outstr  = strcat(outstr, sprintf('reptime: %f\n',         img.reptime));
outstr  = strcat(outstr, sprintf('imgpcyc: %d\n',         img.imgpcyc));
outstr  = strcat(outstr, sprintf('xmtgain: %d\n',         img.xmtgain));
outstr  = strcat(outstr, sprintf('rcvgain1: %d\n',        img.rcvgain1));
outstr  = strcat(outstr, sprintf('rcvgain2: %d\n',        img.rcvgain2));
outstr  = strcat(outstr, sprintf('mr_flip: %d\n',         img.mr_flip));
outstr  = strcat(outstr, sprintf('mindat: %d\n',          img.mindat));
outstr  = strcat(outstr, sprintf('cphase: %d\n',          img.cphase));
outstr  = strcat(outstr, sprintf('swappf: %d\n',          img.swappf));
outstr  = strcat(outstr, sprintf('pauseint: %d\n',        img.pauseint));
outstr  = strcat(outstr, sprintf('pausetime: %f\n',       img.pausetime));
outstr  = strcat(outstr, sprintf('obplane: %d\n',         img.obplane));
outstr  = strcat(outstr, sprintf('slocfov: %d\n',         img.slocfov));
outstr  = strcat(outstr, sprintf('xmtfreq: %d\n',         img.xmtfreq));
outstr  = strcat(outstr, sprintf('autoxmtfreq: %d\n',     img.autoxmtfreq));
outstr  = strcat(outstr, sprintf('autoxmtgain: %d\n',     img.autoxmtgain));
outstr  = strcat(outstr, sprintf('prescan_r1: %d\n',      img.prescan_r1));
outstr  = strcat(outstr, sprintf('prescan_r2: %d\n',      img.prescan_r2));
outstr  = strcat(outstr, sprintf('user_bitmap: %d\n',     img.user_bitmap));
outstr  = strcat(outstr, sprintf('cenfreq: %d\n',         img.cenfreq));
outstr  = strcat(outstr, sprintf('imode: %d\n',           img.imode));
outstr  = strcat(outstr, sprintf('iopt: %d\n',            img.iopt));
outstr  = strcat(outstr, sprintf('pseq: %d\n',            img.pseq));
outstr  = strcat(outstr, sprintf('pseqmode: %d\n',        img.pseqmode));
outstr  = strcat(outstr, sprintf('psdname: %s\n',         cstring(img.psdname)));
outstr  = strcat(outstr, sprintf('psd_datetime: %d\n',    img.psd_datetime));
outstr  = strcat(outstr, sprintf('psd_iname: %s\n',       cstring(img.psd_iname)));
outstr  = strcat(outstr, sprintf('ctyp: %d\n',            img.ctyp));
outstr  = strcat(outstr, sprintf('cname: %s\n',         cstring(img.cname)));
outstr  = strcat(outstr, sprintf('surfctyp: %d\n',      img.surfctyp));
outstr  = strcat(outstr, sprintf('surfcext: %d\n',      img.surfcext));
outstr  = strcat(outstr, sprintf('rawrunnum: %d\n',     img.rawrunnum));
outstr  = strcat(outstr, sprintf('cal_fldstr: %d\n',    img.cal_fldstr));
outstr  = strcat(outstr, sprintf('supp_tech: %d\n',     img.supp_tech));
outstr  = strcat(outstr, sprintf('vbw: %f\n',           img.vbw));
outstr  = strcat(outstr, sprintf('slquant: %d\n',       img.slquant));
outstr  = strcat(outstr, sprintf('gpre: %d\n',          img.gpre));
outstr  = strcat(outstr, sprintf('intr_del: %d\n',      img.intr_del));
outstr  = strcat(outstr, sprintf('user0: %f\n',         img.user0));
outstr  = strcat(outstr, sprintf('user1: %f\n',         img.user1));
outstr  = strcat(outstr, sprintf('user2: %f\n',         img.user2));
outstr  = strcat(outstr, sprintf('user3: %f\n',         img.user3));
outstr  = strcat(outstr, sprintf('user4: %f\n',         img.user4));
outstr  = strcat(outstr, sprintf('user5: %f\n',         img.user5));
outstr  = strcat(outstr, sprintf('user6: %f\n',         img.user6));
outstr  = strcat(outstr, sprintf('user7: %f\n',         img.user7));
outstr  = strcat(outstr, sprintf('user8: %f\n',         img.user8));
outstr  = strcat(outstr, sprintf('user9: %f\n',         img.user9));
outstr  = strcat(outstr, sprintf('user10: %f\n',        img.user10));
outstr  = strcat(outstr, sprintf('user11: %f\n',        img.user11));
outstr  = strcat(outstr, sprintf('user12: %f\n',        img.user12));
outstr  = strcat(outstr, sprintf('user13: %f\n',        img.user13));
outstr  = strcat(outstr, sprintf('user14: %f\n',        img.user14));
outstr  = strcat(outstr, sprintf('user15: %f\n',        img.user15));
outstr  = strcat(outstr, sprintf('user16: %f\n',        img.user16));
outstr  = strcat(outstr, sprintf('user17: %f\n',        img.user17));
outstr  = strcat(outstr, sprintf('user18: %f\n',        img.user18));
outstr  = strcat(outstr, sprintf('user19: %f\n',        img.user19));
outstr  = strcat(outstr, sprintf('user20: %f\n',          img.user20));
outstr  = strcat(outstr, sprintf('user21: %f\n',          img.user21));
outstr  = strcat(outstr, sprintf('user22: %f\n',          img.user22));
outstr  = strcat(outstr, sprintf('user23: %f\n',          img.user23));
outstr  = strcat(outstr, sprintf('user24: %f\n',          img.user24));
outstr  = strcat(outstr, sprintf('im_alloc_key: %s\n',    sprintf('%s',img.im_alloc_key)));
outstr  = strcat(outstr, sprintf('im_lastmod: %d\n',      img.im_lastmod));
outstr  = strcat(outstr, sprintf('im_verscre: %s\n',      char(img.im_verscre)));
outstr  = strcat(outstr, sprintf('im_verscur: %s\n',      char(img.im_verscur)));
outstr  = strcat(outstr, sprintf('im_pds_a: %d\n',        img.im_pds_a));
outstr  = strcat(outstr, sprintf('im_pds_c: %d\n',        img.im_pds_c));
outstr  = strcat(outstr, sprintf('im_pds_u: %d\n',        img.im_pds_u));
outstr  = strcat(outstr, sprintf('im_checksum: %d\n',     img.im_checksum));
outstr  = strcat(outstr, sprintf('im_archived: %d\n',     img.im_archived));
outstr  = strcat(outstr, sprintf('im_complete: %d\n',     img.im_complete));
outstr  = strcat(outstr, sprintf('satbits: %d\n',         img.satbits));
outstr  = strcat(outstr, sprintf('scic: %d\n',            img.scic));
outstr  = strcat(outstr, sprintf('satxloc1: %d\n',        img.satxloc1));
outstr  = strcat(outstr, sprintf('satxloc2: %d\n',        img.satxloc2));
outstr  = strcat(outstr, sprintf('satyloc1: %d\n',        img.satyloc1));
outstr  = strcat(outstr, sprintf('satyloc2: %d\n',        img.satyloc2));
outstr  = strcat(outstr, sprintf('satzloc1: %d\n',        img.satzloc1));
outstr  = strcat(outstr, sprintf('satzloc2: %d\n',        img.satzloc2));
outstr  = strcat(outstr, sprintf('satxthick: %d\n',       img.satxthick));
outstr  = strcat(outstr, sprintf('satythick: %d\n',       img.satythick));
outstr  = strcat(outstr, sprintf('satzthick: %d\n',       img.satzthick));
outstr  = strcat(outstr, sprintf('flax: %d\n',            img.flax));
outstr  = strcat(outstr, sprintf('venc: %d\n',            img.venc));
outstr  = strcat(outstr, sprintf('thk_disclmr: %d\n',     img.thk_disclmr));
outstr  = strcat(outstr, sprintf('ps_flag: %d\n',         img.ps_flag));
outstr  = strcat(outstr, sprintf('ps_status: %d\n',       img.ps_status));
outstr  = strcat(outstr, sprintf('image_type: %d\n',      img.image_type));
outstr  = strcat(outstr, sprintf('vas_collapse: %d\n',    img.vas_collapse));
outstr  = strcat(outstr, sprintf('user23n: %f\n',         img.user23n));
outstr  = strcat(outstr, sprintf('user24n: %f\n',         img.user24n));
outstr  = strcat(outstr, sprintf('proj_alg: %d\n',        img.proj_alg));
outstr  = strcat(outstr, sprintf('proj_name: %s\n',       cstring(img.proj_name)));
outstr  = strcat(outstr, sprintf('x_axis_rot: %f\n',      img.x_axis_rot));
outstr  = strcat(outstr, sprintf('y_axis_rot: %f\n',      img.y_axis_rot));
outstr  = strcat(outstr, sprintf('z_axis_rot: %f\n',      img.z_axis_rot));
outstr  = strcat(outstr, sprintf('thresh_min1: %d\n',     img.thresh_min1));
outstr  = strcat(outstr, sprintf('thresh_max1: %d\n',     img.thresh_max1));
outstr  = strcat(outstr, sprintf('thresh_min2: %d\n',     img.thresh_min2));
outstr  = strcat(outstr, sprintf('thresh_max2: %d\n',     img.thresh_max2));
outstr  = strcat(outstr, sprintf('echo_trn_len: %d\n',    img.echo_trn_len));
outstr  = strcat(outstr, sprintf('frac_echo: %d\n',       img.frac_echo));
outstr  = strcat(outstr, sprintf('prep_pulse: %d\n',      img.prep_pulse));
outstr  = strcat(outstr, sprintf('cphasenum: %d\n',       img.cphasenum));
outstr  = strcat(outstr, sprintf('var_echo: %d\n',        img.var_echo));
outstr  = strcat(outstr, sprintf('ref_img: %s\n',         char(img.ref_img)));
outstr  = strcat(outstr, sprintf('sum_img: %s\n',         char(img.sum_img)));
outstr  = strcat(outstr, sprintf('img_window: %d\n',      img.img_window));
outstr  = strcat(outstr, sprintf('img_level: %d\n',       img.img_level));
outstr  = strcat(outstr, sprintf('slop_int_1: %d\n',      img.slop_int_1));
outstr  = strcat(outstr, sprintf('slop_int_2: %d\n',      img.slop_int_2));
outstr  = strcat(outstr, sprintf('slop_int_3: %d\n',      img.slop_int_3));
outstr  = strcat(outstr, sprintf('slop_int_4: %d\n',      img.slop_int_4));
outstr  = strcat(outstr, sprintf('slop_int_5: %d\n',      img.slop_int_5));
outstr  = strcat(outstr, sprintf('slop_float_1: %f\n',    img.slop_float_1));
outstr  = strcat(outstr, sprintf('slop_float_2: %f\n',    img.slop_float_2));
outstr  = strcat(outstr, sprintf('slop_float_3: %f\n',    img.slop_float_3));
outstr  = strcat(outstr, sprintf('slop_float_4: %f\n',    img.slop_float_4));
outstr  = strcat(outstr, sprintf('slop_float_5: %f\n',    img.slop_float_5));
outstr  = strcat(outstr, sprintf('slop_str_1: %s\n',      cstring(img.slop_str_1)));
outstr  = strcat(outstr, sprintf('slop_str_2: %s\n',      cstring(img.slop_str_2)));
outstr  = strcat(outstr, sprintf('scanactno: %d\n',       img.scanactno));
outstr  = strcat(outstr, sprintf('vasflags: %d\n',        img.vasflags));
outstr  = strcat(outstr, sprintf('vencscale: %f\n',       img.vencscale));
outstr  = strcat(outstr, sprintf('integrity: %d\n',       img.integrity));
outstr  = strcat(outstr, sprintf('fphase: %d\n',          img.fphase));
outstr  = strcat(outstr, sprintf('freq_dir: %d\n',        img.freq_dir));
outstr  = strcat(outstr, sprintf('vas_mode: %d\n',        img.vas_mode));
outstr  = strcat(outstr, sprintf('image_uid: %s\n',       sprintf('%s',img.image_uid)));
outstr  = strcat(outstr, sprintf('sop_uid: %s\n',         sprintf('%s',img.sop_uid)));
outstr  = strcat(outstr, sprintf('dont_use_1: %d\n',      img.dont_use_1));
outstr  = strcat(outstr, sprintf('dont_use_2: %d\n',      img.dont_use_2));
outstr  = strcat(outstr, sprintf('dont_use_3: %d\n',      img.dont_use_3));
outstr  = strcat(outstr, sprintf('pscopts: %d\n',         img.pscopts));
outstr  = strcat(outstr, sprintf('asoffsetx: %d\n',       img.asoffsetx));
outstr  = strcat(outstr, sprintf('asoffsety: %d\n',       img.asoffsety));
outstr  = strcat(outstr, sprintf('asoffsetz: %d\n',           img.asoffsetz));
outstr  = strcat(outstr, sprintf('unoriginal: %d\n',          img.unoriginal));
outstr  = strcat(outstr, sprintf('interleaves: %d\n',         img.interleaves));
outstr  = strcat(outstr, sprintf('effechospace: %d\n',        img.effechospace));
outstr  = strcat(outstr, sprintf('viewsperseg: %d\n',         img.viewsperseg));
outstr  = strcat(outstr, sprintf('rbpm: %d\n',                img.rbpm));
outstr  = strcat(outstr, sprintf('rtpoint: %d\n',             img.rtpoint));
outstr  = strcat(outstr, sprintf('rcvrtype: %d\n',            img.rcvrtype));
outstr  = strcat(outstr, sprintf('dbdt: %f\n',                img.dbdt));
outstr  = strcat(outstr, sprintf('dbdtper: %f\n',             img.dbdtper));
outstr  = strcat(outstr, sprintf('estdbdtper: %f\n',          img.estdbdtper));
outstr  = strcat(outstr, sprintf('estdbdtts: %f\n',           img.estdbdtts));
outstr  = strcat(outstr, sprintf('saravghead: %f\n',          img.saravghead));
outstr  = strcat(outstr, sprintf('neg_scanspacing: %f\n',     img.neg_scanspacing));
outstr  = strcat(outstr, sprintf('offsetfreq: %d\n',          img.offsetfreq));
outstr  = strcat(outstr, sprintf('user_usage_tag: %d\n',      img.user_usage_tag));
outstr  = strcat(outstr, sprintf('user_fill_mapMSW: %d\n',    img.user_fill_mapMSW));
outstr  = strcat(outstr, sprintf('user_fill_mapLSW: %d\n',    img.user_fill_mapLSW));
outstr  = strcat(outstr, sprintf('user25: %f\n',              img.user25));
outstr  = strcat(outstr, sprintf('user26: %f\n',              img.user26));
outstr  = strcat(outstr, sprintf('user27: %f\n',              img.user27));
outstr  = strcat(outstr, sprintf('user28: %f\n',              img.user28));
outstr  = strcat(outstr, sprintf('user29: %f\n',              img.user29));
outstr  = strcat(outstr, sprintf('user30: %f\n',              img.user30));
outstr  = strcat(outstr, sprintf('user31: %f\n',              img.user31));
outstr  = strcat(outstr, sprintf('user32: %f\n',              img.user32));
outstr  = strcat(outstr, sprintf('user33: %f\n',              img.user33));
outstr  = strcat(outstr, sprintf('user34: %f\n',              img.user34));
outstr  = strcat(outstr, sprintf('user35: %f\n',              img.user35));
outstr  = strcat(outstr, sprintf('user36: %f\n',              img.user36));
outstr  = strcat(outstr, sprintf('user37: %f\n',              img.user37));
outstr  = strcat(outstr, sprintf('user38: %f\n',              img.user38));
outstr  = strcat(outstr, sprintf('user39: %f\n',              img.user39));
outstr  = strcat(outstr, sprintf('user40: %f\n',              img.user40));
outstr  = strcat(outstr, sprintf('user41: %f\n',              img.user41));
outstr  = strcat(outstr, sprintf('user42: %f\n',              img.user42));
outstr  = strcat(outstr, sprintf('user43: %f\n',              img.user43));
outstr  = strcat(outstr, sprintf('user44: %f\n',              img.user44));
outstr  = strcat(outstr, sprintf('user45: %f\n',              img.user45));
outstr  = strcat(outstr, sprintf('user46: %f\n',              img.user46));
outstr  = strcat(outstr, sprintf('user47: %f\n',              img.user47));
outstr  = strcat(outstr, sprintf('user48: %f\n',              img.user48));
outstr  = strcat(outstr, sprintf('slop_int_6: %d\n',          img.slop_int_6));
outstr  = strcat(outstr, sprintf('slop_int_7: %d\n',          img.slop_int_7));
outstr  = strcat(outstr, sprintf('slop_int_8: %d\n',          img.slop_int_8));
outstr  = strcat(outstr, sprintf('slop_int_9: %d\n',          img.slop_int_9));
outstr  = strcat(outstr, sprintf('mr_padding: %s\n',          cstring(img.mr_padding)));

return


function geneScoreStructure=mapCompartments(geneScoreStructure,varargin)
% mapCompartments
%   Maps compartments in the geneScoreStructure. This is used if you do not
%   want a models that uses all of the compartment from the predictor. This
%   function will then let you define rules on how the compartments should
%   be merged.
%
%   Any number of rules could be defined as consecutive strings or in a cell array.
%   'comp1'             comp1 should be kept in the structure

%   'comp1=comp2'       The scores in comp2 are merged to comp1 and comp2 is
%                       removed from the structure. This automatically
%                       keeps comp1 in the structure

%   'comp1=comp2 comp3' The scores in comp2 and comp3 are merged to comp1
%                       and comp2 & comp2 are removed from the structure.
%                       This automatically keeps comp1 in the structure

%   'comp1 comp2=comp3' The scores in comp3 are split between comp1 and
%                       comp2. This automatically keeps comp1 and comp2 in
%                       the structure

%   'comp1=other'       The scores in any compartment not included are
%                       merged to comp1. This is applied after all other
%                       rules.
%
%   When one compartment is merged to another the resulting scores will be
%   the best for each gene in either of the compartments. In the case where
%   one compartment is split among several, the scores for the compartment
%   to be merged is weighted with the number of compartments to split to.
%
%   Example: The predictor you use give prediction for Extracellular,
%   Cytosol, Nucleus, Peroxisome, Mitochondria, ER, and Lysosome. You want to
%   have a model with Extracellular, Cytosol, Mitochondria, and Peroxisome
%   where Lysosome is merged with Peroxisome and all other compartments
%   are merged to the Cytosol.
%
%   GSS=mapCompartments(GSS,'Extracellular','Mitochondria','Peroxisome=Lyso
%   some','Cytosol=other');
%
%   geneScoreStructure  a structure to be used in predictLocalization
%
%   Usage: geneScoreStructure=mapCompartments(geneScoreStructure,varargin)

varargin=upper(varargin);

%First find the compartment that will end up in the final structure. They
%are the ones that stand alone or are to the left of some '='
toKeep={};
toMerge={};
I=regexp(varargin,'=','split');
for i=1:numel(varargin)
    if numel(I{i})==1
        toKeep=[toKeep;I{i}];
    else
        J=regexp(I{i}(1),' ','split');
        K=regexp(I{i}(2),' ','split');
        toKeep=[toKeep;J{1}(:)];
        toMerge=[toMerge;K{1}(:)];
    end
end

%Check that there are no compartment that should both be merged and kept
if ~isempty(intersect(toKeep,toMerge))
    EM='There are inconsistencies where one or more compartment(s) should be both kept and merged to another';
    dispEM(EM);
end

%Check that there are no compartments in the rules that are not in the
%geneScoreStructure.
uComps=upper(geneScoreStructure.compartments);
J=[uComps;{'OTHER'}];

if ~isempty(setdiff([toKeep;toMerge],J))
    EM='There are compartment in the rules that are not in geneScoreStructure.compartments';
    dispEM(EM);
end

%Loop through it again and do the mapping
otherIndex=[]; %This stores the rule which maps 'other'.

for i=1:numel(I)
    if numel(I{i})>1
        %Get the compartment indexes that should be mapped
        J=regexp(I{i}(2),' ','split');
        if strcmpi(J{1},'other')
            otherIndex=i;
            continue;
        end
        [k, K]=ismember(J{1},uComps);

        %And to where they should be mapped
        J=regexp(I{i}(1),' ','split');
        [l, L]=ismember(J{1},uComps);

        %It's not allowed to have rules like A B=C D
        if numel(K)>1 && numel(L)>1
            EM='It is not allowed to have rules like "A B=C D" (map more than one compartment to more than one compartment)';
            dispEM(EM);
        end

        if ~all(k) || ~all(l)
            EM='Error in mapping. This most likely means that some compartment(s) are mapped to different compartments in different rules. Use A B=C if you want to map C to several compartments';
            dispEM(EM);
        end

        %Get the sum of the scores for the compartments that should be
        %merged to something else
        S=max(geneScoreStructure.scores(:,K),[],2);
        for j=1:numel(L)
            %If the scores are mapped to several different compartments
            %then split the scores between them
            geneScoreStructure.scores(:,L(j))=max(geneScoreStructure.scores(:,L(j)),S./numel(L));
        end

        %Remove the comparement that were merged
        geneScoreStructure.compartments(K)=[];
        geneScoreStructure.scores(:,K)=[];
        uComps(K)=[];
    end
end

%Then check if there are remaining compartments that should be removed or
%mapped as 'other'
J=find(~ismember(uComps,toKeep));
if any(J)
    if any(otherIndex)
        K=regexp(I{otherIndex}(1),' ','split');
        [l, L]=ismember(K{1},uComps);
        if l==1 && numel(l)==1
            S=max(geneScoreStructure.scores(:,J),[],2);
            geneScoreStructure.scores(:,L)=max(geneScoreStructure.scores(:,L),S);
        else
            EM='Could not map "other" to more than one compartment';
            dispEM(EM);
        end
    else
        EM='There are compartments that are not defined if they should be kept or removed. Use "A=other" or define more rules if you do not want them to be deleted';
        dispEM(EM,false);
    end

    %Remove the comparement that were merged
    geneScoreStructure.compartments(J)=[];
    geneScoreStructure.scores(:,J)=[];
end

%Renormalize
I=max(geneScoreStructure.scores,[],2);
geneScoreStructure.scores=bsxfun(@times, geneScoreStructure.scores, 1./I);

%If there are genes that have score 0 in all compartments, remove them and
%print a warning.
I=find(isnan(geneScoreStructure.scores(:,1))); %Only looks a the first colum as it will be the same for the other ones
if any(I)
    EM='The following genes had score 0.0 in all compartments. They have been removed from the structure. Consider using more rules or "A=other" in order to prevent this:';
    dispEM(EM,false,geneScoreStructure.genes(I));
    geneScoreStructure.scores(I,:)=[];
    geneScoreStructure.genes(I)=[];
end
end


%% COMPILE_MATCONVNET
%
% Compile MatConvNet
%
% Hyeonseob Nam, 2015
%

run matconvnet/matlab/vl_setupnn ;
cd matconvnet;
vl_compilenn('enableGpu', true, ...
               'cudaRoot', '/usr/local/cuda-7.5', ...
               'cudaMethod', 'nvcc');
cd ..;


function structNum = getStructNum(str,planC,indexS)
%Get the structure number for a structure with a given name.
%Returns 0 if not found.
%14 Oct 02, JOD
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

structNum = 0;
for i = 1 : length(planC{indexS.structures})
  if strcmp(str,planC{indexS.structures}(i).structureName)
    structNum = i;
    return
  end
end


function res = is_atom(x)
% Determine whether an expression can be further subdivided into parts
% literal matlab expressions (including matrices, most structs, strings, function_handles) are considered atomic
%
% The exceptions are:
%  * struct with .head / .part fields      (canonically represented expression)
%  * struct with .tracking.expression field  (impure expression, i.e. expression with value)
%
% Notes:
%  in the future, more data structures may be made accessible to the expression system
%
% See also:
%   exp_eval, exp_head, exp_parts
%
%                                                     Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                                     2010-04-15

if isfield(x,{'head','parts'})
    res = true;
elseif isfield(x,'tracking') && isfield(x.tracking,'expression')
    res = is_atom(x.tracking.expression);
else
    res = false;
end