function SoftScope(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},'display')  %scope event
    fcn='display';
    fig=findobj('tag','BRLscope');
else
    fcn=varargin{1};
    fig=findobj('tag','BRLscope');
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);

        %========================================
        %==Controls for Scope========
        %========================================
        % ===Create main figure==========================
        fig = figure('Position',centerfig(800,600),...
            'Resize','off',...
            'NumberTitle','off',...
            'Name','SoftScope',...
            'Interruptible','off',...
            'tag','BRLscope',...
            'doublebuffer','on',...
            'HandleVisibility','on',...
            'Color',[.7 .7 .7]);
            
        data.line1color = [.5 1 1];
        data.line2color = [1 1 .5];
        data.scopecolor = [.4 .4 .4]; 
        
        %===Header text===================================
        uicontrol(gcf,'Style','text', ...
            'String','Neurobiology SoftScope',...
            'fontsize',14, ...
            'HorizontalAlignment','Center',...
            'Position',[5,570,250,25],...
            'BackgroundColor',[0.8 .8 0.8]);
        
        uicontrol(gcf,'Style','text', ...
            'String','Version 2.4',...
            'fontsize',12, ...
            'HorizontalAlignment','Center',...
            'Position',[300,570,100,20],...
            'BackgroundColor',[0.8 .8 0.8]); 
        
        % ===The quit button===============================
        uicontrol('Style','pushbutton',...
            'Position',[750 570 45 20],...
            'String','Quit',...
            'Interruptible','off',...
            'BusyAction','cancel',...
            'tag','quitscope',...
            'Callback',[data.myname,' quit']);

        %===Create axes=================================
        data.oax = axes('Units','pixels',...
            'Position',[100 250 600 300],...
            'Box','on',...
            'yticklabel', []);
        
        %=== about menu =================================
        data.aboutMenu = uimenu(gcf,'label','About...',...
            'callback','msgbox(''Based on r2007a MATLAB(R) Copyright 1984-2007 The MathWorks,Inc.'');');
        
        %=== beep checkbox =================================
        x=100; y=200; w=120; h=20;
        data.beepChk = uicontrol('style','checkbox',...
            'position', [x, y, w, h], ...
            'enable','off', ...
            'string','Signal when done');
        
        data.beepFile = uicontrol('Style','pushbutton',...
            'Position',[x+w, y 60 h],...
            'String','Sound File',...
            'Interruptible','off',...
            'Callback',[data.myname,' setBeepFile'], ...
            'BusyAction','cancel'...
            );
        
        %===Save button=================================
        x=730; y=500; w=70; h=20;
        data.initfile='c:\*.nbb';
        uicontrol('style','pushbutton',...
            'position', [x, y, w, h], ...
            'string','Save nbb',...
            'callback',[data.myname,' save']);

        %===Restore button=================================
        x=730; y=475; w=70; h=20;
        data.initfile='c:\*.nbb';
        uicontrol('style','pushbutton',...
            'position', [x, y, w, h], ...
            'string','Restore nbb',...
            'Interruptible','off',...
            'callback',[data.myname,' restore']);

        %===export button=================================
        x=730; y=250; w=60; h=20;
        uicontrol('style','pushbutton',...
            'position', [x, y, w, h], ...
            'string','Export',...
            'callback','ScopeData=get(gcf,''UserData'');');

        %===Xcell export button=================================
        x=730; y=400; w=60; h=20;
        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y w h], ...
            'string','Save XL',...
            'callback', [data.myname,' exportXL']...
            );
        %===Xcell region export button=================================
        x=730; y=375; w=60; h=20;
        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y w h], ...
            'string','XL region',...
            'callback', [data.myname,' exportXLregion']...
            );
        %Added by John Olthoff 4/2006
        
        %=== save as wav ==================================
        x=730; y=330; w=60; h=20;
        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y w h], ...
            'string','Save WAV',...
            'callback', [data.myname,' saveWAV']...
            );
        
        %===capture button=================================
        x=730; y=450; w=60; h=20;
        uicontrol('style','pushbutton',...
            'position', [x, y, w, h], ...
            'string','Capture',...
            'callback',[data.myname,' capture']);

        %==scope trigger mode===============================
        x=710 ; y=155 ; 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',data.line1color, ...
            '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',data.line2color, ...
            '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=700; 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',data.line1color,...
            'tag','vpos1',...
            'Interruptible','off',...
            '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',data.line2color,...
            'tag','vpos2',...
            'Interruptible','off',...
            'CallBack', [data.myname,' setvpos']);

        %Vert 1 controls==================================
        data.vscale=1;
        x=465; y=55; w=70; h=150;
        data.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    
            'Interruptible','off',...
            'Fontsize',8,...
            'callback', [data.myname,' setvscale']...
            );

        uicontrol(...
            'style', 'text',...
            'string','Ch1 fullscale',...
            'Fontsize',8,...
            'backgroundcolor', data.line1color, ...
            'position', [x, y+h, w, 20]...
            );
        
        %Vert 2 controls==================================
        data.vscale2=1;
        data.scaleratio=1;
        x=545; y=55; w=70; h=150;
        data.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
            'Interruptible','off',...
            'callback', [data.myname,' setvscale2']...
            );

        uicontrol(...
            'style', 'text',...
            'string','Ch2 fullscale',...
            'Fontsize',8,...
            'position', [x, y+h, w, 20], ...
            'backgroundcolor', data.line2color ...
            );

        %Horizontal controls======================
        data.hscale=.1;
        x=625; y=55; w=70; h=150;
        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', ...
            'Interruptible','off',...
            'callback', [data.myname,' sethscale']...
            );

        uicontrol(...
            'style', 'text',...
            'string','T fullscale',...
            'position', [x, y+h, w, 20]...
            );

        %==channel on/off=========================
        x=700; y=545; w=15; h=15;
        data.chan1box=uicontrol('style','checkbox',...
            'position', [x, y, w, h], ...
            'string','1',...
            'backgroundcolor',data.line1color,...
            'value',1);
        uicontrol(...
            'style', 'text',...
            'string','1',...
            'backgroundcolor',data.line1color,...
            'position', [x, y+h, w, 15]...
            );

        x=715; y=545; w=15; h=15;
        data.chan2box=uicontrol('style','checkbox',...
            'position', [x, y, w, h], ...
            'string','1',...
            'backgroundcolor',data.line2color,...
            'value',1);
        uicontrol(...
            'style', 'text',...
            'string','2',...
            'backgroundcolor',data.line2color,...
            'position', [x, y+h, w, 15]...
            );
        uicontrol(...
            'style', 'text',...
            'string','On',...
            'position', [x-w/2, y+2*h, w, 15]...
            );

        %==channel AC coupled=========================
        x=700; 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=715; y=235; w=15; h=15;
        data.chan2ACbox=uicontrol('style','checkbox',...
            'position', [x, y, w, h], ...
            'string','1',...
            'value',0);

        %==sample rate===================================
        data.Fsin=10000;
        x=625; y=30; 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=30; 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=430; w=65; h=20;
        data.measureOn=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');
        
        data.snaptopeak=uicontrol(...
            'style', 'checkbox', ...
            'position', [x y-180 w+5 h], ...
            'backgroundcolor','w',...
            'enable','on',...
            'string','SnapPeak');
        
        data.snapwidth=uicontrol(...
            'style', 'edit', ...
            'position', [x y-220 w h], ...
            'backgroundcolor',[1 1 1],...
            'enable','on',...
            'string','3');
        
        uicontrol(...
            'style', 'text', ...
            'position', [x y-200 w h], ...
            'backgroundcolor',[1 1 1],...
            'enable','on',...
            'string','Snap width');
        %=========================================
        %zoom enable button
        x=10; y=530; w=55; h=20;

        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y w h], ...
            'string','Expand T',...
            'callback', [data.myname,' zoomin']...
            );

        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y-22 w h], ...
            'string','Reset T',...
            'callback', [data.myname,' zoomout']...
            );

        data.scroll=uicontrol(...
            'style', 'slider', ...
            'position', [100 250 600 10], ...
            'Value', 0,...
            'BackgroundColor',[1 1 1],...
            'visible','off',...
            'CallBack', [data.myname,' scroll']);

        %=== Audio buttons ======================================
        x=10; y=480; w=55; h=20;
        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y w h], ...
            'backgroundcolor',[1 1 1],...
            'string','Audio Ch1',...
            'backgroundcolor', data.line1color, ...
            'callback', [data.myname,' audio1']...
            );

        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y-21 w h], ...
            'backgroundcolor',[1 1 1],...
            'string','Audio Ch2',...
            'backgroundcolor', data.line2color, ...
            'callback', [data.myname,' audio2']...
            );
        
        %=== Logging controls ======================================
        x=10; y=90; w=55; h=20;
        data.logonbutton=uicontrol(...
            'style', 'pushbutton', ...
            'position', [x+w+55 y-45 w h], ...
            'string','Log Data',...
            'callback', [data.myname,' logon'],...
            'tag','crittime' ...
            );

        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x+2*w+60 y-45 w h], ...
            'string','End Log',...
            'tag','crittime', ...
            'callback', [data.myname,' logoff']...
            );
        
        data.logindicator=uicontrol(...
            'style', 'pushbutton', ...
            'position', [x+4.2*w y-45 w/2 h], ...
            'backgroundcolor','r',...
            'string','off' ...
            );
        
        data.genlog = uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y-45 w+50 h], ...
            'string','Generate Filename',...
            'callback', [data.myname,' logfilegen']...
            );
        
        data.logname=uicontrol(...
            'style', 'edit', ...
            'position', [x+w 22 w+475 h], ...
            'enable','on',...
            'string',[datestr(datevec(now),30),'n01']);
        data.lognamesel=uicontrol(...
            'style', 'pushbutton', ...
            'position', [x 22 w h], ...
            'enable','on',...
            'string','LogFile',...
            'callback', [data.myname,' logfileget']...
            );
        
        data.logpath=uicontrol(...
            'style', 'edit', ...
            'position', [x+w 0 w+475 h], ...
            'enable','on',...
            'fontsize',8,...
            'string',[pwd,'\']);
        data.logpathsel=uicontrol(...
            'style', 'pushbutton', ...
            'position', [x 0 w h], ...
            'enable','on',...
            'string','LogPath',...
            'callback', [data.myname,' logpathget']...
            );
        
        y = 75;
        data.logread = uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y w h], ...
            'enable','on',...
            'string','Read Log',...
            'callback', [data.myname,' readlog']...
            );
        data.logreadend = uicontrol(...
            'style', 'pushbutton', ...
            'position', [x+w+5 y w h], ...
            'enable','on',...
            'string','End Read',...
            'callback', [data.myname,' readlogend']...
            );
        data.readindicator=uicontrol(...
            'style', 'pushbutton', ...
            'position', [x+2*(w+5) y w/2 h], ...
            'backgroundcolor','r',...
            'string','off' ...
            );
        data.readfilename=uicontrol(...
            'style', 'text', ...
            'position', [x+2*(w+5)+w/2 y 220 h], ...
            'string','No read file' ...
            );
        
        x=x+150;  y=y+h;
        data.readpos1 = uicontrol(gcf,'Style','text', ...
            'String','Beginning Time',...
            'Position',[x,y,100,20],...
            'BackgroundColor',[0.8,0.8,0.8]);
        data.readpos2 = uicontrol(gcf,...
            'Style','slider',...
            'Min' ,0,'Max',1, ...
            'Position',[x+100,y,80,20], ...
            'Value', 0,...
            'SliderStep',[1 1], ...
            'BackgroundColor',[.8 .8 .8],...
            'tag','posSlider',...
            'CallBack', [data.myname,' logpos']);
        data.readpos3 = uicontrol(gcf,'Style','edit',...
            'String',num2str(0),...
            'Position',[x+115,y,50,20],...
            'BackgroundColor',[.8 .8 .8],...
            'tag','posEdit',...
            'CallBack', [data.myname,'  logpos']);
        set(data.readpos2,'enable','off')
        set(data.readpos3,'enable','off')
        %========================================================
        %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),'color',data.line1color);
        data.line2 = plot(data.x,data.y(:,2),'color',data.line2color);
        data.initialpt(1,1)=0;
        data.initialpt(1,2)=0;
        data.line1Scale = text(.01,1.0,... % data.vscale-data.vscale/20,...
            '1.000',...
            'units', 'normalized',...
            'backgroundcolor',data.line1color);
        data.line2Scale = text(.1,1.0,...
            '1.000',...
            'units', 'normalized',...
            'backgroundcolor',data.line2color);
        text(-0.02,0.5,'0.0','backgroundcolor','w','units', 'normalized');
        set(data.oax, 'XLim', [0 data.hscale]);
        set(data.oax, 'YLim', [-1 1]*data.vscale);
        set(data.oax, 'color', data.scopecolor); %[.1 .4 .2]
        
        grid on
        
        %==========================================================
        % setup the adaptor
        %find adaptors available
        %daqregister('nidaq');
        [adaptorStrArray, aiParams, CHnames] = daqgate('privateGetAdaptor', 'analoginput');
        [sel,ok] = listdlg('PromptString','Select an analog input source:',...
                'SelectionMode','single',...
                'ListSize', [200 80], ...
                'Name', 'Choose Adaptor', ...
                'ListString',adaptorStrArray);
        if ok %the user actually chose something
            %parse the adaptor info
            adaptorStr = adaptorStrArray{sel};
            index = find(adaptorStr == ' ');
            adaptor = adaptorStr(1:index(1)-1);
            id = adaptorStr(index(1)+1:index(2)-1);
            if ~strcmp(lower(adaptor), 'winsound') 
                Input_type = adaptorStr(index(2)+2:end-1);
            end
        else %no choice made
        	errordlg('You must choose a adaptor')
            close gcf
            return
        end
        %use the adaptor info to build the input object
        data.adaptor = adaptor ; %'nidaq';
        data.id = id ; %'Dev1';
        data.ai = analoginput(data.adaptor, data.id);
        
        if ~strcmp(lower(adaptor), 'winsound')
            set(data.ai,'InputType',Input_type)
            data.chi = addchannel(data.ai, 0:2);
            set(data.ai, 'SampleRate', data.Fsin);
            
            %configure hardware gain
            data.aiinfo = daqhwinfo(data.ai);
            if strcmp(lower(Input_type), 'differential')
                set(data.ai.channel, 'InputRange',data.aiinfo.InputRanges(2,:));
                x=355; y=55; w=100; h=120;
                data.channelGainSel = uicontrol(...
                    'style', 'listbox', ...
                    'position', [x, y, w, h], ...
                    'string',num2str(data.aiinfo.InputRanges,'%4.1f  %4.1f'), ...
                    'value', 1, ...  %initially
                    'tag','crittime', ...
                    'callback', [ data.myname, ' HWgainSel']);

                uicontrol(...
                    'style', 'text', ...
                    'position', [x y+h w 20], ...
                    'backgroundcolor',[1 1 1],...
                    'enable','on',...
                    'string','ADC input range');
            end
        else %winsound
            data.chi = addchannel(data.ai, 1:2);
            data.Fsin = 44100;
            set(data.ai, 'SampleRate', 44100);
            set(Fsinedit,'string',num2str(data.Fsin));
            %set(Fsinedit,'enable','off');
            set(data.trig3, 'enable','off');
        end
        % Configure the analog input rate.
        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);


        %========================================
        %UIcontrol callbacks for the Scope
        %========================================
    case 'quit'
        data=get(gcf,'UserData');
        close(gcf)
        try
            stop(data.ai)
        end
        delete(data.ai);
        clear data
        
    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('tag','quitscope'), 'enable','on');
            set(findobj('tag','crittime'),'enable','on');
            if (strcmp(data.ai.Running,'On'))
                stop(data.ai)
            end
            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('tag','quitscope'), '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','manual');
            %set(data.ai,'samplespertrigger',inf);
            set(data.ai,'triggertype','software');
            set(data.ai,'triggerchannel',data.chi(1));
            set(data.ai,'triggercondition','Rising');
            set(data.ai,'triggerconditionvalue',mean(data.y(:,1))); %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);
            %trigger(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('tag','quitscope'), '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('tag','quitscope'), '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(data)

    case 'display'
        data=get(fig,'UserData');
        %data.ai
        %data.ai.SamplesPerTrigger
        try
            data.y = getdata(data.ai, data.ai.SamplesPerTrigger);
        end
        data.x=linspace(0,data.hscale,length(data.y))';
        %set(fig,'UserData',data);
        drawtrace(data)
%         if strcmp(data.tmode,'Continuous')
%             start(data.ai)
%             trigger(data.ai)
%         end

    case 'capture'
        data=get(fig,'UserData');
        figure
        axes
        hold on

        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 (Ch1)')
        text(data.hscale*.1,data.vscale*.9,datestr(now),...
            'fontname','Helvetica','fontweight','bold')
        text(.0,.05,['Ch1 fullscale=',num2str(get(gca,'ylim'),'%7.3f')], ...
            'units','normalized')
        text(.5,.05,['Ch2 fullscale=',num2str(get(gca,'ylim')*data.scaleratio,'%7.3f')], ...
            'units','normalized')
        grid on
        

    case 'setvpos'
        data=get(fig,'UserData');
        drawtrace(data)

    case 'setvscale'
        data=get(fig,'UserData');
        drawtrace(data)

    case 'setvscale2'
        data=get(fig,'UserData');
        drawtrace(data)

    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);
        if strcmp(get(data.readpos2,'enable'),'on')
            set(data.readpos2, 'sliderstep', [data.hscale data.hscale]/data.totalTime) ; %for log file read frame
        end
        set(fig,'UserData',data);

    case 'setrate'
        data=get(fig,'UserData');
        data.Fsin=str2num(get(gco,'string'));
        if strcmp(lower(data.adaptor), 'winsound')
            %8.000 kHz, 11.025 kHz, 22.050 kHz, and 44.100 kHz
            freqs = [8000, 11025, 22050, 44100];
            [mf,p]=min(abs(data.Fsin-freqs));
            data.Fsin = freqs(p);
            set(gco,'string',num2str(data.Fsin));
        end
        set(data.ai, 'SampleRate', data.Fsin);
        set(data.ai, 'SamplesPerTrigger', fix(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');
        if strcmp(get(data.measureOn,'string'),'Measure')
            set(data.tmeasure,'enable','on');
            set(data.vmeasure,'enable','on');
            set(data.measureOn,'string','MeasureOff')
            data.initialpt(1,1)=0;
            data.initialpt(1,2)=0;

            set(gcf,'WindowButtonUpfcn','')
            set(gcf,'WindowButtonDownFcn',...
                ['fig=findobj(''tag'',''BRLscope'');',...
                'data=get(fig,''UserData'');' ...
                'sw = str2num(get(data.snapwidth,''string''));',...
                'ch = str2num(get(data.measurech,''string''));',...
                'plot(data.initialpt(1,1),data.initialpt(1,2),''x'',''color'',data.scopecolor);', ...
                'data.initialpt=get(gca,''currentpoint'');'...
                'if get(data.snaptopeak,''value'') ;', ...
                '[val,index]=min((data.x-data.initialpt(1,1)).^2);',...
                '[val,indexmax]=max(data.y(index-sw:index+sw,ch));', ...
                'data.initialpt(1,1)=data.x(indexmax+index-sw-1);',...
                'data.initialpt(1,2)=data.y(indexmax+index-sw-1,ch);',...
                'end;',...
                'plot(data.initialpt(1,1),data.initialpt(1,2),''wx'');' ...
                'set(fig,''UserData'',data);' ...
                ]);

            set(gcf,'WindowButtonMotionFcn',...
                [...
                'fig=findobj(''tag'',''BRLscope'');',...
                'data=get(fig,''UserData'');'...
                'sw = str2num(get(data.snapwidth,''string''));',...
                'ch = str2num(get(data.measurech,''string''));',...
                'finalpt=get(gca,''currentpoint'');'...
                'if get(data.snaptopeak,''value'') & finalpt(1,1)>data.x(sw+1) & finalpt(1,1)<data.x(end-sw-1);', ...
                '[val,index]=min((data.x-finalpt(1,1)).^2);',...
                '[val,indexmax]=max(data.y(index-sw:index+sw,ch));', ...
                'finalpt(1,1)=data.x(indexmax+index-sw);',...
                'finalpt(1,2)=data.y(indexmax+index-sw,ch);',...
                'end;',...
                'dt=(finalpt(1,1)-data.initialpt(1,1));'...
                'dv=(finalpt(1,2)-data.initialpt(1,2));'...
                'set(data.tmeasure,''backgroundcolor'',data.line1color);', ...
                'set(data.vmeasure,''backgroundcolor'',data.line1color);', ...
                'set(data.snaptopeak,''backgroundcolor'',data.line1color);', ...
                'if str2num(get(data.measurech,''string''))==2;'...
                'dv=(finalpt(1,2)-data.initialpt(1,2))*data.scaleratio;'...
                'set(data.tmeasure,''backgroundcolor'',data.line2color);', ...
                'set(data.vmeasure,''backgroundcolor'',data.line2color);', ...
                'set(data.snaptopeak,''backgroundcolor'',data.line2color);', ...
                'end;' ...
                'mscl=str2num(get(data.measurescale,''string''));' ...
                'set(data.tmeasure,''string'',num2str(dt,''%9.5f''));'...
                'set(data.vmeasure,''string'',num2str(dv/mscl,''%9.5f''));'...
                ]);
        else %turn it off
            set(data.tmeasure,'enable','off');
            set(data.vmeasure,'enable','off');
            set(data.measureOn,'string','Measure')
            set(gcf,'WindowButtonMotionFcn','')
            set(gcf,'WindowButtonDownFcn','') 
            plot(data.initialpt(1,1),data.initialpt(1,2),'x','color',data.scopecolor);
            set(data.tmeasure,'backgroundcolor',[1 1 1]);
            set(data.vmeasure,'backgroundcolor',[1 1 1]);
            set(data.snaptopeak,'backgroundcolor','w');
        end
        set(fig,'UserData',data);
        
    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(data.scroll,'value',0);
        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',...
            [...
            'fig=findobj(''tag'',''BRLscope'');',...
            'data=get(fig,''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(fig, ''UserData'', data);'...
            ]);

        set(gcf,'WindowButtonUpFcn',...
            [...
            'fig=findobj(''tag'',''BRLscope'');',...
            'data=get(fig,''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(fig, ''UserData'', data);'...
            ]);

    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(fig,'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(fig,'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 'saveWAV'
        data=get(fig,'UserData');
        [fname,pname] = uiputfile('*.wav','Save as WAV file');
        fullname=strcat(pname,fname,'.wav');
        wavwrite(data.y(:,1:2), data.Fsin, 16, fullname);
        data.initfile=strcat(pname,'*.wav');
        set(fig,'UserData',data);
        
    case 'restore'
        data=get(fig,'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(data)

    case 'bogusdraw'
        data=get(fig,'UserData');
        drawtrace(data)

    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
        
    case 'logpathget'
        data=get(gcf,'UserData');
        dirname = uigetdir('','Log file folder');
        if dirname~=0
            set(data.logpath,'string',[dirname,'\'])
        end
        set(fig,'UserData',data);
    
    case 'logfilegen'
        data=get(gcf,'UserData');
        filename = [datestr(datevec(now),30),'n01'];
        set(data.logname,'string',filename)
        set(fig,'UserData',data);
    
    case 'logfileget'
        data=get(gcf,'UserData');
        [filename, dirname,filter] = uiputfile(get(data.logpath,'string'),'Log file');
        if filter~=0
            set(data.logpath,'string',dirname)
            set(data.logname,'string',filename)
        end
        set(fig,'UserData',data);
        
    case 'logon'
        data=get(gcf,'UserData');
        set(data.ai,'logfilename',[get(data.logpath,'string'),get(data.logname,'string')]);
        set(data.ai,'loggingmode','disk&memory');
        set(data.ai,'logtodiskmode','index');
        set(data.logname,'enable','off')
        set(data.lognamesel,'enable','off')
        set(data.logpath,'enable','off')
        set(data.logpathsel,'enable','off')
        set(data.genlog,'enable','off')
        set(data.logindicator,'backgroundcolor','g','string','log')
        set(fig,'UserData',data);
        
    case 'logoff'
        data=get(gcf,'UserData');
        set(data.ai,'loggingmode','memory');
        set(data.logname,'enable','on')
        set(data.lognamesel,'enable','on')
        set(data.logpath,'enable','on')
        set(data.logpathsel,'enable','on')
        set(data.genlog,'enable','on')
        set(data.logindicator,'backgroundcolor','r','string','off')
        set(fig,'UserData',data);
    
    case 'readlog'
        data=get(gcf,'UserData');
        set(findobj('tag','tmodegrp'),'enable','off');
        set(data.Otrigger,'enable','off');
        set(data.readindicator,'backgroundcolor','g','string','read')
        set(data.readpos2,'enable','on')
        set(data.readpos3,'enable','on')
        [data.rfname,data.rfpath] = uigetfile([get(data.logpath,'string'),'*.daq']);
        if data.rfname~=0
            daqinfo = daqread([data.rfpath,data.rfname], 'info');
            [data.y,data.x]=daqread([data.rfpath,data.rfname], 'time', [0 data.hscale]); %read one frame
            %max slider #samples/samplerate-display length
            data.totalTime = daqinfo.ObjInfo.SamplesAcquired/daqinfo.ObjInfo.SampleRate ;
            set(data.readpos2, 'max', (data.totalTime - data.hscale ) );
             set(data.readpos2, 'sliderstep', [data.hscale data.hscale]/data.totalTime) ;
            set(data.readfilename,'string',[data.rfname,':Tmax=',num2str(get(data.readpos2, 'max'))]);
            set(fig,'UserData',data);
            drawtrace(data)     
        end
    
    case 'logpos'
        data=get(gcf,'UserData');
        if strcmp(get(gco,'tag'),'posSlider')
            set(data.readpos3,'string', num2str(get(gco,'value')))
        else
            set(data.readpos2,'value', str2num(get(gco,'string')))
        end     
        timeFrame = get(data.readpos2, 'value') ;
        [data.y,data.x]=daqread([data.rfpath,data.rfname], ...
            'time', [timeFrame,  timeFrame+data.hscale]);  %read one frame
        data.x = data.x - timeFrame ;
        set(fig,'UserData',data);
        drawtrace(data)
        
    case 'readlogend'
        data=get(gcf,'UserData');
        set(findobj('tag','tmodegrp'),'enable','on');
        set(data.Otrigger,'enable','on');
        set(data.readindicator,'backgroundcolor','r','string','off')
        set(data.readfilename,'string','No read file');
        set(data.readpos2,'enable','off')
        set(data.readpos3,'enable','off')
        set(fig,'UserData',data);
        
    case 'HWgainSel'
        data=get(gcf,'UserData');
        g=get(data.channelGainSel,'value');
        set(data.ai.channel, 'InputRange',data.aiinfo.InputRanges(g,:));
    
    case 'setBeepFile'
        data=get(gcf,'UserData');
        [fname,fpath] = uigetfile('*.wav');
        if fname~=0
            [data.beep, data.beepFS] = wavread([fpath,fname]); 
            set(data.beepChk,'enable','on')
            set(fig,'UserData',data);
        end
        
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


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

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

data.vscale=str2num(popupstr(data.vscalebox));
data.vscale2=str2num(popupstr(data.vscalebox2));
data.vpos1=get(data.vpos1slider,'value');
data.vpos2=get(data.vpos2slider,'value');
set(data.oax, 'YLim', [-1 1]*data.vscale);
set(data.line1Scale,'string',num2str(data.vscale,'%6.3f'),'position',[0.01, 1.0]);
set(data.line2Scale,'string',num2str(data.vscale2,'%6.3f'),'position',[0.1, 1.0]);


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

data.scaleratio = data.vscale2/data.vscale;

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;
if (get(data.beepChk,'value'))
    sound(data.beep,data.beepFS);
end
set(fig,'UserData',data);
return

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