 function stimScope(varargin)
%Physiological stimulator and oscilloscope

global fig

% By default make the GUI
%from the command line with no parameters

if (nargin == 0)
    fcn = 'makeGUI';
elseif nargin == 3 & strcmp(varargin{3},'stimaction')  %stim event
    fcn='stimaction';
elseif nargin == 3 & strcmp(varargin{3},'display')  %scope event
    fcn='display';
else
    fcn=varargin{1};
end

%varargin %for debugging

%This is the main decision point of the function.
%The switch statement is executed once-per-fuction call
switch fcn
    
    %This code is executed ONCE when the function enters with
    %no arguments
case 'makeGUI'
    
    delete(daqfind);
    
    %store the name of this executing file
    data.myname = mfilename;
    
    feature('javafigures',0);
    %=============================================
    %==Stimulator controls
    %============================================
    
    data.Fs = 70; %stimulator sample rate
    data.adaptor = 'nidaq'; %can be 'nidaq' or 'winsound'
    
    % ===Create main figure==========================
    fig = figure('Position',centerfig(800,600),...
        'Resize','off',...
        'NumberTitle','off',...
        'Name','Cornell BioNB 491',...
        'Interruptible','off',...
        'doublebuffer','on',...
        'HandleVisibility','on',...
        'Color',[.7 .7 .7]);
    
    %===Header text===================================
    uicontrol(gcf,'Style','text', ...
        'String','Cornell BioNB 491',...
        'fontsize',14, ...
        'HorizontalAlignment','Center',...
        'Position',[5,570,200,25],...
        'BackgroundColor',[0.8 .8 0.8]);
    
    %==frame for stim=================================
    uicontrol('style','frame',...
        'Position',[5 60 795 90],...
        'backgroundcolor',[.7 .7 .7]);
    
    % ===Create axes=================================
    data.sax = axes('Units','pixels',...
        'Position',[10 10 780 50],...
        'Box','on');
    
    % ===The quit button===============================
    uicontrol('Style','pushbutton',...
        'Position',[750 570 45 20],...
        'String','Quit',...
        'Interruptible','off',...
        'BusyAction','cancel',...
        'tag','stim',...
        'Callback',[data.myname,' quit']);
    
    %==Mode Chooser=========================
    x=10 ; y=100 ; w=140 ; h=20 ;
    data.mode='Single';
    data.mode1=uicontrol(gcf,'Style','radiobutton', ...
        'String','Single',...
        'Position',[x,y,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'tag','modegrp',...
        'value',1,...
        'CallBack',[data.myname,' mode'] );
    data.mode2=uicontrol(gcf,'Style','radiobutton', ...
        'String','Continuous',...
        'Position',[x,y-h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'tag','modegrp',...
        'CallBack',[data.myname,' mode'] );
    data.mode3=uicontrol(gcf,'Style','radiobutton', ...
        'String','External',...
        'Position',[x,y-2*h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'tag','modegrp',...
        'enable','off',...
        'CallBack',[data.myname,' mode'] );
    uicontrol(gcf,'style','text',...
        'Position',[x,y+h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8],...
        'string','Mode');
    data.start=uicontrol(gcf,'Style','Pushbutton', ...
        'String','Start',...
        'Position',[x+80,y-20,60,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'enable','off',...
        'CallBack',[data.myname,' start'] );
    data.trigger=uicontrol(gcf,'Style','Pushbutton', ...
        'String','Pulse',...
        'Position',[x+80,y,60,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'enable','on',...
        'CallBack',[data.myname,' trigger'] );
    
    
    %==repeat time slider=========================== 
    x=400 ; y=120 ; w=140 ; h=20 ;
    
    data.repeattime=10;
    data.repeattime1 = uicontrol(gcf,'Style','text', ...
        'String','Repeat interval',...
        'fontsize', 12, ...
        'Position',[x,y,100,20],...
        'BackgroundColor',[0.8,0.8,0.8]);
    data.repeattime3 = uicontrol(gcf,...
        'Style','slider',...
        'Min' ,-1,'Max',1, ...
        'Position',[x+100,y,80,20], ...
        'Value', 0,...
        'SliderStep',[0.0084 0.2], ...
        'BackgroundColor',[0.8,0.8,0.8],...
        'tag','stim',...
        'CallBack', [data.myname,' setrepeattime']);
    data.repeattime2 = uicontrol(gcf,'Style','edit',...
        'String',num2str(data.repeattime),...
        'Position',[x+115,y,50,20],...
        'BackgroundColor',[0.8,0.8,0.8],...
        'tag','stim',...
        'CallBack', [data.myname,' setrepeattime']);
    data.repeattime4=uicontrol(gcf,'Style','text',...
        'String',num2str(1/data.repeattime,'f=%6.3f'),...
        'Position',[x+180,y,50,20],...
        'BackgroundColor',[0.8,0.8,0.8]...
        );
    
    
    %==Waveform Chooser=========================
    x=170 ; y=100 ; w=80 ; h=20 ;
    data.wave='One pulse';
    data.wave1=uicontrol(gcf,'Style','radiobutton', ...
        'String','One pulse',...
        'Position',[x,y,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'tag','wavegrp',...
        'value',1,...
        'CallBack',[data.myname,' wave'] );
    data.wave2=uicontrol(gcf,'Style','radiobutton', ...
        'String','Two pulse',...
        'Position',[x,y-h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'tag','wavegrp',...
        'CallBack',[data.myname,' wave'] );
    data.wave3=uicontrol(gcf,'Style','radiobutton', ...
        'String','Tetanic',...
        'Position',[x,y-2*h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'tag','wavegrp',...
        'enable','on',...
        'CallBack',[data.myname,' wave'] );
    uicontrol(gcf,'style','text',...
        'Position',[x,y+h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8],...
        'string','Waveform');
    
    %==Pulse width slider=================
    x=240 ; y=120 ; w=60 ; h=20 ;
    
    data.width=0.001;
    data.width1 = uicontrol(gcf,'Style','text', ...
        'String','Pulse dur',...
        'Position',[x,y,w,20],...
        'BackgroundColor',[0.8,0.8,0.8]);
    data.width3 = uicontrol(gcf,...
        'Style','slider',...
        'Min' ,-1,'Max',1, ...
        'Position',[x+w,y,80,20], ...
        'Value', 0,...
        'SliderStep',[0.1 0.2], ...
        'BackgroundColor',[1 .6 .6],...
        'tag','stim',...
        'CallBack', [data.myname,' setwidth']);
    data.width2 = uicontrol(gcf,'Style','edit',...
        'String',num2str(data.width),...
        'Position',[x+w+15,y,50,20],...
        'BackgroundColor',[1 .6 .6],...
        'tag','stim',...
        'CallBack', [data.myname,' setwidth']);
    
    %==Tetanic burst duration slider=================
    x=400 ; y=95 ; w=140 ; h=20 ;
    
    data.burst=0.01;
    data.burst1 = uicontrol(gcf,'Style','text', ...
        'String','Tetanic duration',...
        'fontsize', 12, ...
        'Position',[x,y,100,20],...
        'BackgroundColor',[0.8,0.8,0.8]);
    data.burst3 = uicontrol(gcf,...
        'Style','slider',...
        'Min' ,-1,'Max',1, ...
        'Position',[x+100,y,80,20], ...
        'Value', 0,...
        'SliderStep',[0.1 0.2], ...
        'BackgroundColor',[.6 .6 .2],...
        'tag','stim',...
        'CallBack', [data.myname,' setburst']);
    data.burst2 = uicontrol(gcf,'Style','edit',...
        'String',num2str(data.burst),...
        'Position',[x+115,y,50,20],...
        'BackgroundColor',[.9 .9 .4],...
        'tag','stim',...
        'CallBack', [data.myname,' setburst']);
    
    %==Tetanic burst interval slider========
    x=400 ; y=70 ; w=140 ; h=20 ;
    
    data.burstrepeat=0.002;
    data.burstrepeat1 = uicontrol(gcf,'Style','text', ...
        'String','Tetanic interval',...
        'fontsize', 12, ...
        'Position',[x,y,100,20],...
        'BackgroundColor',[0.8,0.8,0.8]);
    data.burstrepeat3 = uicontrol(gcf,...
        'Style','slider',...
        'Min' ,-1,'Max',1, ...
        'Position',[x+100,y,80,20], ...
        'Value', 0,...
        'SliderStep',[0.0105 0.25], ...
        'BackgroundColor',[.8 .6 .2],...
        'tag','stim',...
        'CallBack', [data.myname,' setburstrepeat']);
    data.burstrepeat2 = uicontrol(gcf,'Style','edit',...
        'String',num2str(data.burstrepeat),...
        'Position',[x+115,y,50,20],...
        'BackgroundColor',[1 .8 .4],...
        'tag','stim',...
        'CallBack', [data.myname,' setburstrepeat']);
    data.burstrepeat4=uicontrol(gcf,'Style','text',...
        'String',num2str(1/data.burstrepeat,'f=%5.2f'),...
        'Position',[x+180,y,50,20],...
        'BackgroundColor',[0.8,0.8,0.8]...
        );
    
    %==Delay 1 slider=================
    x=250 ; y=100 ; w=50 ; h=20 ;
    
    data.delay1=0.002;
    data.delay11 = uicontrol(gcf,'Style','text', ...
        'String','Delay 1',...
        'Position',[x,y,w,20],...
        'BackgroundColor',[0.8,0.8,0.8]);
    data.delay13 = uicontrol(gcf,...
        'Style','slider',...
        'Min' ,-1,'Max',1, ...
        'Position',[x+w,y,80,20], ...
        'Value', 0,...
        'SliderStep',[0.1 0.2], ...
        'BackgroundColor',[0.6,1,0.6],...
        'tag','stim',...
        'CallBack', [data.myname,' setdelay1']);
    data.delay12 = uicontrol(gcf,'Style','edit',...
        'String',num2str(data.delay1),...
        'Position',[x+w+15,y,50,20],...
        'BackgroundColor',[0.6,1,0.6],...
        'tag','stim',...
        'CallBack', [data.myname,' setdelay1']);
    
    %==Delay 2 slider=================
    x=250 ; y=80 ; w=50 ; h=20 ;
    
    data.delay2=0.003;
    data.delay21 = uicontrol(gcf,'Style','text', ...
        'String','Delay 2',...
        'Position',[x,y,w,20],...
        'BackgroundColor',[0.8,0.8,0.8]);
    data.delay23 = uicontrol(gcf,...
        'Style','slider',...
        'Min' ,-1,'Max',1, ...
        'Position',[x+w,y,80,20], ...
        'Value', 0,...
        'SliderStep',[0.1 0.2], ...
        'BackgroundColor',[.8 .8 1],...
        'tag','stim',...
        'CallBack', [data.myname,' setdelay2']);
    data.delay22 = uicontrol(gcf,'Style','edit',...
        'String',num2str(data.delay2),...
        'Position',[x+w+15,y,50,20],...
        'BackgroundColor',[.8 .8 1],...
        'tag','stim',...
        'CallBack', [data.myname,' setdelay2']);
    
    %==Delay 3 slider=================
    x=250 ; y=60 ; w=50 ; h=20 ;
    
    data.delay3=0.003;
    data.delay31 = uicontrol(gcf,'Style','text', ...
        'String','Delay 3',...
        'Position',[x,y,w,20],...
        'BackgroundColor',[0.8,0.8,0.8]);
    data.delay33 = uicontrol(gcf,...
        'Style','slider',...
        'Min' ,-1,'Max',1, ...
        'Position',[x+w,y,80,20], ...
        'Value', 0,...
        'SliderStep',[0.1 0.2], ...
        'BackgroundColor',[.3 .7 .7],...
        'tag','stim',...
        'CallBack', [data.myname,' setdelay3']);
    data.delay32 = uicontrol(gcf,'Style','edit',...
        'String',num2str(data.delay3),...
        'Position',[x+w+15,y,50,20],...
        'BackgroundColor',[.5 1 1],...
        'tag','stim',...
        'CallBack', [data.myname,' setdelay3']);
    
    %Now set up the analog output stuff
    % setup for the adaptor   
    data.id = 'Dev1';
    data.ao = analogoutput(data.adaptor, data.id);
    data.cho = addchannel(data.ao, 0:1);
    try
        set(data.ao,'transfermode','Interrupt') ;
    catch
        error('RESTART MATLAB')
    end
    % Configure the analog output rate.
    set(data.ao, 'SampleRate', data.Fs);
    
    %========================================
    %==Controls for Scope========
    %========================================
    
    %===Create axes=================================
    data.oax = axes('Units','pixels',...
        'Position',[100 250 400 300],...
        'Box','on');
    
    %===Save button=================================
    x=120; y=200; w=35; h=20;
    data.initfile='c:\*.nbb';
    uicontrol('style','pushbutton',...
        'position', [x, y, w, h], ...
        'string','Save',...
        'callback',[data.myname,' save']);
    
    %===Restore button=================================
    x=120; y=170; w=60; h=20;
    data.initfile='c:\*.nbb';
    uicontrol('style','pushbutton',...
        'position', [x, y, w, h], ...
        'string','Restore',...
        'callback',[data.myname,' restore']);
    
    %===export button=================================
    x=170; y=200; w=60; h=20;
    uicontrol('style','pushbutton',...
        'position', [x, y, w, h], ...
        'string','Export',...
        'callback','ScopeData=get(gcf,''UserData'');');
    
    %===Xcell export button=================================
    x=200; y=170; w=50; h=20;
    uicontrol(...
        'style', 'pushbutton', ...
        'position', [x y w h], ...
        'string','exportXL',...
        'callback', [data.myname,' exportXL']...
        );
     %===Xcell region export button=================================
    x=265; y=170; w=100; h=20;
    uicontrol(...
        'style', 'pushbutton', ...
        'position', [x y w h], ...
        'string','exportXL region',...
        'callback', [data.myname,' exportXLregion']...
        );
       %Added by John Olthoff 4/2006 
    %===capture button=================================
    x=245; y=200; w=60; h=20;
    uicontrol('style','pushbutton',...
        'position', [x, y, w, h], ...
        'string','Capture',...
        'callback',[data.myname,' capture']);
    
    %==scope trigger mode===============================
    x=710 ; y=500 ; w=80 ; h=20 ;
    data.tmode='Manual';
    data.trigmode1=uicontrol(gcf,'Style','radiobutton', ...
        'String','Manual',...
        'Position',[x,y,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'tag','tmodegrp',...
        'value',1,...
        'CallBack',[data.myname,' tmode'] );
    data.trig2=uicontrol(gcf,'Style','radiobutton', ...
        'String','Continuous',...
        'Position',[x,y-2*h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'tag','tmodegrp',...
        'CallBack',[data.myname,' tmode'] );
    data.trig3=uicontrol(gcf,'Style','radiobutton', ...
        'String','External',...
        'Position',[x,y-3*h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'tag','tmodegrp',...
        'enable','on',...
        'CallBack',[data.myname,' tmode'] );
    data.trig4=uicontrol(gcf,'Style','radiobutton', ...
        'String','Channel 1',...
        'Position',[x,y-4*h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'tag','tmodegrp',...
        'enable','on',...
        'CallBack',[data.myname,' tmode'] );
    data.trig5=uicontrol(gcf,'Style','radiobutton', ...
        'String','Channel 2',...
        'Position',[x,y-5*h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'tag','tmodegrp',...
        'enable','on',...
        'CallBack',[data.myname,' tmode'] );
    
    uicontrol(gcf,'style','text',...
        'Position',[x,y+h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8],...
        'string','Trigger Mode');
    data.Otrigger=uicontrol(gcf,'Style','Pushbutton', ...
        'String','Trigger',...
        'Position',[x,y-h,w,h],...
        'BackgroundColor',[0.8,0.8,0.8], ...
        'enable','on',...
        'CallBack',[data.myname,' Otrigger'] );
    
    %==vert pos sliders=====================================
    data.vpos1=0;
    data.vpos2=0;
    x=500; y=250; w=15; h=300;
    data.vpos1slider = uicontrol(gcf,...
        'Style','slider',...
        'Min' ,-1,'Max',1, ...
        'Position',[x,y,w,h], ...
        'Value', 0,...
        'SliderStep',[0.01 0.1], ...
        'BackgroundColor',[0.8,0.8,0.8],...
        'tag','vpos1',...
        'CallBack', [data.myname,' setvpos']);
    data.vpos2slider = uicontrol(gcf,...
        'Style','slider',...
        'Min' ,-1,'Max',1, ...
        'Position',[x+w,y,w,h], ...
        'Value', 0,...
        'SliderStep',[0.01 0.1], ...
        'BackgroundColor',[0.8,0.8,0.8],...
        'tag','vpos2',...
        'CallBack', [data.myname,' setvpos']);
    
    %Vert 1 controls==================================
    data.vscale=1;
    x=540; y=400; w=70; h=100;
    vscalebox = uicontrol(...
        'style', 'listbox', ...
        'position', [x, y, w, h], ...
        'string','0.001|0.002|0.005|.01|.02|.05|0.1|0.2|0.5|1.0|2.0|5.0|10.0', ...
        'value', 10, ...  %initially 1.0 fullscale
        'callback', [data.myname,' setvscale']...
        );
    
    uicontrol(...
        'style', 'text',...
        'string','Ch1 V fullscale',...
        'position', [x, y+h, w, 20]...
        );
    
    %Vert 1 controls==================================
    data.vscale2=1;
    data.scaleratio=1;
    x=540; y=270; w=70; h=100;
    vscalebox2 = uicontrol(...
        'style', 'listbox', ...
        'position', [x, y, w, h], ...
        'string','0.001|0.002|0.005|.01|.02|.05|0.1|0.2|0.5|1.0|2.0|5.0|10.0', ...
        'value', 10, ...  %initially 1.0 fullscale
        'callback', [data.myname,' setvscale2']...
        );
    
    uicontrol(...
        'style', 'text',...
        'string','Ch2 V fullscale',...
        'position', [x, y+h, w, 20]...
        );
    
    %Horizontal controls======================
    data.hscale=.1;
    x=625; y=400; w=70; h=100;
    hscalebox = uicontrol(...
        'style', 'listbox', ...
        'position', [x, y, w, h], ...
        'string','0.001|0.002|0.005|0.01|0.02|0.05|0.10|0.20|0.50|1.0|2.0|5.0|10.0|20.0|30.0', ...
        'value', 7, ...  %initially 0.10 fullscale time
        'tag','crittime', ...
        'callback', [data.myname,' sethscale']...
        );
    
    uicontrol(...
        'style', 'text',...
        'string','T fullscale',...
        'position', [x, y+h, w, 20]...
        );
    
    %==channel on/off=========================
    x=500; y=545; w=15; h=15;
    data.chan1box=uicontrol('style','checkbox',...
        'position', [x, y, w, h], ...
        'string','1',...
        'value',1);
    uicontrol(...
        'style', 'text',...
        'string','1',...
        'position', [x, y+h, w, 15]...
        );
    
    x=515; y=545; w=15; h=15;
    data.chan2box=uicontrol('style','checkbox',...
        'position', [x, y, w, h], ...
        'string','1',...
        'value',1);
    uicontrol(...
        'style', 'text',...
        'string','2',...
        'position', [x, y+h, w, 15]...
        );
    uicontrol(...
        'style', 'text',...
        'string','On',...
        'position', [x-w/2, y+2*h, w, 15]...
        );
    
    %==channel AC coupled=========================
    x=500; y=235; w=15; h=15;
    data.chan1ACbox=uicontrol('style','checkbox',...
        'position', [x, y, w, h], ...
        'string','1',...
        'value',0);
    uicontrol(...
        'style', 'text',...
        'string','AC',...
        'position', [x+w/2, y-h, w, 15]...
        );
    
    x=515; y=235; w=15; h=15;
    data.chan2ACbox=uicontrol('style','checkbox',...
        'position', [x, y, w, h], ...
        'string','1',...
        'value',0);
    
    %==sample rate===================================
    data.Fsin=3000;
    x=625; y=380; w=70; h=20;
    uicontrol(...
        'style', 'text', ...
        'position', [x, y, w, h], ...
        'string','Sample rate');
    Fsinedit=uicontrol(...
        'style', 'edit', ...
        'position', [x, y-h, w, h], ...
        'string',num2str(data.Fsin,'%6.0f'), ...
        'tag','crittime', ...
        'callback', [data.myname,' setrate']...
        );
    
    %==trigger level===================================
    data.triggerlevel=0;
    x=710; y=380; w=80; h=20;
    uicontrol(...
        'style', 'text', ...
        'position', [x, y, w, h], ...
        'string','Trigger level');
    triggerleveledit=uicontrol(...
        'style', 'edit', ...
        'position', [x, y-h, w, h], ...
        'string',num2str(data.triggerlevel,'%6.3f'), ...
        'tag','crittime', ...
        'callback', [data.myname,' settriggerlevel']...
        );
    
    %=========================================
    %measure enable button
    x=10; y=330; w=55; h=20;
    uicontrol(...
        'style', 'pushbutton', ...
        'position', [x y w h], ...
        'backgroundcolor',[1 1 1],...
        'string','Measure',...
        'callback', [data.myname,' measure']...
        );
    
    uicontrol(...
        'style', 'text', ...
        'position', [x y-20 w h], ...
        'backgroundcolor',[1 1 1],...
        'enable','on',...
        'string','Time diff');
    
    data.tmeasure=uicontrol(...
        'style', 'text', ...
        'position', [x y-40 w h], ...
        'backgroundcolor',[1 1 1],...
        'enable','off',...
        'string','--');
    
    uicontrol(...
        'style', 'text', ...
        'position', [x y-62 w h], ...
        'backgroundcolor',[1 1 1],...
        'enable','on',...
        'string','V diff');
    
    data.vmeasure=uicontrol(...
        'style', 'text', ...
        'position', [x y-82 w h], ...
        'backgroundcolor',[1 1 1],...
        'enable','off',...
        'string','--');
    
    uicontrol(...
        'style', 'text', ...
        'position', [x y-102 w h], ...
        'backgroundcolor',[1 1 1],...
        'enable','on',...
        'string','Ext. Gain');
    
    data.measurescale=uicontrol(...
        'style', 'edit', ...
        'position', [x y-122 w h], ...
        'backgroundcolor',[1 1 1],...
        'enable','on',...
        'string','1');
    
    uicontrol(...
        'style', 'text', ...
        'position', [x y-144 w h], ...
        'backgroundcolor',[1 1 1],...
        'enable','on',...
        'string','Channel');
    
    data.measurech=uicontrol(...
        'style', 'edit', ...
        'position', [x y-160 w h], ...
        'backgroundcolor',[1 1 1],...
        'enable','on',...
        'string','1');
        
    %=========================================
    %zoom enable button
    x=10; y=450; w=55; h=20;
    
    uicontrol(...
        'style', 'pushbutton', ...
        'position', [x y w h], ...
        'backgroundcolor',[1 1 1],...
        'string','Expand T',...
        'callback', [data.myname,' zoomin']...
        );
    
    uicontrol(...
        'style', 'pushbutton', ...
        'position', [x y-22 w h], ...
        'backgroundcolor',[1 1 1],...
        'string','Reset T',...
        'callback', [data.myname,' zoomout']...
        );
    
    data.scroll=uicontrol(...
        'style', 'slider', ...
        'position', [100 250 400 10], ...
        'Value', 0,...
        'BackgroundColor',[1 1 1],...
        'visible','off',...
        'CallBack', [data.myname,' scroll']);
    
     %===Audio  1 button======================================
    x=10; y=400; w=55; h=20;
    uicontrol(...
        'style', 'pushbutton', ...
        'position', [x y w h], ...
        'backgroundcolor',[1 1 1],...
        'string','Audio Ch1',...
        'callback', [data.myname,' audio1']...
        );
     
    uicontrol(...
        'style', 'pushbutton', ...
        'position', [x y-21 w h], ...
        'backgroundcolor',[1 1 1],...
        'string','Audio Ch2',...
        'callback', [data.myname,' audio2']...
        );
    %=========================================
    %make up some data and plot the initial lines
    data.x=(0:1/data.Fsin:data.hscale)';
    data.y(:,1)=zeros(length(data.x),1);
    data.y(:,2)=zeros(length(data.x),1);
    
    set(fig,'currentaxes',data.oax)
    hold on
    data.line1 = plot(data.x,data.y(:,1),'w');
    data.line2 = plot(data.x,data.y(:,2),'y');
    data.initialpt(1,1)=0;
    data.initialpt(1,2)=0;
    set(data.oax, 'XLim', [0 data.hscale]);
    set(data.oax, 'YLim', [-1 1]*data.vscale);
    set(data.oax, 'color', [.1 .4 .2]);
    data.ch2text = text(.5,.97,['Ch2 fullscale=',num2str(data.vscale2,'%7.3f')], ...
          'units','normalized','color',[1,1,0])
    grid on
    
    % setup for the adaptor
    data.id = 'Dev1';
    data.ai = analoginput(data.adaptor, data.id);
    data.chi = addchannel(data.ai, 0:2);
    set(data.ai,'InputType','SingleEnded')
    % Configure the analog input rate.
    set(data.ai, 'SampleRate', data.Fsin);
    set(data.ai, 'SamplesPerTrigger', data.hscale*data.Fsin);
    
    %put all the variables in a safe place (the figure's data area)
    set(fig,'UserData',data);
    
    buildwave; %and make the output waveforms
    
    %========================================
    %UIcontrol callbacks for the Stimulator
    %========================================
case 'start'
    data=get(gcf,'UserData');   
    
    %determine if starting or stopping
    if strcmp(get(gco,'string'),'Start')
        set(gco,'string','Stop')
        set(data.mode1,'enable','off')
        set(findobj('tag','wavegrp'),'enable','off')
        set(findobj('tag','stim'),'enable','off');
        stop(data.ao)
        set(data.ao,'bufferingconfig',[50000,2])
        putdata(data.ao,[data.trigwave data.waveform]);
        set(data.ao,'repeatoutput',inf);
        set(data.ao,'triggertype','manual');
        start(data.ao);
        trigger(data.ao);        
    elseif strcmp(get(gco,'string'),'Stop')
        set(gco,'string','Start')
        set(data.mode1,'enable','on')
        set(findobj('tag','wavegrp'),'enable','on')
        set(findobj('tag','stim'),'enable','on')
        stop(data.ao);
        set(data.ao,'repeatoutput',0)
    end  
    set(gcf,'UserData',data);
    
case 'stimaction'
    %data=get(gcf,'UserData');
    %stop(data.ao)
    %putdata(data.ao,[data.trigwave data.waveform]);
    %start(data.ao);
    %'stim repeat'
    %trigger(data.ao);
    %set(gcf,'UserData',data);
    
case 'quit'
    data=get(gcf,'UserData');
    %quit_reply = questdlg('Quit stimulator?');
    %if strcmp(quit_reply,'Yes')
    close(gcf);
    try
        stop(data.ao)
    end
    try
        stop(data.ai)
    end
    delete(data.ao);
    delete(data.ai);
    clear data
    %end
    
case 'trigger'
    data=get(gcf,'UserData');
    stop(data.ao); 
    set(data.ao,'bufferingconfig',[50000,2])
    set(data.ao,'triggertype','manual');
    putdata(data.ao,[data.trigwave data.waveform]);
    start(data.ao);
    trigger(data.ao);   
         
case 'mode'
    data=get(gcf,'UserData'); 
    objhandle=findobj('tag','modegrp');
    clrindex=find(objhandle ~= gco);
    set(objhandle(clrindex),'value',0);
    set(gco,'value',1);
    data.mode=get(gco,'string');
    if strcmp(data.mode,'Continuous')
        set(data.start,'enable','on')
        set(data.trigger,'enable','off')
        set(data.wave3,'enable','off')
    elseif strcmp(data.mode,'Single')
        set(data.start,'enable','off')
        set(data.start,'string','Start');
        set(data.trigger,'enable','on')
        set(data.wave3,'enable','on')
    end   
    set(gcf,'UserData',data);
    
case 'setrepeattime'   
    data=get(gcf,'UserData');
    
    if strcmp(get(gco,'style'),'slider')
        if get(gco,'value')>0
            data.repeattime=...
                min(10,data.repeattime*2);
        else
            data.repeattime=...
                max(.0001,data.repeattime/2);
        end
        set(gco,'value',0);
        set(data.repeattime2,...
            'string',num2str(data.repeattime));
        set(data.repeattime4,...
            'string',num2str(1/data.repeattime,'f=%6.3f'));
    elseif strcmp(get(gco,'style'),'edit')
        data.repeattime=str2num(get(gco,'string'));
        set(data.repeattime4,...
            'string',num2str(1/data.repeattime,'f=%6.3f'));
    end
    
    set(gcf,'UserData',data);
    buildwave
    
case 'setwidth'
    data=get(gcf,'UserData');
    
    if strcmp(get(gco,'style'),'slider')
        if get(gco,'value')>0
            data.width=...
                min(10,data.width*2);
        else
            data.width=...
                max(.0001,data.width/2);
        end
        set(gco,'value',0);
        set(data.width2,...
            'string',num2str(data.width));
    elseif strcmp(get(gco,'style'),'edit')
        data.width=str2num(get(gco,'string'));
    end
    
    set(gcf,'UserData',data);
    buildwave;
    
case 'setburst'
    data=get(gcf,'UserData');
    
    if strcmp(get(gco,'style'),'slider')
        if get(gco,'value')>0
            data.burst=...
                min(10,data.burst*2);
        else
            data.burst=...
                max(.0001,data.burst/2);
        end
        set(gco,'value',0);
        set(data.burst2,...
            'string',num2str(data.burst));
    elseif strcmp(get(gco,'style'),'edit')
        data.burst=str2num(get(gco,'string'));
    end
    
    set(gcf,'UserData',data);
    buildwave;
    
case 'setburstrepeat'
    data=get(gcf,'UserData');
    
    if strcmp(get(gco,'style'),'slider')
        if get(gco,'value')>0
            data.burstrepeat=...
                min(10,data.burstrepeat*2);
        else
            data.burstrepeat=...
                max(.0001,data.burstrepeat/2);
        end
        set(gco,'value',0);
        set(data.burstrepeat2,...
            'string',num2str(data.burstrepeat));
        set(data.burstrepeat4,...
            'string',num2str(1/data.burstrepeat,'f=%5.2f'));
    elseif strcmp(get(gco,'style'),'edit')
        data.burstrepeat=str2num(get(gco,'string'));
        set(data.burstrepeat4,...
            'string',num2str(1/data.burstrepeat,'f=%5.2f'));
    end
    
    set(gcf,'UserData',data);
    buildwave;
    
    
case 'setdelay1'
    data=get(gcf,'UserData');
    
    if strcmp(get(gco,'style'),'slider')
        if get(gco,'value')>0
            data.delay1=...
                min(10,data.delay1*2);
        else
            data.delay1=...
                max(.0001,data.delay1/2);
        end
        set(gco,'value',0);
        set(data.delay12,...
            'string',num2str(data.delay1));
    elseif strcmp(get(gco,'style'),'edit')
        data.delay1=str2num(get(gco,'string'));
    end
    set(gcf,'UserData',data);
    buildwave
    
case 'setdelay2'
    data=get(gcf,'UserData');
    
    if strcmp(get(gco,'style'),'slider')
        if get(gco,'value')>0
            data.delay2=...
                min(10,data.delay2*2);
        else
            data.delay2=...
                max(.0001,data.delay2/2);
        end
        set(gco,'value',0);
        set(data.delay22,...
            'string',num2str(data.delay2));
    elseif strcmp(get(gco,'style'),'edit')
        data.delay2=str2num(get(gco,'string'));
    end
    set(gcf,'UserData',data);
    buildwave
    
case 'setdelay3'
    data=get(gcf,'UserData');
    
    if strcmp(get(gco,'style'),'slider')
        if get(gco,'value')>0
            data.delay3=...
                min(10,data.delay3*2);
        else
            data.delay3=...
                max(.0001,data.delay3/2);
        end
        set(gco,'value',0);
        set(data.delay32,...
            'string',num2str(data.delay3));
    elseif strcmp(get(gco,'style'),'edit')
        data.delay3=str2num(get(gco,'string'));
    end
    set(gcf,'UserData',data);
    buildwave
    
case 'wave'
    data=get(gcf,'UserData');
    
    objhandle=findobj('tag','wavegrp');
    clrindex=find(objhandle ~= gco);
    set(objhandle(clrindex),'value',0);
    set(gco,'value',1);
    data.wave=get(gco,'string');
    if strcmp(data.wave,'One pulse')
        set(data.mode2,'enable','on')
        
    elseif strcmp(data.wave,'Two pulse')
        set(data.mode2,'enable','on')
        
    elseif strcmp(data.wave,'Tetanic')
        set(data.mode2,'enable','off')
    end
    
    set(gcf,'UserData',data);
    buildwave
    
    %========================================
    %UIcontrol callbacks for the Scope
    %========================================
case 'tmode'
    data=get(fig,'UserData');
    
    objhandle=findobj('tag','tmodegrp');
    clrindex=find(objhandle ~= gco);
    set(objhandle(clrindex),'value',0);
    set(gco,'value',1);
    data.tmode=get(gco,'string');
    
    if strcmp(data.tmode,'Manual')
        set(data.Otrigger,'enable','on')
        set(findobj('string','Quit'), 'enable','on');
        set(findobj('tag','crittime'),'enable','on');
        
        if (strcmp(data.ai.Running,'On'))
            stop(data.ai)
        end
        %delete(data.ai);
        %clear data.ai;
        %data.ai = analoginput(data.adaptor, data.id);
        %data.chi = addchannel(data.ai, 0:2);
        %set(data.ai,'InputType','SingleEnded')
        %set(data.ai, 'SampleRate', data.Fsin);
        %set(data.ai, 'SamplesPerTrigger', data.hscale*data.Fsin);
        set(data.ai, 'timerfcn', '')
        set(data.ai, 'triggerfcn', '');
        set(data.ai, 'TriggerRepeat', 0);
        set(data.ai,'triggertype','immediate');
    else
        set(data.Otrigger,'enable','off')
    end
    
    if strcmp(data.tmode,'Continuous')
        set(findobj('string','Quit'), 'enable','off'); 
        set(findobj('tag','crittime'),'enable','off');
        if (strcmp(data.ai.Running,'On'))
            stop(data.ai)
        end
        flushdata(data.ai);
        %set(data.ai,'ManualTriggerHwOn','Start')
        set(data.ai,'triggertype','software');
        set(data.ai,'triggerchannel',data.chi(1));
        set(data.ai,'triggercondition','Rising');
        set(data.ai,'triggerconditionvalue',0); %setting a zero level is continuous
        set(data.ai, 'TriggerRepeat', inf);
        set(data.ai, 'triggerfcn', {data.myname,'display'});
        %set(data.ai, 'timerfcn', '');
        start(data.ai);
    end
    
    if strcmp(data.tmode,'External')
        set(findobj('string','Quit'), 'enable','off');
        set(findobj('tag','crittime'),'enable','off');
        if (strcmp(data.ai.Running,'On'))
            stop(data.ai)
        end
        flushdata(data.ai);
        set(data.ai,'triggertype','software');
        set(data.ai,'triggerchannel',data.chi(3));
        set(data.ai,'triggercondition','Rising');
        set(data.ai,'triggerconditionvalue',...
            data.triggerlevel);
        set(data.ai, 'TriggerRepeat', inf);
        set(data.ai, 'triggerfcn', {data.myname,'display'});
        %set(data.ai, 'timerfcn', '');
        start(data.ai);
    end
    
    if strcmp(data.tmode,'Channel 1');
        set(findobj('string','Quit'), 'enable','off');
        set(findobj('tag','crittime'),'enable','off');
        if (strcmp(data.ai.Running,'On'))
            stop(data.ai)
        end
        flushdata(data.ai);
        %set(data.ai,'ManualTriggerHwOn','trigger')
        set(data.ai,'triggertype','software');
        set(data.ai,'triggerchannel',data.chi(1));
        set(data.ai,'triggercondition','Rising');
        set(data.ai,'triggerconditionvalue',...
            data.triggerlevel);
        set(data.ai, 'TriggerRepeat', inf);
        set(data.ai, 'triggerfcn', {data.myname,'display'});
        %set(data.ai, 'timerfcn', '');
        start(data.ai);
    end
    
    if strcmp(data.tmode,'Channel 2');
        set(findobj('string','Quit'), 'enable','off');
        set(findobj('tag','crittime'),'enable','off');
        if (strcmp(data.ai.Running,'On'))
            stop(data.ai)
        end
        flushdata(data.ai);
        %set(data.ai,'ManualTriggerHwOn','trigger')
        set(data.ai,'triggertype','software');
        set(data.ai,'triggerchannel',data.chi(2));
        set(data.ai,'triggerconditionvalue',...
            data.triggerlevel);
        set(data.ai, 'TriggerRepeat', inf);
        set(data.ai, 'triggerfcn', {data.myname,'display'});
        %set(data.ai, 'timerfcn', '');
        start(data.ai);
    end
    
    set(fig,'UserData',data);
    
case 'Otrigger'
    data=get(fig,'UserData');
    if (strcmp(data.ai.Running,'On'))
            stop(data.ai)
    end
    flushdata(data.ai);
    start(data.ai);
    data.y = getdata(data.ai, data.ai.SamplesPerTrigger);
    stop(data.ai)
    data.x=linspace(0,data.hscale,length(data.y))';
    set(fig,'UserData',data);
    drawtrace
    
case 'display'
    data=get(fig,'UserData');  
    localflag=1; %pgm can switch modes in loop and then hang
    %while (data.ai.SamplesAcquired < data.ai.SamplesPerTrigger) ...
     %       & localflag==1 ...
     %       & strcmp(data.ai.Running,'On')
     %   if(strcmp(data.tmode,'Manual')) 
      %      localflag=0; 
      %  end ;
      % end
    %if localflag==1 
        %if strcmp(data.tmode,'Continuous') %| ...
             %strcmp(data.tmode,'Channel 1') | ...
             %strcmp(data.tmode,'Channel 2')
         
           % data.y = peekdata(data.ai, data.ai.SamplesPerTrigger); %peek
           %else
           try
                data.y = getdata(data.ai, data.ai.SamplesPerTrigger); 
           end
            %end
        data.x=linspace(0,data.hscale,length(data.y))';  
        set(fig,'UserData',data);
        drawtrace
        %end
        
case 'capture'
    data=get(fig,'UserData');
    figure
    axes
    hold on
    %if get(data.chan1box,'value')==1
     %   data.line1 = plot(data.x, ...
     %       data.y(:,1)+data.vpos1*data.vscale, ...
      %      'k','linewidth',2);
      %end
    
    
    if get(data.chan1box,'value')==1
        if get(data.chan1ACbox,'value')==1
           data.line1 = plot(data.x, ...
                (data.y(:,1)-mean(data.y(:,1)))+data.vpos1*data.vscale, ...
                'k','linewidth',2);
        else
            data.line1 = plot(data.x, ...
                data.y(:,1)+data.vpos1*data.vscale, ...
                'k','linewidth',2);
    end
        set(data.line1,'visible','on')
    else
        set(data.line1,'visible','off')
    end
    
    %if get(data.chan2box,'value')==1
     %   data.line2 = plot(data.x, ...
     %       data.y(:,2)/data.scaleratio+data.vpos2*data.vscale, ...
     %       'k','linewidth',1);
     %end
    
    if get(data.chan2box,'value')==1
        if get(data.chan2ACbox,'value')==1
            data.line2 = plot(data.x, ...
                (data.y(:,2)-mean(data.y(:,2)))/data.scaleratio...
                    +data.vpos2*data.vscale, ...
                'k','linewidth',1 );
        else
            data.line2 = plot(data.x, ...
                data.y(:,2)/data.scaleratio...
                    +data.vpos2*data.vscale, ...
                'k','linewidth',1 );
    end    
        set(data.line2,'visible','on')
    else
        set(data.line2,'visible','off')
    end


    legend('Channel 1', 'Channel 2')
    %set(gca, 'XLim', [0 data.hscale]);
    %set(gca, 'YLim', [-1 1]*data.vscale);
    set(gca,'XLim', get(data.oax,'XLim'));
    set(gca,'YLim', get(data.oax,'YLim'));
    %set(gca, 'color', [.1 .4 .2]);
    xlabel('Seconds')
    ylabel('Volts')
    text(data.hscale*.1,data.vscale*.9,datestr(now),...
        'fontname','Helvetica','fontweight','bold')
    text(.65,.85,['Ch2 fullscale=',num2str(get(gca,'ylim')*data.scaleratio,'%7.3f')], ...
    'units','normalized')
    grid on
    %drawtrace
    
case 'setvpos'
    data=get(fig,'UserData');
    if strcmp(get(gco,'tag'),'vpos1')
        data.vpos1=get(gco,'value');
    else
        data.vpos2=get(gco,'value');
    end
    set(fig,'UserData',data);
    drawtrace
    
case 'setvscale'
    data=get(fig,'UserData');
    data.vscale=str2num(popupstr(gco));
    set(data.oax, 'YLim', [-1 1]*data.vscale);
    set(fig,'UserData',data);
    drawtrace
    
case 'setvscale2'
    data=get(fig,'UserData');
    data.vscale2=str2num(popupstr(gco));
    %set(data.oax, 'YLim', [-1 1]*data.vscale);
    set(fig,'UserData',data);
    drawtrace
    
case 'sethscale'
    data=get(fig,'UserData');
    data.hscale=str2num(popupstr(gco));
    set(data.oax, 'xLim', [0 data.hscale]);
    set(data.ai, 'SamplesPerTrigger', data.hscale*data.Fsin);
    set(fig,'UserData',data);
    
case 'setrate'
    data=get(fig,'UserData');
    data.Fsin=str2num(get(gco,'string'));
    set(data.ai, 'SampleRate', data.Fsin);
    set(data.ai, 'SamplesPerTrigger', data.hscale*data.Fsin);
    set(fig,'UserData',data);
    
case 'settriggerlevel'
    data=get(fig,'UserData');
    data.triggerlevel=str2num(get(gco,'string'));
    set(fig,'UserData',data);
    
case 'measure'
    data=get(fig,'UserData');
    set(data.tmeasure,'enable','on');
    set(data.vmeasure,'enable','on');
    data.initialpt(1,1)=0;
    data.initialpt(1,2)=0;
    set(fig,'UserData',data);
    
    set(gcf,'WindowButtonUpfcn','')
        
    set(gcf,'WindowButtonDownFcn',...
        [ 'data=get(gcf,''UserData'');' ...
            'plot(data.initialpt(1,1),data.initialpt(1,2),''x'',''color'',[.1 .4 .2]);' ...
            'data.initialpt=get(gca,''currentpoint'');'...
            'plot(data.initialpt(1,1),data.initialpt(1,2),''wx'');' ...
            'set(gcf,''UserData'',data);' ...
        ]);
    
    set(gcf,'WindowButtonMotionFcn',...
        [...
            'data=get(gcf,''UserData'');'...
            'finalpt=get(gca,''currentpoint'');'...
            'dt=(finalpt(1,1)-data.initialpt(1,1));'...
            'dv=(finalpt(1,2)-data.initialpt(1,2));'...
            'if str2num(get(data.measurech,''string''))==2;'...
                'dv=(finalpt(1,2)-data.initialpt(1,2))*data.scaleratio;'...
            'end;' ...
            'mscl=str2num(get(data.measurescale,''string''));' ...
            'set(data.tmeasure,''string'',num2str(dt,''%9.5f''));'...
            'set(data.vmeasure,''string'',num2str(dv/mscl,''%9.5f''));'...
        ]);
    
case 'zoomin'
    data=get(fig,'UserData');
    set(data.tmeasure,'enable','off');
    set(data.vmeasure,'enable','off');
    set(data.scroll,'visible','on');
    set(data.scroll,'min',0,'max',data.hscale);  
    set(fig,'currentaxes',data.oax)
    hold on
    plot(data.initialpt(1,1),data.initialpt(1,2),'x','color',[.1 .4 .2]);
    set(fig,'UserData',data);
    
    set(gcf,'WindowButtonMotionFcn','')
    
    set(gcf,'WindowButtonDownFcn',...
        [...
            'data=get(gcf,''UserData'');'...
            'initialpt=get(gca,''currentpoint'');'...
            'rect=rbbox;' ...
            ' if (gca == data.oax & strcmp(get(gcf,''selectiontype''),''alt''))' ...
            '    t=get(data.oax,''xlim'');' ...
            '    set(data.oax, ''xlim'', [t(1)-(t2-t1)*1, t(2)+(t2-t1)*1]);' ...
            '    set(data.scroll,''value'', t(1)/2);'...
            'end;' ...
            'set(gcf, ''UserData'', data);'...
        ]);
    
    set(gcf,'WindowButtonUpFcn',...
        [...
            'data=get(gcf,''UserData'');'...
            'if (gca == data.oax & strcmp(get(gcf,''selectiontype''),''normal''))' ...
            '    finalpt=get(gca,''currentpoint'');'...
            '    t1=initialpt(1,1);'...
            '    t2=finalpt(1,1);'...
            '    if(t2<t1) temp=t2; t2=t1; t1=temp; end;'...
            '    data.t1 = t1; data.t2 = t2;'...
            '    set(data.oax, ''xLim'', [t1, t2]);' ...
            '    set(data.scroll,''value'', t1);' ...
            'end ; ' ...
            'set(gcf, ''UserData'', data);'...
        ]);
    %set(gcf,'WindowButtonDownFcn',...
    %    ['initialpt=get(gca,''currentpoint'');'...
     %       'rect=rbbox;' ...
     %    ]);
    
    %set(gcf,'WindowButtonUpFcn',...
    %   [...
     %       'data=get(gcf,''UserData'');'...
     %       'finalpt=get(gca,''currentpoint'');'...
     %       't1=initialpt(1,1);'...
     %       't2=finalpt(1,1);'...
      %      'if(t2<t1) temp=t2; t2=t1; t1=temp; end;'...
      %      'set(data.oax, ''xLim'', [t1, t2]);'...
      %      'set(data.scroll,''value'', t1);'...
      %  ]);
    
case 'zoomout'
    data=get(fig,'UserData');
    set(data.oax, 'xLim', [0 data.hscale]);
    set(data.scroll,'visible','off');
    set(fig,'UserData',data);
    
case 'scroll'
    data=get(gcf,'UserData');
    t=get(data.oax, 'xLim');
    tbase=get(data.scroll,'value');
    set(data.oax, 'xLim', [tbase, tbase+(t(2)-t(1))]);
    set(fig,'UserData',data);
    
case 'save'
    data=get(gcf,'UserData');
    [fname,pname] = uiputfile(data.initfile,'Save data');
    fullname=strcat(pname,fname,'.nbb');
    save(fullname, 'data')
    data.initfile=strcat(pname,'*.nbb');
    set(fig,'UserData',data);
    
case 'restore'
    data=get(gcf,'UserData');
    [fname,pname] = uigetfile(data.initfile,'Restore data');
    fullname=strcat(pname,fname);
    bogus = load(fullname, '-mat');
    data.initfile=strcat(pname,'*.nbb');
    data.x = bogus.data.x;
    data.y = bogus.data.y;
    set(fig,'UserData',data);
    drawtrace
    
case 'bogusdraw'
    drawtrace
    
case 'audio1'
    data=get(gcf,'UserData');
    sound(data.y(:,1)/max(data.y(:,1)),data.Fsin);
    
case 'audio2'
    data=get(gcf,'UserData');
    sound(data.y(:,2)/max(data.y(:,2)),data.Fsin);
    
case 'exportXL'
	data=get(gcf,'UserData');
	[fname,pname] = uiputfile('c:\my documents\*','Save Spreadsheet');
    filename = [pname,fname];
    m = [data.x, data.y(:,1), data.y(:,2)];
    wk1write(filename,m);   
	%set(fighist,'UserData',data);
    
case 'exportXLregion'
	data=get(gcf,'UserData');
	[fname,pname] = uiputfile('c:\my documents\*','Save Spreadsheet');
    filename = [pname,fname];
    beginindex = find(abs((data.x - data.t1))<.00005) + 1;
    endindex = find(abs((data.x - data.t2))<.00005) + 1;
    m = [data.x(beginindex:endindex), data.y(beginindex:endindex,1), data.y(beginindex:endindex,2)];
    wk1write(filename,m);   
	%set(fighist,'UserData',data);
    %the above lets one export the region they're zoomed up on.
    %Added by John Olthoff 4/2006 
end %of main case statement

%===========================================
%===various subroutines=====================
%============================================================
%===A utility to center the window on the screen============
%===========================================================
function pos = centerfig(width,height)
% Find the screen size in pixels
screen_s = get(0,'ScreenSize');
pos = [screen_s(3)/2 - width/2, screen_s(4)/2 - height/2, width, height];
return

%============================================================
%===Build the stimulator output waveforms
%============================================================
function buildwave
data=get(gcf,'UserData');

set(gcf,'pointer','watch');

Fs=data.Fs; %sample rate

%convert all the times to sample numbers
dur=fix(data.width*Fs);
tet=fix(data.burst*Fs);
tetrep=fix(data.burstrepeat*Fs);
d1=fix(data.delay1*Fs);
d2=fix(data.delay2*Fs);
d3=fix(data.delay3*Fs);
rpt=fix(data.repeattime*Fs);
wave=data.wave;

numpulse=1+(tet-dur)/tetrep; %tetanic burst pulse number

%now just enumerate all the pulses
if strcmp(wave,'One pulse')
    waveform=zeros(d1+1,1);  
    waveform=[waveform; ones(dur,1)];   
elseif strcmp(wave,'Two pulse')
    waveform=zeros(d1+1,1);  
    waveform=[waveform; ones(dur,1)];
    waveform=[waveform; zeros(d2-dur,1)];
    waveform=[waveform; ones(dur,1)];  
elseif strcmp(wave,'Tetanic')
    waveform=zeros(d1+1,1);  
    waveform=[waveform; ones(dur,1)];
    waveform=[waveform; zeros(d2-dur,1)];
    for i=1:numpulse-1
        waveform=[waveform; ones(dur,1)];
        waveform=[waveform; zeros(tetrep-dur,1)];
    end
    waveform=[waveform; ones(dur,1)]; %last tetanic pulse
    endburst=length(waveform); %need this for drawing
    waveform=[waveform; zeros(d3-dur,1)];
    waveform=[waveform; ones(dur,1); ];
end

wavelength=length(waveform);

%now pad for repetition rate
waveform=[waveform; zeros(rpt-length(waveform),1)]; 

%and copy into global data structure
data.waveform=5*waveform;

%trigger waveform must be same length
data.trigwave=[0; 1; zeros(length(waveform)-2,1)];

set(gcf,'UserData',data);

%build the actual plot
%depending on whether the plot has been padded
x=linspace(0,length(waveform)/Fs,length(waveform));
set(gcf,'CurrentAxes',data.sax);
if  rpt/Fs<11.0
    plot(x(1:wavelength+1),[waveform(1:wavelength);0],...
        'k','linewidth',2); 
else
    plot(x,waveform,'k','linewidth',2); 
end


text(0,.2,'Stimulator waveform','color','white');
curlim=get(gca,'xlim');
text(curlim(2)*.9,.2,...
    num2str(curlim(2),'time=%5.3f'),...
    'color','white');
set(gca,'ylim',[0 1.3], 'tickdir','in');
set(gca,'yticklabel',[],'color',[.6 .6 .6])
set(gca,'xticklabel',[]);

%lines to show various parameters
line([0 d1/Fs], [.5 .5], ...
    'color', [.6 1 .6],'linewidth',4)

line([d1/Fs (d1+dur)/Fs], [.8 .8], ...
    'color', [1 .6 .6],'linewidth',4)

if strcmp(wave,'Two pulse') | strcmp(wave,'Tetanic')
    line([d1/Fs d1/Fs+d2/Fs], [.5 .5], ...
        'color', [.8 .8 1],'linewidth',4)
end

if  strcmp(wave,'Tetanic')
    line([(endburst-dur)/Fs (endburst-dur)/Fs+d3/Fs], [.5 .5], ...
        'color', [.5 1 1],'linewidth',4)
    line([(d1+d2)/Fs (endburst)/Fs], [1.1 1.1], ...
        'color', [.9 .9 .4],'linewidth',4)
    line([(d1+d2)/Fs (d1+d2+tetrep)/Fs], [.8 .8], ...
        'color', [1 .8 .4],'linewidth',4)
end

%compute the violation function
if (dur>=d2 & strcmp(wave,'Two pulse')) ...
        | (dur>=d2 & strcmp(wave,'Tetanic')) ...
        | (dur>=d3 & strcmp(wave,'Tetanic')) ...
        | rpt<=wavelength ...
        | (dur>=tetrep & strcmp(wave,'Tetanic'))
    curlim=get(gca,'xlim');
    text(curlim(2)/3,.5,...
        'Violation','color','red','fontsize',30)
end

set(gcf,'pointer','arrow');

return

%============================================================
%==draw the traces================================
%============================================================

function drawtrace
global fig

data=get(fig,'UserData');
% Update the plot.
if strcmp(get(gcf,'name'),'Cornell BioNB 491')
    set(gcf,'currentaxes',data.oax)
end

if get(data.chan1box,'value')==1
    if get(data.chan1ACbox,'value')==1
        set(data.line1, ...
            'YData', (data.y(:,1)-mean(data.y(:,1)))+data.vpos1*data.vscale, ...
            'XData', data.x);
    else
        set(data.line1, ...
            'YData', data.y(:,1)+data.vpos1*data.vscale, ...
            'XData', data.x);
    end
    set(data.line1,'visible','on')
else
    set(data.line1,'visible','off')
end

x=get(data.oax, 'xlim');
y=get(data.oax, 'ylim');
w=x(2)/2.1;
h=y(2)*.1;
drawnow
data.scaleratio = data.vscale2/data.vscale;
%text(.5,.97,['Ch2 fullscale=',num2str(get(gca,'ylim')*data.scaleratio,'%7.3f')], ...
  %  'units','normalized','color',[1,1,0])
set(data.ch2text,'string',...
    ['Ch2 fullscale=',num2str(data.vscale2,'%7.3f')])
if get(data.chan2box,'value')==1
    if get(data.chan2ACbox,'value')==1
        set(data.line2, ...
            'YData', (data.y(:,2)-mean(data.y(:,2)))/data.scaleratio...
                +data.vpos2*data.vscale, ...
            'XData', data.x);
    else
        set(data.line2,...
            'YData', data.y(:,2)/data.scaleratio...
                +data.vpos2*data.vscale, ...
            'XData', data.x);
    end    
    set(data.line2,'visible','on')
else
    set(data.line2,'visible','off')
end

drawnow;
set(fig,'UserData',data);
return

%=================================

