Home > matlabmk > actplot.m

actplot

PURPOSE ^

actplot() - Creates a GUI for scrolling (horizontally and/or vertically)

SYNOPSIS ^

function actplot(command,varargin) % p1,p2,p3,p4,p5,p6,p7,p8,p9)

DESCRIPTION ^

 actplot() - Creates a GUI for scrolling (horizontally and/or vertically) 
             through multiple trials of independent component activations. 
             The GUI also allows manual marking and unmarking of trials 
             for rejection.  Only works with epoched data (i.e., it will 
             not work with continuous data) and requires the data set to 
             be visualized to be in a global EEGLAB "EEG" variable.

 Usage:
           >> actplot(command, 'key1', value1 ...); 
  

 Required Global Variable:
     EEG - An EEGLAB "EEG" variable that contains all the data that will be
           visualized.  If you are running the EEGLAB GUI, there will be a
           global EEG variable that equals the dataset currently displayed.
           To make a global EEG variable, type "global EEG" and then load 
           an EEGLAB set file.

 Menu items:
    "Figure > Print" - Print figure in portrait or landscape.
    "Figure > Edit figure" -  Remove menus and buttons and call up the standard
                  Matlab figure menu. Select "Tools > Edit" to format the figure
                  for publication. Command line equivalent: 'noui'
    "Figure > Accept and close" - Saves any changes made to trial rejection 
                  status to global EEG variable and closes GUI. Same as the bottom-
                  right "SAVE TO WORKSPACE" button.
    "Figure > Cancel and close" -  Discard any changes made to trial rejection 
                  status to global EEG variable and closes GUI. Same as the
                  bottom-left "CLOSE" button.
    "Display > Data mark/unmark > [Hide|Show] marks" - Show or hide patches of
                  background color behind the data.  Background color indicates that 
                  a trial has been marked for rejection.  Click on the selected
                  trials to toggle its rejection status. 
    "Display > Data mark/unmark > Choose color" - Change the background marking
                  color. The marking color(s) of previously marked trials are preserved.
                  Command line equivalent: 'wincolor'.
    "Display > Grid > X Grid on/off" - Toggle (on or off) time axis 
                  grids in the activity plot. Command line equivalents:
                  'xgrid'.
    "Display > Grid > Y Grid on/off" - Toggle (on or off) component axis 
                  grids in the activity plot. Command line equivalents:
                  'ygrid'.
    "Display > Grid > Grid style" - Determine the line style (e.g., dashed
                  or dotted) of X and Y grids.
    "Display > Show scale" - Show (or hide if shown) the scale on the bottom
                  right corner of the activity window. Command line equivalent:
                  'scale'.
    "Display > Title" - Change the title of the figure. Command line equivalent:
                  'title'.
    "Settings > Time range to display"  - This item pops up a query window
                  that asks for the number of epochs to display (this can be 
                  fractional). Command line equivalent: 'winlength'
    "Settings > Number of components to display" - Number of components to display
                  in the activity window.  If not all components are displayed, the
                  user may scroll through components using the slider on the left
                  of the activity plot. Command line equivalent: 'dispchans'
    "Settings > Channel numbers > Show numbers "  - Use component index
                  numbers for component labels.
    "Settings > Channel numbers > Load .loc(s) file "  - Get component 
                  labels from an electrode location file from disk. Command line
                  equivalent: 'eloc_file'.
    "Settings > Zoom on/off" - Toggle Matlab figure zoom on or off for time and
                  electrode axes. left-click to zoom (x2); right-click to reverse-zoom.
                  Else, draw a rectange in the activity window to zoom the display into
                  that region. NOTE: When zoom is on, data cannot be marked for rejection.
    "Settings > Events" - Toggle event on or off (assuming events have been
                  given as input). Press "legend" to pop up a legend window for events.

 Display window interface:
  "Activity plot"    - [main window] This axis displays the component activities.
                        The x-axis label indicate time within each epoch.
  "CLOSE"            - [button] Closes the window and discards any changes to data rejection marks.
  "<<"               - [button] Scroll backwards though time or epochs by one window length.
  "<"                - [button] Scroll backwards though time or epochs by one epoch.
  "Epoch ID box"     - [edit box] Enter a epoch to jump to. "1" would be the first
                        epoch of all the epochs selected for visualization.
  ">"                - [button] Scroll forward though time or epochs by one epoch.
  ">>"               - [button] Scroll forward though time or epochs by one window length.
  "Chan/Time/Value"  - [text] If the mouse is within the activity window, indicates
                        which component, time, and activity value the cursor is closest to.
  "Scale edit box"   - [edit box] Scales the displayed amplitude in activity units.
                        Command line equivalent: 'spacing'
  "+ / -"            - [buttons] Use these buttons to +/- the amplitude scale by 10%.
  "SAVE TO WORKSPACE"- [button] When pressed, save any changes to rejection marks to global 
                       variable EEG and close the figure.  EEG variable still needs to be saved
                       to disk to make changes permanent.

 Required command line input:
    command        - One of the following strings:
                  'initialize'   -> Create a new GUI
                  'drawp'        -> Redraw EEG and change position
                  'drawb'        -> Draw background
                  'draws'        -> Redraw EEG and change scale
                  'window'       -> Change window size
                  'winelec'      -> Change channel window size
                  'loadelect'    -> Load channels
                  'setelect'     -> Set channels
                  'title'        -> Get new title
                  'scaleeye'     -> Turn scale I on/off
                  'noui'         -> Remove interactive parts of GUI
                  'zoom'         -> Zoom.
                  'updateslider' -> Update slider if zoom
                  'drawlegend'   -> Draw legend
                  'defmotioncom' -> Move windows or display current position (channel, time and activation)
                  'defupcom'     -> Release button: check window consistency, add to trial boundaries
                  'defdowncom'   -> Push button: create/remove window
 
 Optional command line keywords:
    'srate'      - Sampling rate in Hz {default|0: 256 Hz}
    'spacing'    - Display range per component (default|0: max(whole_data)-min(whole_data))
    'eloc_file'  - Electrode filename (as in  >> topoplot example) to read
                    ascii component labels. Else,
                   [vector of integers] -> Show specified component numbers. Else,
                   [] -> Do not show component labels {default|0 -> Show [1:nchans]}
    'limits'     - [start end] Time limits for data epochs in ms (for labeling
                   purposes only).
    'winlength'  - [value] Seconds (or epochs) of data to display in window {default: 5}
    'dispchans'  - [integer] Number of components to display in the activity window
                   {default: from data}.  If < total number of components, a vertical
                   slider on the left side of the figure allows vertical data scrolling.
    'title'      - Figure title {default: none}
    'xgrid'      - ['on'|'off'] Toggle display of the x-axis grid {default: 'off'}
    'ygrid'      - ['on'|'off'] Toggle display of the y-axis grid {default: 'off'}
    'ploteventdur' - ['on'|'off'] Toggle display of event duration { default: 'off' }
    'data2'      - [float array] identical size to the original data and
                   plotted on top of it.

 Additional keywords:
    'btn_command'- ['string'] Matlab command to evaluate when the 'REJECT' button is
                   clicked. The 'REJECT' button is visible only if this parameter is
                   not empty. As explained in the "Output" section below, the variable
                   'TMPREJ' contains the rejected windows (See also: functions
                   actplot2event() and actplot2trial()).
    'butlabel'   - Reject button label. {default: 'REJECT'}
    'winrej'     - [start end R G B e1 e2 e3 ...] Matrix giving data periods to mark
                   for rejection, each row indicating a different period
                      [start end] = period limits (in frames from beginning of data);
                      [R G B] = specifies the marking color;
                      [e1 e2 e3 ...] = a (1,nchans) logical [0|1] vector giving
                         components (1) to mark and (0) not mark for rejection.
    'color'      - ['on'|'off'|cell array] Plot components with different colors.
                   If an RGB cell array {'r' 'b' 'g'}, components will be plotted
                   using the cell-array color elements in cyclic order {default:'off'}.
    'wincolor'   - [color] Color to use to mark data stretches or epochs {default:
                   [ 0.8345 1 0.956] is the default marking color}
    'events'     - [struct] EEGLAB event structure (EEG.event) to use to show events.
    'submean'    - ['on'|'off'] Remove component means in each window {default: 'on'}
    'position'   - [lowleft_x lowleft_y width height] Position of the figure in pixels.
    'tag'        - [string] Matlab object tag to identify this actplot() window (allows
                    keeping track of several simultaneous actplot() windows).
    'children'   - [integer] Figure handle of a *dependent* actplot() window. Scrolling
                    horizontally in the master window will produce the same scroll in
                    the dependent window. Allows comparison of two concurrent datasets,
                    or of component and component data from the same dataset.
    'scale'      - ['on'|'off'] Display the amplitude scale {default: 'on'}.
    'mocap'      - ['on'|'off'] Display motion capture data in a separate figure.
                     To run, select an EEG data period in the scolling display using
                     the mouse. Motion capture (mocap) data should be
                     under EEG.moredata.mocap.markerPosition in xs, ys and zs fields which are
                     (number of markers, number of time points) arrays.
                    {default: 'off'}.
    'selectcommand' - [cell array] list of 3 commands (strings) to run when the mouse
                      button is down, when it is moving and when the mouse button is up.
    'ctrlselectcommand' - [cell array] same as above in conjunction with pressing the
                      CTRL key.
 Outputs:
    None.  Changes are made to global variable EEG if desired.

 Function derived from eegplot.m by:
 David Groppe
 Kutaslab, 12/2009

 This function is simply a somewhat modified version of the eegplot.m function written by:
 Arnaud Delorme & Colin Humphries, CNL/Salk Institute, SCCN/INC/UCSD, 1998-2001

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

SOURCE CODE ^

0001 % actplot() - Creates a GUI for scrolling (horizontally and/or vertically)
0002 %             through multiple trials of independent component activations.
0003 %             The GUI also allows manual marking and unmarking of trials
0004 %             for rejection.  Only works with epoched data (i.e., it will
0005 %             not work with continuous data) and requires the data set to
0006 %             be visualized to be in a global EEGLAB "EEG" variable.
0007 %
0008 % Usage:
0009 %           >> actplot(command, 'key1', value1 ...);
0010 %
0011 %
0012 % Required Global Variable:
0013 %     EEG - An EEGLAB "EEG" variable that contains all the data that will be
0014 %           visualized.  If you are running the EEGLAB GUI, there will be a
0015 %           global EEG variable that equals the dataset currently displayed.
0016 %           To make a global EEG variable, type "global EEG" and then load
0017 %           an EEGLAB set file.
0018 %
0019 % Menu items:
0020 %    "Figure > Print" - Print figure in portrait or landscape.
0021 %    "Figure > Edit figure" -  Remove menus and buttons and call up the standard
0022 %                  Matlab figure menu. Select "Tools > Edit" to format the figure
0023 %                  for publication. Command line equivalent: 'noui'
0024 %    "Figure > Accept and close" - Saves any changes made to trial rejection
0025 %                  status to global EEG variable and closes GUI. Same as the bottom-
0026 %                  right "SAVE TO WORKSPACE" button.
0027 %    "Figure > Cancel and close" -  Discard any changes made to trial rejection
0028 %                  status to global EEG variable and closes GUI. Same as the
0029 %                  bottom-left "CLOSE" button.
0030 %    "Display > Data mark/unmark > [Hide|Show] marks" - Show or hide patches of
0031 %                  background color behind the data.  Background color indicates that
0032 %                  a trial has been marked for rejection.  Click on the selected
0033 %                  trials to toggle its rejection status.
0034 %    "Display > Data mark/unmark > Choose color" - Change the background marking
0035 %                  color. The marking color(s) of previously marked trials are preserved.
0036 %                  Command line equivalent: 'wincolor'.
0037 %    "Display > Grid > X Grid on/off" - Toggle (on or off) time axis
0038 %                  grids in the activity plot. Command line equivalents:
0039 %                  'xgrid'.
0040 %    "Display > Grid > Y Grid on/off" - Toggle (on or off) component axis
0041 %                  grids in the activity plot. Command line equivalents:
0042 %                  'ygrid'.
0043 %    "Display > Grid > Grid style" - Determine the line style (e.g., dashed
0044 %                  or dotted) of X and Y grids.
0045 %    "Display > Show scale" - Show (or hide if shown) the scale on the bottom
0046 %                  right corner of the activity window. Command line equivalent:
0047 %                  'scale'.
0048 %    "Display > Title" - Change the title of the figure. Command line equivalent:
0049 %                  'title'.
0050 %    "Settings > Time range to display"  - This item pops up a query window
0051 %                  that asks for the number of epochs to display (this can be
0052 %                  fractional). Command line equivalent: 'winlength'
0053 %    "Settings > Number of components to display" - Number of components to display
0054 %                  in the activity window.  If not all components are displayed, the
0055 %                  user may scroll through components using the slider on the left
0056 %                  of the activity plot. Command line equivalent: 'dispchans'
0057 %    "Settings > Channel numbers > Show numbers "  - Use component index
0058 %                  numbers for component labels.
0059 %    "Settings > Channel numbers > Load .loc(s) file "  - Get component
0060 %                  labels from an electrode location file from disk. Command line
0061 %                  equivalent: 'eloc_file'.
0062 %    "Settings > Zoom on/off" - Toggle Matlab figure zoom on or off for time and
0063 %                  electrode axes. left-click to zoom (x2); right-click to reverse-zoom.
0064 %                  Else, draw a rectange in the activity window to zoom the display into
0065 %                  that region. NOTE: When zoom is on, data cannot be marked for rejection.
0066 %    "Settings > Events" - Toggle event on or off (assuming events have been
0067 %                  given as input). Press "legend" to pop up a legend window for events.
0068 %
0069 % Display window interface:
0070 %  "Activity plot"    - [main window] This axis displays the component activities.
0071 %                        The x-axis label indicate time within each epoch.
0072 %  "CLOSE"            - [button] Closes the window and discards any changes to data rejection marks.
0073 %  "<<"               - [button] Scroll backwards though time or epochs by one window length.
0074 %  "<"                - [button] Scroll backwards though time or epochs by one epoch.
0075 %  "Epoch ID box"     - [edit box] Enter a epoch to jump to. "1" would be the first
0076 %                        epoch of all the epochs selected for visualization.
0077 %  ">"                - [button] Scroll forward though time or epochs by one epoch.
0078 %  ">>"               - [button] Scroll forward though time or epochs by one window length.
0079 %  "Chan/Time/Value"  - [text] If the mouse is within the activity window, indicates
0080 %                        which component, time, and activity value the cursor is closest to.
0081 %  "Scale edit box"   - [edit box] Scales the displayed amplitude in activity units.
0082 %                        Command line equivalent: 'spacing'
0083 %  "+ / -"            - [buttons] Use these buttons to +/- the amplitude scale by 10%.
0084 %  "SAVE TO WORKSPACE"- [button] When pressed, save any changes to rejection marks to global
0085 %                       variable EEG and close the figure.  EEG variable still needs to be saved
0086 %                       to disk to make changes permanent.
0087 %
0088 % Required command line input:
0089 %    command        - One of the following strings:
0090 %                  'initialize'   -> Create a new GUI
0091 %                  'drawp'        -> Redraw EEG and change position
0092 %                  'drawb'        -> Draw background
0093 %                  'draws'        -> Redraw EEG and change scale
0094 %                  'window'       -> Change window size
0095 %                  'winelec'      -> Change channel window size
0096 %                  'loadelect'    -> Load channels
0097 %                  'setelect'     -> Set channels
0098 %                  'title'        -> Get new title
0099 %                  'scaleeye'     -> Turn scale I on/off
0100 %                  'noui'         -> Remove interactive parts of GUI
0101 %                  'zoom'         -> Zoom.
0102 %                  'updateslider' -> Update slider if zoom
0103 %                  'drawlegend'   -> Draw legend
0104 %                  'defmotioncom' -> Move windows or display current position (channel, time and activation)
0105 %                  'defupcom'     -> Release button: check window consistency, add to trial boundaries
0106 %                  'defdowncom'   -> Push button: create/remove window
0107 %
0108 % Optional command line keywords:
0109 %    'srate'      - Sampling rate in Hz {default|0: 256 Hz}
0110 %    'spacing'    - Display range per component (default|0: max(whole_data)-min(whole_data))
0111 %    'eloc_file'  - Electrode filename (as in  >> topoplot example) to read
0112 %                    ascii component labels. Else,
0113 %                   [vector of integers] -> Show specified component numbers. Else,
0114 %                   [] -> Do not show component labels {default|0 -> Show [1:nchans]}
0115 %    'limits'     - [start end] Time limits for data epochs in ms (for labeling
0116 %                   purposes only).
0117 %    'winlength'  - [value] Seconds (or epochs) of data to display in window {default: 5}
0118 %    'dispchans'  - [integer] Number of components to display in the activity window
0119 %                   {default: from data}.  If < total number of components, a vertical
0120 %                   slider on the left side of the figure allows vertical data scrolling.
0121 %    'title'      - Figure title {default: none}
0122 %    'xgrid'      - ['on'|'off'] Toggle display of the x-axis grid {default: 'off'}
0123 %    'ygrid'      - ['on'|'off'] Toggle display of the y-axis grid {default: 'off'}
0124 %    'ploteventdur' - ['on'|'off'] Toggle display of event duration { default: 'off' }
0125 %    'data2'      - [float array] identical size to the original data and
0126 %                   plotted on top of it.
0127 %
0128 % Additional keywords:
0129 %    'btn_command'- ['string'] Matlab command to evaluate when the 'REJECT' button is
0130 %                   clicked. The 'REJECT' button is visible only if this parameter is
0131 %                   not empty. As explained in the "Output" section below, the variable
0132 %                   'TMPREJ' contains the rejected windows (See also: functions
0133 %                   actplot2event() and actplot2trial()).
0134 %    'butlabel'   - Reject button label. {default: 'REJECT'}
0135 %    'winrej'     - [start end R G B e1 e2 e3 ...] Matrix giving data periods to mark
0136 %                   for rejection, each row indicating a different period
0137 %                      [start end] = period limits (in frames from beginning of data);
0138 %                      [R G B] = specifies the marking color;
0139 %                      [e1 e2 e3 ...] = a (1,nchans) logical [0|1] vector giving
0140 %                         components (1) to mark and (0) not mark for rejection.
0141 %    'color'      - ['on'|'off'|cell array] Plot components with different colors.
0142 %                   If an RGB cell array {'r' 'b' 'g'}, components will be plotted
0143 %                   using the cell-array color elements in cyclic order {default:'off'}.
0144 %    'wincolor'   - [color] Color to use to mark data stretches or epochs {default:
0145 %                   [ 0.8345 1 0.956] is the default marking color}
0146 %    'events'     - [struct] EEGLAB event structure (EEG.event) to use to show events.
0147 %    'submean'    - ['on'|'off'] Remove component means in each window {default: 'on'}
0148 %    'position'   - [lowleft_x lowleft_y width height] Position of the figure in pixels.
0149 %    'tag'        - [string] Matlab object tag to identify this actplot() window (allows
0150 %                    keeping track of several simultaneous actplot() windows).
0151 %    'children'   - [integer] Figure handle of a *dependent* actplot() window. Scrolling
0152 %                    horizontally in the master window will produce the same scroll in
0153 %                    the dependent window. Allows comparison of two concurrent datasets,
0154 %                    or of component and component data from the same dataset.
0155 %    'scale'      - ['on'|'off'] Display the amplitude scale {default: 'on'}.
0156 %    'mocap'      - ['on'|'off'] Display motion capture data in a separate figure.
0157 %                     To run, select an EEG data period in the scolling display using
0158 %                     the mouse. Motion capture (mocap) data should be
0159 %                     under EEG.moredata.mocap.markerPosition in xs, ys and zs fields which are
0160 %                     (number of markers, number of time points) arrays.
0161 %                    {default: 'off'}.
0162 %    'selectcommand' - [cell array] list of 3 commands (strings) to run when the mouse
0163 %                      button is down, when it is moving and when the mouse button is up.
0164 %    'ctrlselectcommand' - [cell array] same as above in conjunction with pressing the
0165 %                      CTRL key.
0166 % Outputs:
0167 %    None.  Changes are made to global variable EEG if desired.
0168 %
0169 % Function derived from eegplot.m by:
0170 % David Groppe
0171 % Kutaslab, 12/2009
0172 %
0173 % This function is simply a somewhat modified version of the eegplot.m function written by:
0174 % Arnaud Delorme & Colin Humphries, CNL/Salk Institute, SCCN/INC/UCSD, 1998-2001
0175 %
0176 
0177 
0178 % NOTES:
0179 % -Optional input parameter 'btn_command' can be used to change the command
0180 % executed by the SAVE TO WORKSPACE button. This option is not listed in help
0181 % documentation.
0182 %
0183 % -Other optional input arguments not listed in help documentation:
0184 % freqlimits
0185 %
0186 % -A minor change was made to the code that may screw up the ability of
0187 % this function to visualize continuous data. Since I don't think this function
0188 % will ever be used for continuous data, I don't think it will be a problem.
0189 % Look at revision log for details on how to undo the change.
0190 
0191 % deprecated
0192 %    'colmodif'   - nested cell array of window colors that may be marked/unmarked. Default
0193 %                   is current color only.
0194 
0195 %123456789012345678901234567890123456789012345678901234567890123456789012
0196 
0197 % Copyright (C) 2001 Arnaud Delorme & Colin Humphries, Salk Institute, arno@salk.edu
0198 %
0199 % This program is free software; you can redistribute it and/or modify
0200 % it under the terms of the GNU General Public License as published by
0201 % the Free Software Foundation; either version 2 of the License, or
0202 % (at your option) any later version.
0203 %
0204 % This program is distributed in the hope that it will be useful,
0205 % but WITHOUT ANY WARRANTY; without even the implied warranty of
0206 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0207 % GNU General Public License for more details.
0208 %
0209 % You should have received a copy of the GNU General Public License
0210 % along with this program; if not, write to the Free Software
0211 % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
0212 
0213 %%%%%%%%%%%%%%%% REVISION LOG %%%%%%%%%%%%%%%%%
0214 %
0215 % 5/11/10 Minor modification to make it possible to plot one epoch at a
0216 % time. This may screw up ability of function to plot continuous data. If
0217 % anyone ever does want to use this function for continuous data, you can
0218 % undo the change.  Find it by searching for '?? DG'. -DG
0219 
0220 
0221 % Note for programmers - Internal variable structure:
0222 % All in g. except for Eposition and Eg.spacingwhich are inside the boxes
0223 % gcf
0224 %    1 - winlength
0225 %    2 - srate
0226 %    3 - children
0227 % 'backeeg' axis
0228 %    1 - trialtag
0229 %    2 - g.winrej
0230 %    3 - nested call flag
0231 % 'eegaxis'
0232 %    1 - data
0233 %    2 - colorlist
0234 %    3 - submean    % on or off, subtract the mean
0235 %    4 - maxfreq    % empty [] if no gfrequency content
0236 % 'buttons hold other informations' Eposition for instance hold the current postition
0237 
0238 function actplot(command,varargin) % p1,p2,p3,p4,p5,p6,p7,p8,p9)
0239 
0240 % Defaults (can be re-defined):
0241 
0242 DEFAULT_PLOT_COLOR = { [0 0 1], [0.7 0.7 0.7]};         % EEG line color
0243 try, icadefs;
0244     DEFAULT_FIG_COLOR = BACKCOLOR;
0245     BUTTON_COLOR = GUIBUTTONCOLOR;
0246 catch
0247     DEFAULT_FIG_COLOR = [1 1 1];
0248     BUTTON_COLOR =[0.8 0.8 0.8];
0249 end;
0250 DEFAULT_AXIS_COLOR = 'k';         % X-axis, Y-axis Color, text Color
0251 DEFAULT_GRID_SPACING = 1;         % Grid lines every n seconds
0252 DEFAULT_GRID_STYLE = '-';         % Grid line style
0253 YAXIS_NEG = 'off';                % 'off' = positive up
0254 DEFAULT_NOUI_PLOT_COLOR = 'k';    % EEG line color for noui option
0255 %   0 - 1st color in AxesColorOrder
0256 SPACING_EYE = 'on';               % g.spacingI on/off
0257 SPACING_UNITS_STRING = '';        % '\muV' for microvolt optional units for g.spacingI Ex. uV
0258 MAXEVENTSTRING = 10;
0259 DEFAULT_AXES_POSITION = [0.0964286 0.15 0.842 0.75-(MAXEVENTSTRING-5)/100];
0260 % dimensions of main EEG axes
0261 ORIGINAL_POSITION = [50 50 800 500];
0262 
0263 global EEG;
0264 if isempty(EEG),
0265    error('The data to be visualized need to be in a global variable called EEG.'); 
0266 end
0267 
0268 if nargin < 1
0269     help actplot
0270     return
0271 end
0272 
0273 % %%%%%%%%%%%%%%%%%%%%%%%%
0274 % Setup inputs
0275 % %%%%%%%%%%%%%%%%%%%%%%%%
0276 
0277 if strcmpi(command,'initialize'), % If NOT a 'noui' call or a callback from uicontrols
0278    
0279     try
0280         options = varargin;
0281         for index = 1:length(options)
0282             if iscell(options{index}) & ~iscell(options{index}{1}), options{index} = { options{index} }; end;
0283         end;
0284         if ~isempty( varargin ), g=struct(options{:});
0285         else g= []; end;
0286     catch
0287         disp('actplot() error: calling convention {''key'', value, ... } error'); return;
0288     end;
0289     
0290     
0291     % push button: create/remove window
0292     % ---------------------------------
0293     defdowncom   = 'actplot(''defdowncom'',   gcbf);'; % push button: create/remove window
0294     defmotioncom = 'actplot(''defmotioncom'', gcbf);'; % motion button: move windows or display current position
0295     defupcom     = 'actplot(''defupcom'',     gcbf);';
0296     defctrldowncom = ''; % CTRL press and motion -> do nothing by default
0297     defctrlmotioncom = ''; % CTRL press and motion -> do nothing by default
0298     defctrlupcom = ''; % CTRL press and up -> do nothing by default
0299     
0300     try, g.srate;             catch, g.srate        = 256;     end;
0301     try, g.spacing;             catch, g.spacing    = 0;     end;
0302     try, g.eloc_file;         catch, g.eloc_file    = 0;     end; % 0 mean numbered
0303     try, g.winlength;         catch, g.winlength    = 5;     end; % Number of seconds of EEG displayed
0304     try, g.position;         catch, g.position    = ORIGINAL_POSITION;     end;
0305     try, g.title;             catch, g.title        = ['Scroll activity -- actplot()'];     end;
0306     try, g.trialstag;         catch, g.trialstag    = -1;     end;
0307     try, g.winrej;             catch, g.winrej        = [];     end;
0308     try, g.btn_command;             catch, g.btn_command    = '';     end;
0309     try, g.tag;                 catch, g.tag        = 'EEGPLOT'; end;
0310     try, g.xgrid;            catch, g.xgrid        = 'off'; end;
0311     try, g.ygrid;            catch, g.ygrid        = 'off'; end;
0312     try, g.color;            catch, g.color        = 'off'; end;
0313     try, g.submean;            catch, g.submean    = 'on'; end;
0314     try, g.children;            catch, g.children    = 0; end;
0315     try, g.limits;            catch, g.limits        = [0 1000*(size(EEG.icaact,2)-1)/g.srate]; end;
0316     try, g.freqlimits;        catch, g.freqlimits    = []; end;
0317     try, g.showepochs;        catch, g.showepochs    = 1:size(EEG.icaact,3); end;
0318     try, g.dispchans;         catch, g.dispchans  = size(EEG.icaact,1); end;
0319     try, g.wincolor;         catch, g.wincolor   =  EEG.reject.rejmanualcol; end; %epoch background color when clicked; same color as manual reject
0320     %        try, g.wincolor;         catch, g.wincolor   = [ 0.8345 1 0.9560];
0321     %        end; <--original cyan-ish color
0322     try, g.butlabel;         catch, g.butlabel   = 'REJECT'; end;
0323     try, g.colmodif;         catch, g.colmodif   = { g.wincolor }; end;
0324     try, g.scale;             catch, g.scale      = 'on'; end;
0325     try, g.events;             catch, g.events      = []; end;
0326     try, g.ploteventdur;     catch, g.ploteventdur = 'off'; end;
0327     try, g.data2;            catch, g.data2      = []; end;
0328     try, g.plotdata2;        catch, g.plotdata2 = 'off'; end;
0329     try, g.mocap;            catch, g.mocap        = 'off'; end; % nima
0330     try, g.selectcommand;     catch, g.selectcommand     = { defdowncom defmotioncom defupcom }; end;
0331     try, g.ctrlselectcommand; catch, g.ctrlselectcommand = { defctrldowncom defctrlmotioncom defctrlupcom }; end;
0332 
0333     if isempty(EEG.icawinv),
0334         error('ICA has not been applied to these data.  You need to run ICA before using this function.');
0335     end
0336     data=EEG.icaact(:,:,g.showepochs);
0337     g.winrej=[];
0338      %manually rejected epochs
0339      if isempty(EEG.reject.icarejmanual),
0340          EEG.reject.icarejmanual=zeros(1,size(EEG.icaact,3)); %initialize
0341      else
0342          already_rejected=[];
0343          if ~isempty(EEG.reject.icarejmanualE),
0344              already_rejected=find(sum(EEG.reject.icarejmanualE(:,g.showepochs))>0);
0345          end
0346          if ~isempty(EEG.reject.icarejmanual),
0347              already_rejected=[already_rejected find(EEG.reject.icarejmanual(g.showepochs)>0)];
0348              already_rejected=unique(already_rejected);
0349          end
0350          if ~isempty(already_rejected),
0351              g.winrej=[g.winrej; zeros(length(already_rejected),EEG.nbchan+5)];
0352              ar_count=0;
0353             for ar=already_rejected,
0354                 ar_count=ar_count+1;
0355                 g.winrej(ar_count,1:5)=[EEG.pnts*(ar-1) EEG.pnts*ar EEG.reject.rejmanualcol];
0356                 % First two numbers are the first and final time point of the epoch.
0357                 % Lattermost three numbers refer to background color for
0358                 % the epoch
0359                 
0360                 if ~isempty(EEG.reject.icarejmanualE),
0361                     blame_comp=find(EEG.reject.icarejmanualE(:,g.showepochs(ar))>0);
0362                     if ~isempty(blame_comp),
0363                         g.winrej(ar_count,5+blame_comp)=1;
0364                     end
0365                 end
0366             end
0367         end
0368     end
0369         
0370     %Improbable Data
0371     already_rejected=[];
0372     if ~isempty(EEG.reject.icarejjpE),
0373         already_rejected=find(sum(EEG.reject.icarejjpE(:,g.showepochs))>0);
0374     end
0375     if ~isempty(EEG.reject.icarejjp),
0376         already_rejected=[already_rejected find(EEG.reject.icarejjp(g.showepochs)>0)];
0377         already_rejected=unique(already_rejected);
0378     end
0379     if ~isempty(already_rejected),
0380         ar_count=size(g.winrej,1);
0381         g.winrej=[g.winrej; zeros(length(already_rejected),EEG.nbchan+5)];
0382         for ar=already_rejected,
0383             ar_count=ar_count+1;
0384             g.winrej(ar_count,1:5)=[EEG.pnts*(ar-1) EEG.pnts*ar EEG.reject.rejjpcol];
0385             
0386             if ~isempty(EEG.reject.icarejjpE),
0387                 blame_comp=find(EEG.reject.icarejjpE(:,g.showepochs(ar))>0);
0388                 if ~isempty(blame_comp),
0389                     g.winrej(ar_count,5+blame_comp)=1;
0390                 end
0391             end
0392         end
0393     end
0394         
0395     %Abnormal Distributions
0396     already_rejected=[];
0397     if ~isempty(EEG.reject.icarejkurtE),
0398         already_rejected=find(sum(EEG.reject.icarejkurtE(:,g.showepochs))>0);
0399     end
0400     if ~isempty(EEG.reject.icarejkurt),
0401         already_rejected=[already_rejected find(EEG.reject.icarejkurt(g.showepochs)>0)];
0402         already_rejected=unique(already_rejected);
0403     end
0404     if ~isempty(already_rejected),
0405         ar_count=size(g.winrej,1);
0406         g.winrej=[g.winrej; zeros(length(already_rejected),EEG.nbchan+5)];
0407         for ar=already_rejected,
0408             ar_count=ar_count+1;
0409             g.winrej(ar_count,1:5)=[EEG.pnts*(ar-1) EEG.pnts*ar EEG.reject.rejkurtcol];
0410             
0411             if ~isempty(EEG.reject.icarejkurtE),
0412                 blame_comp=find(EEG.reject.icarejkurtE(:,g.showepochs(ar))>0);
0413                 if ~isempty(blame_comp),
0414                     g.winrej(ar_count,5+blame_comp)=1;
0415                 end
0416             end
0417         end
0418     end
0419                 
0420     %Abnormal Value
0421     already_rejected=[];
0422     if ~isempty(EEG.reject.icarejthreshE),
0423         already_rejected=find(sum(EEG.reject.icarejthreshE(:,g.showepochs))>0);
0424     end
0425     if ~isempty(EEG.reject.icarejthresh),
0426         already_rejected=[already_rejected find(EEG.reject.icarejthresh(g.showepochs)>0)];
0427         already_rejected=unique(already_rejected);
0428     end
0429     if ~isempty(already_rejected),
0430         ar_count=size(g.winrej,1);
0431         g.winrej=[g.winrej; zeros(length(already_rejected),EEG.nbchan+5)];
0432         for ar=already_rejected,
0433             ar_count=ar_count+1;
0434             g.winrej(ar_count,1:5)=[EEG.pnts*(ar-1) EEG.pnts*ar EEG.reject.rejthreshcol];
0435                         
0436             if ~isempty(EEG.reject.icarejthreshE),
0437                 blame_comp=find(EEG.reject.icarejthreshE(:,g.showepochs(ar))>0);
0438                 if ~isempty(blame_comp),
0439                     g.winrej(ar_count,5+blame_comp)=1;
0440                 end
0441             end
0442         end
0443     end
0444         
0445     %Abnormal Trends (Drift)
0446     already_rejected=[];
0447     if ~isempty(EEG.reject.icarejconstE),
0448         already_rejected=find(sum(EEG.reject.icarejconstE(:,g.showepochs))>0);
0449     end
0450     if ~isempty(EEG.reject.icarejconst),
0451         already_rejected=[already_rejected find(EEG.reject.icarejconst(g.showepochs)>0)];
0452         already_rejected=unique(already_rejected);
0453     end
0454     if ~isempty(already_rejected),
0455         ar_count=size(g.winrej,1);
0456         g.winrej=[g.winrej; zeros(length(already_rejected),EEG.nbchan+5)];
0457         for ar=already_rejected,
0458             ar_count=ar_count+1;
0459             g.winrej(ar_count,1:5)=[EEG.pnts*(ar-1) EEG.pnts*ar EEG.reject.rejconstcol];
0460             
0461             if ~isempty(EEG.reject.icarejconstE),
0462                 blame_comp=find(EEG.reject.icarejconstE(:,g.showepochs(ar))>0);
0463                 if ~isempty(blame_comp),
0464                     g.winrej(ar_count,5+blame_comp)=1;
0465                 end
0466             end
0467         end
0468     end
0469     
0470     %Abnormal Spectra
0471     already_rejected=[];
0472     if ~isempty(EEG.reject.icarejfreqE),
0473         already_rejected=find(sum(EEG.reject.icarejfreqE(:,g.showepochs))>0);
0474     end
0475     if ~isempty(EEG.reject.icarejfreq),
0476         already_rejected=[already_rejected find(EEG.reject.icarejfreq(g.showepochs)>0)];
0477         already_rejected=unique(already_rejected);
0478     end
0479     if ~isempty(already_rejected),
0480         ar_count=size(g.winrej,1);
0481         g.winrej=[g.winrej; zeros(length(already_rejected),EEG.nbchan+5)];
0482         for ar=already_rejected,
0483             ar_count=ar_count+1;
0484             g.winrej(ar_count,1:5)=[EEG.pnts*(ar-1) EEG.pnts*ar EEG.reject.rejfreqcol];
0485             
0486             if ~isempty(EEG.reject.icarejfreqE),
0487                 blame_comp=find(EEG.reject.icarejfreqE(:,g.showepochs(ar))>0);
0488                 if ~isempty(blame_comp),
0489                     g.winrej(ar_count,5+blame_comp)=1;
0490                 end
0491             end
0492         end
0493     end
0494     
0495     if strcmpi(g.ploteventdur, 'on'), g.ploteventdur = 1; else g.ploteventdur = 0; end;
0496     %Uncomment the stuff below if you want to use this function for
0497     %continuous data. It was commented out because it screws up plotting a
0498     %single epoch of data. ?? DG
0499     %if ndims(data) > 2
0500     %    g.trialstag = size(    data, 2);
0501     %end;
0502     g.trialstag = size(    data, 2); % Delete this line if you want to use this function for continuous data
0503     
0504     gfields = fieldnames(g);
0505     for index=1:length(gfields)
0506         switch gfields{index}
0507             case {'spacing', 'srate' 'eloc_file' 'winlength' 'position' 'title' ...
0508                     'trialstag'  'winrej' 'btn_command' 'tag' 'xgrid' 'ygrid' 'color' 'colmodif'...
0509                     'freqlimits' 'submean' 'children' 'limits' 'dispchans' 'wincolor' 'showepochs' ...
0510                     'ploteventdur' 'butlabel' 'scale' 'events' 'data2' 'plotdata2' 'mocap' 'selectcommand' 'ctrlselectcommand'},;
0511             otherwise, error(['actplot: unrecognized option: ''' gfields{index} '''' ]);
0512         end;
0513     end;
0514     
0515     g.data=data;
0516     
0517     if length(g.srate) > 1
0518         disp('Error: srate must be a single number'); return;
0519     end;
0520     if length(g.spacing) > 1
0521         disp('Error: ''spacing'' must be a single number'); return;
0522     end;
0523     if length(g.winlength) > 1
0524         disp('Error: winlength must be a single number'); return;
0525     end;
0526     if isstr(g.title) > 1
0527         disp('Error: title must be a string'); return;
0528     end;
0529     if isstr(g.btn_command) > 1
0530         disp('Error: command must be a string'); return;
0531     end;
0532     if isstr(g.tag) > 1
0533         disp('Error: tag must be a string'); return;
0534     end;
0535     if length(g.position) ~= 4
0536         disp('Error: position must be a 4 elements array'); return;
0537     end;
0538     switch lower(g.xgrid)
0539         case { 'on', 'off' },;
0540         otherwise disp('Error: xgrid must be either ''on'' or ''off'''); return;
0541     end;
0542     switch lower(g.ygrid)
0543         case { 'on', 'off' },;
0544         otherwise disp('Error: ygrid must be either ''on'' or ''off'''); return;
0545     end;
0546     switch lower(g.submean)
0547         case { 'on' 'off' };
0548         otherwise disp('Error: submean must be either ''on'' or ''off'''); return;
0549     end;
0550     switch lower(g.scale)
0551         case { 'on' 'off' };
0552         otherwise disp('Error: scale must be either ''on'' or ''off'''); return;
0553     end;
0554     
0555     if ~iscell(g.color)
0556         switch lower(g.color)
0557             case 'on', g.color = { 'k', 'm', 'c', 'b', 'g' };
0558             case 'off', g.color = { [ 0 0 0.4] };
0559             otherwise
0560                 disp('Error: color must be either ''on'' or ''off'' or a cell array');
0561                 return;
0562         end;
0563     end;
0564     if length(g.dispchans) > size(data,1)
0565         g.dispchans = size(data,1);
0566     end;
0567     if ~iscell(g.colmodif)
0568         g.colmodif = { g.colmodif };
0569     end;
0570     if strcmpi(g.submean, 'on')
0571         g.submean = 'nan';
0572     end;
0573     
0574     % convert color to modify into array of float
0575     % -------------------------------------------
0576     for index = 1:length(g.colmodif)
0577         tmpcolmodif(index) = g.colmodif{index}(1) ...
0578             + g.colmodif{index}(2)*10 ...
0579             + g.colmodif{index}(3)*100;
0580     end;
0581     g.colmodif = tmpcolmodif;
0582     
0583     [g.chans,g.frames, tmpnb] = size(data);
0584     g.frames = g.frames*tmpnb;
0585     
0586     if g.spacing == 0
0587         maxindex = min(1000, g.frames);
0588         stds = std(data(:,1:maxindex),[],2);
0589         stds = sort(stds);
0590         if length(stds) > 2
0591             stds = mean(stds(2:end-1));
0592         else
0593             stds = mean(stds);
0594         end;
0595         g.spacing = stds*3;
0596         if g.spacing > 10
0597             g.spacing = round(g.spacing);
0598         end
0599         if g.spacing  == 0 | isnan(g.spacing)
0600             g.spacing = 1; % default
0601         end;
0602     end
0603     
0604     % set defaults
0605     % ------------
0606     g.incallback = 0;
0607     g.winstatus = 1;
0608     g.setelectrode  = 0;
0609     [g.chans,g.frames,tmpnb] = size(data);
0610     g.frames = g.frames*tmpnb;
0611     g.nbdat = 1; % deprecated
0612     g.time  = 0;
0613     g.elecoffset = 0;
0614     
0615     % %%%%%%%%%%%%%%%%%%%%%%%%
0616     % Prepare figure and axes
0617     % %%%%%%%%%%%%%%%%%%%%%%%%
0618     
0619     figh = figure('UserData', g,... % store the settings here
0620         'Color',DEFAULT_FIG_COLOR, 'name', g.title,...
0621         'MenuBar','none','tag', g.tag ,'Position',g.position, ...
0622         'numbertitle', 'off', 'visible', 'off');
0623     
0624     pos = get(figh,'position'); % plot relative to current axes
0625     q = [pos(1) pos(2) 0 0];
0626     s = [pos(3) pos(4) pos(3) pos(4)]./100;
0627     clf;
0628     
0629     % Background axis
0630     % ---------------
0631     ax0 = axes('tag','backeeg','parent',figh,...
0632         'Position',DEFAULT_AXES_POSITION,...
0633         'Box','off','xgrid','off', 'xaxislocation', 'top');
0634     
0635     % Drawing axis
0636     % ---------------
0637     YLabels = num2str((1:g.chans)');  % Use numbers as default
0638     YLabels = flipud(str2mat(YLabels,' '));
0639     ax1 = axes('Position',DEFAULT_AXES_POSITION,...
0640         'userdata', data, ...% store the data here
0641         'tag','eegaxis','parent',figh,...%(when in g, slow down display)
0642         'Box','on','xgrid', g.xgrid,'ygrid', g.ygrid,...
0643         'gridlinestyle',DEFAULT_GRID_STYLE,...
0644         'Xlim',[0 g.winlength*g.srate],...
0645         'xtick',[0:g.srate*DEFAULT_GRID_SPACING:g.winlength*g.srate],...
0646         'Ylim',[0 (g.chans+1)*g.spacing],...
0647         'YTick',[0:g.spacing:g.chans*g.spacing],...
0648         'YTickLabel', YLabels,...
0649         'XTickLabel',num2str((0:DEFAULT_GRID_SPACING:g.winlength)'),...
0650         'TickLength',[.005 .005],...
0651         'Color','none',...
0652         'XColor',DEFAULT_AXIS_COLOR,...
0653         'YColor',DEFAULT_AXIS_COLOR);
0654     
0655     if isstr(g.eloc_file) | isstruct(g.eloc_file)  % Read in electrode names
0656         if isstruct(g.eloc_file) & length(g.eloc_file) > size(data,1)
0657             g.eloc_file(end) = []; % common reference channel location
0658         end;
0659         actplot('setelect', g.eloc_file, ax1);
0660     end;
0661     
0662     % %%%%%%%%%%%%%%%%%%%%%%%%%
0663     % Set up uicontrols
0664     % %%%%%%%%%%%%%%%%%%%%%%%%%
0665     
0666     % positions of buttons
0667     posbut(1,:) = [ 0.0464    0.0254    0.0385    0.0339 ]; % <<
0668     posbut(2,:) = [ 0.0924    0.0254    0.0288    0.0339 ]; % <
0669     posbut(3,:) = [ 0.1924    0.0254    0.0299    0.0339 ]; % >
0670     posbut(4,:) = [ 0.2297    0.0254    0.0385    0.0339 ]; % >>
0671     posbut(5,:) = [ 0.1287    0.0203    0.0561    0.0390 ]; % Eposition
0672     posbut(6,:) = [ 0.4744    0.0236    0.0582    0.0390 ]; % Espacing
0673     posbut(7,:) = [ 0.2762    0.01    0.0582    0.0390 ]; % elec
0674     posbut(8,:) = [ 0.3256    0.01    0.0707    0.0390 ]; % g.time
0675     posbut(9,:) = [ 0.4006    0.01    0.0582    0.0390 ]; % value
0676     posbut(14,:) = [ 0.2762    0.05    0.0582    0.0390 ]; % elec tag
0677     posbut(15,:) = [ 0.3256    0.05    0.0707    0.0390 ]; % g.time tag
0678     posbut(16,:) = [ 0.4006    0.05    0.0582    0.0390 ]; % value tag
0679     posbut(10,:) = [ 0.5437    0.0458    0.0275    0.0270 ]; % +
0680     posbut(11,:) = [ 0.5437    0.0134    0.0275    0.0270 ]; % -
0681     posbut(12,:) = [ 0.6    0.02    0.14    0.05 ]; % cancel
0682     posbut(13,:) = [-0.15   0.02    0.07    0.05 ]; % cancel
0683     posbut(17,:) = [-0.06    0.02    0.09    0.05 ]; % events types
0684     posbut(20,:) = [-0.17   0.15     0.015    0.8 ]; % slider
0685     posbut(:,1) = posbut(:,1)+0.2;
0686     
0687     % Five move buttons: << < text > >>
0688     
0689     u(1) = uicontrol('Parent',figh, ...
0690         'Units', 'normalized', ...
0691         'Position', posbut(1,:), ...
0692         'Tag','Pushbutton1',...
0693         'string','<<',...
0694         'ToolTipString','Show immediately preceding set of epochs (if any).', ...
0695         'Callback','actplot(''drawp'',1)');
0696     u(2) = uicontrol('Parent',figh, ...
0697         'Units', 'normalized', ...
0698         'Position', posbut(2,:), ...
0699         'Tag','Pushbutton2',...
0700         'string','<',...
0701         'ToolTipString','Go back one epoch (if possible).', ...
0702         'Callback','actplot(''drawp'',2)');
0703     u(5) = uicontrol('Parent',figh, ...
0704         'Units', 'normalized', ...
0705         'BackgroundColor',[1 1 1], ...
0706         'Position', posbut(5,:), ...
0707         'Style','edit', ...
0708         'Tag','EPosition',...
0709         'ToolTipString',sprintf('The integer in the box is the order of the leftmost epoch out of the %d epochs visualized in this figure (e.g., 1 means it is the first epoch)', ...
0710             length(g.showepochs)), ...
0711         'string', 1,...
0712         'Callback', 'actplot(''drawp'',0);' );
0713     u(3) = uicontrol('Parent',figh, ...
0714         'Units', 'normalized', ...
0715         'Position',posbut(3,:), ...
0716         'Tag','Pushbutton3',...
0717         'string','>',...
0718          'ToolTipString','Go forward one epoch (if possible).', ...
0719         'Callback','actplot(''drawp'',3)');
0720     u(4) = uicontrol('Parent',figh, ...
0721         'Units', 'normalized', ...
0722         'Position',posbut(4,:), ...
0723         'Tag','Pushbutton4',...
0724         'string','>>',...
0725         'ToolTipString','Show the subsequent set of epochs (if any).', ...
0726         'Callback','actplot(''drawp'',4)');
0727     
0728     % Text edit fields: ESpacing
0729     
0730     u(6) = uicontrol('Parent',figh, ...
0731         'Units', 'normalized', ...
0732         'BackgroundColor',[1 1 1], ...
0733         'Position', posbut(6,:), ...
0734         'Style','edit', ...
0735         'Tag','ESpacing',...
0736         'string',num2str(g.spacing),...
0737         'Callback', 'actplot(''draws'',0);' );
0738     
0739     % Slider for vertical motion
0740     u(20) = uicontrol('Parent',figh, ...
0741         'Units', 'normalized', ...
0742         'Position', posbut(20,:), ...
0743         'Style','slider', ...
0744         'visible', 'off', ...
0745         'sliderstep', [0.9 1], ...
0746         'Tag','eegslider', ...
0747         'callback', [ 'tmpg = get(gcbf, ''userdata'');' ...
0748         'tmpg.elecoffset = get(gcbo, ''value'')*(tmpg.chans-tmpg.dispchans);' ...
0749         'set(gcbf, ''userdata'', tmpg);' ...
0750         'actplot(''drawp'',0);' ...
0751         'clear tmpg;' ], ...
0752         'value', 0);
0753     
0754     % Channels, position, value and tag
0755     
0756     u(9) = uicontrol('Parent',figh, ...
0757         'Units', 'normalized', ...
0758         'BackgroundColor',DEFAULT_FIG_COLOR, ...
0759         'Position', posbut(7,:), ...
0760         'Style','text', ...
0761         'Tag','Eelec',...
0762         'string',' ');
0763     u(10) = uicontrol('Parent',figh, ...
0764         'Units', 'normalized', ...
0765         'BackgroundColor',DEFAULT_FIG_COLOR, ...
0766         'Position', posbut(8,:), ...
0767         'Style','text', ...
0768         'Tag','Etime',...
0769         'string','0.00');
0770     u(11) = uicontrol('Parent',figh, ...
0771         'Units', 'normalized', ...
0772         'BackgroundColor',DEFAULT_FIG_COLOR, ...
0773         'Position',posbut(9,:), ...
0774         'Style','text', ...
0775         'Tag','Evalue',...
0776         'string','0.00');
0777     
0778     u(14)= uicontrol('Parent',figh, ...
0779         'Units', 'normalized', ...
0780         'BackgroundColor',DEFAULT_FIG_COLOR, ...
0781         'Position', posbut(14,:), ...
0782         'Style','text', ...
0783         'Tag','Eelecname',...
0784         'string','Chan.');
0785     u(15) = uicontrol('Parent',figh, ...
0786         'Units', 'normalized', ...
0787         'BackgroundColor',DEFAULT_FIG_COLOR, ...
0788         'Position', posbut(15,:), ...
0789         'Style','text', ...
0790         'Tag','Etimename',...
0791         'string','Time');
0792     u(16) = uicontrol('Parent',figh, ...
0793         'Units', 'normalized', ...
0794         'BackgroundColor',DEFAULT_FIG_COLOR, ...
0795         'Position',posbut(16,:), ...
0796         'Style','text', ...
0797         'Tag','Evaluename',...
0798         'string','Value');
0799     
0800     % ESpacing buttons: + -
0801     u(7) = uicontrol('Parent',figh, ...
0802         'Units', 'normalized', ...
0803         'Position',posbut(10,:), ...
0804         'Tag','Pushbutton5',...
0805         'string','+',...
0806         'FontSize',8,...
0807         'Callback','actplot(''draws'',1)');
0808     u(8) = uicontrol('Parent',figh, ...
0809         'Units', 'normalized', ...
0810         'Position',posbut(11,:), ...
0811         'Tag','Pushbutton6',...
0812         'string','-',...
0813         'FontSize',8,...
0814         'Callback','actplot(''draws'',2)');
0815     
0816     if isempty(g.btn_command) tmpcom = ['fprintf(''%d epoch(s) out of the %d displayed have been marked for rejection in ', ...
0817             'global variable EEG\n'',nrej,length(g.showepochs));'];
0818     else tmpcom = g.btn_command;
0819     end;
0820     acceptcommand = [ 'g = get(gcbf, ''userdata'');' ...
0821         'uni_rej=unique(g.winrej(:,1));' ...
0822         'nrej=length(uni_rej); ' ...
0823         'binary_rej=zeros(1,length(g.showepochs)); ', ...
0824         'for rejep=1:nrej, ep_id=1+uni_rej(rejep)/EEG.pnts; binary_rej(ep_id)=1; end; ', ...
0825         'EEG.reject.icarejmanual(g.showepochs)=binary_rej; ' ...
0826         'if g.children, delete(g.children); end;' ...
0827         'delete(gcbf);' ...
0828         tmpcom ...
0829         '; clear g;']; % quitting expression
0830     if ~isempty(g.btn_command)
0831         u(12) = uicontrol('Parent',figh, ...
0832             'Units', 'normalized', ...
0833             'Position',posbut(12,:), ...
0834             'Tag','Accept',...
0835             'string',g.butlabel, 'callback', acceptcommand);
0836     end;
0837 
0838     %h_close = uicontrol('Parent',figh, ...
0839     u(13) = uicontrol('Parent',figh, ...
0840         'Units', 'normalized', ...
0841         'Position',posbut(13,:), ...
0842         'ToolTipString','Closes figure without saving any changes to epoch rejection labels.', ...
0843         'string',fastif(isempty(g.btn_command),'CLOSE', 'CANCEL'), 'callback', ...
0844         [    'g = get(gcbf, ''userdata'');' ...
0845         'if g.children, delete(g.children); end;' ...
0846         'close(gcbf);'] );
0847     
0848     h_acpt = uicontrol('Parent',figh, ...
0849         'Units', 'normalized', ...
0850         'Position',posbut(13,:)+[.73 0 .12 0], ...
0851         'string','SAVE TO WORKSPACE', ...
0852         'Tag','SAVE', ...
0853         'ToolTipString',['Saves any changes to epoch rejection labels to global EEG variable and closes figure.', ...
0854         10 'EEG variable will still need to be saved to disk to make changes permanent.'], ...
0855         'units','normalized', ...
0856         'style','pushbutton', ...
0857         'enable','off', ...
0858         'callback',acceptcommand);
0859     g.h_acpt=h_acpt; %add to g so that it is saved with userdata later
0860     
0861     if ~isempty(g.events)
0862         u(17) = uicontrol('Parent',figh, ...
0863             'Units', 'normalized', ...
0864             'Position',posbut(17,:), ...
0865             'string', 'Event types', 'callback', 'actplot(''drawlegend'', gcbf)');
0866     end;
0867     
0868     set(u,'Units','Normalized')
0869     
0870     % %%%%%%%%%%%%%%%%%%%%%%%%%%%
0871     % Set up uimenus
0872     % %%%%%%%%%%%%%%%%%%%%%%%%%%%
0873     
0874     % Figure Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0875     
0876     m(7) = uimenu('Parent',figh,'Label','Figure');
0877     m(8) = uimenu('Parent',m(7),'Label','Print');
0878     uimenu('Parent',m(7),'Label','Edit figure', 'Callback', 'actplot(''noui'');');
0879     uimenu('Parent',m(7),'Label','Accept and close', 'Callback', acceptcommand );
0880     uimenu('Parent',m(7),'Label','Cancel and close', 'Callback','delete(gcbf)')
0881     
0882     % Portrait %%%%%%%%
0883     timestring = ['[OBJ1,FIG1] = gcbo;',...
0884         'PANT1 = get(OBJ1,''parent'');',...
0885         'OBJ2 = findobj(''tag'',''orient'',''parent'',PANT1);',...
0886         'set(OBJ2,''checked'',''off'');',...
0887         'set(OBJ1,''checked'',''on'');',...
0888         'set(FIG1,''PaperOrientation'',''portrait'');',...
0889         'clear OBJ1 FIG1 OBJ2 PANT1;'];
0890     
0891     uimenu('Parent',m(8),'Label','Portrait','checked',...
0892         'on','tag','orient','callback',timestring)
0893     
0894     % Landscape %%%%%%%
0895     timestring = ['[OBJ1,FIG1] = gcbo;',...
0896         'PANT1 = get(OBJ1,''parent'');',...
0897         'OBJ2 = findobj(''tag'',''orient'',''parent'',PANT1);',...
0898         'set(OBJ2,''checked'',''off'');',...
0899         'set(OBJ1,''checked'',''on'');',...
0900         'set(FIG1,''PaperOrientation'',''landscape'');',...
0901         'clear OBJ1 FIG1 OBJ2 PANT1;'];
0902     
0903     uimenu('Parent',m(8),'Label','Landscape','checked',...
0904         'off','tag','orient','callback',timestring)
0905     
0906     % Print command %%%%%%%
0907     uimenu('Parent',m(8),'Label','Print','tag','printcommand','callback',...
0908         ['RESULT = inputdlg2( { ''Command:'' }, ''Print'', 1,  { ''print -r72'' });' ...
0909         'if size( RESULT,1 ) ~= 0' ...
0910         '  eval ( RESULT{1} );' ...
0911         'end;' ...
0912         'clear RESULT;' ]);
0913     
0914     % Display Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0915     
0916     m(1) = uimenu('Parent',figh,...
0917         'Label','Display', 'tag', 'displaymenu');
0918     
0919     % window grid %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0920     
0921     % userdata = 4 cells : display yes/no, color, electrode yes/no,
0922     %                      trial boundary adapt yes/no (1/0)
0923     m(11) = uimenu('Parent',m(1),'Label','Data mark/unmark', 'tag', 'displaywin', ...
0924         'userdata', { 1, [0.8 1 0.8], 0, fastif( g.trialstag(1) == -1, 0, 1)});
0925     
0926     uimenu('Parent',m(11),'Label','Hide marks','Callback', ...
0927         ['g = get(gcbf, ''userdata'');' ...
0928         'if ~g.winstatus' ...
0929         '  set(gcbo, ''label'', ''Hide marks'');' ...
0930         'else' ...
0931         '  set(gcbo, ''label'', ''Show marks'');' ...
0932         'end;' ...
0933         'g.winstatus = ~g.winstatus;' ...
0934         'set(gcbf, ''userdata'', g);' ...
0935         'actplot(''drawb''); clear g;'] )
0936     
0937     % color %%%%%%%%%%%%%%%%%%%%%%%%%%
0938     if isunix % for some reasons, does not work under Windows
0939         uimenu('Parent',m(11),'Label','Choose color', 'Callback', ...
0940             [ 'g = get(gcbf, ''userdata'');' ...
0941             'g.wincolor = uisetcolor(g.wincolor);' ...
0942             'set(gcbf, ''userdata'', g ); ' ...
0943             'clear g;'] )
0944     end;
0945     
0946     % set channels
0947     %uimenu('Parent',m(11),'Label','Mark channels', 'enable', 'off', ...
0948     %'checked', 'off', 'Callback', ...
0949     %['g = get(gcbf, ''userdata'');' ...
0950     % 'g.setelectrode = ~g.setelectrode;' ...
0951     % 'set(gcbf, ''userdata'', g); ' ...
0952     % 'if ~g.setelectrode setgcbo, ''checked'', ''on''); ...
0953     % else set(gcbo, ''checked'', ''off''); end;'...
0954     % ' clear g;'] )
0955     
0956     % trials boundaries
0957     %uimenu('Parent',m(11),'Label','Trial boundaries', 'checked', fastif( g.trialstag(1) == -1, 'off', 'on'), 'Callback', ...
0958     %['hh = findobj(''tag'',''displaywin'',''parent'', findobj(''tag'',''displaymenu'',''parent'', gcbf ));' ...
0959     % 'hhdat = get(hh, ''userdata'');' ...
0960     % 'set(hh, ''userdata'', { hhdat{1},  hhdat{2}, hhdat{3}, ~hhdat{4}} ); ' ...
0961     %'if ~hhdat{4} set(gcbo, ''checked'', ''on''); else set(gcbo, ''checked'', ''off''); end;' ...
0962     %' clear hh hhdat;'] )
0963     
0964     % plot durations
0965     % --------------
0966     if g.ploteventdur & isfield(g.events, 'duration')
0967         disp(['Use menu "Display > Hide event duration" to hide colored regions ' ...
0968             'representing event duration']);
0969     end;
0970     if isfield(g.events, 'duration')
0971         uimenu('Parent',m(1),'Label','Hide event duration','Callback', ...
0972             ['g = get(gcbf, ''userdata'');' ...
0973             'if ~g.ploteventdur' ...
0974             '  set(gcbo, ''label'', ''Hide event duration'');' ...
0975             'else' ...
0976             '  set(gcbo, ''label'', ''Show event duration'');' ...
0977             'end;' ...
0978             'g.ploteventdur = ~g.ploteventdur;' ...
0979             'set(gcbf, ''userdata'', g);' ...
0980             'actplot(''drawb''); clear g;'] )
0981     end;
0982     
0983     % X grid %%%%%%%%%%%%
0984     m(3) = uimenu('Parent',m(1),'Label','Grid');
0985     timestring = ['FIGH = gcbf;',...
0986         'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
0987         'if size(get(AXESH,''xgrid''),2) == 2' ... %on
0988         '  set(AXESH,''xgrid'',''off'');',...
0989         '  set(gcbo,''label'',''X grid on'');',...
0990         'else' ...
0991         '  set(AXESH,''xgrid'',''on'');',...
0992         '  set(gcbo,''label'',''X grid off'');',...
0993         'end;' ...
0994         'clear FIGH AXESH;' ];
0995     uimenu('Parent',m(3),'Label',fastif(strcmp(g.xgrid, 'off'), ...
0996         'X grid on','X grid off'), 'Callback',timestring)
0997     
0998     % Y grid %%%%%%%%%%%%%
0999     timestring = ['FIGH = gcbf;',...
1000         'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
1001         'if size(get(AXESH,''ygrid''),2) == 2' ... %on
1002         '  set(AXESH,''ygrid'',''off'');',...
1003         '  set(gcbo,''label'',''Y grid on'');',...
1004         'else' ...
1005         '  set(AXESH,''ygrid'',''on'');',...
1006         '  set(gcbo,''label'',''Y grid off'');',...
1007         'end;' ...
1008         'clear FIGH AXESH;' ];
1009     uimenu('Parent',m(3),'Label',fastif(strcmp(g.ygrid, 'off'), ...
1010         'Y grid on','Y grid off'), 'Callback',timestring)
1011     
1012     % Grid Style %%%%%%%%%
1013     m(5) = uimenu('Parent',m(3),'Label','Grid Style');
1014     timestring = ['FIGH = gcbf;',...
1015         'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
1016         'set(AXESH,''gridlinestyle'',''--'');',...
1017         'clear FIGH AXESH;'];
1018     uimenu('Parent',m(5),'Label','- -','Callback',timestring)
1019     timestring = ['FIGH = gcbf;',...
1020         'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
1021         'set(AXESH,''gridlinestyle'',''-.'');',...
1022         'clear FIGH AXESH;'];
1023     uimenu('Parent',m(5),'Label','_ .','Callback',timestring)
1024     timestring = ['FIGH = gcbf;',...
1025         'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
1026         'set(AXESH,''gridlinestyle'','':'');',...
1027         'clear FIGH AXESH;'];
1028     uimenu('Parent',m(5),'Label','. .','Callback',timestring)
1029     timestring = ['FIGH = gcbf;',...
1030         'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
1031         'set(AXESH,''gridlinestyle'',''-'');',...
1032         'clear FIGH AXESH;'];
1033     uimenu('Parent',m(5),'Label','__','Callback',timestring)
1034     
1035     % Scale Eye %%%%%%%%%
1036     timestring = ['[OBJ1,FIG1] = gcbo;',...
1037         'actplot(''scaleeye'',OBJ1,FIG1);',...
1038         'clear OBJ1 FIG1;'];
1039     m(7) = uimenu('Parent',m(1),'Label','Show scale','Callback',timestring);
1040     
1041     % Title %%%%%%%%%%%%
1042     uimenu('Parent',m(1),'Label','Title','Callback','actplot(''title'')')
1043     
1044     % Settings Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1045     m(2) = uimenu('Parent',figh,...
1046         'Label','Settings');
1047     
1048     % Window %%%%%%%%%%%%
1049     uimenu('Parent',m(2),'Label','Time range to display',...
1050         'Callback','actplot(''window'')')
1051     
1052     % Electrode window %%%%%%%%
1053     uimenu('Parent',m(2),'Label','Number of components to display',...
1054         'Callback','actplot(''winelec'')')
1055     
1056     % Electrodes %%%%%%%%
1057     m(6) = uimenu('Parent',m(2),'Label','Component labels');
1058     
1059     timestring = ['FIGH = gcbf;',...
1060         'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
1061         'YTICK = get(AXESH,''YTick'');',...
1062         'YTICK = length(YTICK);',...
1063         'set(AXESH,''YTickLabel'',flipud(str2mat(num2str((1:YTICK-1)''),'' '')));',...
1064         'clear FIGH AXESH YTICK;'];
1065     uimenu('Parent',m(6),'Label','Show number(s)','Callback',timestring)
1066     uimenu('Parent',m(6),'Label','Load .loc(s) file',...
1067         'Callback','actplot(''loadelect'');')
1068     
1069     % Zooms %%%%%%%%
1070     zm = uimenu('Parent',m(2),'Label','Zoom off/on');
1071     commandzoom = [ 'set(gcbf, ''windowbuttondownfcn'', [ ''zoom(gcbf,''''down''''); actplot(''''zoom'''', gcbf, 1);'' ]);' ...
1072         'tmpg = get(gcbf, ''userdata'');' ...
1073         'set(gcbf, ''windowbuttonmotionfcn'', tmpg.commandselect{2}); clear tmpg tmpstr;'];
1074     
1075     %uimenu('Parent',zm,'Label','Zoom time', 'callback', ...
1076     %             [ 'zoom(gcbf, ''xon'');' commandzoom ]);
1077     %uimenu('Parent',zm,'Label','Zoom channels', 'callback', ...
1078     %             [ 'zoom(gcbf, ''yon'');' commandzoom ]);
1079     uimenu('Parent',zm,'Label','Zoom on', 'callback', ...
1080         [ 'zoom(gcbf, ''on'');' commandzoom ]);
1081     uimenu('Parent',zm,'Label','Zoom off', 'separator', 'on', 'callback', ...
1082         ['zoom(gcbf, ''off''); tmpg = get(gcbf, ''userdata'');' ...
1083         'set(gcbf, ''windowbuttondownfcn'', tmpg.commandselect{1});' ...
1084         'set(gcbf, ''windowbuttonmotionfcn'', tmpg.commandselect{2});' ...
1085         'set(gcbf, ''windowbuttonupfcn'', tmpg.commandselect{3});' ...
1086         'clear tmpg;' ]);
1087     uimenu('Parent',figh,'Label', 'Help', 'callback', 'pophelp(''actplot'');');
1088     
1089     % Events %%%%%%%%
1090     zm = uimenu('Parent',m(2),'Label','Events');
1091     complotevent = [ 'tmpg = get(gcbf, ''userdata'');' ...
1092         'tmpg.plotevent = ''on'';' ...
1093         'set(gcbf, ''userdata'', tmpg); clear tmpg; actplot(''drawp'', 0);'];
1094     comnoevent   = [ 'tmpg = get(gcbf, ''userdata'');' ...
1095         'tmpg.plotevent = ''off'';' ...
1096         'set(gcbf, ''userdata'', tmpg); clear tmpg; actplot(''drawp'', 0);'];
1097     comeventleg  = [ 'actplot(''drawlegend'', gcbf);'];
1098     
1099     uimenu('Parent',zm,'Label','Events on'    , 'callback', complotevent, 'enable', fastif(isempty(g.events), 'off', 'on'));
1100     uimenu('Parent',zm,'Label','Events off'   , 'callback', comnoevent  , 'enable', fastif(isempty(g.events), 'off', 'on'));
1101     uimenu('Parent',zm,'Label','Events'' legend', 'callback', comeventleg , 'enable', fastif(isempty(g.events), 'off', 'on'));
1102     
1103     
1104     % %%%%%%%%%%%%%%%%%
1105     % Set up autoselect
1106     % %%%%%%%%%%%%%%%%%
1107     g.commandselect{1} = [ 'if strcmp(get(gcbf, ''SelectionType''),''alt''),' g.ctrlselectcommand{1} ...
1108         'else '                                            g.selectcommand{1} 'end;' ];
1109     g.commandselect{2} = [ 'if strcmp(get(gcbf, ''SelectionType''),''alt''),' g.ctrlselectcommand{2} ...
1110         'else '                                            g.selectcommand{2} 'end;' ];
1111     g.commandselect{3} = [ 'if strcmp(get(gcbf, ''SelectionType''),''alt''),' g.ctrlselectcommand{3} ...
1112         'else '                                            g.selectcommand{3} 'end;' ];
1113     
1114     set(figh, 'windowbuttondownfcn',   g.commandselect{1});
1115     set(figh, 'windowbuttonmotionfcn', g.commandselect{2});
1116     set(figh, 'windowbuttonupfcn',     g.commandselect{3});
1117     set(figh, 'interruptible', 'off');
1118     set(figh, 'busyaction', 'cancel');
1119     
1120     %  set(figh, 'windowbuttondownfcn', commandpush);
1121     %  set(figh, 'windowbuttonmotionfcn', commandmove);
1122     %  set(figh, 'windowbuttonupfcn', commandrelease);
1123     %  set(figh, 'interruptible', 'off');
1124     %  set(figh, 'busyaction', 'cancel');
1125     
1126     % prepare event array if any
1127     % --------------------------
1128     if ~isempty(g.events)
1129         if ~isfield(g.events, 'type') | ~isfield(g.events, 'latency'), g.events = []; end;
1130     end;
1131     
1132     if ~isempty(g.events)
1133         if isstr(g.events(1).type)
1134             [g.eventtypes tmpind indexcolor] = unique({g.events.type}); % indexcolor countinas the event type
1135         else [g.eventtypes tmpind indexcolor] = unique([ g.events.type ]);
1136         end;
1137         g.eventcolors     = { 'r', [0 0.8 0], 'm', 'c', 'k', 'b', [0 0.8 0] };
1138         g.eventstyle      = { '-' '-' '-'  '-'  '-' '-' '-' '--' '--' '--'  '--' '--' '--' '--'};
1139         g.eventwidths     = [ 2.5 1 ];
1140         g.eventtypecolors = g.eventcolors(mod([1:length(g.eventtypes)]-1 ,length(g.eventcolors))+1);
1141         g.eventcolors     = g.eventcolors(mod(indexcolor-1               ,length(g.eventcolors))+1);
1142         g.eventtypestyle  = g.eventstyle (mod([1:length(g.eventtypes)]-1 ,length(g.eventstyle))+1);
1143         g.eventstyle      = g.eventstyle (mod(indexcolor-1               ,length(g.eventstyle))+1);
1144         
1145         % for width, only boundary events have width 2 (for the line)
1146         % -----------------------------------------------------------
1147         indexwidth = ones(1,length(g.eventtypes))*2;
1148         if iscell(g.eventtypes)
1149             for index = 1:length(g.eventtypes)
1150                 if strcmpi(g.eventtypes{index}, 'boundary'), indexwidth(index) = 1; end;
1151             end;
1152         end;
1153         g.eventtypewidths = g.eventwidths (mod(indexwidth([1:length(g.eventtypes)])-1 ,length(g.eventwidths))+1);
1154         g.eventwidths     = g.eventwidths (mod(indexwidth(indexcolor)-1               ,length(g.eventwidths))+1);
1155         
1156         % latency and duration of events
1157         % ------------------------------
1158         g.eventlatencies  = [ g.events.latency ]+1;
1159         if isfield(g.events, 'duration')
1160             g.eventlatencyend   = g.eventlatencies + [ g.events.duration ]+1;
1161         else g.eventlatencyend   = [];
1162         end;
1163         g.plotevent       = 'on';
1164     end;
1165     if isempty(g.events)
1166         g.plotevent      = 'off';
1167     end;
1168     
1169     set(figh, 'userdata', g);
1170     
1171     % %%%%%%%%%%%%%%%%%%%%%%%%%%
1172     % Plot EEG Data
1173     % %%%%%%%%%%%%%%%%%%%%%%%%%%
1174     axes(ax1) %this line actually generates figure
1175     hold on
1176     
1177     % %%%%%%%%%%%%%%%%%%%%%%%%%%
1178     % Plot Spacing I
1179     % %%%%%%%%%%%%%%%%%%%%%%%%%%
1180     YLim = get(ax1,'Ylim');
1181     A = DEFAULT_AXES_POSITION;
1182     axes('Position',[A(1)+A(3) A(2) 1-A(1)-A(3) A(4)],'Visible','off','Ylim',YLim,'tag','eyeaxes')
1183     axis manual
1184     if strcmp(SPACING_EYE,'on'),  set(m(7),'checked','on')
1185     else set(m(7),'checked','off');
1186     end
1187     actplot('scaleeye', [], gcf);
1188     if strcmp(lower(g.scale), 'off')
1189         actplot('scaleeye', 'off', gcf);
1190     end;
1191     
1192     actplot('drawp', 0); 
1193     if g.dispchans ~= g.chans
1194         actplot('zoom', gcf);
1195     end;
1196     actplot('scaleeye', [], gcf);
1197     
1198     h = findobj(gcf, 'style', 'pushbutton');
1199     set(h, 'backgroundcolor', BUTTON_COLOR);
1200     h = findobj(gcf, 'tag', 'eegslider');
1201     set(h, 'backgroundcolor', BUTTON_COLOR);
1202     set(figh, 'visible', 'on');
1203     set(u(13), 'backgroundcolor', 'm');
1204     
1205     % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1206     % End Main Function
1207     % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1208     
1209 else
1210     try, p1 = varargin{1}; p2 = varargin{2}; p3 = varargin{3}; catch, end;
1211     switch command,
1212         case 'drawp' % Redraw EEG and change position
1213             
1214             % this test help to couple actplot windows
1215             if exist('p3')
1216                 figh = p3;
1217                 figure(p3);
1218             else
1219                 figh = gcf;                          % figure handle
1220             end;
1221             
1222             if strcmp(get(figh,'tag'),'dialog')
1223                 figh = get(figh,'UserData');
1224             end
1225             ax0 = findobj('tag','backeeg','parent',figh); % axes handle
1226             ax1 = findobj('tag','eegaxis','parent',figh); % axes handle
1227             g = get(figh,'UserData');
1228             data = get(ax1,'UserData');
1229             ESpacing = findobj('tag','ESpacing','parent',figh);   % ui handle
1230             EPosition = findobj('tag','EPosition','parent',figh); % ui handle
1231             if g.trialstag(1) == -1
1232                 g.time    = str2num(get(EPosition,'string')); 
1233             else
1234                 g.time    = str2num(get(EPosition,'string')); 
1235                 g.time    = g.time - 1;
1236             end;
1237             g.spacing = str2num(get(ESpacing,'string'));
1238             
1239             if p1 == 1
1240                 g.time = g.time-g.winlength;     % << subtract one window length
1241             elseif p1 == 2
1242                 g.time = g.time-fastif(g.winlength>=1, 1, g.winlength/5);             % < subtract one second
1243             elseif p1 == 3
1244                 g.time = g.time+fastif(g.winlength>=1, 1, g.winlength/5);             % > add one second
1245             elseif p1 == 4
1246                 g.time = g.time+g.winlength;     % >> add one window length
1247             end
1248             
1249             if g.trialstag ~= -1 % time in second or in trials
1250                 multiplier = g.trialstag;
1251             else
1252                 multiplier = g.srate;
1253             end;
1254             
1255             % Update edit box
1256             % ---------------
1257             g.time = max(0,min(g.time,ceil((g.frames-1)/multiplier)-g.winlength));
1258             if g.trialstag(1) == -1
1259                 set(EPosition,'string',num2str(g.time));
1260             else
1261                 set(EPosition,'string',num2str(g.time+1));
1262             end;
1263             set(figh, 'userdata', g);
1264             
1265             lowlim = round(g.time*multiplier+1); 
1266             highlim = round(min((g.time+g.winlength)*multiplier+2,g.frames));
1267             
1268             % Plot data and update axes
1269             % -------------------------
1270             if ~isempty(g.data2)
1271                 switch lower(g.submean) % subtract the mean ?
1272                     case 'on',
1273                         meandata = mean(g.data2(:,lowlim:highlim)');
1274                         if any(isnan(memdata))
1275                             meandata = nan_mean(g.data2(:,lowlim:highlim)');
1276                         end;
1277                     otherwise, meandata = zeros(1,g.chans);
1278                 end;
1279             else
1280                 switch lower(g.submean) % subtract the mean ?
1281                     case 'on',
1282                         meandata = mean(data(:,lowlim:highlim)');
1283                         if any(isnan(memdata))
1284                             meandata = nan_mean(data(:,lowlim:highlim)');
1285                         end;
1286                     otherwise, meandata = zeros(1,g.chans);
1287                 end;
1288             end;
1289             if strcmpi(g.plotdata2, 'off')
1290                 axes(ax1)
1291                 cla
1292             end;
1293             
1294             % plot data
1295             % ---------
1296             axes(ax1)
1297             hold on
1298             
1299             % plot channels whose "badchan" field is set to 1.
1300             % Bad channels are plotted first so that they appear behind the good
1301             % channels in the actplot figure window.
1302             for i = 1:g.chans
1303                 if strcmpi(g.plotdata2, 'on')
1304                     tmpcolor = [ 1 0 0 ];
1305                 else tmpcolor = g.color{mod(i-1,length(g.color))+1};
1306                 end;
1307                 
1308                 if isfield(g, 'eloc_file') & ...
1309                         isfield(g.eloc_file, 'badchan') & ...
1310                         g.eloc_file(g.chans-i+1).badchan;
1311                     tmpcolor = [ .85 .85 .85 ];
1312                     plot(data(g.chans-i+1,lowlim:highlim) -meandata(g.chans-i+1)+i*g.spacing, ...
1313                         'color', tmpcolor, 'clipping','on')
1314                     plot(1,mean(data(g.chans-i+1,lowlim:highlim) -meandata(g.chans-i+1)+i*g.spacing,2),'<r','MarkerFaceColor','r','MarkerSize',6);
1315                 end
1316                 
1317             end
1318             
1319             % plot good channels on top of bad channels (if g.eloc_file(i).badchan = 0... or there is no bad channel information)
1320             for i = 1:g.chans
1321                 if strcmpi(g.plotdata2, 'on')
1322                     tmpcolor = [ 1 0 0 ];
1323                 else tmpcolor = g.color{mod(i-1,length(g.color))+1};
1324                 end;
1325                 
1326                 %        keyboard;
1327                 if (isfield(g, 'eloc_file') & ...
1328                         isfield(g.eloc_file, 'badchan') & ...
1329                         ~g.eloc_file(g.chans-i+1).badchan) | ...
1330                         (~isfield(g, 'eloc_file')) | ...
1331                         (~isfield(g.eloc_file, 'badchan'));
1332                     plot(data(g.chans-i+1,lowlim:highlim) -meandata(g.chans-i+1)+i*g.spacing, ...
1333                         'color', tmpcolor, 'clipping','on') 
1334                 end
1335                 
1336             end
1337             
1338             % draw selected channels
1339             % ------------------------
1340             if ~isempty(g.winrej)
1341                 for tpmi = 1:size(g.winrej,1) % scan rows
1342                     if (g.winrej(tpmi,1) >= lowlim & g.winrej(tpmi,1) <= highlim) | ...
1343                             (g.winrej(tpmi,2) >= lowlim & g.winrej(tpmi,2) <= highlim)
1344                         abscmin = max(1,round(g.winrej(tpmi,1)-lowlim));
1345                         abscmax = round(g.winrej(tpmi,2)-lowlim);
1346                         maxXlim = get(gca, 'xlim');
1347                         abscmax = min(abscmax, round(maxXlim(2)-1));
1348                         for i = 1:g.chans
1349                             if g.winrej(tpmi,g.chans-i+1+5)
1350                                 plot(abscmin+1:abscmax+1,data(g.chans-i+1,abscmin+lowlim:abscmax+lowlim) ...
1351                                     -meandata(g.chans-i+1)+i*g.spacing, 'color','r','clipping','on')
1352                             end;
1353                         end
1354                     end;
1355                 end;
1356             end;
1357             
1358             set(ax1, 'Xlim',[1 g.winlength*multiplier+1],...
1359                 'XTick',[1:multiplier*DEFAULT_GRID_SPACING:g.winlength*multiplier+1]);
1360             set(ax1, 'XTickLabel', num2str((g.time:DEFAULT_GRID_SPACING:g.time+g.winlength)'))
1361             
1362             % ordinates: even if all elec are plotted, some may be hidden
1363             set(ax1, 'ylim',[g.elecoffset*g.spacing (g.elecoffset+g.dispchans+1)*g.spacing] );
1364             
1365             if g.children ~= 0
1366                 if ~exist('p2')
1367                     p2 =[];
1368                 end;
1369                 actplot( 'drawp', p1, p2, g.children);
1370                 figure(figh);
1371             end;
1372             
1373             % draw second data if necessary
1374             if ~isempty(g.data2)
1375                 tmpdata = data;
1376                 set(ax1, 'userdata', g.data2);
1377                 g.data2 = [];
1378                 g.plotdata2 = 'on';
1379                 set(figh, 'userdata', g);
1380                 actplot('drawp', 0);
1381                 g.plotdata2 = 'off';
1382                 g.data2 = get(ax1, 'userdata');
1383                 set(ax1, 'userdata', tmpdata);
1384                 set(figh, 'userdata', g);
1385             else
1386                 actplot('drawb');
1387             end;
1388             
1389         case 'drawb' % Draw background ******************************************************
1390             % Redraw EEG and change position
1391             
1392             ax0 = findobj('tag','backeeg','parent',gcf); % axes handle
1393             ax1 = findobj('tag','eegaxis','parent',gcf); % axes handle
1394             
1395             g = get(gcf,'UserData');  % Data (Note: this could also be global)
1396             
1397             % Plot data and update axes
1398             axes(ax0);
1399             cla;
1400             hold on;
1401             % plot rejected windows
1402             if g.trialstag ~= -1
1403                 multiplier = g.trialstag;
1404             else
1405                 multiplier = g.srate;
1406             end;
1407             
1408             % draw rejection windows
1409             % ----------------------
1410             lowlim = round(g.time*multiplier+1);
1411             highlim = round(min((g.time+g.winlength)*multiplier+1));
1412             displaymenu = findobj('tag','displaymenu','parent',gcf);
1413             if ~isempty(g.winrej) & g.winstatus
1414                 if g.trialstag ~= -1 % epoched data
1415                     indices = find((g.winrej(:,1)' >= lowlim & g.winrej(:,1)' <= highlim) | ...
1416                         (g.winrej(:,2)' >= lowlim & g.winrej(:,2)' <= highlim));
1417                     if ~isempty(indices)
1418                         tmpwins1 = g.winrej(indices,1)';
1419                         tmpwins2 = g.winrej(indices,2)';
1420                         tmpcols  = g.winrej(indices,3:5);
1421                         try, eval('[cumul indicescount] = histc(tmpwins1, (min(tmpwins1)-1):g.trialstag:max(tmpwins2));');
1422                         catch, [cumul indicescount] = myhistc(tmpwins1, (min(tmpwins1)-1):g.trialstag:max(tmpwins2));
1423                         end;
1424                         count = zeros(size(cumul));
1425                         %if ~isempty(find(cumul > 1)), find(cumul > 1), end;
1426                         for tmpi = 1:length(tmpwins1)
1427                             poscumul = indicescount(tmpi);
1428                             heightbeg = count(poscumul)/cumul(poscumul);
1429                             heightend = heightbeg + 1/cumul(poscumul);
1430                             count(poscumul) = count(poscumul)+1;
1431                             h = patch([tmpwins1(tmpi)-lowlim tmpwins2(tmpi)-lowlim ...
1432                                 tmpwins2(tmpi)-lowlim tmpwins1(tmpi)-lowlim], ...
1433                                 [heightbeg heightbeg heightend heightend], ...
1434                                 tmpcols(tmpi,:));  % this argument is color
1435                             set(h, 'EdgeColor', get(h, 'facecolor'))
1436                         end;
1437                     end;
1438                 else
1439                     event2plot1 = find ( g.winrej(:,1) >= lowlim & g.winrej(:,1) <= highlim );
1440                     event2plot2 = find ( g.winrej(:,2) >= lowlim & g.winrej(:,2) <= highlim );
1441                     event2plot3 = find ( g.winrej(:,1) <  lowlim & g.winrej(:,2) >  highlim );
1442                     event2plot  = union(union(event2plot1, event2plot2), event2plot3);
1443                     
1444                     for tpmi = event2plot(:)'
1445                         h = patch([g.winrej(tpmi,1)-lowlim g.winrej(tpmi,2)-lowlim ...
1446                             g.winrej(tpmi,2)-lowlim g.winrej(tpmi,1)-lowlim], ...
1447                             [0 0 1 1], [g.winrej(tpmi,3) g.winrej(tpmi,4) g.winrej(tpmi,5)]);
1448                         set(h, 'EdgeColor', get(h, 'facecolor'))
1449                     end;
1450                 end;
1451             end;
1452             
1453             % plot tags
1454             % ---------
1455             %if trialtag(1) ~= -1 & displaystatus % put tags at arbitrary places
1456             %     for tmptag = trialtag
1457             %        if tmptag >= lowlim & tmptag <= highlim
1458             %            plot([tmptag-lowlim tmptag-lowlim], [0 1], 'b--');
1459             %        end;
1460             %    end;
1461             %end;
1462             
1463             % draw events if any
1464             % ------------------
1465             if strcmpi(g.plotevent, 'on')
1466                 
1467                 % find event to plot
1468                 % ------------------
1469                 event2plot    = find ( g.eventlatencies >=lowlim & g.eventlatencies <= highlim );
1470                 if ~isempty(g.eventlatencyend)
1471                     event2plot2 = find ( g.eventlatencyend >= lowlim & g.eventlatencyend <= highlim );
1472                     event2plot3 = find ( g.eventlatencies  <  lowlim & g.eventlatencyend >  highlim );
1473                     event2plot  = union(union(event2plot, event2plot2), event2plot3);
1474                 end;
1475                 for index = 1:length(event2plot)
1476                     % draw latency line
1477                     % -----------------
1478                     tmplat = g.eventlatencies(event2plot(index))-lowlim-1;
1479                     tmph   = plot([ tmplat tmplat ], ylim, 'color', g.eventcolors{ event2plot(index) }, ...
1480                         'linestyle', g.eventstyle { event2plot(index) }, ...
1481                         'linewidth', g.eventwidths( event2plot(index) ) );
1482                     
1483                     % schtefan: add Event types text above event latency line
1484                     % -------------------------------------------------------
1485                     EVENTFONT = ' \fontsize{10} ';
1486                     ylims=ylim;
1487                     evntxt = strrep(num2str(g.events(event2plot(index)).type),'_','-');
1488                     if length(evntxt)>MAXEVENTSTRING, evntxt = [ evntxt(1:MAXEVENTSTRING-1) '...' ]; end; % truncate
1489                     try,
1490                         tmph2 = text([tmplat], ylims(2)-0.005, [EVENTFONT evntxt], ...
1491                             'color', g.eventcolors{ event2plot(index) }, ...
1492                             'horizontalalignment', 'left',...
1493                             'rotation',90);
1494                     catch, end;
1495                     
1496                     % draw duration is not 0
1497                     % ----------------------
1498                     if g.ploteventdur & ~isempty(g.eventlatencyend) ...
1499                             & g.eventwidths( event2plot(index) ) ~= 2.5 % do not plot length of boundary events
1500                         tmplatend = g.eventlatencyend(event2plot(index))-lowlim-1;
1501                         if tmplatend ~= 0,
1502                             tmplim = ylim;
1503                             tmpcol = g.eventcolors{ event2plot(index) };
1504                             h = patch([ tmplat tmplatend tmplatend tmplat ], ...
1505                                 [ tmplim(1) tmplim(1) tmplim(2) tmplim(2) ], ...
1506                                 tmpcol );  % this argument is color
1507                             set(h, 'EdgeColor', 'none')
1508                         end;
1509                     end;
1510                 end;
1511             end;
1512             
1513             if g.trialstag(1) ~= -1
1514                 
1515                 % plot trial limits
1516                 % -----------------
1517                 tmptag = [lowlim:highlim];
1518                 tmpind = find(mod(tmptag-1, g.trialstag) == 0);
1519                 for index = tmpind
1520                     plot([tmptag(index)-lowlim-1 tmptag(index)-lowlim-1], [0 1], 'b--');
1521                 end;
1522                 alltag = tmptag(tmpind);
1523                 
1524                 % compute Xticks
1525                 % --------------
1526                 tagnum = (alltag(1:length(alltag)-1)-1)/g.trialstag+1;
1527                 epoch_ids=g.showepochs(tagnum);
1528                 set(ax0,'XTickLabel', epoch_ids,'YTickLabel', [],...
1529                     'Xlim',[0 g.winlength*multiplier],...
1530                     'XTick',alltag-lowlim+g.trialstag/2, 'YTick',[], 'tag','backeeg');
1531                 
1532                 axes(ax1);
1533                 tagpos  = [];
1534                 tagtext = [];
1535                 if ~isempty(alltag)
1536                     alltag = [alltag(1)-g.trialstag alltag alltag(end)+g.trialstag]; % add border trial limits
1537                 else
1538                     alltag = [ floor(lowlim/g.trialstag)*g.trialstag ceil(highlim/g.trialstag)*g.trialstag ]+1;
1539                 end;
1540                 
1541                 nbdiv = 20/g.winlength; % approximative number of divisions
1542                 divpossible = [ 100000./[1 2 4 5] 10000./[1 2 4 5] 1000./[1 2 4 5] 100./[1 2 4 5 10 20]]; % possible increments
1543                 [tmp indexdiv] = min(abs(nbdiv*divpossible-(g.limits(2)-g.limits(1)))); % closest possible increment
1544                 
1545                 incrementpoint = divpossible(indexdiv)/1000*g.srate;
1546                 if g.limits(2) < 0, tagzerooffset  = (g.limits(2)-g.limits(1))/1000*g.srate+1;
1547                 else                tagzerooffset  = -g.limits(1)/1000*g.srate;
1548                 end;
1549                 
1550                 alltag=[alltag alltag(end)+EEG.pnts];
1551                 for i=1:length(alltag)-1          
1552                     if ~isempty(tagpos) & tagpos(end)-alltag(i)<2*incrementpoint/3
1553                         tagpos  = tagpos(1:end-1);
1554                     end;
1555                     if ~isempty(g.freqlimits)
1556                         tagpos  = [ tagpos linspace(alltag(i),alltag(i+1)-1, nbdiv) ];
1557                     else
1558                         if tagzerooffset ~= 0
1559                             tmptagpos = [alltag(i)+tagzerooffset:-incrementpoint:alltag(i)];
1560                         else
1561                             tmptagpos = [];
1562                         end;
1563                         tagpos  = [ tagpos [tmptagpos(end:-1:2) alltag(i)+tagzerooffset:incrementpoint:(alltag(i+1)-1)]];
1564                     end;
1565                 end;
1566                 % find corresponding epochs
1567                 % -------------------------
1568                 tagtext = eeg_point2lat(tagpos, floor((tagpos)/g.trialstag)+1, g.srate, g.limits, 1E-3);
1569                 set(ax1,'XTickLabel', tagtext,'XTick', tagpos-lowlim);
1570                 
1571                 
1572             else
1573                 set(ax0,'XTickLabel', [],'YTickLabel', [],...
1574                     'Xlim',[0 g.winlength*multiplier],...
1575                     'XTick',[], 'YTick',[], 'tag','backeeg');
1576                 
1577                 axes(ax1);
1578                 set(ax1,'XTickLabel', num2str((g.time:DEFAULT_GRID_SPACING:g.time+g.winlength)'),...
1579                     'XTick',[1:multiplier*DEFAULT_GRID_SPACING:g.winlength*multiplier+1]) %this is were ms ticks are added ?? fix (missing 800 ms)
1580             end;
1581             
1582             % ordinates: even if all elec are plotted, some may be hidden
1583             set(ax1, 'ylim',[g.elecoffset*g.spacing (g.elecoffset+g.dispchans+1)*g.spacing] );
1584             
1585             axes(ax1)
1586             
1587         case 'draws'
1588             % Redraw EEG and change scale
1589             
1590             ax1 = findobj('tag','eegaxis','parent',gcf);         % axes handle
1591             g = get(gcf,'UserData');
1592             data = get(ax1, 'userdata');
1593             ESpacing = findobj('tag','ESpacing','parent',gcf);   % ui handle
1594             EPosition = findobj('tag','EPosition','parent',gcf); % ui handle
1595             if g.trialstag(1) == -1
1596                 g.time    = str2num(get(EPosition,'string'));
1597             else
1598                 g.time    = str2num(get(EPosition,'string'))-1;
1599             end;
1600             g.spacing = str2num(get(ESpacing,'string'));
1601             
1602             orgspacing= g.spacing;
1603             if p1 == 1
1604                 g.spacing= g.spacing+ 0.1*orgspacing; % increase g.spacing(5%)
1605             elseif p1 == 2
1606                 g.spacing= max(0,g.spacing-0.1*orgspacing); % decrease g.spacing(5%)
1607             end
1608             if round(g.spacing*100) == 0
1609                 maxindex = min(10000, g.frames);
1610                 g.spacing = 0.01*max(max(data(:,1:maxindex),[],2),[],1)-min(min(data(:,1:maxindex),[],2),[],1);  % Set g.spacingto max/min data
1611             end;
1612             
1613             % update edit box
1614             % ---------------
1615             set(ESpacing,'string',num2str(g.spacing,4))
1616             set(gcf, 'userdata', g);
1617             actplot('drawp', 0);
1618             set(ax1,'YLim',[0 (g.chans+1)*g.spacing],'YTick',[0:g.spacing:g.chans*g.spacing])
1619             set(ax1, 'ylim',[g.elecoffset*g.spacing (g.elecoffset+g.dispchans+1)*g.spacing] );
1620             
1621             % update scaling eye (I) if it exists
1622             % -----------------------------------
1623             eyeaxes = findobj('tag','eyeaxes','parent',gcf);
1624             if ~isempty(eyeaxes)
1625                 eyetext = findobj('type','text','parent',eyeaxes,'tag','thescalenum');
1626                 set(eyetext,'string',num2str(g.spacing,4))
1627             end
1628             
1629             return;
1630             
1631         case 'window'  % change window size
1632             % get new window length with dialog box
1633             % -------------------------------------
1634             g = get(gcf,'UserData');
1635             result       = inputdlg2( { fastif(g.trialstag==-1,'New window length (s):', 'Number of epoch(s):') }, 'Change window length', 1,  { num2str(g.winlength) });
1636             if size(result,1) == 0 return; end;
1637             
1638             g.winlength = eval(result{1});
1639             set(gcf, 'UserData', g);
1640             actplot('drawp',0);
1641             return;
1642             
1643         case 'winelec'  % change channel window size
1644             % get new window length with dialog box
1645             % -------------------------------------
1646             fig = gcf;
1647             g = get(gcf,'UserData');
1648             result = inputdlg2( ...
1649                 { 'Number of components to display:' } , 'Change number of components to display', 1,  { num2str(g.dispchans) });
1650             if size(result,1) == 0 return; end;
1651             
1652             g.dispchans = eval(result{1});
1653             if g.dispchans<0 | g.dispchans>g.chans
1654                 g.dispchans =g.chans;
1655             end;
1656             set(gcf, 'UserData', g);
1657             actplot('updateslider', fig);
1658             actplot('drawp',0);
1659             actplot('scaleeye', [], fig);
1660             return;
1661             
1662         case 'loadelect' % load channels
1663             [inputname,inputpath] = uigetfile('*','Channel locations file');
1664             if inputname == 0 return; end;
1665             if ~exist([ inputpath inputname ])
1666                 error('no such file');
1667             end;
1668             
1669             AXH0 = findobj('tag','eegaxis','parent',gcf);
1670             actplot('setelect',[ inputpath inputname ],AXH0);
1671             return;
1672             
1673         case 'setelect'
1674             % Set channels
1675             eloc_file = p1;
1676             axeshand = p2;
1677             outvar1 = 1;
1678             if isempty(eloc_file)
1679                 outvar1 = 0;
1680                 return
1681             end
1682             
1683             tmplocs = readlocs(eloc_file);
1684             YLabels = { tmplocs.labels };
1685             YLabels = strvcat(YLabels);
1686             
1687             YLabels = flipud(str2mat(YLabels,' '));
1688             set(axeshand,'YTickLabel',YLabels)
1689             
1690         case 'title'
1691             % Get new title
1692             h = findobj('tag', 'actplottitle');
1693             
1694             if ~isempty(h)
1695                 result       = inputdlg2( { 'New title:' }, 'Change title', 1,  { get(h(1), 'string') });
1696                 if ~isempty(result), set(h, 'string', result{1}); end;
1697             else
1698                 result       = inputdlg2( { 'New title:' }, 'Change title', 1,  { '' });
1699                 if ~isempty(result), h = textsc(result{1}, 'title'); set(h, 'tag', 'actplottitle');end;
1700             end;
1701             
1702             return;
1703             
1704         case 'scaleeye'
1705             % Turn scale I on/off
1706             obj = p1;
1707             figh = p2;
1708             g = get(figh,'UserData');
1709             % figh = get(obj,'Parent');
1710             
1711             if ~isempty(obj)
1712                 eyeaxes = findobj('tag','eyeaxes','parent',figh);
1713                 children = get(eyeaxes,'children');
1714                 if isstr(obj)
1715                     if strcmp(obj, 'off')
1716                         set(children, 'visible', 'off');
1717                         set(eyeaxes, 'visible', 'off');
1718                         return;
1719                     else
1720                         set(children, 'visible', 'on');
1721                         set(eyeaxes, 'visible', 'on');
1722                     end;
1723                 else
1724                     toggle = get(obj,'checked');
1725                     if strcmp(toggle,'on')
1726                         set(children, 'visible', 'off');
1727                         set(eyeaxes, 'visible', 'off');
1728                         set(obj,'checked','off');
1729                         return;
1730                     else
1731                         set(children, 'visible', 'on');
1732                         set(eyeaxes, 'visible', 'on');
1733                         set(obj,'checked','on');
1734                     end;
1735                 end;
1736             end;
1737             
1738             eyeaxes = findobj('tag','eyeaxes','parent',figh);
1739             ax1 = findobj('tag','eegaxis','parent',gcf); % axes handle
1740             YLim = get(ax1, 'ylim');
1741             
1742             ESpacing = findobj('tag','ESpacing','parent',figh);
1743             g.spacing= str2num(get(ESpacing,'string'));
1744             
1745             axes(eyeaxes); cla; axis off;
1746             set(eyeaxes, 'ylim', YLim);
1747             
1748             Xl = [.35 .65; .5 .5; .35 .65];
1749             Yl = [ g.spacing g.spacing; g.spacing 0; 0 0] + YLim(1);
1750             plot(Xl(1,:),Yl(1,:),'color',DEFAULT_AXIS_COLOR,'clipping','off', 'tag','eyeline'); hold on;
1751             plot(Xl(2,:),Yl(2,:),'color',DEFAULT_AXIS_COLOR,'clipping','off', 'tag','eyeline');
1752             plot(Xl(3,:),Yl(3,:),'color',DEFAULT_AXIS_COLOR,'clipping','off', 'tag','eyeline');
1753             text(.5,(YLim(2)-YLim(1))/23+Yl(1),num2str(g.spacing,4),...
1754                 'HorizontalAlignment','center','FontSize',10,...
1755                 'tag','thescalenum')
1756             text(Xl(2)+.1,Yl(1),'+','HorizontalAlignment','left',...
1757                 'verticalalignment','middle', 'tag', 'thescale')
1758             text(Xl(2)+.1,Yl(4),'-','HorizontalAlignment','left',...
1759                 'verticalalignment','middle', 'tag', 'thescale')
1760             if ~isempty(SPACING_UNITS_STRING)
1761                 text(.5,-YLim(2)/23+Yl(4),SPACING_UNITS_STRING,...
1762                     'HorizontalAlignment','center','FontSize',10, 'tag', 'thescale')
1763             end
1764             text(.5,(YLim(2)-YLim(1))/10+Yl(1),'Scale',...
1765                 'HorizontalAlignment','center','FontSize',10, 'tag', 'thescale')
1766             set(eyeaxes, 'tag', 'eyeaxes');
1767             
1768         case 'noui'
1769             if ~isempty(varargin)
1770                 actplot( varargin{:} ); fig = gcf;
1771             else
1772                 fig = findobj('tag', 'EEGPLOT');
1773             end;
1774             set(fig, 'menubar', 'figure');
1775             
1776             % find button and text
1777             obj = findobj(fig, 'style', 'pushbutton'); delete(obj);
1778             obj = findobj(fig, 'style', 'edit'); delete(obj);
1779             obj = findobj(fig, 'style', 'text');
1780             %objscale = findobj(obj, 'tag', 'thescale');
1781             %delete(setdiff(obj, objscale));
1782             obj = findobj(fig, 'tag', 'Eelec');delete(obj);
1783             obj = findobj(fig, 'tag', 'Etime');delete(obj);
1784             obj = findobj(fig, 'tag', 'Evalue');delete(obj);
1785             obj = findobj(fig, 'tag', 'Eelecname');delete(obj);
1786             obj = findobj(fig, 'tag', 'Etimename');delete(obj);
1787             obj = findobj(fig, 'tag', 'Evaluename');delete(obj);
1788             obj = findobj(fig, 'type', 'uimenu');delete(obj);
1789             
1790         case 'zoom' % if zoom
1791             fig = varargin{1};
1792             ax1 = findobj('tag','eegaxis','parent',fig);
1793             ax2 = findobj('tag','backeeg','parent',fig);
1794             tmpxlim  = get(ax1, 'xlim');
1795             tmpylim  = get(ax1, 'ylim');
1796             tmpxlim2 = get(ax2, 'xlim');
1797             set(ax2, 'xlim', get(ax1, 'xlim'));
1798             g = get(fig,'UserData');
1799             
1800             % deal with abscissa
1801             % ------------------
1802             if g.trialstag ~= -1
1803                 Eposition = str2num(get(findobj('tag','EPosition','parent',fig), 'string'));
1804                 g.winlength = (tmpxlim(2) - tmpxlim(1))/g.trialstag;
1805                 Eposition = Eposition + (tmpxlim(1) - tmpxlim2(1)-1)/g.trialstag;
1806                 Eposition = round(Eposition*1000)/1000;
1807                 set(findobj('tag','EPosition','parent',fig), 'string', num2str(Eposition));
1808             else
1809                 Eposition = str2num(get(findobj('tag','EPosition','parent',fig), 'string'))-1;
1810                 g.winlength = (tmpxlim(2) - tmpxlim(1))/g.srate;
1811                 Eposition = Eposition + (tmpxlim(1) - tmpxlim2(1)-1)/g.srate;
1812                 Eposition = round(Eposition*1000)/1000;
1813                 set(findobj('tag','EPosition','parent',fig), 'string', num2str(Eposition+1));
1814             end;
1815             
1816             % deal with ordinate
1817             % ------------------
1818             g.elecoffset = tmpylim(1)/g.spacing;
1819             g.dispchans  = round(1000*(tmpylim(2)-tmpylim(1))/g.spacing)/1000;
1820             
1821             set(fig,'UserData', g);
1822             actplot('updateslider', fig);
1823             actplot('drawp', 0);
1824             actplot('scaleeye', [], fig);
1825             
1826             % reactivate zoom if 3 arguments
1827             % ------------------------------
1828             if exist('p2') == 1
1829                 zoom on;
1830                 set(gcbf, 'windowbuttondownfcn', [ 'zoom(gcbf,''down''); actplot(''zoom'', gcbf, 1);' ]);
1831                 set(gcbf, 'windowbuttonmotionfcn', g.commandselect{2});
1832             end;
1833             
1834         case 'updateslider' % if zoom
1835             fig = varargin{1};
1836             g = get(fig,'UserData');
1837             sliider = findobj('tag','eegslider','parent',fig);
1838             if g.elecoffset < 0
1839                 g.elecoffset = 0;
1840             end;
1841             if g.dispchans >= g.chans
1842                 g.dispchans = g.chans;
1843                 g.elecoffset = 0;
1844                 set(sliider, 'visible', 'off');
1845             else
1846                 set(sliider, 'visible', 'on');
1847                 set(sliider, 'value', g.elecoffset/g.chans, ...
1848                     'sliderstep', [1/(g.chans-g.dispchans) g.dispchans/(g.chans-g.dispchans)]);
1849                 %'sliderstep', [1/(g.chans-1) g.dispchans/(g.chans-1)]);
1850             end;
1851             if g.elecoffset < 0
1852                 g.elecoffset = 0;
1853             end;
1854             if g.elecoffset > g.chans-g.dispchans
1855                 g.elecoffset = g.chans-g.dispchans;
1856             end;
1857             set(fig,'UserData', g);
1858             actplot('scaleeye', [], fig);
1859             
1860         case 'drawlegend'
1861             fig = varargin{1};
1862             g = get(fig,'UserData');
1863             
1864             if ~isempty(g.events) % draw vertical colored lines for events, add event name text above
1865                 nleg = length(g.eventtypes);
1866                 fig2 = figure('numbertitle', 'off', 'name', '', 'visible', 'off', 'menubar', 'none', 'color', DEFAULT_FIG_COLOR);
1867                 pos = get(fig2, 'position');
1868                 set(fig2, 'position', [ pos(1) pos(2) 130 14*nleg+20]);
1869                 
1870                 for index = 1:nleg
1871                     plot([10 30], [(index-0.5) * 10 (index-0.5) * 10], 'color', g.eventtypecolors{index}, 'linestyle', ...
1872                         g.eventtypestyle{ index }, 'linewidth', g.eventtypewidths( index )); hold on;
1873                     if iscell(g.eventtypes)
1874                         th=text(35, (index-0.5)*10, g.eventtypes{index}, ...
1875                             'color', g.eventtypecolors{index});
1876                     else
1877                         th=text(35, (index-0.5)*10, num2str(g.eventtypes(index)), ...
1878                             'color', g.eventtypecolors{index});
1879                     end;
1880                 end;
1881                 xlim([0 130]);
1882                 ylim([0 nleg*10]);
1883                 axis off;
1884                 set(fig2, 'visible', 'on');
1885             end;
1886             
1887             
1888             % motion button: move windows or display current position (channel, g.time and activation)
1889             % ----------------------------------------------------------------------------------------
1890         case 'defmotioncom'
1891             fig = varargin{1};
1892             g = get(fig,'UserData');
1893             
1894             ax1 = findobj('tag','backeeg','parent',fig);
1895             tmppos = get(ax1, 'currentpoint');
1896             
1897             if g.trialstag ~= -1,
1898                 lowlim = round(g.time*g.trialstag+1);
1899             else, lowlim = round(g.time*g.srate+1);
1900             end;
1901             if g.incallback
1902                 g.winrej = [g.winrej(1:end-1,:)' [g.winrej(end,1) tmppos(1)+lowlim g.winrej(end,3:end)]']';
1903                 set(fig,'UserData', g);
1904                 actplot('drawb');
1905             else
1906                 hh = findobj('tag','Etime','parent',fig);
1907                 if g.trialstag ~= -1,
1908                     set(hh, 'string', num2str(mod(tmppos(1)+lowlim-1,g.trialstag)/g.trialstag*(g.limits(2)-g.limits(1)) + g.limits(1)));
1909                 else set(hh, 'string', num2str((tmppos(1)+lowlim-1)/g.srate)); % put g.time in the box
1910                 end;
1911                 ax1 = findobj('tag','eegaxis','parent',fig);
1912                 tmppos = get(ax1, 'currentpoint');
1913                 tmpelec = round(tmppos(1,2) / g.spacing);
1914                 tmpelec = min(max(double(tmpelec), 1),g.chans);
1915                 labls = get(ax1, 'YtickLabel');
1916                 hh = findobj('tag','Eelec','parent',fig);  % put electrode in the box
1917                 set(hh, 'string', labls(tmpelec+1,:));
1918                 hh = findobj('tag','Evalue','parent',fig);
1919                 actplotdata = get(ax1, 'userdata');
1920                 set(hh, 'string', num2str(actplotdata(g.chans+1-tmpelec, min(g.frames,max(1,double(round(tmppos(1)+lowlim)))))));  % put value in the box
1921                 
1922             end;
1923             
1924             % release button: check window consistency, add to trial boundaries
1925             % -------------------------------------------------------------------
1926         case 'defupcom'
1927             fig = varargin{1};
1928             g = get(fig,'UserData');
1929             ax1 = findobj('tag','backeeg','parent',fig);
1930             g.incallback = 0;
1931             set(fig,'UserData', g);  % early save in case of bug in the following
1932             if strcmp(g.mocap,'on'), g.winrej = g.winrej(end,:);end; % nima
1933             if ~isempty(g.winrej)', ...
1934                     if g.winrej(end,1) == g.winrej(end,2) % remove unitary windows
1935                     g.winrej = g.winrej(1:end-1,:);
1936                     else
1937                         if g.winrej(end,1) > g.winrej(end,2) % reverse values if necessary
1938                             g.winrej(end, 1:2) = [g.winrej(end,2) g.winrej(end,1)];
1939                         end;
1940                         g.winrej(end,1) = max(1, g.winrej(end,1));
1941                         g.winrej(end,2) = min(g.frames, g.winrej(end,2));
1942                         if g.trialstag == -1 % find nearest trials boundaries if necessary
1943                             I1 = find((g.winrej(end,1) >= g.winrej(1:end-1,1)) & (g.winrej(end,1) <= g.winrej(1:end-1,2)) );
1944                             if ~isempty(I1)
1945                                 g.winrej(I1,2) = max(g.winrej(I1,2), g.winrej(end,2)); % extend epoch
1946                                 g.winrej = g.winrej(1:end-1,:); % remove if empty match
1947                             else,
1948                                 I2 = find((g.winrej(end,2) >= g.winrej(1:end-1,1)) & (g.winrej(end,2) <= g.winrej(1:end-1,2)) );
1949                                 if ~isempty(I2)
1950                                     g.winrej(I2,1) = min(g.winrej(I2,1), g.winrej(end,1)); % extend epoch
1951                                     g.winrej = g.winrej(1:end-1,:); % remove if empty match
1952                                 else,
1953                                     I2 = find((g.winrej(end,1) <= g.winrej(1:end-1,1)) & (g.winrej(end,2) >= g.winrej(1:end-1,1)) );
1954                                     if ~isempty(I2)
1955                                         g.winrej(I2,:) = []; % remove if empty match
1956                                     end;
1957                                 end;
1958                             end;
1959                         end;
1960                     end;
1961             end;
1962             set(fig,'UserData', g);
1963             actplot('drawp', 0);
1964             if strcmp(g.mocap,'on'), show_mocap_for_actplot(g.winrej); g.winrej = g.winrej(end,:); end; % nima
1965             
1966             % push button: create/remove window
1967             % ---------------------------------
1968         case 'defdowncom'
1969             show_mocap_timer = timerfind('tag','mocapDisplayTimer'); if ~isempty(show_mocap_timer),  end; % nima
1970             fig = varargin{1};
1971             g = get(fig,'UserData');
1972             EEG.saved='no';
1973             set(g.h_acpt,'enable','on');
1974             
1975             ax1 = findobj('tag','backeeg','parent',fig);
1976             tmppos = get(ax1, 'currentpoint');
1977             if strcmp(get(fig, 'SelectionType'),'normal');
1978                 g = get(fig,'UserData'); % get data of backgroung image {g.trialstag g.winrej incallback}
1979                 if g.incallback ~= 1 % interception of nestest calls
1980                     if g.trialstag ~= -1,
1981                         lowlim = round(g.time*g.trialstag+1);
1982                         highlim = round(g.winlength*g.trialstag);
1983                     else,
1984                         lowlim  = round(g.time*g.srate+1);
1985                         highlim = round(g.winlength*g.srate);
1986                     end;
1987                     if (tmppos(1) >= 0) & (tmppos(1) <= highlim),
1988                         if isempty(g.winrej) Allwin=0;
1989                         else Allwin = (g.winrej(:,1) < lowlim+tmppos(1)) & (g.winrej(:,2) > lowlim+tmppos(1));
1990                         end;
1991                         if any(Allwin) % remove the mark or select electrode if necessary
1992                             lowlim = find(Allwin==1);
1993                             if g.setelectrode  % select electrode
1994                                 ax2 = findobj('tag','eegaxis','parent',fig);
1995                                 tmppos = get(ax2, 'currentpoint');
1996                                 tmpelec = g.chans + 1 - round(tmppos(1,2) / g.spacing);
1997                                 tmpelec = min(max(tmpelec, 1), g.chans);
1998                                 g.winrej(lowlim,tmpelec+5) = ~g.winrej(lowlim,tmpelec+5); % set the electrode
1999                             else  % remove mark
2000                                 g.winrej(lowlim,:) = [];
2001                             end;
2002                         else
2003                             if g.trialstag ~= -1 % find nearest trials boundaries if epoched data
2004                                 alltrialtag = [0:g.trialstag:g.frames];
2005                                 I1 = find(alltrialtag < (tmppos(1)+lowlim) );
2006                                 if ~isempty(I1) & I1(end) ~= length(alltrialtag),
2007                                     g.winrej = [g.winrej' [alltrialtag(I1(end)) alltrialtag(I1(end)+1) g.wincolor zeros(1,g.chans)]']';
2008                                 end;
2009                             else,
2010                                 g.incallback = 1;  % set this variable for callback for continuous data
2011                                 g.winrej = [g.winrej' [tmppos(1)+lowlim tmppos(1)+lowlim g.wincolor zeros(1,g.chans)]']';
2012                             end;
2013                         end;
2014                         set(fig,'UserData', g);
2015                         actplot('drawp', 0);  % redraw background
2016                     end;
2017                 end;
2018             end;
2019         otherwise
2020             error(['Error - invalid actplot() parameter: ',command])
2021     end
2022 end
2023 
2024 % function not supported under Mac
2025 % --------------------------------
2026 function [reshist, allbin] = myhistc(vals, intervals);
2027 
2028 reshist = zeros(1, length(intervals));
2029 allbin = zeros(1, length(vals));
2030 
2031 for index=1:length(vals)
2032     minvals = vals(index)-intervals;
2033     bintmp  = find(minvals >= 0);
2034     [mintmp indextmp] = min(minvals(bintmp));
2035     bintmp = bintmp(indextmp);
2036     
2037     allbin(index) = bintmp;
2038     reshist(bintmp) = reshist(bintmp)+1;
2039 end;

Generated on Tue 10-May-2016 16:37:45 by m2html © 2005