function graph(varargin)
%GRAPH - displays attributes and traces from CED Saccade analysis.
%
% DESIGN PHILOSOPHY:  Minimize any Saccade-Graph interdependency.F~if
%
%  Graph is designed, as much as possible, to read attributes and traces
%  without without any rigid conventions.  In Graph, all attributes are the
%  same and all traces are same.  It knows nothing about attribute names or
%  trace names - those are passed from Saccade to Graph in the *.mat file.
%  One EXCEPTION  to this universal scheme is the unit data. The second to
%  the last trace is reserved for rasters and the last trace is reserved
%  for the instantaneous firing rate.
%
%  DATA FILES: Graph plots attribute and trace data as saved by Spike2.
%  GRAPH is written so that the attributes and traces are read-in from
%  separate files with the same name (*.txt & *.mat).
%
%  GRAPH is designed so that all its functions can be contained in one
%  file.  To do that, all the uicontrol callback routines call the main
%  program, GRAPH with a unique first function argument, (graph(6) is an
%  example).  This is a standard Matlab technique.
%
%
%  Fuchs' Lab
%  University of Washington
%  Seattle, WA  USA
%
%--------------------------------------------------------------------------


%==============================
% M A I N    P R O G R A M
%==============================

global gAfter
global gAttribSelected
global gAttribX
global gAttribY
global gAutoSize
global gBefore
global gBinSize
global gComputedEquations
global gComputedNames
global gDataHighlighted
global gDeleteAttribute
global gFigHandleAttr
global gFigHandleHisto
global gFigHandleXY
global gFigPosAttr
global gFigPosHisto
global gFigPosXY
global gFilesLoaded
global gFitType
global gFullLabel
global gHistogram
global gIFR
global gLineUpAttribute
global gManHi
global gManLo
global gNumPlots
global gPlotAvg
global gPlotInd
global gPlotColor
global gPlotOrder               %order to plot the traces excluding any that have been deleted
global gPlotShown
global gPrefsUpdate
global gRaster
global gRasterSize
global gRegularAttributes
global gSequential
global gSmoothPts
global gSortOnAttribute
global gStdDevBarPopItem
global gTotalAttributes
global gTraceLength
global gZeroLineUp

%callback routines (buttons) have more than zero arguments, launching the program does not
if nargin==0

    %clear all;     %clear all variables in the workspace
    clear gData                 %5/10/06 need this or else gData is wrong in attributeWrite

    %9/21/06 - some of these global vars are initialize here so Matlab does
    %not suggest to remove the global declaration above.
    gAfter              = 50;
    gAttribSelected     = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16];
    gBefore             = 50;
    gBinSize            = 10;
    gFilesLoaded        = 0;
    gFigHandleHisto     = 0;
    gFigHandleXY        = 0;
    gFullLabel          = 0;
    gDataHighlighted    = [];
    gNumPlots           = 1;                                                    %set this automatically soon
    gPlotOrder          = 0;
    gRasterSize         = 2;
    gRegularAttributes  = 16;
    gTotalAttributes    = 24;
    gTraceLength        = 0;
    gZeroLineUp         = 1;
    gSequential         = 0;
    gStdDevBarPopItem   = 1;
    gSmoothPts          = 1;
    gPrefsUpdate        = 0;


    %be safe, prepare for 20 traces
    gAutoSize           = [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1];
    gPlotInd            = [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1];
    gPlotAvg            = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];
    gManHi              = [10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10];
    gManLo              = [-10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10];
    gPlotColor          = ['r' 'b' 'r' 'b' 'r' 'b' 'k' 'k' 'k' 'k' 'k' 'k' 'k' 'k' 'k' 'k' 'k' 'k' 'k'];            %colors used to draw traces
    gPlotShown          = [1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];
    gRaster             = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];
    gIFR                = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];
    gHistogram          = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];

    cbH                 = 22;
    cbW                 = 20;
    cbV                 = 22;
    cbLabel             = 30;

    puH                 = 22;
    puW                 = 275;
    puV                 = 22;
    puLabel             = puW;

    edH                 = 22;
    edW                 = 50;
    edV                 = 22;
    edLabel             = edW;

    height              = 690;
    width               = 800;
    superLabel          = height-20;
    subLabel            = height-35;
    top                 = height-35;            %where the controls start


    set(0,'defaultfigurecolor',[0.831  0.816  0.784]);              %make sure the background and figure are the same color on all compters
    set(0,'defaultuicontrolbackgroundcolor',[0.831  0.816  0.784]);


    %set(0,'units','points');
    %gScreenSizePoints = get(0,'ScreenSize');

    set(0,'units','pixels');
    %gScreenSizePixels = get(0,'ScreenSize');
    %aSize          = gScreenSizePixels;
    aSize = get(0,'ScreenSize');
    gFigPosAttr    = [(aSize(3)-width)/2  (aSize(4)-height)/1.2 width height];   % X Y W H  [(aSize(3)-width)/2  (aSize(4)-height)/2  width height];
    gFigPosXY      = [0.00 0 0.75 0.75]; % X Y W H
    gFigPosHisto   = [0.25 0 0.75 0.75]; % X Y W H

    % get the general pref file, if there is one.  the pref file for the
    % specific data file will be loaded later, if there is one no need to
    % use prefOpen because no windows have been created yet that need to be
    % updated
    test = dir('C:\Documents and Settings\All Users\Desktop\prefs.mat');
    if isempty(test) == 0
        load('C:\Documents and Settings\All Users\Desktop\prefs.mat', '-mat');   %load it if it exists
    end


    gFigHandleAttr = figure(...
        'numbertitle',          'off',...
        'name',                 'Attributes',...
        'units',                'pixels',...
        'paperorientation',     'portrait',...
        'paperunits',           'inches',...
        'paperposition',        [0.25 0.25 8 10.5],...
        'resize',               'off',...
        'menubar',              'none',...
        'position',             gFigPosAttr);   % X Y W H
    uimenu(...
        'Label',                'Open',...
        'callback',             'graph(1);');
    uimenu(...
        'Label',                'Merge',...
        'callback',             'graph(15)',...
        'enable',               'off');
    uimenu(...
        'Label',                'WriteAttr',...
        'callback',             'graph(26)',...
        'enable',               'off');
    uimenu(...
        'Label',                'ListAttr',...
        'callback',             'graph(25);',...
        'enable',               'off');
    uimenu(...
        'Label',                'PrefLoad',...
        'callback',             'graph(20)',...
        'enable',               'off');
    uimenu(...
        'Label',                'PrefSave',...
        'callback',             'graph(21,1)',...
        'enable',               'off');
    uimenu(...
        'Label',                'XY',...
        'callback',             'global gSequential; graph(33)',...          %initializeA()-->plotXY(), reset fitted line
        'enable',               'off');
    uimenu(...
        'Label',                'Histogram',...
        'callback',             'graph(4)',...
        'enable',               'off');
    uimenu(...
        'Label',                'HistoOptions',...
        'callback',             'graph(10);',...
        'enable',               'off');
    uimenu(...
        'Label',                'Help',...
        'callback',             'graph(23)',...
        'Accelerator',          'H');
    uimenu(...
        'Label',                'Print',...
        'callback',             'printdlg',...
        'Accelerator',          'P');
    uimenu(...
        'Label',                'Quit',...
        'callback',             'graph(21,0); clear; close all;');  %PrefSave

    uicontrol(...
        'style',                'text',...
        'string',               'Inclusive Limit',...
        'position',              [535  superLabel  edLabel*2  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'Exclusive Limit',...
        'position',             [675  superLabel  edLabel*2  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'X',...
        'horizontalalignment',  'left',...
        'position',             [30  subLabel  cbW  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'Y',...
        'horizontalalignment',  'left',...
        'position',             [60  subLabel  cbW  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'Attributes',...
        'position',             [100  subLabel  puLabel  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'Line',...
        'horizontalalignment',  'left',...
        'position',             [400  subLabel  cbLabel  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'Sort',...
        'horizontalalignment',  'left',...
        'position',             [430  subLabel  cbLabel  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'Abs',...
        'horizontalalignment',  'left',...
        'position',             [460  subLabel  cbLabel  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'Theta',...
        'horizontalalignment',  'left',...
        'position',             [490  subLabel  cbLabel  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'Lower',...
        'position',              [530  subLabel  edLabel  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'Upper',...
        'position',             [590  subLabel  edLabel  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'Lower',...
        'position',              [670  subLabel  edLabel  cbH ]);   % X Y W H
    uicontrol(...
        'style',                'text',...
        'string',               'Upper',...
        'position',             [730  subLabel  edLabel  cbH ]);   % X Y W H

    j = 0;
    gComputedNames = {'Vert Err at Saccade Start'...
        'Horz Err at Saccade Start'...
        ''...
        ''...
        ''...
        'Example: div attr(1) by 2'...
        'Example: square of attr(1)'...
        'Example: sq root of attr(1)'...
        };
    gComputedEquations = {'gData(k,8) - gData(k,48)'...
        'gData(k,4) - gData(k,46)'...
        ''...
        ''...
        ''...
        'gData(k,1) ./ 2'...
        'gData(k,1) .^ 2'...
        'gData(k,1) .^ (1/2)'...
        };


    for i = 1:gTotalAttributes
        aStr = num2str(i);

        j = j + 1;

        %prepare the regular attributes
        if i <= gRegularAttributes
            theCallback = ['graph('   num2str(5)   ','   num2str(i)   ','  '''cbX''' ')'];      %graph(5)   X-axis
            uicontrol(...
                'style',        'checkbox',...
                'callback',     theCallback,...
                'tag',          ['cbX'   aStr],...
                'units',        'pixels',...
                'position',     [30  top-cbV*j  cbW  cbH ]);   % X Y W H


            theCallback = ['graph('   num2str(5)   ','   num2str(i)   ','  '''cbY''' ')'];      %graph(5)   Y-axis
            uicontrol(...
                'style',        'checkbox',...
                'callback',     theCallback,...
                'tag',          ['cbY' aStr],...
                'units',        'pixels',...
                'position',     [60  top-cbV*j  cbW  cbH]);   % X Y W H
            %end same as below

            theCallback = ['graph('   num2str(7)   ','   num2str(i)   ','  '''puAttr''' ')'];      %graph(7)    Chosen attribute
            uicontrol(...
                'style',        'popupmenu',...
                'callback',     theCallback,...
                'tag',          ['puAttr' aStr],...
                'background',   [1  1  1],...
                'units',        'pixels',...
                'string',       'no file has been opened',...
                'position',     [100  top-puV*j  puW  puH ]);   % X Y W H

        else
            %prepare the computed attribute
            if i == gRegularAttributes + 1
                j = j + 1;
                uicontrol(...
                    'style',                'text',...
                    'string',               'Computed Attributes',...
                    'position',             [100  top-puV*j  puW  puH ]);   % X Y W H
                j = j + 1;
                uicontrol(...
                    'style',                'text',...
                    'string',               'Name',...
                    'horizontalalignment',  'center',...
                    'position',             [100  top-puV*j  puW/2  puH ]);   % X Y W H
                uicontrol(...
                    'style',                'text',...
                    'string',               'Equation',...
                    'horizontalalignment',  'center',...
                    'position',             [100+puW/2  top-puV*j  puW/2  puH ]);   % X Y W H
                j = j + 1;
            end;
            %start same as above
            theCallback = ['graph('   num2str(5)   ','   num2str(i)   ','  '''cbX''' ')'];      %graph(5)   X-axis
            uicontrol(...
                'style',        'checkbox',...
                'callback',     theCallback,...
                'tag',          ['cbX'   aStr],...
                'units',        'pixels',...
                'position',     [30  top-cbV*j  cbW  cbH ]);   % X Y W H


            theCallback = ['graph('   num2str(5)   ','   num2str(i)   ','  '''cbY''' ')'];      %graph(5)   Y-axis
            uicontrol(...
                'style',        'checkbox',...
                'callback',     theCallback,...
                'tag',          ['cbY' aStr],...
                'units',        'pixels',...
                'position',     [60  top-cbV*j  cbW  cbH]);   % X Y W H
            %end same as above

            uicontrol(...
                'style',                'edit',...
                'tag',                  ['edName' aStr],...
                'background',           [1  1  1],...
                'units',                'pixels',...
                'string',               char(gComputedNames(i-gRegularAttributes)),...
                'horizontalalignment',  'left',...
                'position',             [100  top-puV*j  puW/2  puH ]);   % X Y W H

            uicontrol(...
                'style',                'edit',...
                'tag',                  ['edEquation' aStr],...
                'background',           [1  1  1],...
                'units',                'pixels',...
                'string',               char(gComputedEquations(i-gRegularAttributes)),...
                'horizontalalignment',  'left',...
                'position',             [100+puW/2  top-puV*j  puW/2  puH ]);   % X Y W H
        end;

        theCallback = ['graph('   num2str(5)   ','   num2str(i)   ','  '''cbLine''' ')'];      %graph(5)    Line-up
        uicontrol(...
            'style',        'checkbox',...
            'callback',     theCallback,...
            'tag',          ['cbLine' aStr],...
            'units',        'pixels',...
            'position',      [400  top-cbV*j  cbW  cbH ]);   % X Y W H


        theCallback = ['graph('   num2str(5)   ','   num2str(i)   ','  '''cbSort''' ')'];      %graph(5)    Sort-on
        uicontrol(...
            'style',        'checkbox',...
            'callback',     theCallback,...
            'tag',          ['cbSort' aStr],...
            'units',        'pixels',...
            'position',     [430  top-cbV*j  cbW  cbH ]);   % X Y W H


        uicontrol(...
            'style',        'checkbox',...
            'tag',          ['cbAbs' aStr],...
            'units',        'pixels',...
            'position',     [460  top-cbV*j  cbW  cbH ]);   % X Y W H


        uicontrol(...
            'style',        'checkbox',...
            'tag',          ['cbTheta' aStr],...
            'units',        'pixels',...
            'position',     [490  top-cbV*j  cbW  cbH ]);   % X Y W H


        uicontrol(...
            'style',        'edit',...
            'tag',          ['edLowerInclusive' aStr],...
            'background',   [1  1  1],...
            'units',        'pixels',...
            'position',     [530  top-edV*j  edW  edH ]);   % X Y W H


        uicontrol(...
            'style',        'edit',...
            'tag',          ['edUpperInclusive' aStr],...
            'background',   [1  1  1],...
            'units',        'pixels',...
            'position',     [590  top-edV*j  edW  edH ]);   % X Y W H

        uicontrol(...
            'style',        'edit',...
            'tag',          ['edLowerExclusive' aStr],...
            'background',   [1  1  1],...
            'units',        'pixels',...
            'position',     [670  top-edV*j  edW  edH ]);   % X Y W H


        uicontrol(...
            'style',        'edit',...
            'tag',          ['edUpperExclusive' aStr],...
            'background',   [1  1  1],...
            'units',        'pixels',...
            'position',     [730  top-edV*j  edW  edH ]);   % X Y W H
    end;


    gAttribX = 1;                                               %store the attribute selected for X
    gAttribY = 2;                                               %store the attribute selected for Y
    h = findobj('Tag','cbX1');                                  %get the handle for the attribute popup menu
    set(h,'value', 1)                                           %install the list in the popup mentu
    h = findobj('Tag','cbY2');                                  %get the handle for the attribute popup menu
    set(h,'value', 1)                                           %install the list in the popup menu

    gLineUpAttribute    = 10;
    h = findobj('Tag',['cbLine' num2str(gLineUpAttribute)]);    %get the handle for the checkbox
    set(h,'value', 1)                                           %install the list in the popup mentu

    gSortOnAttribute    = 1;
    h = findobj('Tag',['cbSort' num2str(gSortOnAttribute)]);    %ROBI
    set(h,'value', 1);                                          %ROBI

    % end MAIN program


    %callback routines (buttons) have > 0 arguments, launching the program does not
elseif nargin==1 && varargin{1}==1
    fileOpen();

    %elseif nargin==1 && varargin{1}==2
    % end SAVE

% elseif nargin==2 && varargin{1}==3      %elseif nargin==1 && varargin{1}==3
%     xyPlot(varargin{2});
elseif nargin==1 && varargin{1}==3
    xyPlot();

elseif nargin==1 && varargin{1}==4
    histogram();

elseif nargin==3 && varargin{1}==5                               %called when user clicks on X, Y, Line-up, Sort-on checkboxes
    exclusiveCheckboxes(varargin{2},varargin{3});

elseif nargin==1 && varargin{1}==6
    attributeDialog();

elseif nargin==3 && varargin{1}==7
    popupGetAttribute(varargin{2}, varargin{3});

elseif nargin==3 && varargin{1}==8
    zoomPlot(varargin{2}, varargin{3});

elseif nargin==2 && varargin{1}==9
    histoNext(varargin{2});

elseif nargin==1 && varargin{1}==10
    dialogHistoOptionsOpen();

elseif nargin==2 && varargin{1}==11
    dialogHistoOptionsClose(varargin{2});

elseif nargin==1 && varargin{1}==12
    keypadHist();

elseif nargin==2 && varargin{1}==13
    traceOptionsDialogBox(varargin{2});

elseif nargin==3 && varargin{1}==14
    exclusivePlotCheckboxes(varargin{2}, varargin{3});

elseif nargin==1 && varargin{1}==15
    fileMerge();

elseif nargin==1 && varargin{1}==16
    traceDelete();

elseif nargin==1 && varargin{1}==17
    traceRestore();

elseif nargin==1 && varargin{1}==20
    prefLoad();

elseif nargin==2 && varargin{1}==21
    prefSave(varargin{2});

elseif nargin==2 && varargin{1}==22      %click on a trace
    traceSelect(varargin{2});

elseif nargin==1 && varargin{1}==23
    helpGraph();

elseif nargin==1 && varargin{1}==24
    pointSelectBox();

elseif nargin==1 && varargin{1}==25
    helpAttributes();

elseif nargin==1 && varargin{1}==26
    attributesWrite();

elseif nargin==1 && varargin{1}==27
    traceDeleteAll();

elseif nargin==1 && varargin{1}==28
    keypadXY();

elseif nargin==1 && varargin{1}==29
    customFit();

elseif nargin==1 && varargin{1}==30
    pointDelete();

elseif nargin==1 && varargin{1}==31
    pointDeleteStdDev();

elseif nargin==1 && varargin{1}==32
    smooth();

elseif nargin==1 && varargin{1}==33
    initializeA();

end  %main




%==============================
% S U B R O U T I N E S
%==============================

%--------------------------------------------------------------------------
% helpGraph
% Displays things to remember about Graph.
% 4/28/04
%--------------------------------------------------------------------------
function helpGraph()

global gFigHandleAttr
global gFigHandleHisto
global gFigHandleXY


fprintf('\n\n\n\n\n')
fprintf('==============================================================\n')
fprintf('                   G R A P H   H E L P\n')
fprintf('..............................................................\n\n')

if gcf == gFigHandleAttr
    fprintf('* A T T R I B U T E   N A M E S :\n')
    fprintf('Click the ListAttr button to see a list of all the attribute \n')
    fprintf('names and numbers. \n\n')
    %
    fprintf('* S A V E   P R E F E R E N C E S :\n')
    fprintf('Save the user-entered choices from the entire program by clicking\n')
    fprintf('the PrefSave button.\n\n')
    %
    fprintf('* L O A D   P R E F E R E N C E S :\n')
    fprintf('Load the user-entered choices from the entire program by clicking\n')
    fprintf('the PrefLoad button.\n\n')
end

if gcf == gFigHandleHisto
    fprintf('* D E L E T E   A   T R I A L :\n')
    fprintf('Select a trace by CLICKing on it or by navigating to it with\n')
    fprintf('the UP or DOWN arrow keys.  The DELETE key will non-permanently\n')
    fprintf('remove that trial.  The INSERT key will un-delete all trials.\n')
    fprintf('The HOME and END keys end all highlighting.\n\n')
    %
    fprintf('* R E F R E S H   H I S O T G R A M :\n')
    fprintf('Due to the time it takes to redraw hundreds of traces, the display\n')
    fprintf('is redraw when you make a new choice in the Attribute window\n')
    fprintf('or select the REFRESH menu.  Any traces marked for deletion will\n')
    fprintf('be removed at that time.\n\n')
end

if gcf == gFigHandleXY                          %test if the XY plot is the current figure
    fprintf('* D E L E T E   A   T R I A L :\n')
    fprintf('Select a point or points by click-dragging a box around them.\n')
    fprintf('Hitting the DELETE key will non-permanently remove the highlighted\n')
    fprintf('trials.  The INSERT key will un-delete all trials.\n\n')
end


fprintf('..............................................................\n')
fprintf('                   G R A P H   H E L P\n')
fprintf('==============================================================\n\n')




h = msgbox('Some important features about Graph are now displayed in the Matlab Command Window','Graph Help','help');
uiwait(h);
%END helpGraph


%--------------------------------------------------------------------------
% helpAttributes
% Displays things to remember about Graph.
% 5/3/04
%--------------------------------------------------------------------------
function helpAttributes()

global gAttribNames
global gNumNonComputedAttr


fprintf('\n')
%
fprintf('..............................................................\n')
fprintf('                A T T R I B U T E   H E L P\n')
fprintf('==============================================================\n\n')
%
h = msgbox('The names of the attributes passed to Graph are now displayed in the Matlab Command Window','Attribute Help','help');



fprintf('\n\n\n\n\n')
fprintf('==============================================================\n')
fprintf('                A T T R I B U T E   H E L P\n')
fprintf('..............................................................\n\n')
%
for i = 1:gNumNonComputedAttr
    if i < 10
        fprintf('%d.   %s\n', i, char(gAttribNames(i)));
    elseif i < 100
        fprintf('%d.  %s\n', i, char(gAttribNames(i)));
    else
        fprintf('%d. %s\n', i, char(gAttribNames(i)));
    end
end

uiwait(h);
%END helpAttributes



%--------------------------------------------------------------------------
% keypadHist
% Changes which histogram trace is highlighted.
% 6/6/03
%--------------------------------------------------------------------------
function keypadHist()

k = get(gcf, 'currentkey');

switch k
    case 'home'
        graph(9,0);         %histoNext stop hightlighting
    case 'end'
        graph(9,0);         %histoNext stop hightlighting
    case 'uparrow'
        graph(9,1);         %histoNext forward
    case 'downarrow'
        graph(9,-1)         %histoNext backward
    case 'delete'
        graph(16);          %traceDelete
    case 'insert'
        graph(17);          %traceRestore
end
%end keypadHist



%--------------------------------------------------------------------------
% keypadXY
% Changes which histogram trace is highlighted.
% 6/6/03
%--------------------------------------------------------------------------
function keypadXY()

k = get(gcf, 'currentkey');

switch k
    %    case 'home'
    %        graph(9,0);         %histoNext stop hightlighting
    %    case 'end'
    %        graph(9,0);         %histoNext stop hightlighting
    %    case 'uparrow'
    %        graph(9,1);         %histoNext forward
    %    case 'downarrow'
    %        graph(9,-1)         %histoNext backward
    case 'delete'
        %graph(28);          %traceDelete
        pointDelete()
        %    case 'insert'
        %        graph(17);          %traceRestore
end
%end keypadXY



%--------------------------------------------------------------------------
% attributeDialog
% Brings up the main dialogbox where users select attributes related to
% plots they want to show in XY or histogram modes.
% 4/30/03
%--------------------------------------------------------------------------
function attributeDialog()

h = findobj('name','Attributes');
if ishandle(h)
    figure(h);
end     %attributeDialog



%--------------------------------------------------------------------------
% attributesWrite
% Write the attribute file back to the disk with any changes to attribute
% [73], analysis tag.
% 5/3/04
%--------------------------------------------------------------------------
function attributesWrite()

global gAttribNames
global gDataOriginalAttrib
global gDeleteAttribute
global gFileName
global gFolderName
global gNumNonComputedAttr
global gNumTrials

aAllStr     = 'Write Attributes for All the Trials';
aCancelStr  = 'Cancel';

aStr        = ['Would you like to write to a file, all the attributes including the current Analysis Tag Attribute [' num2str(gDeleteAttribute) '], which records all the trials you have filtered out?'];

button      = questdlg(...
                    aStr,...
                    'Write Attributes to a File',...
                    aAllStr, aCancelStr, aCancelStr);


if strcmp(button, aCancelStr)
    return                                                                  % do nothing, user changed his mind
end

%2/20/07 Commented-out because it could potentiall write out SMOOTHED,
%SEQUENTIALIZED attributes which the user may do unwittingly
% % write the attributes related to the DISPLAYED trials
% if strcmp(button, aDisplayStr)
%     d = size(gData);
%     aTrials = d(1);
%     %if aTrials == 0
%     %    h = warndlg('No file written since no trials have been displayed yet.','Failed')
%     %end
%
%     aStr = strcat(int2str(aTrials), ' trials will be written.  What do you want to do?');
%     button = questdlg(...
%         aStr,...
%         'Number of Trials in the File',...
%         'Continue', aCancelStr, aCancelStr);
%
%     if strcmp(button, aCancelStr)
%         return                                                              % do nothing, user changed his mind
%     end
%
%
%     % let's write a file!
%     currentFile = -1;                                                       %start with an invalid file reference
%     mergedFileAttr = gNumNonComputedAttr - 1;                               %the attr that remembers which file it came from
%     hWait = waitbar(0,'Start');
%     set(hWait,'name','Progress');
%
%     for i = 1:aTrials
%         %2/16/07 The data in gData may be altered by the smoothing or
%         %sequentializing routines in Graph and not output the original
%         %attributes.
%         if gData(i,mergedFileAttr) ~= currentFile                           %test if trial came from a different file
%             currentFile = gData(i,mergedFileAttr);                          %it did, get the file number
%             foldername = gFolderName(currentFile);                          %get that foldername
%             filename = gFileName(currentFile);                              %get that filename
%             aStr = strcat('Writing displayed trials :', filename);
%             eval(['cd ','''',char(foldername),'''']);                       %open up the file
%            %modify the filename
%            filename = strrep(filename, '.txt', '-displayed.txt');
%            fid = fopen(char(filename),'w');
%
%             for k = 1:gNumNonComputedAttr - 2                               %not last two attributes: merge
%                 result = fprintf(fid,'%s \t',gAttribNames{k});
%             end
%             fprintf(fid, '\n');
%         end
%
%         for j = 1:gNumNonComputedAttr - 2                                   %skip last two (unofficial) attributes related to merging files
%             if isnan(gData(i,j))
%                 result = fprintf(fid,'\t');                                 %convert NaN to empty cells
%             else
%                 result = fprintf(fid,'%s \t',num2str(gData(i,j),10));
%             end
%         end
%         fprintf(fid, '\n');
%         waitbar(i/aTrials, hWait, aStr);
%     end
% end

% write the attributes for ALL the trials
if strcmp(button, aAllStr)
    % let's write a file!
    currentFile = -1;                                                       %start with an invalid file reference
    mergedFileAttr = gNumNonComputedAttr - 1;                               %the attr that remembers which file it came from
    hWait = waitbar(0,'Start');
    set(hWait,'name','Progress');

    d = size(gDataOriginalAttrib);
    %aTrials = d(1);
    for i = 1:gNumTrials
        if gDataOriginalAttrib(i,mergedFileAttr) ~= currentFile             %test if trial came from a different file
            currentFile = gDataOriginalAttrib(i,mergedFileAttr);            %it did, get the file number
            foldername = gFolderName(currentFile);                          %get that foldername
            filename = gFileName(currentFile);                              %get that filename
            filename_free = regexprep(filename, '_', '\\_');                %an underscore is a subscript flag
            aStr = strcat('Writing all trials :', filename_free);
            eval(['cd ','''',char(foldername),'''']);                       %open up the file
            fid = fopen(char(filename),'w');

            for k = 1:gNumNonComputedAttr - 2                               %not last two attributes: merge
                result = fprintf(fid,'%s \t',gAttribNames{k});
            end
            fprintf(fid, '\n');
        end

        for j = 1:gNumNonComputedAttr - 2                                   %skip last two (unofficial) attributes related to merging files
            if isnan(gDataOriginalAttrib(i,j))
                result = fprintf(fid,'\t');                                 %convert NaN to empty cells
            else
                result = fprintf(fid,'%s \t',num2str(gDataOriginalAttrib(i,j),10));
            end
        end
        fprintf(fid, '\n');
        waitbar(i/gNumTrials, hWait, aStr);
    end
end

fclose(fid);
close(hWait);
%end attributesWrite



%--------------------------------------------------------------------------
% exclusiveCheckboxes
% Called whenever the user clicks in a column of checkboxes that permits
% only one checkbox to be selected.
% 5/7/03
%--------------------------------------------------------------------------
function exclusiveCheckboxes(which, kind)

global gAttribX
global gAttribY
global gLineUpAttribute
global gPrefsUpdate
global gSortOnAttribute
global gTotalAttributes


for i = 1:gTotalAttributes
    h = findobj('tag', [kind   num2str(i)]  );          %set all of this kind to UNCHECKED
    set(h, 'value', 0);
end

h = findobj('tag', [kind   num2str(which)]  );          %which one was clicked

switch kind
    case 'cbX'
        gAttribX = which;
        set(h, 'value', 1);

    case 'cbY'
        gAttribY = which;
        set(h, 'value', 1);

    case 'cbLine'
        gLineUpAttribute = which;
        set(h, 'value', 1);

    case 'cbSort'                                       %having a SORT checkbox selected is not manditory, it is optional

        %         gSortOnAttribute
        %         which
        %         gPrefsUpdate

        if (gSortOnAttribute == which) && (gPrefsUpdate == 0)
            gSortOnAttribute = NaN;                     %we're de-selecting a previously checked box

        else
            gSortOnAttribute = which;                   %selecting a new box
            set(h, 'value', 1);
        end
end
%end exclusiveCheckboxes



%--------------------------------------------------------------------------
% traceDeleteAll
% Tags all the traces shown so they won't be drawn
% 4/19/06
%--------------------------------------------------------------------------
function traceDeleteAll()

global gData
global gDataOriginalAttrib
global gDeleteAttribute
global gFigHandleXY
global gMergedTrialNumberAttr
global gPlottedTraces


button = questdlg(...
    'You are about to delete all the trials shown on the screen.  Do you want to continue?',...
    'Deleted All Trials',...
    'Yes', 'No', 'Yes');
if strcmp(button,'Yes')

    d = size(gPlottedTraces);
    for j = 1:d(2)          %N-trials
        gDataOriginalAttrib(gData(j,gMergedTrialNumberAttr),gDeleteAttribute) = 1;    %tag a trace for deletion (just don't show it)
    end

    if gcf == gFigHandleXY                          %test if the XY plot is the current figure
        xyPlot(1);                                  %redraw the XY plot, reset the fitted plot
    else
        histogram();                                %redraw the histogram
    end
end
%end    traceDeleteAll



%--------------------------------------------------------------------------
% traceDelete
% Tags a trace so it won't be drawn
% 6/20/03
%--------------------------------------------------------------------------
function traceDelete()

global gData
global gDataOriginalAttrib
global gDeleteAttribute
global gFigHandleXY
global gMergedTrialNumberAttr
global gNextTrace


gDataOriginalAttrib(gData(gNextTrace,gMergedTrialNumberAttr),gDeleteAttribute) = 1;    %tag a trace for deletion (just don't show it)
gNextTrace = 0;                                 %keeps deleted trace highlighted, makes it so there is no "last trace" to redraw in red

if gcf == gFigHandleXY                          %test if the XY plot is the current figure
    xyPlot(1);                                  %redraw the XY plot, reset fitted plot
end
%end traceDelete



%--------------------------------------------------------------------------
% processComputedAttributes
% Loads the computed attribute information and prepares it to be used by
% the program.
% 07/08/03
%--------------------------------------------------------------------------
function processComputedAttributes()

global gAttribNames
global gData
global gNumNonComputedAttr
global gRegularAttributes
global gTotalAttributes


%this routine should come after getting afresh attribute list
%(gData = gDataOriginalAttrib)
j = 0;
for i = gRegularAttributes+1:gTotalAttributes
    j = j + 1;
    h = findobj('Tag',['edName' num2str(i)]);                   %get the handle for the attribute popup menu
    aStr = get(h,'string');                                     %install the list in the popup mentu

    gAttribNames(gNumNonComputedAttr + j) = cellstr(aStr);      %load the user-entered computed attribute name

    h = findobj('Tag',['edEquation' num2str(i)]);               %get the handle for the attribute popup menu
    bStr = get(h,'string');                                     %install the list in the popup mentu

    %process computed attributes
    if (isempty(aStr)==1) || (isempty(bStr)==1)                 %to be valid, a name and equation are required
        gData(:,gNumNonComputedAttr + j) = NaN;                 %unused, fill with NaN
    else
        d = size(gData);
        tempTrials  = d(1);                                     %get the number of trials
        for k = 1:tempTrials
            gData(k,gNumNonComputedAttr + j) = eval(bStr);      %use the equation to compute the attribute
        end
    end
end %processComputedAttributes



%--------------------------------------------------------------------------
% traceRestore
% Untags all the traces so they will be drawn
% 6/20/03
%--------------------------------------------------------------------------
function traceRestore()

global gDataOriginalAttrib
global gDeleteAttribute
global gFigHandleXY


button = questdlg(...
    'You are about to restore all the deleted trials and redraw the screen.  Do you want to continue?',...
    'Restore Deleted Trials',...
    'Yes', 'No', 'Yes');
if strcmp(button,'Yes')
    gDataOriginalAttrib(:,gDeleteAttribute) = 0;        %restore all the traces
    if gcf == gFigHandleXY                          %test if the XY plot is the current figure
        xyPlot(1);                                     %redraw the XY plot, reset the fitted plot
    else
        histogram();                                  %redraw the histogram
    end
end
%end traceRestore



% %--------------------------------------------------------------------------
% % attributeAbsorb
% % Make sure that any value entered in an EditBox without hitting tab, CR,
% % etc. will have its value read when the XY or Histogram windows are
% % selected by the user.
% % 5/2/05
% %--------------------------------------------------------------------------
% function attributeAbsorb()
% 
% h = findobj('name','Attributes');
% if ishandle(h)
%     figure(h);%,'visible','off');
%     h = findobj('tag', 'edLowerInclusive1');                         %absorb all values typed in, "click" here
%     if ishandle(h);
%         uicontrol(h);
%     end
%     h = findobj('tag', 'edLowerInclusive2');                         %absorb all values typed in, "click" here
%     if ishandle(h);
%         uicontrol(h);
%     end 
% end     %attributeAbsorb



%--------------------------------------------------------------------------
% filterItemsUpdate
% Reads uicontrols and stores current selections
% 4/21/04
%--------------------------------------------------------------------------
function filterItemsUpdate()

global gFilterAbs
global gFilterTheta
global gExclusiveLower
global gExclusiveUpper
global gInclusiveLower
global gInclusiveUpper
global gTotalAttributes


%get filter parameters
for i = 1:gTotalAttributes
    aUpperNameInc   = ['edUpperInclusive' num2str(i)];
    aLowerNameInc   = ['edLowerInclusive' num2str(i)];
    aUpperNameExc   = ['edUpperExclusive' num2str(i)];
    aLowerNameExc   = ['edLowerExclusive' num2str(i)];
    aAbsName        = ['cbAbs' num2str(i)];
    aThetaName      = ['cbTheta' num2str(i)];
    %3/13/07 don't need to process X,Y,line-up and sort because they are 
    %handled by the exclusiveCheckboxes() routine


    h = findobj('Tag', aThetaName);                      %THETA selected?
    gFilterTheta(i) = get(h,'value');                   %help?

    
    h = findobj('Tag', aAbsName);                        %ABS selected?
    gFilterAbs(i) = get(h,'value');

    
    h = findobj('Tag', aUpperNameInc);                      %UPPER limit value
    aTemp = get(h,'string');
    if isempty(aTemp)
        gInclusiveUpper(i) = NaN;
    else
        gInclusiveUpper(i) = str2double(aTemp);
    end

    
    h = findobj('Tag', aLowerNameInc);                      %LOWER limit value
    aTemp = get(h,'string');
    if isempty(aTemp)
        gInclusiveLower(i) = NaN;
    else
        gInclusiveLower(i) = str2double(aTemp);
    end

    
    h = findobj('Tag', aUpperNameExc);                      %UPPER limit value
    aTemp = get(h,'string');
    if isempty(aTemp)
        gExclusiveUpper(i) = NaN;
    else
        gExclusiveUpper(i) = str2double(aTemp);
    end
    

    h = findobj('Tag', aLowerNameExc);                      %LOWER limit value
    aTemp = get(h,'string');
    if isempty(aTemp)
        gExclusiveLower(i) = NaN;
    else
        gExclusiveLower(i) = str2double(aTemp);
    end
end
%end filterItemsUpdate



%--------------------------------------------------------------------------
% filterTrials
% Removes the trials that don't meet the user's filter choices
% 6/23/03
%--------------------------------------------------------------------------
function filterTrials()

global gData
global gDeleteAttribute
global gFilterAbs
global gFilterTheta
global gExclusiveLower
global gExclusiveUpper
global gInclusiveLower
global gInclusiveUpper
global gSelectedHistoTrials
global gTotalAttributes


filterItemsUpdate();                                                                           %acquire the current filter settings


%load the upper limits
for i = 1:gTotalAttributes

    %adjust tempTrials everytime trials have been eliminated
    gSelectedHistoTrials = find(gData(:,gDeleteAttribute) == 0);                                %choose the traces that are not deleted
    gData = gData(gSelectedHistoTrials,:);                                                      %form a new attribute list
    d           = size(gData);                                                                  %determine how many trials are there at this time
    tempTrials  = d(1);                                                                         %get the number of trials


    if gFilterAbs(i) == 1
        gData(:,getAttribNumber(i)) = abs(gData(:,getAttribNumber(i)));                     %apply the absolute value filter
    end


    if gFilterTheta(i) == 1
        for j = 1:tempTrials
            if gData(j,getAttribNumber(i)) > 180
                gData(j,getAttribNumber(i)) = gData(j,getAttribNumber(i)) - 360;            %apply the theta degree conversion
            end
        end
    end

    %inclusive filter
    if ~isnan(gInclusiveLower(i))                                                           %lower limit must be valid
        gSelectedHistoTrials = find(gData(:,getAttribNumber(i)) >= gInclusiveLower(i));
        gData = gData(gSelectedHistoTrials,:);                                              %form a new attribute list
    end
    if ~isnan(gInclusiveUpper(i))                                                           %upper limit must be valid
        gSelectedHistoTrials = find(gData(:,getAttribNumber(i)) <= gInclusiveUpper(i));
        gData = gData(gSelectedHistoTrials,:);                                              %form a new attribute list
    end

    %exclusive filter
    if ~isnan(gExclusiveLower(i))  &&  ~isnan(gExclusiveUpper(i))                           %both lower and upper limits must be valid
        gSelectedHistoTrials = find( ~((gData(:,getAttribNumber(i)) >= gExclusiveLower(i)) & (gData(:,getAttribNumber(i)) <= gExclusiveUpper(i))));
        gData = gData(gSelectedHistoTrials,:);                                              %form a new attribute list
    else
        badFilter = 0;                                                                      %initialize
        if isnan(gExclusiveLower(i))  &&  ~isnan(gExclusiveUpper(i))                        %only one limit is valid
            badFilter = 1;
        end
        if ~isnan(gExclusiveLower(i))  &&  isnan(gExclusiveUpper(i))                        %only one limit is valid
            badFilter = 1;
        end
        if badFilter == 1
            aStr = strcat('Exclusive filters must have a lower AND an upper parameter.  Correct filter number = ', num2str(i), ' .');
            h = msgbox(aStr,'Bad filter');
            uiwait(h);
        end
    end
end
%end filterTrials



%--------------------------------------------------------------------------
% exclusivePlotCheckboxes
% 6/13/03
%--------------------------------------------------------------------------
function exclusivePlotCheckboxes(which, kind)

h = findobj('tag', ['off'   num2str(which)]  );         %set all CB in the row to UNCHECKED
set(h, 'value', 0);

h = findobj('tag', ['plot'   num2str(which)]  );        %set all CB in the row to UNCHECKED
set(h, 'value', 0);

h = findobj('tag', ['raster'   num2str(which)]  );      %set all CB in the row to UNCHECKED
set(h, 'value', 0);

h = findobj('tag', [kind   num2str(which)]  );          %set the CB that was clicked to CHECKED
set(h, 'value', 1);
%end exclusivePlotCheckboxes



%--------------------------------------------------------------------------
% getAttribNumber
% Returns the attribute number which can be a regular or computed attribute
% depending on gRegularAttributes
% 7/9/03
%--------------------------------------------------------------------------
function attribNumber = getAttribNumber(which)

global gAttribSelected
global gNumAttr
global gRegularAttributes
global gTotalAttributes


if which <= gRegularAttributes
    attribNumber = gAttribSelected(which);                      %regular attribute
else
    attribNumber = gNumAttr - (gTotalAttributes - which);       %computed attribute
end
%end  getAttribNumber



%--------------------------------------------------------------------------
% traceSelect
% 4/23/04
%--------------------------------------------------------------------------
function traceSelect(whichPlot)

global gPlottedTraces
global gBefore
global gNextTrace
global gPlotOrder
global gPlotShown


click   = get(gca, 'CurrentPoint');            % location of the mouse click
d       = size(gPlottedTraces);
index   = gBefore + click(1,1);
i       = round(index)+1;       %ms points on display
if i < 1
    i = 1;      %click returns floating point numbers that may round down to zero
end

value = click(1,2);
% fprintf(1,'\nTrace type = %d', whichPlot);
% fprintf(1,'\nX-coord = %d', index);
% fprintf(1,'\nY-coord = %d', value);
% fprintf(1,'\n');

traceDraw;          %un-highlight the previous trace

%search for the trace that is closest to where the user clicked.  the
%selection is unpredictable if the user clicks near the intersection of two
%traces
aSmallestDiff = 1000000;  %a very big number
%k = 0;
if gPlotShown(whichPlot) > 0            %bob 5/9/06
    %k = k + 1;
    for j = 1:d(2)          %N-trials
        %you can click on the trace by being within +/-1
        %     index
        %     i
        %     j
        %     whichPlot
        %posValue = gPlottedTraces(i, j, k);
        %posValue = gPlottedTraces(i, j, whichPlot);
        posValue = gPlottedTraces(i, j, gPlotOrder(whichPlot));
        aDiff = abs(value - posValue);
        if aDiff < aSmallestDiff
            aSmallestDiff = aDiff;
            %fprintf(1,'\nposition %d trace value = %d', i, gPlottedTraces(i,round(j),1));
            aMarkThisOne = j;         %which trace to mark
        end
    end
end

%point the adjacent trace, before or after
gNextTrace = aMarkThisOne;        % add the new trace low in the list

%highlight the next trace
traceHighlight();
%end    traceSelect



%--------------------------------------------------------------------------
% histogram
% Display the Histogram figure and fill it in the plots containing families
% of traces chosen by the user
% 5/8/03
%--------------------------------------------------------------------------
function histogram()

global gAfter
global gAutoSize
global gBefore
global gBinSize
global gData
global gDataOriginalAttrib
global gDataWidth
global gFigHandleHisto
global gFigPosHisto
global gFullLabel
global gHistoAccumulator
global gHistogram
global gHistoSubplots
global gIFRAccumulator
global gIFR
global gLineUpAttribute
global gManLo
global gManHi
global gMergedTrialNumberAttr
global gNextTrace
global gNumPlots
global gNumSelectedHistoTrials
global gNumChan
global gPlotColor
global gPlotOrder
global gPlotShown
global gPlotAvg
global gPlotInd
global gPlottedTraces
global gPlottedTracesAvg
global gRaster
global gRasterAccumulator
global gRasterSize
global gSelectedHistoTrials
global gSortOnAttribute
global gTraceLabels
global gTraceLength
global gZeroLineUp


%%%attributeAbsorb();                                    %make sure all the attribute limits, etc. have been loaded

%SAVE  global declaration of a01 a02 a03 a04 a05 a06
for jj = 1:gNumChan
    if jj < 10
        eval(['global a0' num2str(jj)])
    else
        eval(['global a' num2str(jj)])
    end
end

kTickLength = 0.0025;
gNextTrace  = 0;                        %initial, no traces highlighted
aBinSize    = gBinSize*2;               %make a local copy and adjust it for 2kHz unit IFR data
aLeft       = 0.21;                     %move the left edge of the plots
aWide       = 0.77;                     %change the width of the plots
aCRLF       = [char(10), char(13)];

%3/7/07  the XY plot and the Histogram plot are different in at least one 
%very important way:  the number of plots in the figure can change.  The XY
%plot always has two.
h = findobj('name', 'Histogram');                         %close the old one before opening a new one
if ishandle(h);
    gFigHandleHisto = h;                    %re-use the last histogram figure
    figure(gFigHandleHisto);                %re-use the last histogram figure
    %cla;                                            %clear the old plot
    aStats              = findobj('tag', 'Stats');
else
    gFigHandleHisto = figure(...
        'numbertitle',          'off',...
        'name',                 'Histogram',....
        'menubar',              'none',...
        'color',                [0.831 0.816 0.784],...
        'paperorientation',     'landscape',...
        'paperunits',           'inches',...
        'paperposition',        [0.25 0.25 10.5 8],...
        'units',                'normalized',...
        'position',             gFigPosHisto,...    %[0.01 0.1 0.98 .75],...
        'keypressfcn',          'graph(12)');

    %the menu bar
    savecallback = ['[fn,pn,fi]=uiputfile(' '''*.fig''' ',' '''Save figure as''' ',' '''Untitled.fig''' ');' ...
        'if fi ~= 0 ' 'cd(pn);' 'saveas(gcf,fn);' ...
        'else return; end' ];
    uimenu(...
        'Label',                'SaveFig',...
        'callback',             savecallback);
    uimenu(...
        'Label',                'Attributes',...
        'callback',             'graph(6);');
    uimenu(...
        'Label',                'HistoOptions',...
        'callback',             'graph(10);');

    uimenu(...
        'Label',                'DeleteAll',...
        'callback',             'graph(27);');
    uimenu(...
        'Label',                'RestoreAll',...
        'callback',             'graph(17);');
    % uimenu(...
    %     'Label',                'ReDraw',...
    %     'callback',             'graph(4);');
    uimenu(...
        'Label',                'Help',...
        'callback',             'graph(23)',...
        'Accelerator',          'H');
    uimenu(...
        'Label',                'Print',...
        'callback',             'printdlg',...
        'Accelerator',          'P');

    uimenu(...
        'Label',                'Quit',...
        'callback',             'clear; close all;');


    %the information line
    aStats = uicontrol(...
        'style',                'text',...
        'tag',                  'Stats',...
        'Units',                'Normalized',...
        'position',             [0.015 0.02 0.15 0.9],...  % x y w h
        'horizontalalignment',  'left',...
        'fontsize',             10,...
        'backgroundcolor',      [0.831  0.816  0.784]);

    uicontrol(...
        'Style',                'pushbutton',...
        'String',               'Mark Trial for Deletion',...
        'Units',                'normalized',...
        'Position',             [0.015 0.53 0.15 0.02],...
        'Callback',             'graph(16)');%traceDelete()
    uicontrol(...
        'Style',                'pushbutton',...
        'String',               'Delete All Highlighted Trials',...
        'Units',                'normalized',...
        'Position',             [0.015 0.49 0.15 0.02],...
        'Callback',             'graph(4)');%graph()
end %if ishandle(h)


%------- select traces whose attributes meet the set limits ---------------
%get a fresh copy of the attribute data
gData = gDataOriginalAttrib;                                                             %clone the data
processComputedAttributes();

%remove all trials where the line-up attribute is NaN
gSelectedHistoTrials = find(~isnan(gData(:,getAttribNumber(gLineUpAttribute))));         %can't have any NaN for lineup attributes
gData                = gData(gSelectedHistoTrials,:);                                    %form a new attribute list

%remove all trials where the sort-on attribute is NaN
if ~isnan(gSortOnAttribute)
    gSelectedHistoTrials = find(~isnan(gData(:,getAttribNumber(gSortOnAttribute))));     %eliminate trials with sort on = NaNs
    gData                = gData(gSelectedHistoTrials,:);                                %form a new attribute list
end

filterTrials();   % select trials based on the attribute dialog window

% sort the data based on a selected attribute
if ~isnan(gSortOnAttribute)
    gData                = sortrows(gData,getAttribNumber(gSortOnAttribute));        %sort the attributes
    gSelectedHistoTrials = gData(:,1);                                               %using the event number attribute, map the sorted attributes to the traces
else
    gSelectedHistoTrials = gData(:,1);                                               %using the event number attribute, map the sorted attributes to the traces
end

d                       = size(gData);                                      %determine how many trials are there
gNumSelectedHistoTrials = d(1);                                             %get the number of rows
d                       = size(a01);
gDataWidth              = d(1);                                             % length of traces
%gHistoAccumulator       = zeros(gDataWidth*2,1);

%-----use the proper width of data-----------------------------------------
plotIndex = 0;

%dimension arrays and fill the with NAN or zero
gPlottedTraces        = NaN*ones(length(-gBefore:gAfter),gNumSelectedHistoTrials,length(find(gPlotShown)));  % array length x num trials x num plots
gPlottedTracesAvg     = zeros(length(-gBefore:gAfter),length(find(gPlotShown)));                             % array length x num avg plots
gIFRAccumulator       = NaN*ones(length(-gBefore*2:gAfter*2),gNumSelectedHistoTrials,1);                     % array length x num trials x num plots
gRasterAccumulator    = zeros(length(-gBefore*2:gAfter*2),gNumSelectedHistoTrials,1);                        % array length x num trials x num plots
gHistoAccumulator     = zeros(length(-gBefore*2:gAfter*2),1,1);                                              % array length x num trials x num plots


% check if gBefore and gAfter are within the data length
ALLlineUp             = gData(:,getAttribNumber(gLineUpAttribute));
ALLpreOnsetDataPoints = 1000 * (gData(:,24) - gData(:,41));
ALLleftData           = round(ALLpreOnsetDataPoints + ALLlineUp - gBefore);                  % zerotime - left edge
ALLrightData          = gBefore + gAfter + ALLleftData;

%if ~isempty(find(ALLleftData < 1))
if ~isempty(find(ALLleftData < 1, 1, 'first'))    %need only find the first occurance to prove array is NOT empty (Matlab says this is faster, 3/8/07)
    %beep;
    fprintf(1,'\nNumber of left data points is ');
    fprintf(1,'%d points TOO LONG\n',abs(min(ALLleftData) - 1));
    h = msgbox('In HistoOptions, reduce the number of points shown before the line up point.','Too many points','error');
    uiwait(h);
    %if ~isempty(find(ALLrightData > gTraceLength))
    if ~isempty(find(ALLrightData > gTraceLength, 1, 'first'))    %need only find the first occurance to prove array is NOT empty (Matlab says this is faster, 3/8/07)
        fprintf(1,'\nNumber of right data points is ');
        fprintf(1,'%d points TOO LONG\n',max(ALLrightData) - gTraceLength);
    end;
    h = findobj('name', 'Histogram');% close the histo window
    if ishandle(h);
        close(h);
    end
    return;
end;

%if ~isempty(find(ALLrightData > gTraceLength))
if ~isempty(find(ALLrightData > gTraceLength, 1, 'first'))    %need only find the first occurance to prove array is NOT empty (Matlab says this is faster, 3/8/07)
    %beep;
    fprintf(1,'\nNumber of right data points is ');
    fprintf(1,'%d points TOO LONG\n',max(ALLrightData) - gTraceLength);
    h = msgbox('In HistoOptions, reduce the number of points shown after the line up point.','Too many points','error');
    uiwait(h);
    %if ~isempty(find(ALLleftData < 1))
    if ~isempty(find(ALLleftData < 1, 1, 'first'))    %need only find the first occurance to prove array is NOT empty (Matlab says this is faster, 3/8/07)
        fprintf(1,'\nNumber of left data points is ');
        fprintf(1,'%d points TOO LONG\n',abs(min(ALLleftData) - 1));
    end
    h = findobj('name', 'Histogram');   % close the histo window
    if ishandle(h);
        close(h);
    end
    return;
end;


%draw the traces
%---------------
if gNumSelectedHistoTrials > 0              %any trials left to plot?
    rasterIndex = 0;
    for plotNumber = 1:gNumChan

        %collect the data and then draw the LINE PLOTS, form arrays for
        %just the traces drawn
        %-------------------
        if gPlotShown(plotNumber) == 1
            plotIndex = plotIndex + 1;

            gPlotOrder(plotNumber) = plotIndex;
%%%
            gHistoSubplots(plotIndex) = subplot(gNumPlots,1,plotIndex);
            h       = gHistoSubplots(plotIndex);
            aPos    = get(h, 'Position');   %get the Matlab-selected plot position
            aPos(1) = aLeft;                %move the left edge to the right
            aPos(3) = aWide;                %change the width
            set(h, 'Position', aPos);       %pass the parameters

            hold on

            for trialIndex          = 1:gNumSelectedHistoTrials
                trialNumber         = gData(trialIndex,gMergedTrialNumberAttr);
                lineUp              = gData(trialIndex,getAttribNumber(gLineUpAttribute));       %value at the line up point
                preOnsetDataPoints  = 1000 * (gData(trialIndex,24) - gData(trialIndex,41));
                leftData            = round(preOnsetDataPoints + lineUp - gBefore);              %zerotime - left edge
                rightData           = gBefore + gAfter + leftData;

                %test vector must be type double because there is limited matrix math with type single vectors and can't do a matrix subtraction
                if plotNumber < 10
                    test = double(eval(['single(a0' num2str(plotNumber) '(' num2str(leftData,'%11.0f') ':' num2str(rightData,'%11.0f') ',' num2str(trialNumber) '))' ]));
                else
                    test = double(eval(['single(a' num2str(plotNumber) '(' num2str(leftData,'%11.0f') ':' num2str(rightData,'%11.0f') ',' num2str(trialNumber) '))' ]));
                end

                if gZeroLineUp == 1
                    offset  = test(gBefore + 1);     %get the value of the line-up point
                    test    = test - offset;           %bring the line-up point to zero
                end

                gPlottedTraces(:,trialIndex,plotIndex) = test;          %add this trace to the collection to be displayed

                %do all at once from the complete matrix of traces
                %if gPlotAvg(plotNumber) == 1
                %    gPlottedTracesAvg(:,plotIndex) = gPlottedTracesAvg(:,plotIndex) + test; %4/20/06 grab the trace here for the average trace
                %end

                %plot the data if it is the last trial
                if trialIndex == gNumSelectedHistoTrials
                    if gPlotInd(plotNumber) == 1
                        trace = plot(...
                            -gBefore:gAfter,...
                            gPlottedTraces(:,:,plotIndex),...
                            'color', gPlotColor(plotNumber));
                    end

                    %enables traces respond to being clicked on
                    theCallback = ['graph(22,'   num2str(plotNumber)   ');'];
                    set(trace,'ButtonDownFcn',   theCallback);

                    if gPlotAvg(plotNumber) == 1
                        %compute the average trace using MEAN()
                        %gPlottedTracesAvg(:,plotIndex) = gPlottedTracesAvg(:,plotIndex) / gNumSelectedHistoTrials;
                        for i = 1:length(-gBefore:gAfter)
                            gPlottedTracesAvg(i,plotIndex) = mean(gPlottedTraces(i,:,plotIndex));
                            aSDvalues(i) = std(gPlottedTraces(i,:,plotIndex)');
                        end
                        trace = plot(...
                            -gBefore:gAfter,...
                            gPlottedTracesAvg(:,plotIndex),...
                            'color',        'k',...
                            'LineWidth',    2.0);

                        %compute the SD trace using STD()
                        %add STD()values to gPlottedTraceAvg() array (top)
                        gPlottedTracesAvg(:,plotIndex) = gPlottedTracesAvg(:,plotIndex) + aSDvalues';
                        trace = plot(...
                            -gBefore:gAfter,...
                            gPlottedTracesAvg(:,plotIndex),...
                            'color',        'k',...
                            'LineStyle',    ':',...
                            'LineWidth',    1.0);

                        aSDvalues = aSDvalues * (-2);       %multiple whole array by  (-2)
                        %add STD()values to gPlottedTraceAvg() array (bottom)
                        gPlottedTracesAvg(:,plotIndex) = gPlottedTracesAvg(:,plotIndex) + aSDvalues';
                        trace = plot(...
                            -gBefore:gAfter,...
                            gPlottedTracesAvg(:,plotIndex),...
                            'color',        'k',...
                            'LineStyle',    ':',...
                            'LineWidth',    1.0);
                    end


                    xlim([-gBefore-5 gAfter+5]);
                    if gAutoSize(plotNumber) == 1
                        ylim('auto');
                    else
                        ylim('manual');
                        ylim([gManLo(plotNumber) gManHi(plotNumber)]);
                    end;
                    if ishold
                        plot([0 0],get(gca,'ylim'),'-m');                   % draw alignment line
                    else
                        hold on;
                        plot([0 0],get(gca,'ylim'),'-m');                   % draw alignment line
                        hold off;
                    end
                    a = ylim;                                               %get the current y-axis values, if the plot is shown
                    gManLo(plotNumber) = a(1);
                    gManHi(plotNumber) = a(2);
                end
            end     %for trialIndex = 1:gNumSelectedHistoTrials

            theCallback = ['graph(8,'   num2str(plotNumber) ','  num2str(plotIndex)  ');'];        %make it so clicking on the plot will call zoomplot
            set(gca,'ButtonDownFcn',    theCallback);

            set(gca, 'ticklength',      [kTickLength kTickLength]);
            if ~gFullLabel && plotIndex < gNumPlots
                set(gca, 'XTickLabel', []);                                 %no scale numbers
            end
            if plotIndex == gNumPlots
                xlabel('milliseconds');
            end

            ylabel(gTraceLabels(plotNumber));                               %name the traces
            drawnow;        %show the progress, same time as drawnow after all the traces
        end     %draw line plots



        %determine if ANY unit plots selected, if so, do ALL the
        %unit-related computations and fill ALL the unit analysis arrays,
        %but only plot the unit-related traces requested by the user
        %--------------------
        if gRaster(plotNumber) || gIFR(plotNumber) || gHistogram(plotNumber)

            for trialIndex = 1:gNumSelectedHistoTrials

                trialNumber         = gData(trialIndex,gMergedTrialNumberAttr);
                lineUp              = gData(trialIndex,getAttribNumber(gLineUpAttribute));        %value at the line up point
                preOnsetDataPoints  = 1000 * (gData(trialIndex,24) - gData(trialIndex,41));
                leftData            = round(preOnsetDataPoints + lineUp - gBefore);               %zerotime - left edge
                rightData           = gBefore + gAfter + leftData;

                %the IFR trace is sampled at 2kHz instead of 1kHz
                leftData            = 2 * leftData;
                rightData           = 2 * rightData;

                %get the IFR traces
                if plotNumber < 10
                    aIFRdata                                = eval(['single(a0' num2str(plotNumber) '(:,' num2str(trialNumber) '))']);
                else
                    aIFRdata                                = eval(['single(a' num2str(plotNumber) '(:,' num2str(trialNumber) '))']);
                end

                aRasterData                                 = aIFRdata;
                aHistoData                                  = aIFRdata;

                %build the IFR trace
                result                                      = find(aIFRdata == 0);                          %select any ms that has a zero in it
                aIFRdata(result)                            = NaN;                                          %replace them with NaN so they won't plot
                gIFRAccumulator(:,trialIndex,1)             = 1 ./ double(aIFRdata(leftData:rightData));    %invert the IFR to get frequency

                %build the histogram trace
                result                                      = find(aHistoData > 0);                         %select any ms that has a non-zero value in it
                aHistoData(result)                          = 1;                                            %replace values with a 1
                gHistoAccumulator(1:gBefore*2+gAfter*2+1)   = gHistoAccumulator(1:gBefore*2+gAfter*2+1) + double(aHistoData(leftData:rightData));

                %collect the raster traces
                rasterIndex                                 = rasterIndex + 1;
                result                                      = find(aRasterData > 0);                        %select any ms that has a non-zero value in it
                aRasterData(result)                         = rasterIndex;                                  %replace them with the trial number
                result                                      = find(aRasterData == 0);
                aRasterData(result)                         = NaN;                                          %replace them with NaN so they won't plot
                gRasterAccumulator(:,trialIndex,1)          = aRasterData(leftData:rightData);

                %if this is the last trial, plot all the unit-related traces
                if trialIndex == gNumSelectedHistoTrials

                    %plot the Instaneous Firing Rate
                    if gIFR(plotNumber)
                        plotIndex                   = plotIndex + 1;
                        aIFRplotIndex               = plotIndex;
                        gHistoSubplots(plotIndex)   = subplot(gNumPlots,1,aIFRplotIndex);
                        h = gHistoSubplots(plotIndex);
                        aPos = get(h, 'Position');      %get the Matlab-selected plot position
                        aPos(1) = aLeft;                %move the left edge to the right
                        aPos(3) = aWide;                %change the width
                        set(h, 'Position', aPos);       %pass the parameters

                        hold on;

                        trace = plot(...
                            -gBefore:0.5:gAfter,    gIFRAccumulator(:,:,1),...
                            'color',            'r',...
                            'marker',           's',...
                            'markersize',       gRasterSize,...
                            'linestyle' ,       'none',...
                            'markerfacecolor',  'r',...
                            'markeredgecolor',  'r'...
                            );

                        theCallback = ['graph(8,'   num2str(gNumChan+1)  ','  num2str(plotIndex)  ');'];        %make it so clicking on the plot will call zoomplot
                        set(gca,'ButtonDownFcn',    theCallback);

                        xlim([(-gBefore-5) (gAfter+5)]);
                        if gAutoSize(plotNumber) == 1
                            ylim('auto');
                        else
                            ylim('manual');
                            ylim([gManLo(plotNumber) gManHi(plotNumber)]);
                        end;
                        if ishold
                            plot([0 0],get(gca,'ylim'),'-m'); % draw alignment line
                        else
                            hold on;
                            plot([0 0],get(gca,'ylim'),'-m'); % draw alignment line
                            hold off;
                        end
                        a = ylim;                                   %get the current y-axis values, if the plot is shown
                        gManLo(plotNumber) = a(1);
                        gManHi(plotNumber) = a(2);

                        set(gca, 'ticklength',      [kTickLength kTickLength]);
                        if ~gFullLabel && plotIndex < gNumPlots
                            set(gca, 'XTickLabel', []);             %no scale numbers
                        end
                        if plotIndex == gNumPlots
                            xlabel('milliseconds');
                        end
                        ylabel('Inst Fire Rate spk/sec');           %name the traces
                    end %plot the instanteous firing rate


                    %plot the raster
                    if gRaster(plotNumber)
                        plotIndex                   = plotIndex + 1;
                        aRasterPlotIndex            = plotIndex;
                        gHistoSubplots(plotIndex)   = subplot(gNumPlots,1,aRasterPlotIndex);
                        h = gHistoSubplots(plotIndex);
                        aPos = get(h, 'Position');      %get the Matlab-selected plot position
                        aPos(1) = aLeft;                %move the left edge to the right
                        aPos(3) = aWide;                %change the width
                        set(h, 'Position', aPos);       %pass the parameters

                        trace = plot(...
                            -gBefore:0.5:gAfter,    gRasterAccumulator(:,:,1),...
                            'color',            'r',...
                            'marker',           's' ,...
                            'markersize',       gRasterSize,...
                            'linestyle' ,       'none',...
                            'markerfacecolor',  'r',...
                            'markeredgecolor',  'r'...
                            );

                        theCallback = ['graph(8,'   num2str(gNumChan+2) ','  num2str(plotIndex)  ');'];        %make it so clicking on the plot will call zoomplot
                        set(gca,'ButtonDownFcn',    theCallback);

                        xlim([(-gBefore-5) (gAfter+5)]);
                        if gAutoSize(plotNumber) == 1
                            ylim('auto');
                        else
                            ylim('manual');
                            ylim([gManLo(plotNumber) gManHi(plotNumber)]);
                        end;
                        if ishold
                            plot([0 0],get(gca,'ylim'),'-m');       %draw alignment line
                        else
                            hold on;
                            plot([0 0],get(gca,'ylim'),'-m');       %draw alignment line
                            hold off;
                        end
                        a = ylim;                                   %get the current y-axis values, if the plot is shown
                        gManLo(plotNumber) = a(1);
                        gManHi(plotNumber) = a(2);

                        set(gca, 'ticklength',      [kTickLength kTickLength]);
                        if ~gFullLabel && plotIndex < gNumPlots
                            set(gca, 'XTickLabel', []);     %no scale numbers
                        end
                        if plotIndex == gNumPlots
                            xlabel('milliseconds');
                        end
                        ylabel('Rasters');               %name the traces
                    end %plot the IFR


                    %plot the histogram
                    if gHistogram(plotNumber)
                        plotIndex                   = plotIndex + 1;
                        aHistogramPlotIndex         = plotIndex;
                        gHistoSubplots(plotIndex)   = subplot(gNumPlots,1,aHistogramPlotIndex);
                        h = gHistoSubplots(plotIndex);
                        aPos = get(h, 'Position');      %get the Matlab-selected plot position
                        aPos(1) = aLeft;                %move the left edge to the right
                        aPos(3) = aWide;                %change the width
                        set(h, 'Position', aPos);       %pass the parameters

                        lo = 1;
                        hi = aBinSize;
                        for k = 1:(gBefore*2+gAfter*2+1) / aBinSize
                            gHistoAccumulator(lo:hi) = sum(gHistoAccumulator(lo:hi))/gNumSelectedHistoTrials * 2000 /(aBinSize);

                            %group the data into bins
                            lo = lo + aBinSize;
                            hi = hi + aBinSize;
                        end

                        plot(...
                            -gBefore:0.5:gAfter,    gHistoAccumulator(1:gBefore*2+gAfter*2+1),...
                            'color',                gPlotColor(plotNumber));


                        theCallback = ['graph(8,'   num2str(gNumChan+3) ','  num2str(plotIndex)  ');'];        %make it so clicking on the plot will call zoomplot
                        set(gca,'ButtonDownFcn',    theCallback);

                        xlim([-gBefore-5 gAfter+5]);
                        if gAutoSize(plotNumber) == 1
                            ylim('auto');
                        else
                            ylim('manual');
                            ylim([gManLo(plotNumber) gManHi(plotNumber)]);
                        end;
                        if ishold
                            plot([0 0],get(gca,'ylim'),'-m'); % draw alignment line
                        else
                            hold on;
                            plot([0 0],get(gca,'ylim'),'-m'); % draw alignment line
                            hold off;
                        end
                        a = ylim;                                   %get the current y-axis values, if the plot is shown
                        gManLo(plotNumber) = a(1);
                        gManHi(plotNumber) = a(2);
                        ylabel(gTraceLabels(plotNumber));

                        set(gca, 'ticklength',      [kTickLength kTickLength]);
                        if ~gFullLabel && plotIndex < gNumPlots
                            set(gca, 'XTickLabel', []);     %no scale numbers
                        end
                        if plotIndex == gNumPlots
                            xlabel('milliseconds');
                        end
                        ylabel('Histogram Hz');               %name the traces
                    end %plot the histogram

                end
                hold on
            end
            drawnow;        %show the progress, same time as drawnow after all the traces
        end
    end


    %all the traces are drawn, fill the information box
    aStr = histoStats();
    set(aStats,'string', aStr)                              %install the list in the popup menu

else  % no traces to display
    aStr = ['N ='   char(32) int2str(gNumSelectedHistoTrials),...
        aCRLF aCRLF ];
    set(aStats,'string', aStr)                              %install the list in the popup menu
end

%make some values available to the user in the BASE workspace window
assignin('base', 'htrace',  gPlottedTraces);                %line plots
assignin('base', 'hifr',    gIFRAccumulator);               %IFR points
assignin('base', 'hhisto',  gHistoAccumulator);             %histogram data
assignin('base', 'hraster', gRasterAccumulator);            %raster data
assignin('base', 'hattr',   gData);                         %filtered and sorted attributes from the trials in the histogram plots
assignin('base', 'rt',      (-gBefore:gAfter)');            %3/8/07 eliminated brackets
% end HISTOGRAM



%--------------------------------------------------------------------------
% histoStats
% 6/15/04
%--------------------------------------------------------------------------
function aStr = histoStats()

global gAttribNames
global gFileIn_data
global gFilesLoaded
global gLineUpAttribute
global gNumSelectedHistoTrials
global gSortOnAttribute


aCRLF = [char(10), char(13)];
aStr = char(gFileIn_data(1,:));                         %load the first filename
if gFilesLoaded > 1
    for k = 2:gFilesLoaded
        aStr = [aStr aCRLF char(32) ' + ' aCRLF char(gFileIn_data(k,:)) ];        %load the other names if ther are any merged files
    end
end

aStr = [aStr...
    aCRLF aCRLF aCRLF,...
    'N =' char(32) int2str(gNumSelectedHistoTrials) ,...
    aCRLF aCRLF,...
    'LINE-UP:' char(32) char(gAttribNames(getAttribNumber(gLineUpAttribute))),...
    aCRLF aCRLF
    ];

if ~isnan(gSortOnAttribute)
    aStr = [aStr 'SORT:' char(32) char(gAttribNames(getAttribNumber(gSortOnAttribute))) aCRLF aCRLF];
end
%end



%--------------------------------------------------------------------------
% HISTONEXT trace in a Histogram plot.  Positive advance increments,
% negative advance decrements and zero advance removes all highlights.
% 5/15/03
%--------------------------------------------------------------------------
function histoNext(advance)

global gNextTrace
global gNumSelectedHistoTrials


%un-highlight all the highlighted trace
traceDraw;

%advance=0 means STOP hightlighting
if advance == 0
    gNextTrace = 0;
else
    %point to the neighboring trace, before or after
    gNextTrace = gNextTrace + advance;                    %this can increment or decrement
    if gNextTrace < 0                                   %get started going backwards
        gNextTrace = gNumSelectedHistoTrials;
    end
    if gNextTrace > gNumSelectedHistoTrials
        gNextTrace = 0;
    end
    if gNextTrace == 0                                  %this works going up or down
        beep;
    end
end
%highlight the next trace
traceHighlight();
%end histonext



%--------------------------------------------------------------------------
% traceDraw
% Draws individual traces in a plot.  Typically used to un-highlight a
% trace.
% 4/26/04
%--------------------------------------------------------------------------
function traceDraw()

global gAfter
global gBefore
global gHistogram
global gHistoSubplots
global gIFR
global gIFRAccumulator
global gNextTrace
global gNumChan
global gPlotColor
global gPlottedTraces
global gPlotShown
global gRaster
global gRasterAccumulator
global gRasterSize


j = 0;
% restore the previously marked trace
if gNextTrace > 0
    for plotNumber = 1:gNumChan

        if gPlotShown(plotNumber) == 1   %check for line traces to be drawn
            j = j + 1;
            subplot(gHistoSubplots(j));
            hold on

            trace = plot(...
                -gBefore:gAfter,    gPlottedTraces(:,gNextTrace,j),...
                'color',            gPlotColor(plotNumber),...
                'erasemode',        'none');

            %enables traces respond to being clicked on
            theCallback = ['graph(22,'   num2str(plotNumber)   ');'];
            set(trace,'ButtonDownFcn',    theCallback);
        end


        %any UNIT activity plots?
        if (gIFR(plotNumber)==1) || (gRaster(plotNumber)==1) || (gHistogram(plotNumber)==1)

            if gIFR(plotNumber)==1      %check if IFR is shown
                j = j + 1;
                subplot(gHistoSubplots(j));
                hold on
                trace = plot(...
                    -gBefore:0.5:gAfter,    gIFRAccumulator(:,gNextTrace,1),...
                    'color',            'r',...
                    'marker',           's' ,...
                    'markersize',       gRasterSize,...
                    'linestyle' ,       'none',...
                    'markerfacecolor',  'r',...
                    'markeredgecolor',  'r'...
                    );
            end


            if gRaster(plotNumber)==1    %check if Raster is shown
                j = j + 1;
                subplot(gHistoSubplots(j));
                hold on
                trace = plot(...
                    -gBefore:0.5:gAfter,    gRasterAccumulator(:,gNextTrace,1),...
                    'color',            'r',...
                    'marker',           's' ,...
                    'markersize',       gRasterSize,...
                    'linestyle' ,       'none',...
                    'markerfacecolor',  'r',...
                    'markeredgecolor',  'r'...
                    );
            end


            if gHistogram(plotNumber)==1    %check if Histogram is shown
                j = j + 1;                  %nothing to do to Histogram, increment around it
            end
        end
    end
end
%end    tracedraw



%--------------------------------------------------------------------------
% TRACE HIGHLIGHT
% 4/26/04
%--------------------------------------------------------------------------
function traceHighlight()

global gAfter
global gBefore
global gData
global gHistogram
global gHistoSubplots
global gIFR
global gIFRAccumulator
global gMergedTrialNumberAttr
global gNextTrace
global gNumChan
global gPlottedTraces
global gPlotShown
global gRaster
global gRasterAccumulator
global gRasterSize


j = 0;

if gNextTrace > 0                                       % highlight the next trace
    for plotNumber = 1:gNumChan

        %any LINE plots?
        if gPlotShown(plotNumber) == 1
            j = j + 1;
            subplot(gHistoSubplots(j));
            hold on

            trace = plot(...
                -gBefore:gAfter,    gPlottedTraces(:,gNextTrace,j),...
                'color',            'g',...
                'erasemode',        'none');

            %enables traces respond to being clicked on
            theCallback = ['graph(22,'   num2str(plotNumber)   ');'];
            set(trace,'ButtonDownFcn',    theCallback);



        end

        %any UNIT activity plots?
        if (gIFR(plotNumber)==1) || (gRaster(plotNumber)==1) || (gHistogram(plotNumber)==1)

            %check if IFR is shown
            if gIFR(plotNumber)==1      %check if IFR is shown
                j = j + 1;
                subplot(gHistoSubplots(j));
                hold on
                trace = plot(...
                    -gBefore:0.5:gAfter,    gIFRAccumulator(:,gNextTrace,1),...
                    'color',            'g',...
                    'marker',           's' ,...
                    'markersize',       gRasterSize,...
                    'linestyle' ,       'none',...
                    'markerfacecolor',  'g',...
                    'markeredgecolor',  'g'...
                    );
            end

            %check if Raster is shown
            if gRaster(plotNumber)==1
                j = j + 1;
                subplot(gHistoSubplots(j));
                hold on
                trace = plot(...
                    -gBefore:0.5:gAfter,    gRasterAccumulator(:,gNextTrace,1),...
                    'color',            'g',...
                    'marker',           's' ,...
                    'markersize',       gRasterSize,...
                    'linestyle' ,       'none',...
                    'markerfacecolor',  'g',...
                    'markeredgecolor',  'g'...
                    );
            end

            %check if Histogram is shown
            if gHistogram(plotNumber)==1
                j = j + 1;                  %nothing to do to Histogram, increment around it
            end

        end
    end
    aStr = histoStats();
    i = gData(gNextTrace,gMergedTrialNumberAttr);
    aStr = [aStr 'HIGHLIGHTED: ' int2str(i)];
    aStats = findobj('tag', 'Stats');
    set(aStats,'string', aStr);                              %install the list in the popup mentu

    %fprintf(1,'\nTrial %d of %d',gNextTrace,gNumSelectedHistoTrials);

else
    aStr = histoStats();
    aStats = findobj('tag', 'Stats');
    set(aStats,'string', aStr);                              %install the list in the popup mentu
end
%end    traceHighlight



%--------------------------------------------------------------------------
% dialogHistoOptionsOpen
% for the Histogram plot
% 5/16/03
%--------------------------------------------------------------------------
function dialogHistoOptionsOpen()

global gAfter
global gAutoSize
global gPlotAvg
global gPlotInd
global gBefore
global gBinSize
global gFullLabel
global gHistogram
global gIFR
global gManHi
global gManLo
global gNumChan
global gPlotShown
global gRaster
global gRasterSize
global gTraceLabels
global gZeroLineUp


h1  = 25;                    %heights
h2  = 20;
h3  = 22;

w1  = 50;                    %widths
w2  = 80;
w3  = 100;
w4  = 140;


c1 = 20;                    %upper block of controls

cc1 = c1;                   %lower block of controls
cc2 = cc1 + 100;
cc3 = cc2 + 30;
cc4 = cc3 + 30 + 100;
cc5 = cc4 + 40;
cc6 = cc5 + 40;
cc7 = cc6 + 40;
cc8 = cc7 + 60;

b1 = 20;                    %buttons
b2 = b1 + w1 + 20;
b3 = b2 + w1 + 20;
b4 = b3 + w1 + 20;

figureHeight = (16 + gNumChan) * h1;
row = figureHeight;



h = figure(...
    'numbertitle',          'off',...
    'name',                 'Histogram Options',....
    'menubar',              'none',...
    'color',                [.831 .816 .784],...
    'units',                'pixels',...
    'position',             [100 100 575 figureHeight]);            %x y width height

row = row - 30;
uicontrol(...
    'style',                'text',...
    'string',               'Data Before Line-up',...
    'horizontalalignment',  'left',...
    'position',             [c1 row w3 h2]);
uicontrol(...
    'style',                'edit',...
    'tag',                  'edBefore',...
    'string',               num2str(gBefore),...                    %use the last Before value
    'position',             [120 row w1 h2]);
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Data After Line-up',...
    'position',             [190 row w3 h2]);
uicontrol(...
    'style',                'edit',...
    'tag',                  'edAfter',...
    'string',               num2str(gAfter),...                     %use the last After value
    'position',             [280 row w1 h2]);


row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Histo Bin Size',...
    'position',             [20 row w2 h2]);
uicontrol(...
    'style',                'edit',...
    'tag',                  'edBinSize',...
    'string',               num2str(gBinSize),...                    %use the last Before value
    'position',             [120 row w1 h2]);


row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Raster Pt Size',...
    'position',             [20 row w2 h2]);
uicontrol(...
    'style',                'edit',...
    'tag',                  'rasterSize',...
    'string',               num2str(gRasterSize),...                    %use the last Before value
    'position',             [120 row w1 h2]);


row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Full Plot Labels',...
    'position',             [c1 row w2 h2]);
uicontrol(...
    'style',                'checkbox',...
    'horizontalalignment',  'left',...
    'tag',                  'fullLabels',...
    'value',                gFullLabel,...
    'position',             [120 row w1 h2]);

row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Zero Line-up Pts',...
    'position',             [c1 row w2 h2]);
uicontrol(...
    'style',                'checkbox',...
    'horizontalalignment',  'left',...
    'tag',                  'zero',...
    'value',                gZeroLineUp,...
    'position',             [120 row w1 h2]);


row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Indiv',...
    'position',             [cc4 row w1 h2]);
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Avg&',...
    'position',             [cc5 row w1 h2]);
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Auto',...
    'position',             [cc6 row w1 h2]);
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Manual',...
    'position',             [cc7 row w1 h2]);
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Manual',...
    'position',             [cc8 row w1 h2]);

row = row - 15;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Action',...
    'position',             [cc2 row w1 h2]);

uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Trace',...
    'position',             [cc4 row w1 h2]);
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'SDev',...
    'position',             [cc5 row w1 h2]);
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Scale',...
    'position',             [cc6 row w1 h2]);
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Scale Hi',...
    'position',             [cc7 row w1 h2]);
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Scale Lo',...
    'position',             [cc8 row w1 h2]);



for i = 1:gNumChan
    row = row - 30;

    uicontrol(...
        'style',                'text',...
        'horizontalalignment',  'left',...
        'string',               gTraceLabels(i),...
        'units',                'pixels',...
        'position',             [cc1 row 90 h1]);

    if gIFR(i) && gRaster(i) && gHistogram(i)
        a = 9;
    elseif gRaster(i) && gIFR(i)
        a = 8;
    elseif gRaster(i) && gIFR(i)
        a = 7;
    elseif gRaster(i) && gHistogram(i)
        a = 6;
    elseif gIFR(i)
        a = 5;
    elseif gHistogram(i)
        a = 4;
    elseif gRaster(i)
        a = 3;
    elseif gPlotShown(i)
        a = 2;
    else
        a = 1;
    end

    %'value',                [gPlotShown(i)+1],...
    uicontrol(...
        'style',                'popupmenu',...
        'tag',                  ['puAction' num2str(i)],...
        'value',                a,...
        'background',           [1  1  1],...
        'units',                'pixels',...
        'string',               'Hide Trace|Line Plot|Raster|Histogram|IFR|Raster + Histo|Raster + IFR|Histo + IFR|Raster + Histo + IFR',...
        'position',             [cc2  row  w4  h3 ]);   % X Y W H

    uicontrol(...
        'style',                'checkbox',...
        'horizontalalignment',  'left',...
        'tag',                  ['ind' num2str(i)],...
        'value',                gPlotInd(i),...
        'position',             [cc4 row w1 h1]);

    uicontrol(...
        'style',                'checkbox',...
        'horizontalalignment',  'left',...
        'tag',                  ['avg' num2str(i)],...
        'value',                gPlotAvg(i),...
        'position',             [cc5 row w1 h1]);

    uicontrol(...
        'style',                'checkbox',...
        'horizontalalignment',  'left',...
        'tag',                  ['auto' num2str(i)],...
        'value',                gAutoSize(i),...
        'position',             [cc6 row w1 h1]);

    uicontrol(...
        'style',                'edit',...
        'tag',                  ['manHi' num2str(i)],...
        'string',               num2str(gManHi(i)),...                    %use the last Before value
        'position',             [cc7 row w1 h2]);

    uicontrol(...
        'style',                'edit',...
        'tag',                  ['manLo' num2str(i)],...
        'string',               num2str(gManLo(i)),...                    %use the last Before value
        'position',             [cc8 row w1 h2]);
end


%present choices for the locally added histogram trace, to be used if the
%user selects uses this trace
i = i + 1;
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Raster',...
    'units',                'pixels',...
    'position',             [cc1 row 90 h1]);

uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '(from Inst Firing Rate Data)',...
    'units',                'pixels',...
    'position',             [cc2 row 150 h1]);

uicontrol(...
    'style',                'checkbox',...
    'horizontalalignment',  'left',...
    'tag',                  ['auto' num2str(i)],...
    'value',                gAutoSize(i),...
    'position',             [cc6 row w1 h1]);

uicontrol(...
    'style',                'edit',...
    'tag',                  ['manHi' num2str(i)],...
    'string',               num2str(gManHi(i)),...                    %use the last Before value
    'position',             [cc7 row w1 h2]);

uicontrol(...
    'style',                'edit',...
    'tag',                  ['manLo' num2str(i)],...
    'string',               num2str(gManLo(i)),...                    %use the last Before value
    'position',             [cc8 row w1 h2]);


%present choices for the locally added instanteous firing rate trace, to
%be used if the user selects uses this trace
i = i + 1;
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               'Histogram',...
    'units',                'pixels',...
    'position',             [cc1 row 90 h1]);

uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '(from Inst Firing Rate Data)',...
    'units',                'pixels',...
    'position',             [cc2 row 150 h1]);

uicontrol(...
    'style',                'checkbox',...
    'horizontalalignment',  'left',...
    'tag',                  ['auto' num2str(i)],...
    'value',                gAutoSize(i),...
    'position',             [cc6 row w1 h1]);

uicontrol(...
    'style',                'edit',...
    'tag',                  ['manHi' num2str(i)],...
    'string',               num2str(gManHi(i)),...                    %use the last Before value
    'position',             [cc7 row w1 h2]);

uicontrol(...
    'style',                'edit',...
    'tag',                  ['manLo' num2str(i)],...
    'string',               num2str(gManLo(i)),...                    %use the last Before value
    'position',             [cc8 row w1 h2]);




row = row - 60;
uicontrol(...
    'style',                'pushbutton',...
    'string',               'Plot',...
    'callback',             'graph(11, 1)',...
    'position',             [b2 row w1 h2]);
uicontrol(...
    'style',                'pushbutton',...
    'string',               'Store',...
    'callback',             'graph(11, 0)',...
    'position',             [b3 row w1 h2]);
uicontrol(...
    'style',                'pushbutton',...
    'string',               'Cancel',...
    'callback',             'close',...
    'position',             [b4 row w1 h2]);

%end dialogHistoOptionsOpen



%--------------------------------------------------------------------------
% dialogHistoOptionsClose
% the choices for the Histogram plot including time to
% display before and after the line-up point, and which traces to show.
% 5/19/03
%--------------------------------------------------------------------------
function dialogHistoOptionsClose(drawItNow)

global gAfter
global gAutoSize
global gBefore
global gBinSize
global gFullLabel
global gHistogram
global gIFR
global gManLo
global gManHi
global gNumPlots
global gNumChan
global gPlotAvg
global gPlotInd
global gPlotOrder
global gPlotShown
global gRaster
global gRasterSize
global gZeroLineUp

%SAVE  global declaration of a01 a02 a03 a04 a05 a06
for jj = 1:gNumChan
    if jj < 10
        eval(['global a0' num2str(jj)])
    else
        eval(['global a' num2str(jj)])
    end;
end


%detect which traces are sampled at 1kHz and 2kHz.  Unit traces can only be
%plotted from 2kHz traces.
aMaxSize = -50000000;
aMinSize = 50000000;
aBadUnit = 0;

aSize = zeros(1:gNumChan);      %3/8/07 Matlab says for speed, preallocate arrays instead of allowind them to grow
for jj = 1:gNumChan
    if jj < 10
        eval(['bSize = size(a0' num2str(jj) ');']);
    else
        eval(['bSize = size(a' num2str(jj) ');']);
    end

    aSize(jj) = bSize(1);
    if aSize(jj) > aMaxSize
        aMaxSize = aSize(jj);
    end
    if aSize(jj) < aMinSize
        aMinSize = aSize(jj);
    end
end

gNumPlots            = 0;


h           = findobj('tag','edBefore');                    %record the time before the line-up point
s           = get(h, 'string');
gBefore     = str2double(s);

h           = findobj('tag','edAfter');                     %record the time after the line-up point
s           = get(h, 'string');
gAfter      = str2double(s);

h           = findobj('tag','edBinSize');                   %record the histogram bin size
s           = get(h, 'string');
gBinSize    = str2double(s);

h           = findobj('tag','rasterSize');                  %record the raster point size
s           = get(h, 'string');
gRasterSize = str2double(s);

h           = findobj('tag','fullLabels');                  %record the labels needed
gFullLabel  = get(h, 'value');

h           = findobj('tag','zero');                        %record the labels needed
gZeroLineUp = get(h, 'value');


gPlotShown  = gPlotShown.* 0;                               %reset all elements to zero
gIFR        = gIFR.* 0;
gRaster     = gRaster.* 0;
gHistogram  = gHistogram.* 0;
gPlotOrder  = gPlotOrder.* 0;

for i = 1:gNumChan
    h = findobj('tag', ['puAction'   num2str(i)]  );
    if ishandle(h)
        a = get(h,'Value');                                 %store the selected attribute
        a = a - 1;                                          %reduce by one so zero = hide

        if (a==0) || (a==1)                                 %draw LINE PLOT
            gPlotShown(i) = a;
            if gPlotShown(i) > 0
                gNumPlots = gNumPlots + 1;
                gPlotOrder(i) = gNumPlots;
            end
        end


        %gIFR, gRaster & gHisotgram are checked for zero because we can
        %(should) only plot one unit channel, the first one encountered is
        %used
        if sum(gIFR)==0 && (a==4 || a==6 || a==7 || a==8)              %draw INSTANTEOUS FIRING RATE
            if aSize(i) == aMaxSize
                gIFR(i) = 1;
                gNumPlots = gNumPlots + 1;
            else
                aBadUnit = 1;
            end
        end

        if sum(gRaster)==0 && (a==2 || a==5 || a==6 || a==8)           %draw RASTER (only one allowed, the first one encountered)
            if aSize(i) == aMaxSize
                gRaster(i) = 1;
                gNumPlots = gNumPlots + 1;
            else
                aBadUnit = 1;
            end
        end

        if sum(gHistogram)==0 && (a==3 || a==5 || a==7 || a==8)        %draw HISTOGRAM (only one allowed, the first one encountered)
            if aSize(i) == aMaxSize
                gHistogram(i) = 1;
                gNumPlots = gNumPlots + 1;
            else
                aBadUnit = 1;
            end
        end
    end


    h           = findobj('tag',['avg' num2str(i)]);
    gPlotAvg(i) = get(h,'value');

    h           = findobj('tag',['ind' num2str(i)]);
    gPlotInd(i) = get(h,'value');

    h           = findobj('tag',['auto' num2str(i)]);
    gAutoSize(i)= get(h,'value');

    h           = findobj('tag',['manLo' num2str(i)]);                     %record the time after the line-up point
    s           = get(h, 'string');
    gManLo(i)   = str2double(s);

    h           = findobj('tag',['manHi' num2str(i)]);                     %record the time after the line-up point
    s           = get(h, 'string');
    gManHi(i)   = str2double(s);
end

%process the rate differently since it is configured differently
i = i + 1;
h           = findobj('tag',['auto' num2str(i)]);
gAutoSize(i)= get(h,'value');

h           = findobj('tag',['manLo' num2str(i)]);                     %record the time after the line-up point
s           = get(h, 'string');
gManLo(i)   = str2double(s);

h           = findobj('tag',['manHi' num2str(i)]);                     %record the time after the line-up point
s           = get(h, 'string');
gManHi(i)   = str2double(s);

%process the histogram differently since it is configured differently
i = i + 1;
h           = findobj('tag',['auto' num2str(i)]);
gAutoSize(i)= get(h,'value');

h           = findobj('tag',['manLo' num2str(i)]);                     %record the time after the line-up point
s           = get(h, 'string');
gManLo(i)   = str2double(s);

h           = findobj('tag',['manHi' num2str(i)]);                     %record the time after the line-up point
s           = get(h, 'string');
gManHi(i)   = str2double(s);


close;

if drawItNow == 1
    graph(4);       %call Histogram again so it will draw the new selctions
end
if aBadUnit
    h = msgbox('Only the Instanteous Firing Rate trace can be used to plot unit traces.  The trace you selected has not been plotted.');
    uiwait(h);
end
%end dialogHistoOptionsClose



%--------------------------------------------------------------------------
% fileMerge
% Opens additional *.txt and *.mat files.
% 6/18/03
%--------------------------------------------------------------------------
function fileMerge()

global gDataOriginalAttrib
global gFileName
global gFileIn_attr
global gFileIn_data
global gFilesLoaded
global gFolderName
global gMergedTrialNumberAttr
global gNumAttr
global gNumNonComputedAttr
global gNumChan
global gNumTrials
global gRegularAttributes
global gTotalAttributes

%SAVE  global declaration of a01 a02 a03 a04 a05 a06
for jj = 1:gNumChan
    if jj < 10
        eval(['global a0' num2str(jj)])
    else
        eval(['global a' num2str(jj)])
    end
end


% get the file to display
[filename,foldername] = uigetfile('*.txt','Merge an output file from Spike2 Saccade');
filename = lower(filename);     %to prevent upper/lower case problems
foldername = lower(foldername);

if (length(filename) == 1) || (length(foldername) == 1)
    fprintf(1,'\nError, returning back to Command Window\n');
    return;
end

gFilesLoaded = gFilesLoaded + 1;
gFileName{gFilesLoaded} = filename;
gFolderName{gFilesLoaded} = foldername;

hWait = waitbar(0,'Start');
set(hWait,'name','Progress');

eval(['cd ','''',foldername,'''']);
fid = fopen(filename,'r');

textRow = fgets(fid);                                               %read attribute names
gFileIn_attr(gFilesLoaded,:) = {filename};
strread(textRow, '%s','delimiter','\t');

aAttribNames = strread(textRow, '%s','delimiter','\t');
aAttribNames = aAttribNames';                                           %transpose the strings

%3/13/07 Really should have a test that all the attributes are named the
%same thing.  This will be really important when/if the attribute list is
%different for different types of analysis.

d = size(aAttribNames);                                                 %how many attribute names are there
if gNumNonComputedAttr ~= d(2) + 2     %plus 2 temporary attributes
    warndlg('Merged file has a different number of attributes', 'W A R N I N G');
end;

waitbar(0.25, hWait, 'Loading Attributes');
aFileAttr = [];
done = false;

aNumTrials = gNumTrials;
%read in the rows of attributes
while ~done
    aTrialStr = fgets(fid);
    if ~ischar(aTrialStr)
        done = true;
    else
        aTrialAttr = strread(aTrialStr, '%f',gNumAttr,'delimiter','\t','emptyvalue',NaN);
        aFileAttr = [aFileAttr ; aTrialAttr'];      %include a new row of attributes, transpose first
        gNumTrials = gNumTrials + 1;
    end
end
% 2 temporary attributes
aFileAttr(:,gMergedTrialNumberAttr-1) = gFilesLoaded;                        %Merged File Number
aFileAttr(:,gMergedTrialNumberAttr) = aFileAttr(:,1) + aNumTrials;           %Merged Trial Number
for i = 1:gTotalAttributes-gRegularAttributes
    aFileAttr(:,gMergedTrialNumberAttr+i) = NaN;                             %computed attributes
end

d = size(aFileAttr);
if gNumAttr ~= d(2);
    warndlg('Merged file has a different number of data points', 'W A R N I N G')
end
gDataOriginalAttrib = [gDataOriginalAttrib ; aFileAttr];            %merge into the main array

%read in the trace data
waitbar(0.5, hWait, 'Loading Traces');
a = strrep(filename, '.txt', '.mat');    %get ready to load the trace file that accompanies the attribute file
load (a);                                %load the trace data after every set of user choices
a = {a};
gFileIn_data(gFilesLoaded,:) = a;
waitbar(1, hWait, 'Complete');

e = size(TraceNam);
if gNumChan  ~= e(1)
    warndlg('Merged file has a different number of traces', 'W A R N I N G')
end;


%SAVE: t01 t02 t03 t04 t05 t06 t07 t08
for jj = 1:gNumChan
    if jj < 10
        eval(['a0' num2str(jj) '= [a0' num2str(jj) ', t0' num2str(jj) '];'    ])
    else
        eval(['a' num2str(jj) '= [a' num2str(jj) ', t' num2str(jj) '];'    ])
    end
end

fclose(fid);
close(hWait);
% end fileMerge



%--------------------------------------------------------------------------
% fileOpen
% Data comes to this program in two files.  The *.txt file contatins the
% attributes computed from all saved trials.  The *.mat file contains the
% traces and optionally the unit raster and IFR traces from all the saved
% trials.
% 4/30/03
%--------------------------------------------------------------------------
function fileOpen()

global gAttribNames
global gAttribSelected
global gAttribSelectedNames
global gAttribX
global gAttribXname
global gAttribY
global gAttribYname
global gDataOriginalAttrib
global gDeleteAttribute
global gFileName
global gFileIn_attr
global gFileIn_data
global gFilesLoaded
global gFolderName
global gMergedTrialNumberAttr
global gNumAttr
global gNumNonComputedAttr
global gNumChan
global gNumTrials
global gPrefName
global gRegularAttributes
global gTotalAttributes
global gTraceLabels
global gTraceLength
global gUnitData


gDataOriginalAttrib     = [];       %must clear out attributes from any previously opened file
gFileIn_attr            = [];       %clear the list of files loaded
gFileName               = [];
gFolderName             = [];


% get the name of the file to display
[filename,foldername] = uigetfile('*.txt','Open an output file from Spike2 Saccade');
filename = lower(filename);     %to prevent upper/lower case problems
foldername = lower(foldername);

if (length(filename) == 1) || (length(foldername) == 1)
    fprintf(1,'\nError, returning back to Command Window\n');
    return;
end

fullName    = strcat(foldername,filename);
gPrefName   = strrep(fullName,'.txt','-prefs.mat');
test        = dir(gPrefName);
if isempty(test) == 0
    load(gPrefName, '-mat');   %load it if it exists
end

gFilesLoaded = 1;
gFileName{gFilesLoaded}     = filename;
gFolderName{gFilesLoaded}   = foldername;

addpath(foldername);                                                    %add this folder to the search path
hWait = waitbar(0,'Start');
set(hWait,'name','Progress');

%load the attribute names from the *.txt file
eval(['cd ','''',foldername,'''']);
fid = fopen(filename,'r');

textRow = fgets(fid);                                                   %read attribute names
gFileIn_attr = {filename};
gAttribNames = strread(textRow, '%s','delimiter','\t');
gAttribNames = gAttribNames';                                           %transpose the strings


%add any local attribute names
gAttribNames        = [gAttribNames {'Merged File Number'} {'Merged Trial Number'} ];
d                   = size(gAttribNames);                               %how many attribute names are there
gNumNonComputedAttr = d(2);                                             %need to know where the end of the combined attributes is


%find the attribute with the name that contains the string"Analysis tag"
%3/13/07 We search for the attribute name so Graph is not dependent on it 
%beign associated with a specific attribute number.
gDeleteAttribute = -1;              %this will cause Matlab to report an error if TAG is not found
for i = 1:gNumNonComputedAttr
    aTemp = cell2mat(lower(gAttribNames(i)));
    if findstr('analysis tag', aTemp);
        gDeleteAttribute = i;  %this is the Analysis tag attribute
    end
end
%gDeleteAttribute = -1;

if gDeleteAttribute < 1
    h = errordlg('The Analysis tag attribute was not found.  File being closed.');
    waitfor(h);
else
    %tack on the attribute numbers onto the names
    %can't pre-allocate here? aTempNames = zeros(gNumNonComputedAttr);      %3/8/07 Matlab prefers preallocation
    for i = 1:gNumNonComputedAttr
        aTempNames(i) = strcat(int2str(i), '. ', gAttribNames(i));          %add the attribute number to the attribute name
    end

    %make room for the combined attribute names
    for i = gRegularAttributes+1:gTotalAttributes
        gAttribNames = [gAttribNames {''}];
    end
    d = size(gAttribNames);                                                 %how many attribute names are there
    gNumAttr = d(2);                                                        %get the number of columns

    %load the regular attribute names into the popup menus

    %%ROBI
    %set default attibutes shown
    %gAttribSelected(1) = 123;           % Merged trial number
    %gAttribSelected(2) = 122;           % Merged file number
    %gAttribSelected(3) = 58;            % Target HV R
    %gAttribSelected(4) = 59;            % Target theta
    %gAttribSelected(5) = 20;            % Eye HV theta
    %gAttribSelected(6) = 28;            % Total saccade duration
    %gAttribSelected(7) = 62;            % Polar gain
    %gAttribSelected(8) = 60;            % Hor gain
    %gAttribSelected(9) = 3;             % Hor eye start time
    %gAttribSelected(10)= 5;             % Hor eye end time
    %gAttribSelected(11)= 77;            % Adapt 2nd saccade start time
    %gAttribSelected(12)= 111;           % Error interval
    %gAttribSelected(13)= 95;            % Adapt 2nd saccade HV R
    %gAttribSelected(14)= 96;            % Adapt 2nd saccade theta


    for i = 1:gRegularAttributes
        if gAttribSelected(i) >  gNumAttr                                       %the number of attributes is not fixed, skip attributes that don't exist
            gAttribSelected(i) = i;                                             %assign a valid attribute number
        end

        h = strcmp(gAttribNames(gAttribSelected(i)),'');                        %test if attribute has a blank field
        if h == 1
            gAttribSelected(i) = i;                                             %assign an attribute with a valid name
        end

        gAttribSelectedNames{i} = char(gAttribNames(gAttribSelected(i)));        %install the list in the popup mentu

        h = findobj('Tag',['puAttr' num2str(i)]);                                %get the handle for the attribute popup menu
        set(h,'string', aTempNames);                                             %install the list in the popup mentu
        set(h,'value', gAttribSelected(i));
    end;

    waitbar(0.25, hWait, 'Loading Attributes');
    gNumTrials  = 0;
    aFileAttr   = [];
    done        = false;

    %read in the rows of attributes
    while ~done
        aTrialStr = fgets(fid);
        if ~ischar(aTrialStr)
            done = true;
        else
            aTrialAttr = strread(aTrialStr, '%f',gNumAttr,'delimiter','\t','emptyvalue',NaN);
            aFileAttr = [aFileAttr ; aTrialAttr'];                              %include a new row of attributes, transpose first
            gNumTrials = gNumTrials + 1;
            if mod(gNumTrials,100) == 0
                aStr = strcat('Loading Attributes  (trial=', num2str(gNumTrials), ' )' );
                waitbar(0.25, hWait, aStr);
            end
        end
    end

    %load values for the two local attributes and the computed attributes to the matrix
    gMergedTrialNumberAttr = gNumNonComputedAttr;
    aFileAttr(:,gMergedTrialNumberAttr-1) = gFilesLoaded;             %Merged file number attribute
    aFileAttr(:,gMergedTrialNumberAttr) = aFileAttr(:,1);             %Merged trial number attribute
    for i = 1:gTotalAttributes-gRegularAttributes
        aFileAttr(:,gNumNonComputedAttr+i) = NaN;                     %computed attributes
    end
    %perhaps we don't need aFileAttr - confirm this soon
    gDataOriginalAttrib = [gDataOriginalAttrib ; aFileAttr];          %add new attributes to the main array

    %load the attribute names for the default X & Y axes
    gAttribXname = gAttribNames(gAttribX);
    gAttribYname = gAttribNames(gAttribY);

    %load the trace file that accompanies the attribute file
    waitbar(0.5, hWait, 'Loading Traces');

    a = strrep(filename, '.txt', '.mat');   %a = strrep(filename, '.TXT', '.mat');

    gFileIn_data = {a};
    aResult = exist(char(gFileIn_data), 'file');                      %test to make sure directory exists (3/8/07 Matlab says 2 argument form is faster)

    if aResult == 0
        warndlg('The *.mat file containing the traces was not found.  You will not be able to display a histogram.','F i l e   N o t   F o u n d')
    else
        load (a);                                                    %load the trace data after every set of user choices
        waitbar(1, hWait, 'Complete');
        e           = size(TraceNam);
        gNumChan  = e(1);

        %load trace names from Saccade
        for i = 1:gNumChan
            gTraceLabels{i} = TraceLbl(i,1:10);                            %traces passed from Saccade
        end

        %determine if any traces contain the string "Raster".  If so, it signals
        %that unit data has been sent from Saccade in the *.mat file.  This is a
        gUnitData = 0;
        for i = 1:gNumChan
            result = strfind(char(gTraceLabels(i)),'Raster');
            d = size(result);
            if d(1) > 0
                gUnitData = 1;
            end
        end

        if gUnitData == 1                                               %unit data only
            i = gNumChan + 1;
            gTraceLabels(i) = {'Histogram Hz'};                         %trace created here in Graph
        end

        %SAVE  global declaration of a01 a02 a03 a04 a05 a06
        for jj = 1:gNumChan
            %aStr = num2str(jj);
            if jj < 10
                eval(['global a0' num2str(jj)]);
            else
                eval(['global a' num2str(jj)]);
            end
        end

        %gTraceLength = length(t01(:,1));
        gTraceLength = length(t01);

        %SAVE: t01 t02 t03 t04 t05 t06 t07 t08
        %copy the trace data from the file variables into the program variables,
        %e.g.: a01-->t01
        for jj = 1:gNumChan
            if jj < 10
                eval([   'a0' num2str(jj) '= t0' num2str(jj) ';'   ]);
            else
                eval([   'a' num2str(jj) '= t' num2str(jj) ';'   ]);
            end
        end

        %enable only if a *.mat file was found
        h = findobj('label', 'Histogram');
        set(h,'enable', 'on');
        h = findobj('label', 'HistoOptions');
        set(h,'enable', 'on');

    end

    %enable some menus
    h = findobj('label', 'XY');
    set(h,'enable', 'on');
    h = findobj('label', 'Merge');
    set(h,'enable', 'on');
    h = findobj('label', 'ListAttr');
    set(h,'enable', 'on');
    h = findobj('label', 'WriteAttr');
    set(h,'enable', 'on');
    h = findobj('label', 'PrefLoad');
    set(h,'enable', 'on');
    h = findobj('label', 'PrefSave');
    set(h,'enable', 'on');
end %if gdeleteattribute found

fclose(fid);
close(hWait);
% end fileOpen a data file for display



%--------------------------------------------------------------------------
% prefSave
% 4/19/04
%--------------------------------------------------------------------------
function prefSave(presentDialogBox)

%list of globals below must be the same ones as in prefLoad
global gAfter               %KEEP
global gAttribSelected      %KEEP
global gAttribX             %KEEP
global gAttribY             %KEEP
global gAutoSize            %KEEP
global gBefore              %KEEP
global gBinSize             %KEEP
global gComputedEquations
global gComputedNames
global gFigHandleAttr
global gFigHandleHisto
global gFigHandleXY
global gFigPosAttr
global gFigPosHisto
global gFigPosXY
global gFilterAbs           %KEEP
global gFilterTheta         %KEEP
global gFullLabel           %KEEP
global gExclusiveLower      %KEEP
global gExclusiveUpper      %KEEP
global gHistogram           %KEEP
global gInclusiveLower      %KEEP
global gInclusiveUpper      %KEEP
global gLineUpAttribute     %KEEP
global gManLo               %KEEP
global gManHi               %KEEP
global gNumPlots            %KEEP
global gNumChan             %KEEP
global gPlotAvg             %KEEP
global gPlotInd             %KEEP
global gPlotShown           %KEEP
global gPrefName
global gRaster              %KEEP
global gRasterSize          %KEEP
global gRegularAttributes
global gSortOnAttribute     %KEEP
global gTotalAttributes
global gZeroLineUp          %KEEP

if presentDialogBox == 0
    fullName{1} = gPrefName;
else
    % get the name of a file to store preferences to
    % user has clicked the PREF SAVE button
    [filename,foldername] = uiputfile('*.mat');
    if (length(filename) == 1) || (length(foldername) == 1)
        fprintf(1,'\nError, returning back to Command Window\n');
        return;
    end
    
    filterItemsUpdate();
    
    for i = gRegularAttributes+1:gTotalAttributes
        h = findobj('tag', ['edName'   num2str(i)]);
        gComputedNames(i-gRegularAttributes) = cellstr(get(h, 'string'));
        h = findobj('tag', ['edEquation'   num2str(i)]);
        gComputedEquations(i-gRegularAttributes) = cellstr(get(h, 'string'));
    end;
    fullName{1} = strcat(foldername,filename);
end

if ishandle(gFigHandleAttr) && (gFigHandleAttr > 0)
    gFigPosAttr  = get(gFigHandleAttr,'Position');
end
if ishandle(gFigHandleHisto) && (gFigHandleHisto >  0)
    gFigPosHisto = get(gFigHandleHisto,'Position');
end
if ishandle(gFigHandleXY) && (gFigHandleXY > 0)
    gFigPosXY    = get(gFigHandleXY,'Position');
end

% in ALL cases, save a copy of the preferences to the general desktop
% preference file that will be used when a data file has no preference file
% of its own yet
fullName{2} = 'C:\Documents and Settings\All Users\Desktop\prefs.mat'; %,'Create a file to store preferences in';
for i = 1:2
    save(fullName{i},...
        'gAfter',...
        'gAttribSelected',...
        'gAttribX',...
        'gAttribY',...
        'gAutoSize',...
        'gBefore',...
        'gBinSize',...
        'gComputedEquations',...
        'gComputedNames',...
        'gExclusiveLower',...
        'gExclusiveUpper',...
        'gFilterAbs',...
        'gFilterTheta',...
        'gFullLabel',...
        'gHistogram',...
        'gInclusiveLower',...
        'gInclusiveUpper',...
        'gLineUpAttribute',...
        'gManHi',...
        'gManLo',...
        'gNumPlots',...
        'gNumChan',...
        'gPlotShown',...
        'gRaster',...
        'gRasterSize',...
        'gSortOnAttribute',...
        'gZeroLineUp',...
        'gPlotAvg',...
        'gPlotInd',...
        'gFigPosAttr',...
        'gFigPosHisto',...
        'gFigPosXY'...
        );
end
%end    prefSave



%--------------------------------------------------------------------------
% PREFLOAD
% 4/19/04
%--------------------------------------------------------------------------
function prefLoad()

global gPrefsUpdate

%list of globals below must be the same ones as in prefSave
global gAttribNames
global gAttribSelected
global gAttribSelectedNames
global gAttribX
global gAttribY
global gComputedEquations
global gComputedNames
global gFigHandleAttr
global gFigHandleHisto
global gFigHandleXY
global gFigPosAttr
global gFigPosHisto
global gFigPosXY
global gFilterAbs
global gFilterTheta
global gExclusiveLower
global gExclusiveUpper
global gInclusiveLower
global gInclusiveUpper
global gLineUpAttribute
global gRegularAttributes
global gSortOnAttribute
global gTotalAttributes


%get the filename that contains preferences
[filename,foldername] = uigetfile('*.mat','Open a file to retrieve preferences');
filename = lower(filename);     %to prevent upper/lower case problems
foldername = lower(foldername);

if (length(filename) == 1) || (length(foldername) == 1)
    fprintf(1,'\nError, returning back to Command Window\n');
    return;
end

%load the the preference variables
fullName = strcat(foldername,filename);

load(fullName, '-mat');

if gFigHandleAttr > 0
    set(gFigHandleAttr,'Position',gFigPosAttr);
end
if gFigHandleHisto > 0
    set(gFigHandleHisto,'Position',gFigPosHisto);
end
if gFigHandleXY
    set(gFigHandleXY,'Position',gFigPosXY);
end

%apply the preference variables so they appear in the Attribute dialog box
gPrefsUpdate = 1;                                                           %used when applying the preferences
exclusiveCheckboxes(gAttribX,'cbX');                                        %X-axis
exclusiveCheckboxes(gAttribY,'cbY');                                        %Y-axis
exclusiveCheckboxes(gLineUpAttribute,'cbLine');                             %line-up attr
exclusiveCheckboxes(gSortOnAttribute,'cbSort');                             %sort-on attr

aSize = size(gAttribNames);
for i = 1:gRegularAttributes
    h = findobj('tag', ['puAttr'   num2str(i)]  );
    if gAttribSelected(i)> aSize(2)  %protect against a data file pref file attr list size mismatch
        gAttribSelected(i) = 1; %the minimum
    end
    if ishandle(h)
        set(h, 'value', gAttribSelected(i));                                %regular attr name
    end
    %4/20/06
    gAttribSelectedNames{i} = char(gAttribNames(gAttribSelected(i)));        %install the list in the popup menu
end

for i = gRegularAttributes+1:gTotalAttributes
    h = findobj('tag', ['edName'   num2str(i)]);
    set(h, 'string', char(gComputedNames(i-gRegularAttributes)));         %computed attr name
    h = findobj('tag', ['edEquation'   num2str(i)]);
    set(h, 'string', char(gComputedEquations(i-gRegularAttributes)));     %computed attr equation
end;

for i = 1:gTotalAttributes
    aUpperNameInc   = ['edUpperInclusive' num2str(i)];
    aLowerNameInc   = ['edLowerInclusive' num2str(i)];
    aUpperNameExc   = ['edUpperExclusive' num2str(i)];
    aLowerNameExc   = ['edLowerExclusive' num2str(i)];
    aAbsName        = ['cbAbs' num2str(i)];
    aThetaName      = ['cbTheta' num2str(i)];

    h = findobj('Tag', aThetaName);                                         %THETA
    set(h,'value', gFilterTheta(i));


    h = findobj('Tag', aAbsName);                                           %ABS
    set(h,'value', gFilterAbs(i));


    h = findobj('Tag', aUpperNameInc);                                      %UPPER limit
    if isnan(gInclusiveUpper(i))
        set(h,'string', '');
    else
        set(h,'string', num2str(gInclusiveUpper(i)));
    end


    h = findobj('Tag', aLowerNameInc);                                      %LOWER limit
    if isnan(gInclusiveLower(i))
        set(h,'string', '');
    else
        set(h,'string', num2str(gInclusiveLower(i)));
    end

    h = findobj('Tag', aUpperNameExc);                                      %UPPER limit
    if isnan(gExclusiveUpper(i))
        set(h,'string', '');
    else
        set(h,'string', num2str(gExclusiveUpper(i)));
    end


    h = findobj('Tag', aLowerNameExc);                                      %LOWER limit
    if isnan(gExclusiveLower(i))
        set(h,'string', '');
    else
        set(h,'string', num2str(gExclusiveLower(i)));
    end
end
gPrefsUpdate = 0;                                                           %restore to normal condition
%end  prefLoad



%--------------------------------------------------------------------------
% pointSelectBox
% For deleting points in the XY plot
% 4/29/04
%--------------------------------------------------------------------------
function pointSelectBox()%(whichPlot)

global gAttribX
global gAttribY
global gData
global gDataHighlighted
global gSelectedPts


point1 = get(gca,'CurrentPoint');    % button down detected, get plot's XY coords
finalRect = rbbox;                   % SAVE - return percent figure units in finalRect
point2 = get(gca,'CurrentPoint');    % button up detected, get plot's XY coords
point1 = point1(1,1:2);              % extract x and y
point2 = point2(1,1:2);

xMin = min(point1(1), point2(1));    %identify the mins and maxes
xMax = max(point1(1), point2(1));
yMin = min(point1(2), point2(2));
yMax = max(point1(2), point2(2));

x = getAttribNumber(gAttribX);
y = getAttribNumber(gAttribY);

aResults    = find((gData(:,x) >= xMin) & (gData(:,x) <= xMax) & (gData(:,y) >= yMin) & (gData(:,y) <= yMax));     %find the trials with data points in the lassoed area

if isempty(gDataHighlighted)
    gDataHighlighted = gData(aResults,:);                               %start a list of highlighted points
    gSelectedPts = aResults;
else
    gDataHighlighted = [gDataHighlighted(:,:)   ;   gData(aResults,:)]; %add to the list of highlighted points
    gSelectedPts = [gSelectedPts  ;  aResults];
end


h = plot(...
    gDataHighlighted(:,x),  gDataHighlighted(:,y),...
    'linestyle',    'none',...
    'marker',       '.',...
    'color',        'g');
hold on;
%end    pointSelectBox



%--------------------------------------------------------------------------
% pointDelete
% Tags a trial so it won't be drawn.
% Similar to pointDeleteStdDev()
% 4/30/04
%--------------------------------------------------------------------------
function pointDelete()

global gData
global gDataHighlighted
global gDataOriginalAttrib
global gDeleteAttribute
global gMergedTrialNumberAttr
global gSelectedPts

%2/7/07  possibly merge this subroutine with pointStdDevDelete
% look something like this:  pointDelete(aSelectedPts, aDataHighlighted)
d = size(gSelectedPts);
for j = 1:d(1)                      %N-trials
    %save the deletion tags in the original data
    gDataOriginalAttrib(gData(gSelectedPts(j),gMergedTrialNumberAttr),gDeleteAttribute) = 1;    %tag a trace for deletion (just don't show it)
end

gDataHighlighted = [];              %start with an empty set of points to delete

xyPlot();                          %redraw the XY plot, reset the fitted plot
%end pointDelete



%--------------------------------------------------------------------------
% pointDeleteStdDev
% Tags a trial so it won't be drawn
% Similar to pointDelete()
% 2/7/07
%--------------------------------------------------------------------------
function pointDeleteStdDev()

global gData
global gDataOriginalAttrib
global gDataStdDevOutliers
global gDeleteAttribute
global gMergedTrialNumberAttr


d = size(gDataStdDevOutliers);
for j = 1:d(1)                      %N-trials
    %save the deletion tags in the original data
    gDataOriginalAttrib(gData(gDataStdDevOutliers(j),gMergedTrialNumberAttr),gDeleteAttribute) = 1;    %tag a trace for deletion (just don't show it)
end

gDataStdDevOutliers = [];           %start with an empty set of points to delete

xyPlot();                          %redraw the XY plot, fitted plot OK, just changing the STD DEV threshold level
%end pointDeleteStdDev



%--------------------------------------------------------------------------
% popupGetAttribute
% 4/30/03
%--------------------------------------------------------------------------
function popupGetAttribute(which, kind)

global gAttribNames
global gAttribSelected
global gAttribSelectedNames


h = findobj('tag', [kind   num2str(which)]  );
if ishandle(h)
    a = get(h,'Value');                                     %store the selected attribute
    gAttribSelected(which) = a;
    gAttribSelectedNames(which) = gAttribNames(a);          %install the list in the popup mentu
end
%end popupGetAttribute



%--------------------------------------------------------------------------
% dialogCustomFit
% Instructions for people making a custom curve fit
% 1/23/07
%--------------------------------------------------------------------------
function dialogCustomFit()

h2  = 20;
w1  = 50;                    %widths
w2  = 300;
c1  = 20;                    %upper block of controls
b1  = 60;                    %buttons
b2  = b1 + w1 + 20;



figureHeight = 475;
row = figureHeight;



h = figure(...
    'numbertitle',          'off',...
    'name',                 'Custom Fit Checklist',....
    'menubar',              'none',...
    'color',                [.831 .816 .784],...
    'units',                'pixels',...
    'position',             [100 100 250 figureHeight]);            %x y width height

row = row - 30;
uicontrol(...
    'style',                'text',...
    'string',               '-  I N   C U R V E   F I T T I N G   T O O L',...
    'horizontalalignment',  'left',...
    'position',             [c1 row w2 h2]);
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '     1. Click "Fitting..." button',...
    'position',             [c1 row w2 h2]);
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '     2. Click "New fit" button',...
    'position',             [c1 row w2 h2]);
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '     3. Select desired "Type of fit"',...
    'position',             [c1 row w2 h2]);
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '     4. Click "Apply" button',...
    'position',             [c1 row w2 h2]);
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '     5. Click "Save to workspace" button',...
    'position',             [c1 row w2 h2]);
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '     6. MUST rename variables so they end in 1 (ONE):',...
    'position',             [c1 row w2 h2]);
row = row - 20;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '                "fittedmodel1"',...
    'position',             [c1 row w2 h2]);
row = row - 20;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '                "goodness1"',...
    'position',             [c1 row w2 h2]);
row = row - 20;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '                "output1"',...
    'position',             [c1 row w2 h2]);
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '     6. Click "OK" button to close "Save to Workspace"',...
    'position',             [c1 row w2 h2]);
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '     7. Click "Close" button to close "Fitting"',...
    'position',             [c1 row w2 h2]);
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '     8. Click "Use Fit" or "Cancel" to get back to Graph',...
    'position',             [c1 row w2 h2]);
row = row - 30;
uicontrol(...
    'style',                'text',...
    'horizontalalignment',  'left',...
    'string',               '     9. Close the Curve Fitting session',...
    'position',             [c1 row w2 h2]);
row = row - 60;


uicontrol(...
    'style',                'pushbutton',...
    'string',               'Use Fit',...
    'callback',             'close; fittedmodel0=fittedmodel1; graph(3)',...      %xyPlot(), DON'T reset brand new fitted line, but report line is different...transfer var to model zero
    'position',             [b1 row w1 h2]);
uicontrol(...
    'style',                'pushbutton',...
    'string',               'Cancel',...
    'callback',             'clear; close',...         %use the previously shown fit
    'position',             [b2 row w1 h2]);

%uiwait(h);                          %stay here until user clicks dialog away
%end dialogCustomFit



%--------------------------------------------------------------------------
% customFit
% Enables the user to fit any kind of line to the data in XY mode by
% opening the Curve Fitting Toolbox, if it is present.
% 1/16/07
%--------------------------------------------------------------------------
function customFit()

global gAttribX
global gAttribY
global gData


%2/9/07  It is best to have this message so that people without the
%toolbox can be alerted that a special feature is available to those
%who do have it.  If the special fit button only showed up when the
%toolbox is present, the others would never know about the feature.
if license('test','curve_fitting_toolbox') == false;
    msgbox('This feature only works if you have the Curve Fitting Toolbox installed');
else
    theX = getAttribNumber(gAttribX);
    theY = getAttribNumber(gAttribY);
    cftool(gData(:,theX), gData(:,theY));
    dialogCustomFit();
end
%end customFit



%--------------------------------------------------------------------------
% sequential
% Substitute a series of sequential number for the X value plotted in XY
% mode.
% 2/16/07
%--------------------------------------------------------------------------
function sequential()

global gData
global gAttribX


theX = getAttribNumber(gAttribX);

d = size(gData);
for j = 1:d(1)                      %N-trials
    gData(j,theX) = j-1;            %substitute different numbers for X, start at zero
end
%end sequential



%--------------------------------------------------------------------------
% initializeA
% Initialize some things before entering xyPlot
% 2/176/07
%--------------------------------------------------------------------------
function initializeA()

global gFitType;
global gSequential;
global gSmoothPts;


gFitType    = 1;
gSequential = 0;
gSmoothPts  = 1;

evalin('base','clear fittedmodel0');        %eliminate any previous fits
evalin('base','clear output0');
evalin('base','clear goodness0')

xyPlot();

%end initializeA



%--------------------------------------------------------------------------
% xyPlot
% 4/30/03
%--------------------------------------------------------------------------
function xyPlot()

global gAttribNames
global gAttribSelectedNames
global gAttribX
global gAttribY
global gData
global gDataOriginalAttrib
global gDataStdDevOutliers
global gFigHandleXY
global gFigPosXY
global gFileIn_attr
global gFileIn_data
global gFilesLoaded
global gFitType
global gNumNonComputedAttr
global gRegularAttributes
global gResidualPlot
global gSequential
global gSmoothPts
global gStdDevBarPopItem
global gXYplot



%%%attributeAbsorb();                                 %make sure all the attribute limits, etc. have been loaded
aCRLF = [char(10), char(13)];

h = findobj('name', 'XY');                         %close the old one before opening a new one
if ishandle(h);
    gFigHandleXY        = h;                        %re-use the last XY figure
    figure(gFigHandleXY);                           %re-use the last XY figure

    aXYplot             = gXYplot;
    subplot(aXYplot);
    cla;                                            %clear the old plot

    aResidualPlot       = gResidualPlot;
    subplot(aResidualPlot);
    cla;                                            %clear the old plot

    aStats              = findobj('tag', 'Stats');
    pu                  = findobj('tag', 'stddevbarvalue');
    aStdDevBarPopItem   = get(pu,'Value');
    %ed                  = findobj('tag', 'smoothpoints');
    %gSmoothPts          = str2double(get(ed,'string'));
    pu                  = findobj('tag', 'smoothpoints');
    gSmoothPts          = get(pu,'Value');
    gSmoothPts          = (gSmoothPts*2)-1; %converts the item choice to a useable value
    

    % 2/12/07 - I don't understand why 'Value' gives a history of all
    % the last selections.  The output is a number value until there more
    % one, then the type becomes CELL.  The last one is always in (1).
    % I hope this will be undersood and streamlined.
    if iscell(aStdDevBarPopItem)
        aMat  = cell2mat(aStdDevBarPopItem);
        aValue = aMat(1);
        gStdDevBarPopItem = aValue;
    else
        gStdDevBarPopItem = aStdDevBarPopItem;
    end

else
    % d = size(h);
    % if d(1) == 0

    % We must start with a fresh figure or else the last Attribute dialog box
    % field is not flushed and the previous field value is used.
    % 5/28/03, 6/11/04
    gFigHandleXY = figure(...
        'numbertitle',          'off',...
        'name',                 'XY',....
        'menubar',              'none',...
        'color',                [0.831 0.816 0.784],...
        'paperorientation',     'landscape',...
        'paperunits',           'inches',...
        'paperposition',        [0.25 0.25 10.5 8],...
        'units',                'normalized',...
        'position',             gFigPosXY,...       %[0 0.2 1 .75]); %,...
        'keypressfcn',          'graph(28)');       %'keypressfcn',          'graph(12)');

    aLeft = 0.21;
    aWide = 0.77;
    %+xy plot
    %----------------------------------------------------
    gXYplot = subplot(2,1,1);
    aXYplot = gXYplot;
    aPos    = get(aXYplot, 'Position');                 %get the Matlab-selected plot position
    aPos(1) = aLeft;                                    %move the left edge to the right
    aPos(3) = aWide;                                    %change the width
    set(aXYplot, 'Position', aPos);                     %pass the parameters


    %+residual plot
    %----------------------------------------------------
    gResidualPlot   = subplot(2,1,2);
    aResidualPlot   = gResidualPlot;
    aPos            = get(aResidualPlot, 'Position');    %get the Matlab-selected plot position
    aPos(1)         = aLeft;                             %move the left edge to the right
    aPos(3)         = aWide;                             %change the width
    set(aResidualPlot, 'Position', aPos);                %pass the parameters



    %the menu bar
    %----------------------------------------------------
    savecallback = ['[fn,pn,fi]=uiputfile(' '''*.fig''' ',' '''Save figure as''' ',' '''Untitled.fig''' ');' ...
        'if fi ~= 0 ' 'cd(pn);' 'saveas(gcf,fn);' ...
        'else return; end' ];
    uimenu(...
        'Label',                'SaveFig',...
        'callback',             savecallback);
    uimenu(...
        'Label',                'Attributes',...
        'callback',             'graph(6);');        %'close(gcf); graph(6);');
    uimenu(...
        'Label',                'RestoreAll',...
        'callback',             'graph(17);');
%     uimenu(...
%         'Label',                'ReDraw',...
%         'callback',             'graph(3);');     %xyPlot, leave fitted line as is
    uimenu(...
        'Label',                'Help',...
        'callback',             'graph(23)',...
        'Accelerator',          'H');
    uimenu(...
        'Label',                'Print',...
        'callback',             'printdlg',...
        'Accelerator',          'P');

    uimenu(...
        'Label',                'Quit',...
        'callback',             'clear; close all;');


    %left side items
    %----------------------------------------------------
    uicontrol(...
        'Style',                'text',...
        'HorizontalAlignment',  'left',...
        'string',               'Fitted Line',...
        'Units',                'normalized',...
        'Position',             [0.015 0.960 0.070 0.020]);   % X Y W H
 
     uicontrol(...
        'Style',                'checkbox',...
        'tag',                  'linearfit',...
        'string',               'Linear Fit',...
        'Units',                'normalized',...
        'Position',             [0.020 0.935 0.150 0.020],...   % X Y W H
        'Callback',             'global gFitType; gFitType=1; graph(3)');    %xyPlot()
 
    uicontrol(...
        'Style',                'checkbox',...
        'tag',                  'nonlinearfit',...
        'string',               'Custom Fit',...
        'Units',                'normalized',...
        'Position',             [0.020 0.910 0.150 0.02],...   % X Y W H
        'Callback',             'global gFitType; gFitType=2; graph(3)');    %xyPlot()

     uicontrol(...
         'Style',                'pushbutton',...
         'String',               'Fit Type',...
         'Units',                'normalized',...
         'Position',             [0.090 0.910 0.050 0.020],...   % X Y W H
         'Callback',             'graph(29)');  %customFit()-->dialogCustomFit()

    uicontrol(...
        'Style',                'checkbox',...
        'tag',                  'smoothfit',...
        'string',               'Smoothed Data',...
        'Units',                'normalized',...
        'Position',             [0.020 0.885 0.150 0.020'],...   % X Y W H
        'Callback',             'global gFitType; gFitType=3; graph(3)');    %xyPlot()

%     uicontrol(...
%         'style',                'edit',...
%         'tag',                  'smoothpoints',...
%         'background',           [1  1  1],...
%         'string',               num2str(gSmoothPts),...
%         'horizontalalignment',  'center',...
%         'units',                'normalized',...
%         'position',             [0.110 0.885 0.030  0.020 ]);   % X Y W H

    uicontrol(...
        'Style',                'popupmenu',...
        'String',               '1|3|5|7|9|11|13|15|17|19|21|23|25|27|29|31|33|35|37|39|41|43|45|47|49|51|53|55|57|59|61|63|65|67|69|71|73|75|77|79|81|83|85|87|89|91|93|95|97|99',...
        'Units',                'normalized',...
        'background',           [1  1  1],...
        'Position',             [0.110 0.885 0.030  0.020 ],...
        'tag',                  'smoothpoints',...
        'Callback',             'global gFitType; gFitType=3; graph(3)');    %xyPlot()

    
    uicontrol(...
        'Style',                'text',...
        'HorizontalAlignment',  'left',...
        'string',               'pt sm',...
        'Units',                'normalized',...
        'Position',             [0.150 0.880 0.030 0.020]);   % X Y W H
    
    
      uicontrol(...
        'Style',                'checkbox',...
        'tag',                  'sequential',...
        'string',               'Use Sequential X Values',...
        'Units',                'normalized',...
        'Position',             [0.020 0.840 0.150 0.020],...
        'Callback',             'global gSequential; gSequential=1; graph(3)');    %xyPlot()


%     uicontrol(...
%         'Style',                'pushbutton',...
%         'String',               'Smooth Y Data',...
%         'Units',                'normalized',...
%         'Position',             [0.015 0.960 0.070 0.020],...
%         'Callback',             'graph(3)');  %xyPlot()
%     uicontrol(...
%         'style',                'edit',...
%         'tag',                  'smoothpoints',...
%         'background',           [1  1  1],...
%         'string',               num2str(gSmoothPts),...
%         'horizontalalignment',  'center',...
%         'units',                'normalized',...
%         'position',             [0.087 0.960 0.030  0.020 ]);   % X Y W H
%     uicontrol(...
%         'Style',                'text',...
%         'HorizontalAlignment',  'left',...
%         'string',               'point boxcar (odd)',...
%         'Units',                'normalized',...
%         'Position',             [0.119 0.960 0.070 0.020]);
% 
%     uicontrol(...
%         'Style',                'pushbutton',...
%         'String',               'Use Sequential X Values',...
%         'Units',                'normalized',...
%         'Position',             [0.015 0.93 0.15 0.02],...
%         'Callback',             'global gSequential; gSequential=1; graph(3)');    %xyPlot()
% 
%     uicontrol(...
%         'Style',                'pushbutton',...
%         'String',               'Fit with Curve Fitting Toolbox',...
%         'Units',                'normalized',...
%         'Position',             [0.015 0.90 0.15 0.02],...
%         'Callback',             'graph(29)');%customFit()-->dialogCustomFit()

    uicontrol(...
        'Style',                'pushbutton',...
        'String',               'Delete All Highlighted Pts',...
        'Units',                'normalized',...
        'Position',             [0.015 0.80 0.15 0.02],...
        'Callback',             'graph(30)');%pointDelete()


    %the information line
    aStats = uicontrol(...
        'style',                'text',...
        'tag',                  'Stats',...
        'Units',                'Normalized',...
        'position',             [0.015 0.320 0.150 0.460],...   % x y w h
        'horizontalalignment',  'left',...
        'fontsize',             10,...
        'backgroundcolor',      [0.831  0.816  0.784]);

    uicontrol(...
        'Style',                'text',...
        'HorizontalAlignment',  'left',...
        'string',               'Bars = ',...
        'Units',                'normalized',...
        'Position',             [0.015 0.15 0.030 0.02]);

    h = uicontrol(...
        'Style',                'popupmenu',...
        'String',               ' 1| 2| 3',...
        'Units',                'normalized',...
        'background',           [1  1  1],...
        'Position',             [0.045 0.15 0.025 0.020],...
        'tag',                  'stddevbarvalue',...
        'Callback',             'graph(3)');    %xyPlot()

    set(h, 'value', gStdDevBarPopItem);                       %Std Dev bar level

    uicontrol(...
        'Style',                'text',...
        'HorizontalAlignment',  'left',...
        'string',               'x  Standard Deviation',...
        'Units',                'normalized',...
        'Position',             [0.080 0.15 0.100 0.020]);


    uicontrol(...
        'Style',                'pushbutton',...
        'String',               'Delete Pts Beyond Std Dev',...
        'Units',                'normalized',...
        'Position',             [0.015 0.110 0.150 0.020],...
        'Callback',             'graph(31)');
end     %if ishandle(h)


switch gFitType
    case 1
        useCustomFit = false;
        h = findobj('tag', 'linearfit');
        set(h,'Value',1);
        h = findobj('tag', 'nonlinearfit');
        set(h,'Value',0);
        h = findobj('tag', 'smoothfit');
        set(h,'Value',0);
    case 2
        useCustomFit = true;
        h = findobj('tag', 'linearfit');
        set(h,'Value',0);
        h = findobj('tag', 'nonlinearfit');
        set(h,'Value',1);
        h = findobj('tag', 'smoothfit');
        set(h,'Value',0);
    case 3
        useCustomFit = false;
        h = findobj('tag', 'linearfit');
        set(h,'Value',0);
        h = findobj('tag', 'nonlinearfit');
        set(h,'Value',0);
        h = findobj('tag', 'smoothfit');
        set(h,'Value',1);
end

%get the attribute number
theX        = getAttribNumber(gAttribX);
theY        = getAttribNumber(gAttribY);


%get a fresh copy of the attribute data
gData       = gDataOriginalAttrib;                      %clone the data
processComputedAttributes();

%eliminate the trials with unacceptable X and y VALUES
aResults    = find(~isnan(gData(:,theX)));              %eliminate trials with X=NaNs
gData       = gData(aResults,:);                        %form a new attribute list
aResults    = find(~isnan(gData(:,theY)));              %eliminate trials with Y=NaNs
gData       = gData(aResults,:);                        %form a new attribute list

filterTrials();

d           = size(gData);                                  %determine how many trials are there
trials      = d(1);                                         %get the number of columns


%any trials left after applying the limits and user-deletions?
if trials > 0
    if gSequential == 1
        sequential();
    end
%     if (gSmoothPts > 0)
%         gData(:,theY) = smooth(gData(:,theY), gSmoothPts);
%     end
    %1.25.07 all this is necessary to avoid halting errors when trying to
    %access variables on the Base workspace when they don't exist
    lasterror('reset');                             %clear any errors
    evalin('base','try fittedmodel0; catch; end');  %access the variable
    modelError = lasterror;                         %save the error
    useCustomFit = isempty(modelError.message);


    %fill the information column
    aStr = char(gFileIn_attr(1,:));                  %load the first filename
    if gFilesLoaded > 1
        for k = 2:gFilesLoaded
            aStr = [aStr aCRLF char(32) ' + ' aCRLF char(gFileIn_data(k,:)) ];        %load the other names if ther are any merged files
        end
    end

    %compute the mean & std dev of the X & Y data
    aMeanX = mean(gData(:,theX));
    aMeanY = mean(gData(:,theY));

    aStdX = std(gData(:,theX));
    aStdY = std(gData(:,theY));


    aStr = [aStr...
        aCRLF aCRLF,...
        'N = ' int2str(trials)...
        aCRLF aCRLF,...    %char(10), char(13),...
        'meanX = ' num2str(aMeanX,'%12.3f')...
        aCRLF,...
        'meanY = ' num2str(aMeanY,'%12.3f')...
        aCRLF,...
        'stdX = ' num2str(aStdX,'%12.3f')...
        aCRLF,...
        'stdY = ' num2str(aStdY,'%12.3f')...
        aCRLF aCRLF,...
        ];


    if gFitType==3
        aFittedLineX = gData(:,theX); %to plot the fitted line
        aFittedLineY = smooth(gData(:,theY), gSmoothPts);
        aDataResidualY = gData(:,theY) - aFittedLineY;                    %get the y data y fit residual data points
        aCFlicense = false; %there are no prediction lines with smoothing
        bStr = ['fit:  Smoothed data' aCRLF aCRLF];
    else
        aFittedLineX = linspace(min(gData(:,theX)),max(gData(:,theX)),1000); %to plot the fitted line
        aCFlicense = license('test','curve_fitting_toolbox');
        switch aCFlicense
            case true           %the Curve Fitting Toolbox is installed...use it!
                if (gFitType==2) && useCustomFit
                    a = evalin('base','fittedmodel0');            %custom CFToolbox used
                    b = struct(a);
                    c = struct(b.fittype);
                    aStrFit = c.typename;
                else
                    % linear fit like from the CFToolbox when selecting /polynomial/linearPolynomial/
                    aStrFit = 'Poly1'; %default linear regression
                end

                [myModel,myGoodness] = fit(gData(:,theX), gData(:,theY), aStrFit); %default linear regression

                pv = myModel(gData(:,theX));                            %get the y fit data points
                aDataResidualY = gData(:,theY) - pv;                    %get the y data y fit residual data points
                aFittedLineY = myModel(aFittedLineX);                   %get the y fitted data points

                cStr = formula(myModel);
                bStr = strrep(cStr,'  ','');   %replace all groups of 2-spaces with empty string
                bStr = ['fit: ' bStr aCRLF aCRLF];
                myCoeffValues  = coeffvalues(myModel);
                myCoeffNames   = coeffnames(myModel);

                myConfInt = confint(myModel, 0.95);
                myPredictionInt = predint(myModel, aFittedLineX, 0.95, 'observation', 'off');

                for i = 1:numcoeffs(myModel)
                    bStr = [bStr cell2mat(myCoeffNames(i)) ' = ' num2str(myCoeffValues(i),'%12.3f') ' ('  num2str(myConfInt(1,i),'%12.3f')  ' , '  num2str(myConfInt(2,i),'%12.3f')  ')' aCRLF];
                end
                bStr = [bStr aCRLF];
                bStr = [bStr 'r-square = '      num2str(myGoodness.rsquare,'%12.3f')    aCRLF];
                bStr = [bStr 'adj r-square = '  num2str(myGoodness.adjrsquare,'%12.3f') aCRLF aCRLF];

            case false          %non-CFToolbox linear fit for computers without the Curve-Fitting Toolbox
                pf = polyfit(gData(:,theX), gData(:,theY),1);           %compute a linear fit pf(1)=slope pf(2)=y intercept
                pv = polyval(pf, gData(:,theX));                        %get the y fit data points
                aDataResidualY  = gData(:,theY) - pv;                   %get the y data y fit residual data points
                aFittedLineY    = polyval(pf, aFittedLineX);            %get the y fitted data points

                bStr = ['fit:  p1*x + p2' aCRLF];
                bStr = [bStr 'p1 = ' num2str(pf(1),'%12.3f') aCRLF];
                bStr = [bStr 'p2 = ' num2str(pf(2),'%12.3f') aCRLF aCRLF];
                %include linear regression R value.
                %if useCustomFit == false
                %r = linear relationship between X & Y
                %r(1,1) = r of x vs x
                %r(1,2) = r of x vs y
                %r(2,1) = r of y vs x
                %r(2,2) = r of y vs y
                aR = corrcoef(gData(:,theX), gData(:,theY));    %not adjusted r-square
                aRsq = aR * aR;
                bStr = [bStr 'r-square = ' num2str(aRsq(1,2),'%12.3f') aCRLF aCRLF];
        end
    end     %if smooth

    aStr = [aStr bStr];


    %+xy plot
    %----------------------------------------------------
    subplot(aXYplot);
    cla;
    plot(...
        gData(:,theX),  gData(:,theY),...
        'tag',         'xyplot',...
        'linestyle',    'none',...
        'marker',       '.',...
        'color',        'b');
    hold on;

    plot(...
        aFittedLineX,  aFittedLineY,...
        'linestyle',    '-',...
        'color',        'r');

    %load the Y-label

    %if (aCFlicense == true) && (gSmoothPts == 0)   %2/20/07 Robi say prediction lines are meaningless after a smooth
    if (aCFlicense == true) && gFitType == 2
         plot(...
            aFittedLineX,  myPredictionInt,...
            'linestyle',    '--',...
            'color',        'g');
    end

    if gAttribY <= gRegularAttributes
        h = ylabel(gAttribSelectedNames(gAttribY));                                     %regular attribute
    else
        h = ylabel(gAttribNames(gNumNonComputedAttr+(gAttribY-gRegularAttributes)));    %computed attribute
    end
    set(gca,'ButtonDownFcn',    'graph(24)');
    %----------------------------------------------------
    %-xy plot



    %+residual plot
    %----------------------------------------------------
    subplot(aResidualPlot);
    cla;
    plot(...
        gData(:,theX),  aDataResidualY,...
        'tag',         'residualplot',...
        'linestyle',    'none',...
        'marker',       '.',...
        'color',        'b');
    subplot(aResidualPlot);
    hold on;

    resYstd         = aDataResidualY(:);                        %create a new array with same dimensions as the residual data
    theSDthreshold  = gStdDevBarPopItem * std(aDataResidualY);  %fill it with the std of Y values (1x 2x or 3x)
    resYstd(:)      = theSDthreshold;

    plot(...
        gData(:,theX),  resYstd,...
        'color',        'magenta');

    plot(...
        gData(:,theX),  -(resYstd),...
        'color',        'magenta');

    set(gca,'ButtonDownFcn',    'graph(24)');
    gDataStdDevOutliers = find( (aDataResidualY(:) > theSDthreshold) | (aDataResidualY(:) < -(theSDthreshold)) );  %find the trials with data points beyond the Std Dev threshold

    %----------------------------------------------------
    %-residual plot



    %fill the Y-label
    if gAttribY <= gRegularAttributes
        h = ylabel(strcat(gAttribSelectedNames(gAttribY), ' - (fit residual)'));                                %regular attribute
    else
        h = ylabel(strcat(gAttribNames(gNumNonComputedAttr+(gAttribY-gRegularAttributes)), ' - fit residual')); %computed attribute
    end

    %fill the X-label
    if gSequential == 1
        xlabel('sequential X');    %computed attribute
    else
        if gAttribX <= gRegularAttributes
            h = xlabel(gAttribSelectedNames(gAttribX));                                     %regular attribute
        else
            h = xlabel(gAttribNames(gNumNonComputedAttr+(gAttribX-gRegularAttributes)));    %computed attribute
        end
    end


else
    aStr = ['N = ' int2str(trials)];                            %used when N=0
end      %if trials > 0

set(aStats,'string', aStr)                                      %install the list in the popup mentu

%make some values available to the user in the command window
assignin('base', 'x', gData(:,theX));                           %all the X data values
assignin('base', 'y', gData(:,theY));                           %all the Y data values
assignin('base', 'xyAttr', gData);                              %all filtered attributes
% end XY PLOT



%--------------------------------------------------------------------------
% ZOOM PLOT
% Enlarges a Histogram plot
% 5/14/03
%--------------------------------------------------------------------------
function zoomPlot(whichTrace, whichPlot)

global gAfter
global gAutoSize
global gBefore
global gHistoAccumulator
global gIFRAccumulator
global gManHi
global gManLo
global gNumChan
global gPlotColor
global gPlottedTraces
global gRasterAccumulator
global gRasterSize
global gTraceLabels


aActualTrace = whichTrace;
if aActualTrace > gNumChan
    aActualTrace = aActualTrace - 1;
end

modifier    = get(gcbf, 'SelectionType');
switch modifier
    case 'extend'       %SHIFT modifier
        dialogHistoOptionsOpen();

    case 'normal'       %NO modifier
        %draw a new window
        h = figure( ...
            'numbertitle',          'off',...
            'color',                [0.831  0.816  0.784],...
            'paperorientation',     'landscape',...
            'paperposition',        [0.5 0.5 10 7],...
            'menubar',              'none');
        %create menus
        uimenu(...
            'Label',                'Print',...
            'callback',             'printdlg',...
            'Accelerator',          'P');

        subplot(1,1,1);


        %plot the completed RASTER (a synthesized trace)
        if whichTrace == gNumChan+2
            aStr = 'Rasters';
            set(h, 'name', aStr)
            plot(...
                -gBefore:0.5:gAfter,    gRasterAccumulator(:,:,1),...
                'color',                'r',...
                'marker',               's' ,...
                'markersize',           gRasterSize,...
                'markerfacecolor',      'r',...
                'markeredgecolor',      'r',...
                'linestyle' ,           'none'...
                );

            ylabel('Rasters');                               %name the traces
            xlim([-gBefore-5 gAfter+5]);
            if gAutoSize(aActualTrace) == 1
                ylim('auto');
            else
                ylim('manual');
                ylim([gManLo(aActualTrace) gManHi(aActualTrace)]);
            end;

            %plot the completed HISTOGRAM (a synthesized trace)
        elseif whichTrace == gNumChan+3
            aStr = 'Histogram';
            set(h, 'name', aStr)

            plot(...
                -gBefore:0.5:gAfter,    gHistoAccumulator(1:gBefore*2+gAfter*2+1),...
                'color',                'k');

            ylabel('Histogram');                               %name the traces
            xlim([-gBefore-5 gAfter+5]);
            if gAutoSize(aActualTrace) == 1
                ylim('auto');
            else
                ylim('manual');
                ylim([gManLo(aActualTrace) gManHi(aActualTrace)]);
            end;

            %plot the analog traces and the Instanteous Firing Rate
        else
            %rasterIndex = 0;

            if whichTrace == gNumChan+1        %IFR data
                aStr = 'IFR';
                set(h, 'name', aStr)
                plot(...
                    -gBefore:0.5:gAfter,    gIFRAccumulator(:,:,1),...
                    'color',                'r',...
                    'marker',               's' ,...
                    'markersize',           gRasterSize,...
                    'markerfacecolor',      'r',...
                    'markeredgecolor',      'r',...
                    'linestyle' ,           'none'...
                    );

                ylabel('Instaneous Firing Rate   spikes/sec');                               %name the traces
                xlim([-gBefore-5 gAfter+5]);
                if gAutoSize(aActualTrace) == 1
                    ylim('auto');
                else
                    ylim('manual');
                    ylim([gManLo(aActualTrace) gManHi(aActualTrace)]);
                end;

                %regular traces
            else
                aStr = gTraceLabels{aActualTrace};
                set(h, 'name', aStr)

                plot(...
                    -gBefore:gAfter,...
                    gPlottedTraces(:,:,whichPlot),...
                    'color',...
                    gPlotColor(aActualTrace));

                ylabel(gTraceLabels(aActualTrace));                               %name the traces

                xlim([-gBefore-5 gAfter+5]);
                if gAutoSize(aActualTrace) == 1
                    ylim('auto');
                else
                    ylim('manual');
                    ylim([gManLo(aActualTrace) gManHi(aActualTrace)]);
                end;
            end
            hold on
        end

        xlabel('milliseconds');
        zoom xon

end %GRAPH