function varargout = anashow(varargin)
% ANASHOW Application M-file for anashow.fig
%    FIG = ANASHOW launch anashow GUI.
%    ANASHOW('callback_name', ...) invoke the named callback.
%
% Still needs some work: when you reduce the window size and click to move
% left, it takes a few clicks before the window moves over.
%
% Modified 11 Jan 2005, PKS, updated for version 7.  
% LOTS of changes, mostly to how slider functions handle time (window_width), 
% but also I removed some eval statements too.
% I also changed it so that it saves the last directory and reloads it
% automatically the next time Anashow is run.
% 
% Modified 9 Jan 2005, PKS.  Added the "save vals" button to save the value
% of the current EOD in a text file in the c:\EODs directory.
%
% Modified 3 July 2002, PKS, added quotes to eval load statement to allow directories with spaces

if nargin == 0  % LAUNCH GUI
	fig = openfig(mfilename,'reuse');
	% Generate a structure of handles to pass to callbacks, and store it. 
	handles = guihandles(fig);
    set(fig, 'NumberTitle', 'off');
    set(fig, 'Name', 'AnaShow');
    update_file_list(fig,handles);
    guidata(fig, handles);
    setdir(fig,handles);    % set directory for data files from saved value
    if nargout > 0
		varargout{1} = fig;
	end
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
	try
		if (nargout)
			[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
		else
			feval(varargin{:}); % FEVAL switchyard
		end
	catch
		disp(lasterr);
	end
end
%| ABOUT CALLBACKS:
%| GUIDE automatically appends subfunction prototypes to this file, and 
%| sets objects' callback properties to call them through the FEVAL 
%| switchyard above. This comment describes that mechanism.
%|
%| Each callback subfunction declaration has the following form:
%| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)
%|
%| The subfunction name is composed using the object's Tag and the 
%| callback type separated by '_', e.g. 'slider2_Callback',
%| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.
%|
%| H is the callback object's handle (obtained using GCBO).
%|
%| EVENTDATA is empty, but reserved for future use.
%|
%| HANDLES is a structure containing handles of components in GUI using
%| tags as fieldnames, e.g. handles.figure1, handles.slider2. This
%| structure is created at GUI startup using GUIHANDLES and stored in
%| the figure's application data using GUIDATA. A copy of the structure
%| is passed to each callback.  You can store additional information in
%| this structure at GUI startup, and you can change the structure
%| during callbacks.  Call guidata(h, handles) after changing your
%| copy to replace the stored original so that subsequent callbacks see
%| the updates. Type "help guihandles" and "help guidata" for more
%| information.
%|
%| VARARGIN contains any extra arguments you have passed to the
%| callback. Specify the extra arguments by editing the callback
%| property in the inspector. By default, GUIDE sets the property to:
%| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo))
%| Add any extra arguments after the last argument, before the final
%| closing parenthesis.
%
%=====================================================================
% FILE HANDLING FUNCTIONS
function datarray = load_ana_file(handles, file_name)
n = 14; % number of variables saved in ana file
filename = [get(handles.pushbutton_directory,'String'),'\',file_name,'.ana'];
fid=fopen(filename);
[datarray, count] = fread(fid, [n,inf], 'float64');
fclose(fid);
a = datevec(datarray(1,1));
if mod(count,n) == 0
    i = count/n;
else    % else there must be a screwup in data file (it's not a multiple of the record length)
    year = a(1);
    nextyear = year + 1;
    % determine valid data by checking for same or next year in each record
    for i=1:size(datarray,2)
        a = datevec(datarray(1,i));
        if (year ~= a(1)) & (nextyear ~= a(1))  % if not this year or next
            i=i-1;
            break
         end
     end
 end
    datarray = datarray(:,1:i)';                % select valid part of array, invert array
set(gcbf, 'UserData', datarray);            % save UserData
%keyboard
%data = [EODtime, , light, nEODs, median_amp_EOD, ...
%        median_dur_EOD, A1cal, A2cal, Acal, D1, ...
%        D2 ,D, tau, rate];

% --------------------------------------------------------------------
function varargout = pushbutton_update_file_list_Callback(h, eventdata, handles, varargin)
% update file list, create the list of file names from the data directory
update_file_list(gcbo, handles);
% --------------------------------------------------------------------
function update_file_list(fig,handles)
% create the list of file names from the data directory
ana_files=dir([get(handles.pushbutton_directory,'String'),'\*.ana']);
n=length(ana_files);
file_names=cell(n,1);
for i=1:n
    file_names(i)=cellstr(strtok(ana_files(i).name,'.'));
end
if ~isempty(file_names)
    set(handles.popupmenu_select_file,'String',file_names);   % set the file list to show those file names
    set(handles.popupmenu_select_file,'Visible','on');
    guidata(fig, handles);  % save changes to GUI
end
% --------------------------------------------------------------------
function varargout = popupmenu_select_file_Callback(h, eventdata, handles, varargin)
% select ana file from popup file list
selected_file = popupstr(h);                        %returns the currently selected string

axes(handles.axes_ana)
cla
axes(handles.axes_EOD)
cla
set(handles.text_EOD_number, 'String', '');
set(handles.text_openfile,'String',selected_file);  % modify text string at top of graph
guidata(gcbo, handles);                             % save changes to GUI

yindex = get(handles.text_y_units,'Value');         % y variable index
set(handles.listbox_parameter, 'Visible', 'off')
datarray = [];
datarray = load_ana_file(handles,selected_file);    % load data from disk file
if ~isempty(datarray)
    set(handles.listbox_parameter, 'Visible', 'on');
	Xmin = datarray(1,1);                               % lowest time in file
	Xmax = datarray(end,1);                % latest time in file
	window_width = datenum('00:00:01') + Xmax - Xmin;
    set(handles.edit_Xlow, 'Value', Xmin);
	set(handles.edit_Xlow, 'String', datestr(Xmin));
	set(handles.edit_Xhigh, 'Value', Xmax);
	set(handles.edit_Xhigh, 'String', datestr(Xmax));
	set(handles.edit_window_width, 'String', datestr(window_width, 'HH:MM:SS'));
	set(handles.edit_window_width, 'Value', window_width);
	set(handles.slider_window_width, 'Value', window_width);
	set(handles.slider_window_width, 'Max', window_width);
	set(handles.slider_window_width, 'Min', datenum('00:00:01'));
	set(handles.slider_file_position, 'Min',  Xmin);
	set(handles.slider_file_position, 'Max',  Xmax);
	set(handles.slider_file_position, 'Value', Xmax);
	set(handles.edit_file_position, 'Value', Xmax);
	set(handles.edit_file_position,'String', datestr(Xmax));
	if get(handles.listbox_parameter, 'UserData')
        plotdata(handles);
    end
end    
set(gcbf, 'UserData', datarray);                    % save datarray in UserData.

%=====================================================================
% PLOTTING FUNCTIONS
%
function plotdata(handles)
datarray = get(gcbf, 'UserData');
yindex = get(handles.text_y_units, 'Value');
xdata = datarray(:,1);
ydata = datarray(:,yindex);

Ymin = str2num(get(handles.edit_Ylow, 'String'));
Ymax = str2num(get(handles.edit_Yhigh, 'String'));
light = ~(datarray(:,3));
%----
% new light routine
file_name = get(handles.text_openfile,'String'); %returns the currently selected file_name string
load([get(handles.pushbutton_directory,'String'),'\',file_name,'.mat']); 
if max(xdata) > max(light_time) % fix last light value
    light_time = [light_time,xdata(end)];
    lux = [lux,lux(end)];
end
%----
axes(handles.axes_ana)
fig = area(light_time, ~lux*Ymax);  % plot dark
set(fig(1),'FaceColor',[.7 .7 .7],'EdgeColor', [.7 .7 .7])
hold on
fig = plot(xdata,ydata, 'Tag', 'Data_Line_1');  % plot data
hold off
set_axis(handles);
set_symbol_line(handles);
set_grid(handles);
set(handles.text_tank, 'String', ['tank ',num2str(tank)]);
% --------------------------------------------------------------------
function set_axis(handles)
Xlow = get(handles.edit_Xlow, 'Value');
Xhigh = get(handles.edit_Xhigh, 'Value');
Ymin = str2num(get(handles.edit_Ylow, 'String'));
Ymax = str2num(get(handles.edit_Yhigh, 'String'));
axis([Xlow Xhigh Ymin Ymax]);
timestring = 'HH:MM';
datetick('x',timestring, 'keeplimits');     % Replace x-axis ticks with selected labels.
drawnow;  
% --------------------------------------------------------------------
function set_grid(handles)
if get(handles.togglebutton_Ygrid, 'Value')
    set(gca, 'Ygrid', 'on');
end    
if get(handles.togglebutton_Xgrid, 'Value')
    set(gca, 'Xgrid', 'on');
end    

% --------------------------------------------------------------------
function set_symbol_line(handles)
linehandle = findobj('Tag', 'Data_Line_1');
symbol = popupstr(handles.popupmenu_symbol);
if get(handles.pushbutton_line, 'UserData')
    set(linehandle, 'LineStyle', '-');
    set(linehandle, 'Marker', 'none');
elseif get(handles.pushbutton_symbol, 'UserData')
    set(linehandle, 'LineStyle', 'none');
    set(linehandle, 'Marker', symbol);
    set(linehandle, 'MarkerEdgeColor', 'r')
elseif get(handles.pushbutton_both, 'UserData')
    set(linehandle, 'LineStyle', '-');
    set(linehandle, 'Marker', symbol);
    set(linehandle, 'MarkerEdgeColor', 'r')
end
% --------------------------------------------------------------------

function varargout = pushbutton_update_plot_Callback(h, eventdata, handles, varargin)
% reloads data from file and updates plot
selected_file = get(handles.text_openfile,'String'); %returns the currently selected string
yindex = get(handles.text_y_units,'Value');         % y variable index
datarray = load_ana_file(handles, selected_file);            % load data from disk file.
set(gcbf, 'UserData', datarray);                    % save datarray in UserData.
Xmin = datarray(1,1);
Xmax = datarray(size(datarray,1),1);
window_width = datenum('00:00:01') + Xmax - Xmin;
datestr(window_width,'HH:MM:SS')
set(handles.edit_Xhigh, 'Value', Xmax);
set(handles.edit_Xhigh, 'String', datestr(Xmax));
set(handles.slider_window_width, 'Max', window_width);

%set file_position slider and min-max values for slider (these first)
set(handles.slider_file_position, 'Min',  Xmin);
set(handles.slider_file_position, 'Max',  Xmax);
set(handles.slider_file_position, 'Value', Xmax);
set(handles.edit_file_position, 'Value', Xmax);
set(handles.edit_file_position,'String', datestr(Xmax));
plotdata(handles);
% --------------------------------------------------------------------
function varargout = pushbutton_line_Callback(h, eventdata, handles, varargin)
set(gcbo, 'UserData', 1);
set(handles.pushbutton_symbol,'UserData',0);
set(handles.pushbutton_both,'UserData',0);
guidata(gcbo, handles);                             % save changes to GUI
set_symbol_line(handles);

% --------------------------------------------------------------------
function varargout = pushbutton_symbol_Callback(h, eventdata, handles, varargin)
set(gcbo, 'UserData', 1);
set(handles.pushbutton_line,'UserData',0);
set(handles.pushbutton_both,'UserData',0);
guidata(gcbo, handles);                             % save changes to GUI
set_symbol_line(handles);
% --------------------------------------------------------------------
function varargout = pushbutton_both_Callback(h, eventdata, handles, varargin)
set(gcbo,'UserData',1);
set(handles.pushbutton_line,'UserData',0);
set(handles.pushbutton_symbol,'UserData',0);
guidata(gcbo, handles);                             % save changes to GUI
set_symbol_line(handles);

% --------------------------------------------------------------------
function varargout = popupmenu_symbol_Callback(h, eventdata, handles, varargin)
set_symbol_line(handles);

% --------------------------------------------------------------------
function varargout = togglebutton_Xgrid_Callback(h, eventdata, handles, varargin)
if get(gcbo, 'Value')
    set(gca, 'Xgrid', 'on');
else
    set(gca, 'Xgrid', 'off');
end    
% --------------------------------------------------------------------
function varargout = togglebutton_Ygrid_Callback(h, eventdata, handles, varargin)
if get(gcbo, 'Value')
    set(gca, 'Ygrid', 'on');
else
    set(gca, 'Ygrid', 'off');
end    
%=====================================================================
% VARIABLE SELECTION FUNCTIONS
function varargout = listbox_parameter_Callback(h, eventdata, handles, varargin)
% selects the ordinate variable to plot
param_number = get(gcbo, 'Value');
param_string = get(gcbo, 'String');
param = param_string{param_number}; % convert from cell array to string
%data = [EODtime, , light, nEODs, median_amp_EOD, ...
%        median_dur_EOD, A1cal, A2cal, Acal, D1, ...
%        D2 ,D, tau, rate];
switch(param)
    case 'Amplitude P1'
        ystring = 'Ampl P1 mV/cm';
        yindex = 7;
        yrange=[0 1.5];
    case 'Amplitude P2'
        ystring = 'Ampl P2 mV/cm';
        yindex = 8;
        yrange=[0 1.5];
    case 'Amplitude'
        ystring = 'Ampl mV/cm';
        yindex = 9;
        yrange=[0 2.5];
    case 'Duration P1'
        ystring = 'Dur P1';
        yindex = 10;
        yrange=[0.4 0.8];
    case 'Duration P2'
        ystring = 'Dur P2';
        yindex = 11;
        yrange=[0.4 2];
    case 'Duration'
        ystring = 'Dur ms';
        yindex = 12;
        yrange=[1 3];
    case 'Tau P2 recovery'
        ystring = 'Tau ms';
        yindex = 13;
        yrange=[0 .8];
    case 'Rate'
        ystring = 'EODs/s';
        yindex = 14;
        yrange = [0 80];
    case 'Temperature'
        ystring = 'Temp';
        yindex = 2;
        yrange=[25 30];
end

set(handles.text_y_units, 'String', ystring);
set(handles.text_y_units, 'Value', yindex);
set(handles.edit_Ylow, 'String', yrange(1));
set(handles.edit_Yhigh,'String', yrange(2));
set(gcbo,'UserData',1);
guidata(gcbo, handles);  % save changes to GUI

plotdata(handles);
set(handles.pushbutton_update_plot, 'Enable', 'on');

%=====================================================================
% TIME AXIS FUNCTIONS
function [Xlow, Xhigh] = calculate_Xlow_Xhigh(handles)
lock = get(handles.radiobutton_left, 'UserData'); % determine where file position falls in window
Xlows = [0, .5, 1];
Xhighs = [1, .5, 0];
Xlowpos = Xlows(lock);
Xhighpos = Xhighs(lock);
window_width = get(handles.edit_window_width, 'Value');
file_pos = get(handles.edit_file_position,'Value');
Xlow =datenum('00:00:01')+file_pos - (window_width*Xlowpos); % set the Xlow = slider value + window fraction determined by lock
Xhigh=file_pos + (window_width*Xhighpos); % set the Xhigh = slider value + window fraction determined by lock
set(handles.edit_Xlow, 'Value', Xlow);
set(handles.edit_Xhigh, 'Value', Xhigh);
set(handles.edit_Xhigh, 'String', datestr(Xhigh));
set(handles.edit_Xlow, 'String', datestr(Xlow));
% --------------------------------------------------------------------
function varargout = pushbutton_halve_window_width_Callback(h, eventdata, handles, varargin)
ww = get(handles.edit_window_width, 'Value');
window_width = (ww - datenum('00:00:01')) * 0.5 + datenum('00:00:01');
set(handles.edit_window_width,'Value', window_width);
set(handles.edit_window_width,'String', datestr(window_width, 'HH:MM:SS'));
set(handles.slider_window_width,'Value', window_width);
calculate_Xlow_Xhigh(handles);
plotdata(handles);

% --------------------------------------------------------------------
function varargout = pushbutton_double_window_width_Callback(h, eventdata, handles, varargin)
ww = get(handles.edit_window_width, 'Value');
window_width = (ww - datenum('00:00:01')) * 2 + datenum('00:00:01');
window_width = min(get(handles.slider_window_width, 'Max'), window_width);
set(handles.edit_window_width,'Value', window_width);
set(handles.edit_window_width,'String', datestr(window_width, 'HH:MM:SS'));
set(handles.slider_window_width,'Value', window_width);
calculate_Xlow_Xhigh(handles);
plotdata(handles);

% --------------------------------------------------------------------
function varargout = slider_window_width_Callback(h, eventdata, handles, varargin)
window_width = get(gcbo, 'Value');
set(handles.edit_window_width,'Value', window_width);
set(handles.edit_window_width,'String', datestr(window_width, 'HH:MM:SS'));
calculate_Xlow_Xhigh(handles);
plotdata(handles);

% --------------------------------------------------------------------
function varargout = edit_window_width_Callback(h, eventdata, handles, varargin)
%window_width = datenum(get(gcbo,'String'));
%set(gcbo,'Value', window_width);
%calculate_Xlow_Xhigh(handles);
%plotdata(handles);

% --------------------------------------------------------------------
function varargout = slider_file_position_Callback(h, eventdata, handles, varargin)
file_pos = get(gcbo,'Value');   % get the value of the slider
set(handles.edit_file_position, 'Value', file_pos);
set(handles.edit_file_position, 'String', datestr(file_pos));
[Xlow, Xhigh] = calculate_Xlow_Xhigh(handles);
set(handles.edit_Xlow, 'Value', Xlow);
set(handles.edit_Xhigh, 'Value', Xhigh);
set(handles.edit_Xlow, 'String', datestr(Xlow));
set(handles.edit_Xhigh, 'String', datestr(Xhigh));
plotdata(handles);

% --------------------------------------------------------------------
function varargout = edit_file_position_Callback(h, eventdata, handles, varargin)
file_pos = datenum(get(gcbo,'String')); 
set(gcbo,'Value',file_pos);
set(handles.slider_file_position, 'Value', file_pos);
[Xlow, Xhigh] = calculate_Xlow_Xhigh(handles);
set(handles.edit_Xlow, 'Value', Xlow);
set(handles.edit_Xhigh, 'Value', Xhigh);
set(handles.edit_Xlow, 'String', datestr(Xlow));
set(handles.edit_Xhigh, 'String', datestr(Xhigh));
plotdata(handles);

% --------------------------------------------------------------------
function adjust_time_objects(handles)
% correct window_width based on new Xlow or Xhigh
Xlow = get(handles.edit_Xlow, 'Value');
Xhigh = get(handles.edit_Xhigh, 'Value');
window_width = Xhigh - Xlow;
set(handles.edit_window_width, 'Value', window_width);
set(handles.edit_window_width, 'String', datestr(window_width, 'HH:MM:SS'));

% correct file position based on new Xlow or Xhigh
lock = get(handles.radiobutton_left, 'UserData'); % determine where file position falls in window
Xlows = [0, .5, 1];
Xoffset = window_width * Xlows(lock);
datarray = get(gcbf, 'UserData');
Xmin = datarray(1,1);    % earliest time in file
file_pos = Xmin + Xoffset;
set(handles.slider_file_position, 'Value', file_pos);
set(handles.edit_file_position, 'Value', file_pos);
set(handles.edit_file_position, 'String', datestr(file_pos));

% --------------------------------------------------------------------
function varargout = edit_Xlow_Callback(h, eventdata, handles, varargin)
Xlowstr = get(gcbo, 'String');
Xlowval = datenum(Xlowstr);
set(gcbo, 'Value', Xlowval);
adjust_time_objects(handles);
plotdata(handles);
% --------------------------------------------------------------------
function varargout = edit_Xhigh_Callback(h, eventdata, handles, varargin)
Xhighstr = get(gcbo, 'String');
Xhighval = datenum(Xhighstr);
set(gcbo, 'Value', Xhighval);
adjust_time_objects(handles);
plotdata(handles);

% --------------------------------------------------------------------
function varargout = radiobutton_left_Callback(h, eventdata, handles, varargin)
set(handles.radiobutton_center, 'Value', 0);
set(handles.radiobutton_right, 'Value', 0);
set(handles.radiobutton_left, 'UserData', 1);

function varargout = radiobutton_center_Callback(h, eventdata, handles, varargin)
set(handles.radiobutton_left, 'Value', 0);
set(handles.radiobutton_right, 'Value', 0);
set(handles.radiobutton_left, 'UserData', 2);

function varargout = radiobutton_right_Callback(h, eventdata, handles, varargin)
set(handles.radiobutton_left, 'Value', 0);
set(handles.radiobutton_center, 'Value', 0);
set(handles.radiobutton_left, 'UserData', 3);
%=====================================================================
% Y AXIS FUNCTIONS
function varargout = edit_Ylow_Callback(h, eventdata, handles, varargin)
Yhigh = str2num(get(handles.edit_Yhigh,'String'));
Ylow  = str2num(get(handles.edit_Ylow,'String'));
if Ylow >= Yhigh    % prevent overlap of high and low Y limits
    set(handles.edit_Ylow, 'String', Yhigh - 0.001);
end    
plotdata(handles);
% --------------------------------------------------------------------
function varargout = edit_Yhigh_Callback(h, eventdata, handles, varargin)
Yhigh = str2num(get(handles.edit_Yhigh,'String'));
Ylow  = str2num(get(handles.edit_Ylow,'String'));
if Ylow >= Yhigh    % prevent overlap of high and low Y limits
    set(handles.edit_Yhigh, 'String', Ylow + 0.001);
end    
plotdata(handles);
% --------------------------------------------------------------------
function varargout = pushbutton_inc_Yhigh_Callback(h, eventdata, handles, varargin)
Yhigh = str2num(get(handles.edit_Yhigh,'String'));
Ylow  = str2num(get(handles.edit_Ylow,'String'));
Ydif = Yhigh - Ylow;
if Ydif >= 2
    Yhigh = floor(Yhigh + 1);
else
    Yhigh = Yhigh + (Ydif);
end
set(handles.edit_Yhigh, 'String', Yhigh);
plotdata(handles);
% --------------------------------------------------------------------
function varargout = pushbutton_dec_Yhigh_Callback(h, eventdata, handles, varargin)
Yhigh = str2num(get(handles.edit_Yhigh,'String'));
Ylow  = str2num(get(handles.edit_Ylow,'String'));
Ydif = Yhigh - Ylow;
if Ydif >= 2
    Yhigh = floor(Yhigh - 1);
else
    Yhigh = Yhigh - (Ydif/2);
end
set(handles.edit_Yhigh, 'String', Yhigh);
plotdata(handles);
% --------------------------------------------------------------------
function varargout = pushbutton_inc_Ylow_Callback(h, eventdata, handles, varargin)
Yhigh = str2num(get(handles.edit_Yhigh,'String'));
Ylow  = str2num(get(handles.edit_Ylow,'String'));
Ydif = Yhigh - Ylow;
if Ydif >= 2
    Ylow = floor(Ylow + 1);
else
    Ylow = Ylow + (0.5 * Ydif);
end
set(handles.edit_Ylow, 'String', Ylow);
plotdata(handles);
% --------------------------------------------------------------------
function varargout = pushbutton_dec_Ylow_Callback(h, eventdata, handles, varargin)
Yhigh = str2num(get(handles.edit_Yhigh,'String'));
Ylow  = str2num(get(handles.edit_Ylow,'String'));
Ydif = Yhigh - Ylow;
if Ydif >=2 
    Ylow = floor(Ylow - 1);
else
    Ylow = Ylow - (Ydif);
end
Ylow = max(Ylow,0);
set(handles.edit_Ylow, 'String', Ylow);
plotdata(handles);
%=====================================================================
% PROCESS FUNCTIONS
function varargout = pushbutton_close_Callback(h, eventdata, handles, varargin)
close(gcbf);

%=====================================================================
% EOD FUNCTIONS

function varargout = figure1_WindowButtonDownFcn(h, eventdata, handles, varargin)
curr=get(gca,'CurrentPoint');
xcurr=curr(1,1);
ycurr=curr(1,2);

Xlow = get(handles.edit_Xlow, 'Value');
Xhigh = get(handles.edit_Xhigh, 'Value');
Ymin = str2num(get(handles.edit_Ylow, 'String'));
Ymax = str2num(get(handles.edit_Yhigh, 'String'));

if (xcurr >= Xlow) & (xcurr <= Xhigh) & (ycurr >= Ymin) & (ycurr <= Ymax)   % in bounds of figure
    datarray = get(gcbf, 'UserData');
    xdata = datarray(:,1);
    diffs = abs(xdata-xcurr);
    EODindex = min(find(diffs == min(diffs)));
    yindex = get(handles.text_y_units, 'Value');
    yvalue = num2str(datarray(EODindex,yindex));
    datetime = datestr(xdata(EODindex));
    info_string = ['#',num2str(EODindex),'   (',datetime,')  ', yvalue];
    set(handles.text_EOD_number, 'String', info_string);
    set(handles.text_EOD_number, 'Value', EODindex);
    find_EOD(handles);
end
% --------------------------------------------------------------------
function [] = find_EOD(handles)
persistent oldx oldy oldbackground
datarray = get(gcbf, 'UserData');
EODindex = get(handles.text_EOD_number,'Value');
median_amp_EOD = datarray(EODindex,5);
median_dur_EOD = datarray(EODindex,6);

file_name = get(handles.text_openfile,'String'); %returns the currently selected file_name string
fid=fopen([get(handles.pushbutton_directory,'String'),'\',file_name,'.raw'], 'r');   %open EOD file for reading
if fid
    % first, get past header
    fish=fgetl(fid);
    date_time=fread(fid, 1,  'float64');
    sample_rate=fread(fid, 1,'float64');
    block_size=fread(fid, 1, 'float');
    for i = 1:EODindex   % page through file
    	[date_time,count] = fread(fid, 1, 'float64');
        temp     = fread(fid, 1, 'float64');
        light    = fread(fid, 1, 'float64');
        npoints  = fread(fid, 1, 'float64');
		EOD_data = fread(fid, npoints, 'float32');
    end    
    fclose(fid);
    % plotting
    axes(handles.axes_EOD);
    voffset = 2;
    nEODs = floor(double(npoints)/block_size);
    EOD_data=reshape(EOD_data,block_size,nEODs);
    for i=1:nEODs
        h = plot((EOD_data(:,i)+ (voffset*i) ));
        if (i == median_amp_EOD) & (i == median_dur_EOD)
            set(h, 'Color', 'm')
        elseif i == median_amp_EOD
            set(h, 'Color', 'r')
        elseif i == median_dur_EOD
            set(h, 'Color', 'g')
        end % if
        hold on;
	end % for
    axis([0 block_size -3 23]);     % set axis for EODs in window

    yindex = get(handles.text_y_units, 'Value');
    yvalue = datarray(EODindex,yindex);
    set(handles.pushbutton_savevals, 'UserData', yvalue);  % save for later use 
    set(handles.text_EOD_number, 'Visible', 'on');
	hold off
    set(handles.axes_EOD, 'Visible', 'off');

    datarray = get(gcbf, 'UserData');
    yindex = get(handles.text_y_units, 'Value');
    xdata = datarray(EODindex,1);
    ydata = datarray(EODindex,yindex);
    axes(handles.axes_ana);
    hold on
    if oldx
        h=plot(oldx, oldy,'om', 'Color', oldbackground);    % erase old circle
    end
    plot(xdata, ydata,'go')
    oldx = xdata; oldy = ydata;
    if datarray(EODindex,3) == 1   % light
        oldbackground = [1 1 1];
    else
         oldbackground = [.7 .7 .7];
    end
    hold off
    % save EODs in .mat file
    save c:\EODs\eod EODindex EOD_data date_time file_name median_dur_EOD median_amp_EOD  
    end
% --------------------------------------------------------------------
function varargout = pushbutton_prev_EOD_Callback(h, eventdata, handles, varargin)
EODindex = get(handles.text_EOD_number,'Value');
EODindex = EODindex - 1;
datarray = get(gcbf, 'UserData');
xdata = datarray(:,1);
if EODindex > 0
    yindex = get(handles.text_y_units, 'Value');
    yvalue = num2str(datarray(EODindex,yindex));
    datetime = datestr(xdata(EODindex));
    info_string = ['#',num2str(EODindex),'   (',datetime,')  ', yvalue];
    set(handles.text_EOD_number, 'String', info_string);
    set(handles.text_EOD_number, 'Value', EODindex);
    find_EOD(handles);
end

% --------------------------------------------------------------------
function varargout = pushbutton_next_EOD_Callback(h, eventdata, handles, varargin)
EODindex = get(handles.text_EOD_number,'Value');
EODindex = EODindex + 1;
datarray = get(gcbf, 'UserData');
xdata = datarray(:,1);
if EODindex <= size(datarray,1)
    yindex = get(handles.text_y_units, 'Value');
    yvalue = num2str(datarray(EODindex,yindex));
    datetime = datestr(xdata(EODindex));
    info_string = ['#',num2str(EODindex),'   (',datetime,')  ', yvalue];
    set(handles.text_EOD_number, 'String', info_string);
    set(handles.text_EOD_number, 'Value', EODindex);
    find_EOD(handles);
end
    
% --------------------------------------------------------------------
function varargout = pushbutton_save_Callback(h, eventdata, handles, varargin)
load c:\EODs\eod;
sample_interval_ms = 0.02048;                   % ms/ AD sample
t = (1:size(EOD_data,1))*sample_interval_ms;
filestring = [file_name, '_',num2str(EODindex)];
% make a data record
    eod.data = EOD_data;
    eod.t    = t;
    eod.file = file_name;
    eod.time = date_time;
    eod.meddur = median_dur_EOD;
    eod.medamp = median_amp_EOD;
save(['c:\EODs\', filestring, ' eod']);
% --------------------------------------------------------------------
% --- Executes on button press in pushbutton_savevals.
function pushbutton_savevals_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_savevals (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

load c:\EODs\eod;
file_name = get(handles.text_openfile,'String'); %returns the currently selected file_name string
filename = ['c:\EODs\',file_name,'.txt'];  % get name for data file
fid = fopen(filename, 'a');   % open for append, create if necessary
if fid < 0
    errordlg(['could not open ',filedir,filename]);
    soundsc(sin(0:.5:1000*pi));
    return
end
file      = file_name;
datetimestring = datestr(date_time,'dd-mmm-yyyy HH:MM:SS');
var       = get(handles.text_y_units,'string');
value = get(handles.pushbutton_savevals,'UserData');
fprintf(fid,'%s\t%s\t%s\t%5.3f\r', ...
       file, datetimestring, var, value);
fclose(fid);

% --------------------------------------------------------------------
function varargout = Print_menu_Callback(h, eventdata, handles, varargin)
print 

% --------------------------------------------------------------------
function varargout = Print_no_ui_Callback(h, eventdata, handles, varargin)
print -noui
% --------------------------------------------------------------------
function varargout = Print_dlg_setup_Callback(h, eventdata, handles, varargin)
printdlg('-setup',gcf);

% --------------------------------------------------------------------
function varargout = Save_eps_Callback(h, eventdata, handles, varargin)
% saves current figure as color EPS
file_name = get(handles.text_openfile,'String'); %returns the currently selected file_name string
filestring = [file_name,'.eps'];
eval(['print -depsc ',filestring]);
% --------------------------------------------------------------------
function varargout = Save_jpeg150_Callback(h, eventdata, handles, varargin)
% saves current figure as 150 dpi jpeg
file_name = get(handles.text_openfile,'String'); %returns the currently selected file_name string
filestring = [file_name,'.jpg'];
eval(['print -djpeg -r150 ',filestring]);
% --------------------------------------------------------------------
% --- Executes on button press in pushbutton_directory
function pushbutton_directory_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_dir1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if exist('anashowdir.mat','file')
    load('anashowdir.mat');
end
if exist('dir1','var')
    if ischar(dir1)
        if ~exist(dir1, 'dir')
            dir1 = '';
        end
    end
else
    dir1 = '';
end
dir1 = uigetdir(dir1, 'Choose directory');
save anashowdir dir1
set(gcbo,'string',dir1);
update_file_list(gcbo,handles);

% --------------------------------------------------------------------
function setdir(fig,handles)
if exist('anashowdir.mat','file')
    load('anashowdir.mat');
end
if exist('dir1','var')
    if ischar(dir1)
        if exist(dir1, 'dir')
            set(handles.pushbutton_directory,'string',dir1);
            update_file_list(fig,handles);
        end
    end
end