% PURPOSE  :	Plots ERP Scalp Maps
%
% FORMAT   :
%
% >> pop_scalplot( ERP, binArray, latencyArray, options );
%
% or
%
% >> pop_scalplot(ERP);        %Using Gui
%
% EXAMPLE :
%
% >> pop_scalplot( ERP,1,0:50 , 'Animated', 'on', 'Animname',...
% 'C:\Users\Work\Documents\MATLAB\test.gif', 'Blc', 'pre', 'Electrodes',...
% 'on', 'FontSize',10, 'Legend', 'bn-la', 'Maplimit', 'maxmin', 'Maptype', '2D',...
% 'Mapview', '+X', 'Value', 'instsa');
%
% or
%
% >> pop_scalplot(ERP);        %Using Gui
%
% INPUTS     :
%
% ERP           - input dataset
% binArray      - index(es) of bin(s) to plot( 1 2 3 ...)
% latencyArray  - index(es) of latency(ies) to plot in ms (300 or -100:10:0 or  120 400)
%
% options:
%
% 'Blc'         - Baseline Correction
%               -'none'
%               -'pre'
%               -'post'
%               -'all'
% 'Value'       - Value to plot
%               -'insta' - Instantaneous amplitude
%               -'mean'- Mean amplitude between two fixed latencies
%                (requires two latencies)
%               -'area'- Area between two fixed latencies (requires
%                two latencies)
%               -'instalapla'- Instantaneous amplitude Laplacian
%               -'meanlapla'- Mean amplitude Laplacian
% 'Maptype'     -  2D
%               -  3D
% 'Maplimit'    - 'maxmin'
%               - 'absmax'
%               - [custom_min custom_max]- Enter own numbers for min and max
% 'Animated'    - 'on'- Create Animated GIF
% 'Animname'    - pathname and name of file that AGIF will be saved in
%
% OUTPUTS
%
% figure on the screen
%
% *** This function is part of ERPLAB Toolbox ***
% Author: Javier Lopez-Calderon % Sam London & Steve Luck
% 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 [erpcom] = pop_scalplot(ERP, binArray, latencyArray, varargin)

erpcom = '';
if nargin < 1
    help pop_scalplot
    return
end
if isempty(ERP)
    msgboxText =  'No ERPset was found!';
    title_msg  = 'ERPLAB: pop_scalplot() error:';
    errorfound(msgboxText, title_msg);
    return
end
if ~isfield(ERP, 'bindata')
    msgboxText{1} =  'Error: pop_scalplot cannot operate an empty ERP dataset';
    title_msg = 'ERPLAB: pop_scalplot() error:';
    errorfound(msgboxText, title_msg);
    return
end
if isempty(ERP.bindata)
    msgboxText{1} =  'Error: pop_scalplot cannot operate an empty ERP dataset';
    title_msg = 'ERPLAB: pop_scalplot() error:';
    errorfound(msgboxText, title_msg);
    return
end

%
% Searching channel location
%
if isfield(ERP.chanlocs, 'theta')
    ERP = borrowchanloc(ERP);
else
    question = ['This averaged ERP has not channel location info.\n'...
        'Would you like to load it now?'];
    title_msg   = 'ERPLAB: Channel location';
    button   = askquest(sprintf(question), title_msg);
    if ~strcmpi(button,'yes')
        disp('User selected Cancel')
        return
    else
        ERP = borrowchanloc(ERP);
    end
end
if nargin==1
    countp = 0;
    while 1
        %
        % Call GUI
        %
        plotset = scalplotGUI(ERP, ERP.chanlocs); %GUI
        
        if isempty(plotset.pscalp)
            disp('User selected Cancel')
            return
        elseif strcmpi(plotset.pscalp,'pdf')
            erpcom2 = pop_fig2pdf;
            if countp>0
                disp('pop_fig2pdf was called')
            else
                disp('WARNING: Matlab figure(s) might have been generated during a previous round....')
            end
            erpcom = [erpcom ' ' erpcom2];
            return
        elseif strcmpi(plotset.pscalp,'time')
            disp('User called pop_ploterps()')
            return
        end
        
        plotset.pscalp.binArray  = plotset.pscalp.binArray(plotset.pscalp.binArray<=ERP.nbin);
        
        if ~isfield(plotset.pscalp, 'posfig')
            plotset.pscalp.posfig = [];
        end
        
        findplot = findobj('Tag','Scalp');
        
        if ~isempty(findplot)
            lastfig    = figure(findplot(1));
            posfx = get(lastfig,'Position');
            plotset.pscalp.posfig = [posfx(1)+10 posfx(2)-15 posfx(3) posfx(4) ];
        end
        
        %
        % read plotset into variables
        %
        binArray     = plotset.pscalp.binArray;
        latencyArray = plotset.pscalp.latencyArray;
        measurestr   = plotset.pscalp.measurement;
        baseline     = plotset.pscalp.baseline;
        maplimit     = plotset.pscalp.cscale;
        isagif       = plotset.pscalp.agif.value;
        DelayT       = plotset.pscalp.agif.delay;
        fullgifname  = plotset.pscalp.agif.fname;
        posfig       = plotset.pscalp.posfig;
        mtype        = plotset.pscalp.mtype;   % map type: 2D or 3D
        mapview      = plotset.pscalp.mapview;
        splineinfo   = plotset.pscalp.splineinfo;
        plegend      = plotset.pscalp.plegend;
        binleg       = plegend.binnum;         % show bin number at legend
        bindesc      = plegend.bindesc;        % show bin description at legend
        vtype        = plegend.type ;          % show type of measurement at legend
        vlatency     = plegend.latency;        % show latency(ies) at legend
        showelec     = plegend.electrodes;     % show electrodes on scalp
        clrbar       = plegend.colorbar;       % show color bar
        ismaxim      = plegend.maximize;       % show color bar
        
        if strcmpi(mtype, '3d')
            if isempty(ERP.splinefile)
                if isempty(splineinfo.path)
                    splinefile = fullfile(cd(), 'temp_splinefile');%default temp spline
                else
                    splinefile = splineinfo.path;
                end
            else
                splinefile = ERP.splinefile;
            end
            if splineinfo.new==1
                headplot('setup', ERP.chanlocs, splineinfo.path); %Builds the new spline file.
                splineinfo.new = 0;
                plotset.pscalp.splineinfo = splineinfo;
            end
            if splineinfo.save
                if isempty(ERP.splinefile)
                    ERP.splinefile = splinefile;
                    ERP = pop_savemyerp(ERP, 'gui', 'erplab');
                else
                    question = ['This ERPset already has spline file info.\n'...
                        'Would you like to replace it?'];
                    title_msg   = 'ERPLAB: spline file';
                    button   = askquest(sprintf(question), title_msg);
                    
                    if ~strcmpi(button,'yes')
                        disp('User selected Cancel')
                        return
                    else
                        ERP.splinefile = splinefile;
                        ERP = pop_savemyerp(ERP, 'gui', 'erplab');
                    end
                end
                splineinfo.save = 0;
                plotset.pscalp.splineinfo = splineinfo;
            end
        else
            splinefile = '';
        end
        
        %
        % save plotset at command window
        %
        assignin('base','plotset', plotset);
        
        if clrbar==1
            colorbari = 'on';
        else
            colorbari = 'off';
        end
        if isagif==0
            isagifx = 'off';
            aff     = 'off'; % adjust first frame (aff)
        else
            if isagif==1
                aff = 'off'; % adjust first frame (aff)
            else
                aff = 'on';
            end
            isagifx = 'on';
        end
        if binleg==1
            binlegx = 'on';
        else
            binlegx = 'off';
        end
        if showelec==1
            showelecx = 'on';
        else
            showelecx = 'off';
        end
        if ismaxim==1
            maxim = 'on';
        else
            maxim = 'off';
        end
        
        % legend
        logstring = ['bn'*binleg '-'*binleg 'bd'*bindesc '-'*bindesc 'me'*vtype '-'*vtype 'la'*vlatency];
        logstring = nonzeros(logstring)';
        mapleg    = strtrim(char(logstring));
        
        %mapleg = strtrim([char('bn'*binleg) char('-'*binleg) char('bd'*bindesc) char('-'*bindesc) char('me'*vtype) char('-'*vtype)...
        %      char('la'*vlatency)]);
        
        
        %
        % call pop_scalplot
        %
        erpcom = pop_scalplot(ERP, binArray, latencyArray, 'Value', measurestr, 'Blc', baseline, 'Maplimit', maplimit, 'Colorbar', colorbari,...
            'Animated', isagifx, 'AdjustFirstFrame', aff, 'Delay', DelayT, 'Animname', fullgifname, 'Legend', mapleg, 'Electrodes', showelecx,...
            'Position', posfig, 'Maptype', mtype, 'Mapview', mapview, 'Splinefile', splinefile, 'Maximize', maxim);
        pause(0.1)
        countp = countp + 1;
    end
    return    
else
    
    p = inputParser;
    p.FunctionName  = mfilename;
    p.CaseSensitive = false;
    p.addRequired('ERP', @isstruct);
    p.addRequired('binArray', @isnumeric);
    p.addRequired('latencyArray', @isnumeric);
    
    p.addParamValue('Value', 'insta', @ischar);
    p.addParamValue('Blc', 'none');
    p.addParamValue('Maplimit', 'maxmin');
    p.addParamValue('Colorbar', 'on', @ischar);
    p.addParamValue('FontSize', 10, @isnumeric);
    p.addParamValue('Animated', 'off', @ischar);
    p.addParamValue('AdjustFirstFrame', 'off', @ischar);
    p.addParamValue('Delay', 0, @isnumeric);
    p.addParamValue('Animname', [], @ischar);
    p.addParamValue('Electrodes', 'on', @ischar);
    p.addParamValue('Legend', 'bn-la', @ischar); % all -> 'bn-bd-me-lat' (at legend:bin number (bn), bin desc (bd), measure (me), latency (la))
    p.addParamValue('Maximize', 'off', @ischar); % off | on
    p.addParamValue('Position', [], @isnumeric); % off | on
    p.addParamValue('Maptype', '2D', @ischar); % size ([w h] ) for each channel when topoplot is being used.
    p.addParamValue('Mapview', '+X'); % off | on
    p.addParamValue('Splinefile', '', @ischar); % off | on
    
    p.parse(ERP, binArray, latencyArray, varargin{:});
    
    if length(latencyArray)>ERP.pnts
        msgboxText =  'latency array cannot be longer than number of points';
        title_msg = 'ERPLAB: pop_scalplot() invalid channel index';
        errorfound(msgboxText, title_msg);
        return
    end
    if max(binArray)>ERP.nbin
        msgboxText =  ['Bin(s) %g do(es) not exist within this erpset.\n'...
            'Please, check your bin list'];
        title_msg = 'ERPLAB: pop_scalplot() invalid bin index';
        errorfound(sprintf(msgboxText, chanArray(chanArray>ERP.nchan)), title_msg);
        return
    end
    if min(binArray)<1
        msgboxText =  ['Invalid bin indexing.\n'...
            'Bin index(ices) must be positive integer(s) but zero.'];
        title_msg = 'ERPLAB: pop_scalplot() invalid bin index';
        errorfound(sprintf(msgboxText, ERP.erpname), title_msg);
        return
    end
    
    measurestr  = p.Results.Value;
    baseline    = p.Results.Blc;
    maplimit    = p.Results.Maplimit;
    colorbari   = p.Results.Colorbar;
    isagifx     = p.Results.Animated;
    
    if strcmpi(colorbari,'on')
        clrbar = 1;
    else
        clrbar = 0;
    end
    if strcmpi(isagifx,'on')
        if strcmpi(p.Results.AdjustFirstFrame,'on')
            isagif = 2;
        else
            isagif = 1;
        end
    else
        isagif = 0;
    end
    DelayT      = p.Results.Delay;
    fullgifname = p.Results.Animname;
    showelecx    = p.Results.Electrodes;
    if strcmpi(showelecx,'on')
        showelec = 1;
    else
        showelec = 0;
    end
    posfig      = p.Results.Position;
    mtype       = lower(p.Results.Maptype);
    mapview     = lower(p.Results.Mapview);
    splinefile  = p.Results.Splinefile;
    fontsizel   = p.Results.FontSize;
    
    if strcmpi(p.Results.Maximize,'on')
        ismaxim = 1;
    else
        ismaxim = 0;
    end
    
    legstr = p.Results.Legend;
    
    aa = regexp(legstr, 'bn|bd|me|la', 'match');
    bb = num2cell(ismember({'bn','bd','me','la'}, aa));
    [binleg bindesc vtype vlatency] = deal(bb{:});
end
if isempty(ERP.splinefile) && isempty(splinefile) && strcmpi(mtype, '3d')
    error('ERPLAB says: no spline file info was found.')
end
indxh   = find(latencyArray>ERP.xmax*1000,1);
if ~isempty(indxh)
    msgboxText{1} =  ['Latency of ' num2str(latencyArray(indxh)) ' is greater than ERP.xmax = ' num2str(ERP.xmax*1000) ' msec!'];
    title_msg = 'ERPLAB: pop_scalplot() error:';
    errorfound(msgboxText, title_msg);
    pop_scalplot(ERP);
    return
end
indxl  = find(latencyArray<ERP.xmin*1000,1);
if ~isempty(indxl)
    msgboxText{3} =  ['Latency of ' num2str(latencyArray(indxl)) ' is lesser than ERP.xmin = ' num2str(ERP.xmin*1000) ' msec!'];
    title_msg = 'ERPLAB: pop_scalplot() error:';
    errorfound(msgboxText, title_msg);
    pop_scalplot(ERP);
    return
end

%
% Numeric map view, since headplot is not yet working with strings for view...
%
if ischar(mapview)
    switch mapview
        case {'front','f'}
            mview = [-180,30];
        case {'back','b'}
            mview = [0,30];
        case {'left','l'}
            mview =  [-90,30];
        case {'right','r'}
            mview =  [90,30];
        case {'frontright','fr'}
            mview =  [135,30];
        case {'backright','br'}
            mview =  [45,30];
        case {'frontleft','fl'}
            mview =  [-135,30];
        case {'backleft','bl'}
            mview =  [-45,30];
        case 'top'
            mview =  [0,90];
        otherwise
            mview =  [0,90];
    end
else
    % parsing is pending. JLC
    mview = mapview;
end

toffsa    = abs(round(ERP.xmin*ERP.srate))+1;
latArray  = round(latencyArray.*ERP.srate/1000) + toffsa;   %sec to samples
nbin      = length(binArray);

if strcmp(measurestr, 'insta') || strcmp(measurestr, 'instalapla')
    nlat = size(latArray,2);  % only one row array should be defined. e.g. 120 or [0 50 120 350]
else
    nlat = size(latArray,1);  % couples of latencyes can be defined. e.g [50 100; 120 350; 400 600]
end
if showelec==1
    showe = 'on';
else
    showe = 'off';
end

wi   = 0.9/nlat;
hi   = 0.9/nbin;
bdwidth = 30; topbdwidth = 30;
set(0,'Units','pixels')
scnsize = get(0,'ScreenSize');
pos1    = [bdwidth, (1/3)*scnsize(4) + bdwidth, scnsize(3)/4 - 2*bdwidth, scnsize(4)/3 - (topbdwidth + bdwidth)];

%
% If there is a previous "scal map" figure open, then "steal" its dimensions, otherwise set it as default
%
find2 = findobj('Tag','Scalp');
if ~isempty(find2)
    %fig2    = figure(find2(end));
    pos2 = get(find2,'Position');
else
    pos2 = [bdwidth, (1/5)*scnsize(4) + bdwidth, scnsize(3)/2, 0.7*scnsize(4)];
end
if isempty(ERP.erpname)
    fnamet = 'none';
else
    [pathstrt, fnamet, extt] = fileparts(ERP.erpname) ;
end
if isagif==0
    hsig    = figure('Position',pos1, 'Name',['<< ' fnamet ' >>  Plot ERP map by Bins x latency'],...
        'NumberTitle','off', 'Tag','Scalp');
    if ~isempty(posfig)
        set(hsig, 'Position', posfig)
    end
    nadj = 1;
    if ismaxim == 1;
        maximize(hsig)
    end
else
    fra = 1;
    if isagif==2  % adjust first frame size
        nadj =2;
    else
        nadj = 1;
    end
end

%
% Drawing loops
%
iadj = 1;
continueplot = 1;
while iadj<=nadj && continueplot
    for ilat =1:nlat
        if isagif>0
            hsig    = figure('Position',pos2, 'Name',['<< Frame ' num2str(fra) ' >>'],...
                'NumberTitle','off', 'Tag','Scalp');
            if ~isempty(posfig)
                set(hsig, 'Position', posfig)
            end
        end
        for ibin=1:nbin
            if isagif>0
                axes('position',[0.05  0.05+hi*(nbin-ibin)  0.9  hi])
            else
                axes('position',[0.05+wi*(ilat-1)  0.05+hi*(nbin-ibin)  wi  hi])
            end
            if nlat>=1 && ~strcmp(measurestr, 'insta') && ~strcmp(measurestr, 'instalapla')
                latetitle = [num2str(latencyArray(ilat,1)) '-' num2str(latencyArray(ilat,2))];
            else
                latetitle = num2str(latencyArray(ilat));
            end
            if ~isnumeric(baseline)
                if ismember(baseline, {'pre' 'post' 'all' 'none'})
                    for c=1:ERP.nchan
                        blv = blvalue(ERP, c, binArray(ibin), baseline);
                        datap(c,:) = ERP.bindata(c,:,binArray(ibin)) - blv;
                    end
                else
                    error(['ERPLAB says: error at pop_scalplot(). Invalid option: ' baselin])
                end
            else
                if length(baseline)==2
                    for c=1:ERP.nchan
                        blv = blvalue(ERP, c, binArray(ibin), baseline);
                        datap(c,:) = ERP.bindata(c,:,binArray(ibin)) - blv;
                    end
                else
                    error(['ERPLAB says: error at pop_scalplot(). Invalid option: ' num2str(baseline)])
                end
            end
            
            %
            % Measurement setting
            %
            switch measurestr
                case 'insta'
                    data2plot = datap(:,latArray(ilat));%   ERP.bindata(:,latArray(ilat),binArray(ibin));
                case 'mean'
                    data2plot = mean(datap(:,latArray(ilat,1):latArray(ilat,2)), 2);
                case 'area'
                    data2plot = geterpvalues(ERP, [latArray(ilat,1) latArray(ilat,2)],...
                        binArray(ibin), 1:ERP.nchan, 'areat', baseline, 1)';
                case 'instalapla'
                    data2plot = del2map( datap(:,latArray(ilat)), ERP.chanlocs);
                case 'meanlapla'
                    data2plot = mean(datap(:,latArray(ilat,1):latArray(ilat,2)), 2);
                    data2plot = del2map(data2plot, ERP.chanlocs);
            end
            if strcmpi(maplimit,'auto') && ilat==1
                maplimit = [min(data2plot) max(data2plot)];
            end
            
            %
            % Legend
            %
            titulo = titlemaker(ERP, binleg, bindesc, vtype, vlatency, binArray, measurestr, latetitle, ibin);
            
            %
            % Plot 3D
            %
            try
                if strcmpi(mtype, '3d')
                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    %                  Plot 3D scalp map, at current latency, current bin                  %
                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    
                    %
                    % Color Bar
                    %
                    
                    if clrbar==1
                        cb3d = 0;
                    else
                        cb3d = []; % no color bar
                    end
                    
                    %
                    % Plot ERP on a 3D head
                    %
                    headplot(data2plot, splinefile, 'electrodes', showe, 'view', mview, 'maplimits', maplimit, 'cbar', cb3d, 'title', titulo); %Plots the 3d scalp plot.
                    set(get(gca,'Title'),'FontSize', fontsizel)
                    
                    if isagif==0
                        axcopy(gca)
                    end
                elseif strcmpi(mtype, '2d')
                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    %                  Plot scalp map, at current latency, current bin                     %
                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    title(titulo , 'FontSize', fontsizel) % Two line title
                    set(get(gca,'Title'),'Position', [-0.004 0.588 4])
                    
                    %
                    % Plot ERP on a 2D map
                    %
                    topoplot( data2plot, ERP.chanlocs,...
                        'style', 'fill', 'plotrad',0.53, 'headrad', 0.516, 'emarker', {'o','k',8,1},...
                        'numcontour',12, 'maplimits', maplimit, 'electrodes', showe, 'nosedir', mapview);
                    %                               %
                    %                               % Color Bar
                    %                               %
                    %                               if clrbar==1
                    %                                     colorbar('location','EastOutSide');
                    %                               end
                    if isagif==0
                        axcopy(gca)
                    end
                    
                    % Color Bar
                    %
                    if clrbar==1
                        colorbar('location','EastOutSide');
                    end
                else
                    close(hsig)
                    msgboxText =  'pop_scalplot cannot plot a map in %s.';
                    title_msg = 'ERPLAB: pop_scalplot() error:';
                    errorfound(sprintf(msgboxText, upper(mtype)), title_msg);
                    return
                end
                %
            catch
                close(hsig)
                serr = lasterror;
                msgboxText =  ['Something went wrong: \n\n'...
                    serr.message '\n'];
                title_msg = 'ERPLAB: pop_scalplot() error:';
                errorfound(sprintf(msgboxText), title_msg);
                return
            end
            
            %                         %
            %                         % Color Bar
            %                         %
            %                         if clrbar==1
            %                                 colorbar('location','EastOutSide');
            %                         end
        end
        
        set(gcf,'Color', [1 1 1])
        drawnow
        
        %
        % Stack for AGIF
        %
        if isagif>0
            if isagif==2 && iadj==1 % agif --> Adjust frame size
                BackERPLABcolor = [1 0.9 0.3];    % yellow
                question = 'Press OK when ready to continue.';
                titlet   = 'Adjusting frame size';
                oldcolor = get(0,'DefaultUicontrolBackgroundColor');
                set(0,'DefaultUicontrolBackgroundColor',BackERPLABcolor)
                button   = questdlg(question, titlet,'OK', 'OK');
                set(0,'DefaultUicontrolBackgroundColor', oldcolor)
                
                if ~strcmpi(button,'OK')
                    disp('User selected Cancel')
                    continueplot = 0;
                    isagif = 0;
                else
                    findplot = findobj('Tag','Scalp');
                    if ~isempty(findplot)
                        lastfig = figure(findplot(1));
                        posfig   = get(lastfig,'Position');
                        plotset = evalin('base', 'plotset');
                        plotset.pscalp.posfig = posfig;
                        assignin('base','plotset', plotset);
                    end
                end
                close(hsig)
                break
            end
            
            %set(hsig,'nextplot','replacechildren','visible','off')
            
            if fra==1
                f = getframe(hsig);
                pause(0.01)
                [im,map] = rgb2ind(f.cdata,256,'nodither');
                pause(0.01)
                im(1,1,1,nlat) = 0;
            end
            
            fra = fra + 1;
            f   = getframe(hsig);
            pause(0.01)
            im(:,:,1,fra) = rgb2ind(f.cdata,map,'nodither');
            pause(0.02)
            close(hsig)
        end
    end
    iadj = iadj+1;
end

assignin('base','scalpicture', hsig);
binArraystr = vect2colon(binArray);
if size(latencyArray,1)==1
    latencystr  = vect2colon(latencyArray);
else
    latencystr  = mat2colon(latencyArray);
end

fprintf('Mapped Channels: ');

for j=1:ERP.nchan
    fprintf('%s - ', char(ERP.chanlocs(j).labels));
end

fprintf('\n');

%
% Create final Animated GIF
%
if isagif>0
    pause(0.2)
    imwrite(im, map, fullgifname,'DelayTime',DelayT,'LoopCount',inf);
end

%
% History command
%
fn = fieldnames(p.Results);
erpcom = sprintf( 'pop_scalplot( %s, %s, %s ',  inputname(1), binArraystr, latencystr);

for q=1:length(fn)
    fn2com = fn{q}; % inputname
    if ~ismember(fn2com,{'ERP','binArray','latencyArray'})
        fn2res = p.Results.(fn2com); %  input value
        if ~isempty(fn2res)
            if ischar(fn2res)
                if ~strcmpi(fn2res,'off')
                    erpcom = sprintf( '%s, ''%s'', ''%s''', erpcom, fn2com, fn2res);
                end
            elseif iscell(fn2res)
                nn = length(fn2res);
                erpcom = sprintf( '%s, ''%s'', {''%s'' ', erpcom, fn2com, fn2res{1});
                for ff=2:nn
                    erpcom = sprintf( '%s, ''%s'' ', erpcom, fn2res{ff});
                end
                erpcom = sprintf( '%s}', erpcom);
                
            else
                if ~ismember(fn2com,{'Maplimit','Mapview'})
                    erpcom = sprintf( '%s, ''%s'', %s', erpcom, fn2com, vect2colon(fn2res,'Repeat','on'));
                else
                    xyscalestr = sprintf('[ %.1f %.1f  %s ]', fn2res(1), fn2res(2), vect2colon(fn2res(3:end),'Delimiter','off'));
                    erpcom = sprintf( '%s, ''%s'', %s', erpcom, fn2com, xyscalestr);
                end
            end
        end
    end
end
erpcom = sprintf( '%s );', erpcom);

%
% Completion statement
%
msg2end
return

%---------------------------------------------------------------------------------------------------
%-----------------base line mean value--------------------------------------------------------------
function blv = blvalue(ERP, chan, bin, bl)

if isnumeric(bl)
    toffsa   = abs(round(ERP.xmin*ERP.srate))+1;
    baseline = round((bl/1000)*ERP.srate) + toffsa; %msec to samples
    p1 = baseline(1);
    p2 = baseline(2);
else
    switch bl
        case 'none'
            blv = 0;
            return
        case 'pre'
            p1=1;
            p2  = find(ERP.times==0);    % zero-time locked sample
        case 'post'
            p1  = find(ERP.times==0);    % zero-time locked sample
            p2  =  ERP.pnts;
        case 'all'
            p1  = 1;
            p2  =  ERP.pnts;
    end
end

blv = mean(ERP.bindata(chan,p1:p2, bin));

%---------------------------------------------------------------------------------------------------
%-----------------       legend       --------------------------------------------------------------
function titulo = titlemaker(ERP, binleg, bindesc, vtype, vlatency, binArray, measurestr, latetitle, ibin)

strbinnum = ['Bin' num2str(binArray(ibin))];
strequal  = ' = ';
strbindes = ERP.bindescr{binArray(ibin)};
strcomma1 = ',';
strvtype  = [''''  measurestr ''''];
strcomma2 = ',';
strvlate  = [latetitle ' ms'];

t = [strbinnum*binleg  strequal*binleg*bindesc  strbindes*bindesc strcomma1*(vtype&(binleg|bindesc))...
    strvtype*vtype  strcomma2*(vlatency&(binleg|bindesc|vtype))  strvlate*vlatency];
t = nonzeros(t)';
titulo = strtrim(char(t));
