% PURPOSE  :	shuffles (only) specified event codes in a continuous dataset
%
% FORMAT   :
%
% >> EEG = pop_eventshuffler(EEG, valueatfield)
%
% EXAMPLE  :
%
% >> EEG = pop_eventshuffler(EEG, [121 149]); % localizes events 121 and
% 149 at EEG.event field, then randomly replace these locations either with 121 or 149.
%
% INPUTS   :
%
% EEG           - input dataset
% valueatfield     - code to shuffle. It can be any numerical value or the string 'all'
%
% OUTPUTS  :
%
% EEG           - updated dataset
%
%
% GUI: ---  ;  SUBROUTINE: eventshuffler.m
%
% *** This function is part of ERPLAB Toolbox ***
% Author: Javier Lopez-Calderon
% Center for Mind and Brain
% University of California, Davis,
% Davis, CA
% 2009

%b8d3721ed219e65100184c6b95db209bb8d3721ed219e65100184c6b95db209b
%
% ERPLAB Toolbox
% Copyright © 2007 The Regents of the University of California
% Created by Javier Lopez-Calderon and Steven Luck
% Center for Mind and Brain, University of California, Davis,
% javlopez@ucdavis.edu, sjluck@ucdavis.edu
%
% This program 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.
%
% This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

function [EEG com] = pop_eventshuffler(EEG, varargin)

com = '';

if nargin < 1
        help pop_eventshuffler
        return
end
if ~isempty(EEG(1).epoch)
        msgboxText =  'pop_eventshuffler has been tested for continuous data only';
        title = 'ERPLAB: pop_eventshuffler(). Permission denied';
        errorfound(msgboxText, title);
        return
end
if ~isfield(EEG(1), 'event')
        msgboxText =  'pop_eventshuffler did not find EEG.event field.';
        title = 'ERPLAB: pop_eventshuffler(). Permission denied';
        errorfound(msgboxText, title);
        return
end
if ~isfield(EEG(1).event, 'type')
        msgboxText =  'pop_eventshuffler did not find EEG.event.type field.';
        title = 'ERPLAB: pop_eventshuffler(). Permission denied';
        errorfound(msgboxText, title);
        return
end
if ~isfield(EEG(1).event, 'latency')
        msgboxText =  'pop_eventshuffler did not find EEG.event.latency field.';
        title = 'ERPLAB: pop_eventshuffler(). Permission denied';
        errorfound(msgboxText, title);
        return
end
if ischar(EEG(1).event(1).type) && ~isfield(EEG, 'EVENTLIST')
        msgboxText =  ['pop_eventshuffler only works with numeric event codes.\n'...
                'We recommend to use Create EEG Eventlist first.'];
        title = 'ERPLAB: pop_eventshuffler(). Permission denied';
        errorfound(sprintf(msgboxText), title);
        return
elseif ischar(EEG(1).event(1).type) && isfield(EEG, 'EVENTLIST')
        if isempty(EEG.EVENTLIST)
                msgboxText =  ['pop_eventshuffler only works with numeric event codes.\n'...
                        'We recommend to use Create EEG Eventlist first.'];
                title = 'ERPLAB: pop_eventshuffler(). Permission denied';
                errorfound(sprintf(msgboxText), title);
                return
        end
end

%
% Gui is working...
%
if nargin==1
        %prompt    = {'Codes (e.g. 12 21 100 or ''all'''};
        %dlg_title = 'Enter codes to shuffle ';
        %num_lines = 1;
        %def = {'all'};
        %answer = inputvalue(prompt,dlg_title,num_lines,def);
        
        def = erpworkingmemory('pop_eventshuffler');
        
        if isempty(def)
                def = {[] 0};
        end
        
        %
        % call GUI
        %
        answer = shuffleGUI(def);
        
        if isempty(answer)
                disp('User selected Cancel')
                return
        end
        
        valueatfield = answer{1};
        specfield    = answer{2};
        
        if specfield==0
                specfieldstr = 'code';
        elseif specfield==1
                specfieldstr = 'bini';
        else
                error('invalid field')
        end
        if ~isnumeric(valueatfield) && ~strcmpi(valueatfield, 'all')
                valueatfield = str2num(valueatfield);
                if isempty(valueatfield)
                        msgboxText =  'Invalid value for "codes to shuffle"';
                        title = 'ERPLAB: pop_eventshuffler(). Error';
                        errorfound(sprintf(msgboxText), title);
                        return
                end
        elseif ~isnumeric(valueatfield) && strcmpi(valueatfield, 'all')
                fprintf('User selected all %s\n', specfieldstr )
        elseif isnumeric(valueatfield)
                fprintf('User specified %s = %s \n', specfieldstr, vect2colon(valueatfield))
        end
        
        erpworkingmemory('pop_artdiff', {valueatfield specfield});
        
        [EEG com] = pop_eventshuffler(EEG, 'Values', valueatfield, 'Field', specfieldstr);
        return
else
        p = inputParser;
        p.FunctionName  = mfilename;
        p.CaseSensitive = false;
        p.addRequired('EEG');
        p.addParamValue('Values', []);
        p.addParamValue('Field', 'code', @ischar);
        p.parse(EEG, varargin{:});
        
        valueatfield = p.Results.Values;
        
        if strcmpi(p.Results.Field, 'code')%
                specfield = 0;
        elseif strcmpi(p.Results.Field, 'bin') || strcmpi(p.Results.Field, 'bini')
                specfield = 1;
        end
end
if ischar(valueatfield) && ~strcmpi(valueatfield, 'all')
        msgboxText =  'Invalid value for event to shuffle.';
        title = 'ERPLAB: pop_eventshuffler(). Error';
        errorfound(sprintf(msgboxText), title);
        return
end

EEG = eventshuffler(EEG, valueatfield, specfield);
EEG.setname = [EEG.setname '_shuffled']; % suggested name (si queris no mas!)

% com = sprintf( '%s = pop_eventshuffler( %s, %s);', inputname(1), inputname(1), 'all');
skipfields = {'EEG'};
fn  = fieldnames(p.Results);
com = sprintf( '%s  = pop_eventshuffler( %s ', inputname(1), inputname(1));
for q=1:length(fn)
        fn2com = fn{q};
        if ~ismember(fn2com, skipfields)
                fn2res = p.Results.(fn2com);
                if ~isempty(fn2res)
                        if ischar(fn2res)
                                if ~strcmpi(fn2res,'off')
                                        com = sprintf( '%s, ''%s'', ''%s''', com, fn2com, fn2res);
                                end
                        else
                                if iscell(fn2res)
                                        fn2resstr = vect2colon(cell2mat(fn2res), 'Sort','on');
                                        fnformat = '{%s}';
                                else
                                        fn2resstr = vect2colon(fn2res, 'Sort','on');
                                        fnformat = '%s';
                                end
                                com = sprintf( ['%s, ''%s'', ' fnformat], com, fn2com, fn2resstr);
                        end
                end
        end
end
com = sprintf( '%s );', com);

%
% Completion statement
%
msg2end
return