function freqhisto(varargin)
%Frequency histogram generator

global fighist

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

if (nargin == 0)
    fcn = 'makeGUI';
else
    fcn=varargin{1};
end

%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'

        %store the name of this executing file
        data.myname = mfilename;

        % ===Create main figure==========================
        fighist = figure('Position',centerfig(800,600),...
            'Resize','off',...
            'NumberTitle','off',...
            'Name','Cornell BioNB 491: Frequency Histogram',...
            'Interruptible','off',...
            'doublebuffer','on',...
            'HandleVisibility','on',...
            'toolbar','figure',...
            'Color',[.7 .7 .7]);

        %===Header text===================================
        uicontrol(gcf,'Style','text', ...
            'String','ISI analysis',...
            'fontsize',14, ...
            'HorizontalAlignment','Center',...
            'Position',[5,570,100,25],...
            'BackgroundColor',[0.8 .8 0.8]);

        % ===Create raw data axes=================================
        x=100 ; y=405 ; w=630 ; h=155 ;
        data.rawax = axes('Units','pixels',...
            'Position',[x,y,w,h],...
            'color', [.4 .4 .4], ...
            'xgrid', 'on', ...
            'ygrid', 'on', ...
            'YMinorTick', 'on', ...
            'Box','on');

        % ===The quit button===============================
        data.quit=uicontrol('Style','pushbutton',...
            'Position',[750 570 45 20],...
            'String','Quit',...
            'Interruptible','off',...
            'BusyAction','cancel',...
            'tag','stim',...
            'Callback',[data.myname,' quit']);

        %==Channel and data Chooser=========================
        x=10 ; y=500 ; w=60 ; h=20 ;
%         data.mode='Chan 1';
%         data.mode1=uicontrol(gcf,'Style','radiobutton', ...
%             'String','Chan 1',...
%             'Position',[x,y,w,h],...
%             'BackgroundColor',[0.8,0.8,0.8], ...
%             'tag','modegrp',...
%             'value',1,...
%             'enable','off',...
%             'CallBack',[data.myname,' mode'] );
%         data.mode2=uicontrol(gcf,'Style','radiobutton', ...
%             'String','Chan 2',...
%             'Position',[x,y-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','Channel');
        x=10 ; y=480 ; w=60 ; h=70 ;
        data.ChannelChoose = uicontrol(gcf,'Style','listbox', ...
            'String','--',...
            'Position',[x,y,w,h],...
            'BackgroundColor',[0.8,0.8,0.8], ...
            'tag','modegrp',...
            'value',1,...
            'enable','off',...
            'CallBack',[data.myname,' mode'] );
        y=460;
        data.initfile=strcat('c:\my documents\*.wav');
        data.start=uicontrol(gcf,'Style','Pushbutton', ...
            'String','Load WAV',...
            'Position',[x,y,w,20],...
            'BackgroundColor',[0.8,0.8,0.8], ...
            'enable','on',...
            'CallBack',[data.myname,' load'] );
        data.decimateText = uicontrol(...
            'style', 'text', ...
            'position', [x y-25 w 20], ...
            'backgroundcolor',[.8 .8 .8],...
            'enable','on',...
            'string','Decimate'  );
        data.decimateEdit = uicontrol(...
            'style', 'edit', ...
            'position', [x y-45 w,20], ...
            'backgroundcolor',[.8 .8 .8],...
            'enable','on',...
            'string','5');

%         data.startlog=uicontrol(gcf,'Style','Pushbutton', ...
%             'String','Load log',...
%             'Position',[x,y-20,w,20],...
%             'BackgroundColor',[0.8,0.8,0.8], ...
%             'enable','on',...
%             'CallBack',[data.myname,' loadlog'] );
        
        %===zoom enable button for raw data==============
        x=750; y=500; w=50; 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 400 630 10], ...
            'Value', 0,...
            'BackgroundColor',[1 1 1],...
            'visible','off',...
            'CallBack', [data.myname,' scroll']);

        %===left control=============================
        % comment out tow controll
        x=75 ; y=370 ; w=200 ; h=10 ;
        data.Flow=uicontrol(...
            'style', 'slider', ...
            'position', [x y w h], ...
            'Min' ,0,'Max',1, ...
            'Value', 0,...
            'backgroundcolor', [.5 1 1], ...
            'SliderStep',[0.01 0.1], ...
            'visible','on', ...
            'callback', [data.myname,' leftend']);

        data.Flow1=uicontrol(...
            'style', 'text', ...
            'position', [x+w y 120 15], ...
            'backgroundcolor',[.8 .8 .8],...
            'enable','on',...
            'string',strcat(['Left limit ',num2str(get(data.Flow,'value'))])  );

        %===right analysis control===============================
        x=410 ; y=370 ; w=200 ; h=10 ;
        data.Fhi=uicontrol(...
            'style', 'slider', ...
            'position', [x y w h], ...
            'Min' ,0,'Max',1, ...
            'Value', 1,...
            'SliderStep',[0.01 0.1], ...
            'BackgroundColor',[1 1 .5],...
            'visible','on', ...
            'callback' , [data.myname,' rightend']);

        data.Fhi1=uicontrol(...
            'style', 'text', ...
            'position', [x+w y 120 15], ...
            'backgroundcolor',[.8 .8 .8],...
            'enable','on',...
            'string',strcat(['Right limit  ',num2str(get(data.Fhi,'value'))])  );

        %===Invert trace button======================================
        x=750; y=440; w=50; h=20;
        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y w h], ...
            'backgroundcolor',[1 1 1],...
            'string','Invert',...
            'callback', [data.myname,' invert']...
            );

        %===Audio button======================================
        x=20; y=390; w=50; h=20;
        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y w h], ...
            'backgroundcolor',[1 1 1],...
            'string','Audio',...
            'callback', [data.myname,' audio']...
            );

        %===Plot 1/ISI===============================================
        x=730; y=50; w=50; h=20;
        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y w h], ...
            'string','ISI vs T',...
            'callback', [data.myname,' plotisi']...
            );

        %===Plot 1/ISI===============================================
        x=730; y=25; w=50; h=20;
        uicontrol(...
            'style', 'pushbutton', ...
            'position', [x y w h], ...
            'string','1/ISI:XL',...
            'callback', [data.myname,' exportisi']...
            );
        %===Create amp histogram axes=================================
        x=25 ; y=100 ; w=350 ; h=250 ;
        data.ampax = axes('Units','pixels',...
            'Position',[x y w h],...
            'Box','on');

        %===Save button=================================
        x=600; y=0; w=35; h=20;
        %uicontrol('style','pushbutton',...
        %    'position', [x, y, w, h], ...
        %    'string','Save',...
        %   'enable','off',...
        %   'callback',[data.myname,' save']);

        %===compute button=================================
        x=650; y=50; w=60; h=20;
        uicontrol('style','pushbutton',...
            'position', [x, y, w, h], ...
            'string','Compute',...
            'callback',[data.myname,' compute']);

        %=========================================
        %analysis window binnumber
        x=440; y=50; w=55; h=20;
        uicontrol(...
            'style', 'text', ...
            'position', [x y 110 h], ...
            'backgroundcolor',[.8 .8 .8],...
            'string','Number of bins'...
            );

        uicontrol(...
            'style', 'text', ...
            'position', [x y-20 w h], ...
            'backgroundcolor',[.8 .8 .8],...
            'enable','on',...
            'string','Voltage');

        data.vbinNum=uicontrol(...
            'style', 'edit', ...
            'position', [x y-40 w h], ...
            'backgroundcolor',[.8 .8 .8],...
            'enable','on',...
            'string','25');

        uicontrol(...
            'style', 'text', ...
            'position', [x+55 y-20 w h], ...
            'backgroundcolor',[.8 .8 .8],...
            'enable','on',...
            'string','Interval');

        data.tbinNum=uicontrol(...
            'style', 'edit', ...
            'position', [x+55 y-40 w h], ...
            'backgroundcolor',[.8 .8 .8],...
            'enable','on',...
            'string','10');

        %=======================================
        %===number of amp bins
        x=220; y=50; w=55; h=20;
        uicontrol(...
            'style', 'text', ...
            'position', [x y w h], ...
            'backgroundcolor',[.8 .8 .8],...
            'string','Number of' ...
            );

        uicontrol(...
            'style', 'text', ...
            'position', [x y-20 w h], ...
            'backgroundcolor',[.8 .8 .8],...
            'enable','on',...
            'string','windows');

        data.nbins=uicontrol(...
            'style', 'edit', ...
            'position', [x y-40 w h], ...
            'backgroundcolor',[.8 .8 .8],...
            'enable','on',...
            'string','2',...
            'callback', [data.myname,' binnum']...
            );

        %===bin edge setting==================
        x=280 ; y=30 ; w=30 ; h=20 ;
        data.currentbin=1;
        data.binedgeArray(data.currentbin)=0;
        data.b(1)=uicontrol(gcf,'Style','radiobutton', ...
            'String','1',...
            'Position',[x,y,w,h],...
            'BackgroundColor',[0.8,0.8,0.8], ...
            'tag','bingrp',...
            'value',1,...
            'enable','on',...
            'CallBack',[data.myname,' setbin'] );
        data.b(2)=uicontrol(gcf,'Style','radiobutton', ...
            'String','2',...
            'Position',[x+w,y,w,h],...
            'BackgroundColor',[0.8,0.8,0.8], ...
            'tag','bingrp',...
            'enable','off',...
            'CallBack',[data.myname,' setbin'] );
        data.b(3)=uicontrol(gcf,'Style','radiobutton', ...
            'String','3',...
            'Position',[x+2*w,y,w,h],...
            'BackgroundColor',[0.8,0.8,0.8], ...
            'tag','bingrp',...
            'enable','off',...
            'CallBack',[data.myname,' setbin'] );
        data.b(4)=uicontrol(gcf,'Style','radiobutton', ...
            'String','4',...
            'Position',[x+3*w,y,w,h],...
            'BackgroundColor',[0.8,0.8,0.8], ...
            'tag','bingrp',...
            'enable','off',...
            'CallBack',[data.myname,' setbin'] );
        data.b(5)=uicontrol(gcf,'Style','radiobutton', ...
            'String','5',...
            'Position',[x+4*w,y,w,h],...
            'BackgroundColor',[0.8,0.8,0.8], ...
            'tag','bingrp',...
            'enable','off',...
            'CallBack',[data.myname,' setbin'] );
        uicontrol(gcf,'style','text',...
            'Position',[x,y+h,150,h],...
            'BackgroundColor',[0.8,0.8,0.8],...
            'string','Set Window Thresholds');
        data.binedge=uicontrol(...
            'style', 'edit', ...
            'position', [x+30 y-20 75 h], ...
            'backgroundcolor',[.8 .8 .8],...
            'enable','on',...
            'string','0',...
            'callback', [data.myname,' setbinedge']...
            );

        %===Create time histogram axes=================================
        x=430 ; y=100 ; w=350 ; h=250 ;
        data.tax = axes('Units','pixels',...
            'Position',[x y w h],...
            'Box','on');

        %turnn off all controls EXCEPT load and quit
        set(findobj(gcf,'type','uicontrol'),'enable','off');
        set(data.quit,'enable','on');
        set(data.start,'enable','on');
        set(data.decimateEdit,'enable','on');
         set(data.decimateText,'enable','on');
%        set(data.startlog,'enable','on');
        %===save all the controls and settings
        set(fighist, 'UserData', data);


        %========================================
        %UIcontrol callbacks
        %========================================
    case 'load'
        data=get(gcf,'UserData');
        [fname,pname] = uigetfile(data.initfile,'Load data');
        if isequal(fname,0)|isequal(pname,0)
            errordlg('File not found')
        else
            data.filename=strcat(pname,fname);
            [y,Fs] = wavread(data.filename) ;
            data.y  =  decimate(y,10) ;
            Fs = Fs/10 ;
            data.time = linspace(0,  length(data.y )/Fs, length(data.y )) ;
            data.Fs = Fs ;

            data.loadtype=1; %WAV file
            set(data.ChannelChoose,'string','Ch1|Ch2')
            set(data.Flow, 'value', 0);
            set(data.Fhi, 'value', data.time(end));
            set(data.Flow1,'string',...
                strcat(['Left limit ',num2str(0)]));
            set(data.Flow,'max',data.time(end));
            set(data.Fhi1,'string',...
                strcat(['Right limit ',num2str(data.time(end))]));
            set(data.Fhi,'max',data.time(end));
            data.loline=0;
            data.hiline=data.time(end);
            data.initfile=strcat(pname,'*.wav');
            set(findobj(gcf,'type','uicontrol'),'enable','on');
            data.v=data.y(:,1);
            set(fighist,'UserData',data);
            eval([data.myname ' binnum']);
            drawtrace
            eval([data.myname ' compute']);
        end

%     case 'loadlog'
%         data=get(gcf,'UserData');
%         [fname,fpath] = uigetfile('*.daq');
%         if fname~=0
%             data.filename=strcat(fpath,fname);
%             [data.y,data.time]=daqread([fpath,fname]);
%             data.daqvalues = daqread([fpath,fname],'info');
%             nChan = length(data.daqvalues.ObjInfo.Channel) ;
%             str = data.daqvalues.ObjInfo.Channel(1).ChannelName;
%             for i=2:nChan
%                 str = [str,'|',data.daqvalues.ObjInfo.Channel(i).ChannelName];
%             end
%             data.loadtype=2; %log file
%             set(data.ChannelChoose,'string',str)
%             data.v = data.y(:,data.daqvalues.ObjInfo.Channel(1).Index);
%             data.Fs = 1/(data.time(2)-data.time(1));
%             set(data.Flow, 'value', 0);
%             set(data.Fhi, 'value', data.time(end));
%             set(data.Flow1,'string',...
%                 strcat(['Left limit ',num2str(0)]));
%             set(data.Flow,'max',data.time(end));
%             set(data.Fhi1,'string',...
%                 strcat(['Right limit ',num2str(data.time(end))]));
%             set(data.Fhi,'max',data.time(end));
%             data.loline=0;
%             data.hiline=data.time(end);
%             data.initfile=strcat(fpath,'*.daq');
%             set(findobj(gcf,'type','uicontrol'),'enable','on');
%             set(gcf,'UserData',data);
%             eval([data.myname ' binnum']);
%             drawtrace
%             eval([data.myname ' compute']);
%         end
        
    case 'quit'
        %data=get(gcf,'UserData');
        %quit_reply = questdlg('Quit Freq Hisotgram?');
        %if strcmp(quit_reply,'Yes')
        close(gcf);

    case 'mode'
        data=get(gcf,'UserData');
        data.mode=get(gco,'value');
        set(fighist,'UserData',data);
        drawtrace
        eval([data.myname ' binnum']);
        
        
    case 'binnum'
        data=get(gcf,'userdata');
        %make sure that edit field is an integer between 1-5
        set(data.nbins,'string',num2str(min(5,max(1,fix(str2num(get(data.nbins,'string'))))))) ;
        %make an array of voltages equally spaced up to max voltage
        data.binedgeArray = linspace(0,...
            max(data.v), ...
            1 + str2num(get(data.nbins,'string'))) ;
        %reset radio buttons
        data.currentbin = 1;
        objhandle=findobj('tag','bingrp');
        clrindex=find(objhandle);
        set(objhandle(clrindex),'value',0);
        set(data.b(1),'value',1);

        set(data.binedge,'string',num2str(data.binedgeArray(data.currentbin)));
        for i=1:5
            if i<=str2num(get(data.nbins,'string'))
                set(data.b(i),'enable','on');
            else
                set(data.b(i),'enable','off');
            end
        end
        set(gcf, 'UserData', data);
        eval([data.myname ' compute']);
        
    case 'zoomin'
        data=get(fighist,'UserData');
        set(data.scroll,'visible','on');
        set(data.scroll,'min',0,'max',data.time(end));
        set(fighist,'UserData',data);

        set(gcf,'WindowButtonDownFcn',...
            [...
            'data=get(gcf,''UserData'');'...
            'initialpt=get(gca,''currentpoint'');'...
            'rect=rbbox;' ...
            ' if (gca == data.rawax & strcmp(get(gcf,''selectiontype''),''alt''))' ...
            '    t=get(data.rawax,''xlim'');' ...
            '    set(data.rawax, ''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.rawax & 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;'...
            '    set(data.rawax, ''xLim'', [t1, t2]);' ...
            '    set(data.scroll,''value'', t1);' ...
            'end ; ' ...
            'set(gcf, ''UserData'', data);'...
            ]);

    case 'zoomout'
        data=get(fighist,'UserData');
        set(data.rawax, 'xLim', [0 data.time(end)]);
        set(data.scroll,'visible','off');
        set(gcf,'WindowButtonDownFcn','')
        set(gcf,'WindowButtonUpFcn','')
        set(fighist,'UserData',data);

    case 'scroll'
        data=get(gcf,'UserData');
        t=get(data.rawax, 'xLim');
        tbase=get(data.scroll,'value');
        set(data.rawax, 'xLim', [tbase, tbase+(t(2)-t(1))]);
        set(fighist,'UserData',data);
        
    case 'invert'
        data=get(gcf,'UserData');
        i = get(data.ChannelChoose,'value');
        if data.loadtype==1
            data.y(:,i) = -data.y(:,i);
        end
        if data.loadtype==2
            data.y(:,data.daqvalues.ObjInfo.Channel(i).Index) = -data.y(:,data.daqvalues.ObjInfo.Channel(i).Index);
        end
        set(gcf,'UserData',data);
        drawtrace

    case 'plotisi'
        data=get(gcf,'UserData');
        figure
        numbins=str2num(get(data.nbins,'string'));
        col=['r','g','b','y','k'];
        for i=1:numbins
            shortpeak = data.peaktime{i};
            plot(shortpeak(1:end-1), 1./data.bintimes{i},'color',col(i));
            %hist(data.bintimes{i},'color',col(i));
            hold on
        end
        title('bins: red, green, blue, yellow, black')
        set(fighist,'UserData',data);

    case 'exportisi'
        data=get(gcf,'UserData');
        [fname,pname] = uiputfile('c:\my documents\*','Save Spreadsheet');
        numbins=str2num(get(data.nbins,'string'));
        for i=1:numbins
            filename = [pname,fname,num2str(i,'%1d')];
            shortpeak = data.peaktime{i};
            m = [shortpeak(1:end-1)', 1./data.bintimes{i}'];
            wk1write(filename,m);
        end
        set(fighist,'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(fighist,'UserData',data);


    case 'audio'
        data=get(gcf,'UserData');
        sound(data.v/max(data.v),data.Fs);

    case 'compute'
        data=get(gcf,'UserData');
        
        %get temporary analysis vectors
        i = get(data.ChannelChoose,'value');
        if data.loadtype==1
            tempv = data.y(:,i);
        end
        if data.loadtype==2
            tempv = data.y(:,data.daqvalues.ObjInfo.Channel(i).Index);
        end
        %compute data selection index ranges
        loIndex = max(fix(data.loline*data.Fs),1);
        hiIndex = min(fix(data.hiline*data.Fs),length(tempv));
        
        tempv = tempv(loIndex:hiIndex)-mean(tempv(loIndex:hiIndex));
        temptime = data.time(loIndex:hiIndex);

        %get all peaks
        [peaks, peaktimes] = peakAmpHist( tempv, temptime, data.binedgeArray(1));
        binnum=fix(str2num(get(data.vbinNum,'string')));
        [data.vhist,xbin] = hist(peaks,binnum);
        %and plot histogram
        set(gcf,'currentaxes',data.ampax);
        bar(xbin,data.vhist)
        %add lines
        for i=1:5
            if i<=str2num(get(data.nbins,'string'))
                data.vh(i)=line([1 1]*data.binedgeArray(i),...
                    [0 0.9]*max(data.vhist),...
                    'color','r');
                data.th(i)=text(data.binedgeArray(i),...
                    0.9*max(data.vhist),num2str(i),...
                    'HorizontalAlignment','center',...
                    'VerticalAlignment', 'bottom');
                set(data.vh(i),'visible','on');
                set(data.th(i),'visible','on');
            else
                data.vh(i)=line([0 0],[1 1]);
                set(data.vh(i),'visible','off');
                data.th(i)=text(0,...
                    0,num2str(i),...
                    'HorizontalAlignment','center',...
                    'VerticalAlignment', 'bottom');
                set(data.th(i),'visible','off');
            end
        end
        %text(max(xbin)/5, max(data.vhist)*.8, 'Amplitude Histogram')
        title('Amplitude Histogram')
        set(gca,'xlim',[0,max(tempv)]);
        xlabel('Voltage');
        ylabel('Number of Spikes')
        %now separate into amplitude bins
        numbins=str2num(get(data.nbins,'string'));
        longest=0;
        for i=1:numbins
            data.peaktime{i}=peaktimes(...
                find( (peaks>data.binedgeArray(i)) & (peaks<=data.binedgeArray(i+1)) ));
            data.bintimes{i}=diff(data.peaktime{i});
            avgtimes(i)=mean(data.bintimes{i});
            binlegend{i} = [num2str(i,'%1d'),...
                ' T=',num2str(avgtimes(i),3),...
                ' N=',num2str(length(data.bintimes{i}),'%3d')];
            % bintimes{i}
            if max(data.bintimes{i})>longest
                longest = max(data.bintimes{i});
            end
        end
        set(gcf,'currentaxes',data.tax);
        cla
        hold off
        binnum=fix(str2num(get(data.tbinNum,'string')));
        xbin = linspace(0,longest,binnum); %histogram edges
        data.thist=[];
        for i=1:numbins
            [data.thist(:,i)] = hist(data.bintimes{i},xbin);
        end
        b=bar(xbin,data.thist,'grouped');
        colormap(jet)
        xlabel('Spike Interval');
        ylabel('Number of Spikes');
        title('Interval Histogram')
        legend(b,binlegend)
        
        %open a separate window and plot histogram
        figure(2)
        b=bar(xbin,data.thist,'grouped');
        colormap(jet)
        xlabel('Spike Interval');
        ylabel('Number of Spikes');
        title('Interval Histogram')
        legend(b,binlegend)
        %set(gca,'xlim',[0,)]);
        set(0, 'currentfigure', fighist);
        set(fighist,'UserData',data);

    case 'setbin'
        data=get(gcf,'UserData');
        objhandle=findobj('tag','bingrp');
        clrindex=find(objhandle ~= gco);
        set(objhandle(clrindex),'value',0);
        set(gco,'value',1);
        data.currentbin=str2num(get(gco,'string'));
        set(data.binedge, 'string', num2str(data.binedgeArray(data.currentbin)));
        set(fighist,'UserData',data);

    case 'setbinedge'
        data=get(gcf,'UserData');
        data.binedgeArray(data.currentbin)=str2num(get(data.binedge,'string'));
        if ishandle(data.vh(data.currentbin))
            set(data.vh(data.currentbin),'xdata',[1 1]*data.binedgeArray(data.currentbin));
            set(data.th(data.currentbin),...
                'position',[data.binedgeArray(data.currentbin),0.9*max(data.vhist)]);
        end
        set(fighist,'UserData',data);

    case 'leftend'
        data=get(gcf,'UserData');
        set(data.Flow1,'string',...
            strcat(['Left limit ',num2str(get(data.Flow,'value'))]));
        data.loline=get(data.Flow,'value');
        set(fighist,'userdata',data);
        drawtrace

    case 'rightend'
        data=get(gcf,'UserData');
        set(data.Fhi1,'string',...
            strcat(['Right limit ',num2str(get(data.Fhi,'value'))]));
        data.hiline=get(data.Fhi,'value');
        set(fighist,'userdata',data);
        drawtrace

    case 'bogusdraw'
        drawtrace

end %of main case statement


%============================================================
%===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 raw traces
%===========================================================
function drawtrace
data=get(gcf,'UserData');
set(gcf,'currentaxes',data.rawax);
i = get(data.ChannelChoose,'value');
if data.loadtype==1
    v = data.y(:,i);
end
if data.loadtype==2
    data.v = data.y(:,data.daqvalues.ObjInfo.Channel(i).Index);
end

plot(data.time, v, 'w')
hold on
line(data.loline*[1,1], [min(v),max(v)], 'color',[.5 1 1]);
line(data.hiline*[1,1], [min(v),max(v)], 'color',[1 1 .5]);
hold off
title(data.filename,'interpreter','none');
set(gca,'color', [.4 .4 .4]);
set(gca,'xgrid', 'on')
set(gca,'ygrid', 'on')
set(gca,'YMinorTick', 'on')
set(gcf,'UserData',data);

%============================================================
%===find some peaks
%===========================================================
function [peaks, peaktimes] = peakAmpHist( wave, time, thresh )

numfound = 1;
counting = 0;
currmax = -1;
currtime = -1;

for i = 1:length(wave)
    if( wave(i) > thresh )
        if( counting == 1 )
            if( wave(i) > currmax )
                currmax = wave(i);
                currtime = time(i);
            end
        else %not yet counting
            counting = 1;
            currmax = wave(i);
            currtime = time(i);
        end
    else % wave(i) <= threshold
        if( counting == 1 ) %then we just dropped below threshold
            %record peak just found
            peaks(numfound) = currmax;
            peaktimes(numfound) = currtime;
            %update/reset counters
            numfound = numfound + 1;
            counting = 0;
        end
    end
end
