function varargout = analyze_olddata(varargin)
%ANALYZE_OLDDATA M-file for analyze_olddata.fig
%      ANALYZE_OLDDATA, by itself, creates a new ANALYZE_OLDDATA or raises the existing
%      singleton*.
%
%      H = ANALYZE_OLDDATA returns the handle to a new ANALYZE_OLDDATA or the handle to
%      the existing singleton*.
%
%      ANALYZE_OLDDATA('Property','Value',...) creates a new ANALYZE_OLDDATA using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to analyze_olddata_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.
%
%      ANALYZE_OLDDATA('CALLBACK') and ANALYZE_OLDDATA('CALLBACK',hObject,...) call the
%      local function named CALLBACK in ANALYZE_OLDDATA.M with the given input
%      arguments.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help analyze_olddata

% Last Modified by GUIDE v2.5 14-Aug-2006 15:35:36

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @analyze_olddata_OpeningFcn, ...
                   'gui_OutputFcn',  @analyze_olddata_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before analyze_olddata is made visible.
function analyze_olddata_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

% Choose default command line output for analyze_olddata
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

init_gui(hObject, handles, nargin, varargin);

% UIWAIT makes analyze_olddata wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = analyze_olddata_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in exitbutton.
function exitbutton_Callback(hObject, eventdata, handles)
% hObject    handle to exitbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 
close(analyze_olddata)

% --- Executes on button press in backbutton.
function backbutton_Callback(hObject, eventdata, handles)
% hObject    handle to backbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

close(analyze_olddata)
bns_analysis

% --- Executes on button press in analyzebutton.
function analyzebutton_Callback(hObject, eventdata, handles)
% hObject    handle to analyzebutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

aod.data_dir = get(handles.directorytext,'String');
file_string_list = get(handles.choosedata_popup, 'String');
aod.data_file = file_string_list{get(handles.choosedata_popup, 'Value')};
aod.analysis_dir = get(handles.out_analysis_dir,'String');

close(handles.figure1)
choose_single_analysis(aod)

% --- Executes on button press in change_dir.
function change_dir_Callback(hObject, eventdata, handles)
% hObject    handle to change_dir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

old_dir = get(handles.directorytext,'String');
temp = choose_directory('create',old_dir);
set(handles.directorytext,'String', temp);
if ~strcmp(temp,old_dir)
    set(handles.savebutton,'Enable','on');
end
set(handles.out_analysis_dir,'String',temp);

guidata(handles.figure1, handles);
setup_data_files(handles.figure1, handles,[]);


% --- Executes on button press in change_out_dir.
function change_out_dir_Callback(hObject, eventdata, handles)
% hObject    handle to change_out_dir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

old_dir = get(handles.directorytext,'String');
old_analysis_dir = get(handles.out_analysis_dir,'String');
temp = choose_directory('create',old_dir);
set(handles.directorytext,'String', temp);
set(handles.out_analysis_dir,'String',temp);
if ~strcmp(old_dir,temp) | ~strcmp(temp,old_analysis_dir)
    set(handles.savebutton,'Enable','on');
end

guidata(handles.figure1, handles);
%setup_data_files(handles.figure1, handles);


% --- Executes on button press in savebutton.
function savebutton_Callback(hObject, eventdata, handles)
% hObject    handle to savebutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

code_dir = handles.code_dir;

temp_file = fullfile(code_dir,'temp_analysis');
def_file = fullfile(code_dir,'default_analysis_locations.m');

fid = fopen(temp_file,'w');
if fid == -1
    errordlg('Cannot open temp_analysis file','Open File Error!')
    return
end

data_dir = get(handles.directorytext,'String');
file_string_list = get(handles.choosedata_popup, 'String');
data_file = file_string_list{get(handles.choosedata_popup, 'Value')};
analysis_dir = get(handles.out_analysis_dir,'String');

fprintf(fid,'data_directory = ''%s''; \n', data_dir);
fprintf(fid,'data_file = ''%s''; \n',data_file);
fprintf(fid,'analysis_directory = ''%s''; \n',analysis_dir);

fclose(fid);
movefile(temp_file,def_file);

set(handles.savebutton,'Enable','off');

% --- Executes on button press in plotbutton.
function plotbutton_Callback(hObject, eventdata, handles)
% hObject    handle to plotbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

aod.data_dir = get(handles.directorytext,'String');
file_string_list = get(handles.choosedata_popup, 'String');
aod.data_file = file_string_list{get(handles.choosedata_popup, 'Value')};
aod.analysis_dir = get(handles.out_analysis_dir,'String');

%close(analyze_olddata)
close(handles.figure1)

if handles.psetexists
    choose_pset_for_plot(aod)
else
    aod.pset_choice = 1;
    aod.param_string = 'none';
    plot_from_data(aod);
end


% --- Executes on selection change in choosedata_popup.
function choosedata_popup_Callback(hObject, eventdata, handles)
% hObject    handle to choosedata_popup (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns choosedata_popup contents as cell array
%        contents{get(hObject,'Value')} returns selected item from choosedata_popup
set(handles.savebutton,'Enable','on');

evaluate_file_choice(handles.figure1, handles);


% --- Executes during object creation, after setting all properties.
function choosedata_popup_CreateFcn(hObject, eventdata, handles)
% hObject    handle to choosedata_popup (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%********************************************************************
%                   Other functions
%********************************************************************

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function init_gui(fig_handle, handles, nargin, varargin)

if nargin <= 3
    if exist('default_analysis_locations.m','file')
        default_analysis_locations
        data_dir = data_directory;
        if ~exist(data_dir,'dir')
            data_dir = pwd;
        end
        if ~exist(fullfile(data_dir,data_file),'file')
            data_file = [];
        end
        analysis_dir = analysis_directory;
        if ~exist(analysis_dir,'dir')
            analysis_dir = pwd;
        end
    elseif exist('default_directories.m','file')
        default_directories
        if isempty(output_directory)
            output_directory = 'output';
            data_dir = fullfile(models_dir,specific_model_dir,parameters_dir,output_directory);
        else
            data_dir = output_directory;
        end
        if ~exist(data_dir,'dir')
            data_dir = pwd;
        end
        data_file = [];
        analysis_dir = data_dir;
    else
        data_dir = pwd;
        analysis_dir = pwd;
        data_file = [];
    end
elseif nargin == 4
    data_dir = varargin{1}{1}.data_dir;
    data_file = varargin{1}{1}.data_file;
    analysis_dir = varargin{1}{1}.analysis_dir;
else
    error('Incorrect number of arguments passed to analyze_olddata');
end

set(handles.directorytext,'String',data_dir);
set(handles.out_analysis_dir,'String',analysis_dir);
set(handles.savebutton,'Enable','off');

handles.code_dir = pwd;
%handles.data_dir = data_dir;
%handles.data_file = data_file;
%handles.analysis_dir = analysis_dir;
guidata(fig_handle, handles);

setup_data_files(fig_handle, handles, data_file);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function setup_data_files(fig_handle, handles, data_file)

data_dir = get(handles.directorytext,'String');
%data_file = handles.data_file;
analysis_dir = get(handles.out_analysis_dir,'String');

% scan data_dir for valid data files
pf_list = dir(fullfile(data_dir,'*_parsed_1.mat'));
pf_list = struct2cell(pf_list);
pf_list = pf_list(1,:)';

df_list = dir(fullfile(data_dir,'*_data_1'));
df_list = struct2cell(df_list);
df_list = df_list(1,:)';

ef_list = [];
ef_list = dir(fullfile(data_dir,'*_eventlog_1'));
if isempty(ef_list)
    ef_list = dir(fullfile(data_dir,'*_eventlog_1_1'));
end
ef_list = struct2cell(ef_list);
ef_list = ef_list(1,:)';

% don't show event log files that have already been parsed
num_ef = length(ef_list);
keep_ef = [];
for i = 1:num_ef
    ef_loc = strfind(ef_list{i},'_eventlog_1');
    if ~isempty(ef_loc)
        ef_core = ef_list{i}(1:ef_loc(1)-1);
        lose = 0;
        for j = 1:length(pf_list)
            pf_loc = strfind(pf_list{j},'_parsed_1');
            if ~isempty(pf_loc)
                pf_core = pf_list{j}(1:pf_loc(1)-1);
                if strcmp(ef_core, pf_core)
                    lose = 1;
                    break
                end
            end
        end
        if lose == 0
            keep_ef = [keep_ef i];
        end
    end
end
ef_list = ef_list(keep_ef);

file_list = [pf_list; df_list; ef_list];
%handles.keep_ef = length(pf_list) + length(df_list) + keep_ef;

% populate the file pop-up menu
if  ~isempty(file_list)
    set(handles.choosedata_popup, 'Value', 1);
    set(handles.choosedata_popup, 'String', file_list);
    if ~isempty(data_file)      % pre-select named data_file if it exists
        for i = 1:length(file_list)
            if strcmpi(data_file,file_list{i})
                set(handles.choosedata_popup, 'Value', i);
                break;
            end
        end
    end
else
    set(handles.choosedata_popup, 'Value', 1);
    set(handles.choosedata_popup, 'String', {'No Valid Data Files'});
end

guidata(fig_handle, handles)

evaluate_file_choice(fig_handle, handles);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% activate correct buttons and show summary of file choice
function evaluate_file_choice(fig_handle, handles)
file_string_list = get(handles.choosedata_popup, 'String');
file_choice = get(handles.choosedata_popup, 'Value');
file_string = file_string_list{file_choice};
if strcmp(file_string, 'No Valid Data Files')
    set(handles.analyzebutton, 'Enable', 'off');
    set(handles.plotbutton, 'Enable', 'off');
else
    if ~isempty(findstr(file_string,'eventlog'))
        set(handles.analyzebutton, 'Enable', 'on');
       set(handles.plotbutton, 'Enable', 'on');
    else
        set(handles.analyzebutton, 'Enable', 'on');
        set(handles.plotbutton, 'Enable', 'on');
    end
end
guidata(fig_handle,handles)

show_file_summary(fig_handle, handles, file_string)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function show_file_summary(fig_handle, handles, file_string)
if strcmp(file_string, 'No Valid Data Files')
    set(handles.modeltext,'String','');
    set(handles.parametersetstext,'String','');
    set(handles.simtimestext,'String','');
    set(handles.paramdirtext,'String','');
    set(handles.numrunstext,'String','');
    set(handles.dateruntext,'String','');

    guidata(fig_handle,handles)
    return
end

data_dir = get(handles.directorytext,'String');

elf = findstr(file_string,'_eventlog_1');
pf = findstr(file_string,'_parsed_1');
df = findstr(file_string,'_data');
if ~isempty(elf)
    name_core = file_string(1:elf(1)-1);
    datafile_name = [name_core '_rundata.mat'];
elseif ~isempty(pf)
    name_core = file_string(1:pf(1)-1);
    datafile_name = [name_core '_rundata.mat'];
elseif ~isempty(df)
    name_core = file_string(1:df(1)-1);
    datafile_name = [name_core '_rundata.mat'];
end

if exist(fullfile(data_dir, datafile_name),'file')
    load(fullfile(data_dir, datafile_name), 'run_info', 'dir_info');
else
    error([fullfile(data_dir, datafile_name) ' does not exist.  If the data file choice was a parsed or eventlog file, the corresponding _data_ file must also exist.'])
end

[pathstr, name, ext, versn] = fileparts(dir_info.rxns_dir);
set(handles.modeltext,'String',name);

if ~isempty(dir_info.parameter_sets)
    [pathstr, name, ext, versn] = fileparts(dir_info.parameter_sets);
    set(handles.parametersetstext,'String',name);
else
    set(handles.parametersetstext,'String','none');
end

runtimes_text = [num2str(run_info.time_start) ' to ' num2str(run_info.time_end)];
set(handles.simtimestext,'String',runtimes_text);

[pathstr, name, ext, versn] = fileparts(dir_info.param_dir);
set(handles.paramdirtext,'String',name);

datafiles_thiscore = dir(fullfile(data_dir,[name_core '_data*']));
numruns_text = num2str(length(datafiles_thiscore));
set(handles.numrunstext,'String',numruns_text);

date_firstdatafile = datafiles_thiscore(1).date;
set(handles.dateruntext,'String',date_firstdatafile);

if length(run_info.param_sets) < 1
    handles.psetexists = 0;
else
    handles.psetexists = 1;
end

guidata(fig_handle,handles)
