function varargout = view_old_analysis(varargin)
% VIEW_OLD_ANALYSIS M-file for view_old_analysis.fig
%      VIEW_OLD_ANALYSIS, by itself, creates a new VIEW_OLD_ANALYSIS or raises the existing
%      singleton*.
%
%      H = VIEW_OLD_ANALYSIS returns the handle to a new VIEW_OLD_ANALYSIS or the handle to
%      the existing singleton*.
%
%      VIEW_OLD_ANALYSIS('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in VIEW_OLD_ANALYSIS.M with the given input arguments.
%
%      VIEW_OLD_ANALYSIS('Property','Value',...) creates a new VIEW_OLD_ANALYSIS or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before view_old_analysis_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to view_old_analysis_OpeningFcn via varargin.
%
%      *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 view_old_analysis

% Last Modified by GUIDE v2.5 17-Aug-2006 09:08:14

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @view_old_analysis_OpeningFcn, ...
                   'gui_OutputFcn',  @view_old_analysis_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 view_old_analysis is made visible.
function view_old_analysis_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   command line arguments to view_old_analysis (see VARARGIN)

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


%guidata(handles.figure1, handles);

% Update handles structure
guidata(hObject, handles);

init_gui(hObject, handles, nargin, varargin);

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


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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 view_old_analysis');
end

set(handles.directorytext,'String',data_dir);
set(handles.out_analysis_dir,'String',analysis_dir);
set(handles.editoutstub,'String','bns_')

handles.code_dir = pwd;

handles.closefigs = 0;

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');
analysis_dir = get(handles.out_analysis_dir,'String');

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

file_list = af_list;

% populate the file pop-up menu
if  ~isempty(file_list)
    set(handles.choosedata_popup, 'Value', 1);
    set(handles.choosedata_popup, 'String', file_list);
else
    set(handles.choosedata_popup, 'Value', 1);
    set(handles.choosedata_popup, 'String', {'No Valid Analysis 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 Analysis Files')
    set(handles.analyzebutton, 'Enable', 'off');
else
    set(handles.analyzebutton, 'Enable', 'on');
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 Analysis Files')
    set(handles.modeltext,'String','');
    set(handles.parametersetstext,'String','');
    set(handles.simtimestext,'String','');
    set(handles.paramdirtext,'String','');
    set(handles.text_analysistype,'String','');

    guidata(fig_handle,handles)
    return
end

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

if exist(fullfile(data_dir, file_string),'file')
    load(fullfile(data_dir, file_string), 'pstruc')
    run_info = pstruc.run_info;
    dir_info = pstruc.dir_info;
else
    error([fullfile(data_dir, file_string) ' does not exist in view_old_analysis.'])
end

set(handles.text_analysistype,'String',pstruc.analysis_type);

[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);


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

guidata(fig_handle,handles)


% --- Outputs from this function are returned to the command line.
function varargout = view_old_analysis_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(view_old_analysis)

% --- 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(view_old_analysis)
bns_analysis


% --- 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');
%old_file_string_list = get(handles.choosedata_popup, 'String');
%old_file_string = old_file_string_list{get(handles.choosedata_popup, 'Value')};
temp = choose_directory('create',old_dir);
set(handles.directorytext,'String', temp);
set(handles.out_analysis_dir,'String',temp);

guidata(handles.figure1, handles);
%setup_data_files(handles.figure1, handles,old_file_string);
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.out_analysis_dir,'String');
temp = choose_directory('create',old_dir);
set(handles.out_analysis_dir,'String',temp);

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


% --- 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)
file_string_list = get(handles.choosedata_popup, 'String');
file_choice = get(handles.choosedata_popup, 'Value');
file_string = file_string_list{file_choice};
analysis_dir = get(handles.out_analysis_dir,'String');
data_dir = get(handles.directorytext,'String');

if exist(fullfile(data_dir, file_string),'file')
    load(fullfile(data_dir, file_string), 'pstruc')
else
    error([fullfile(data_dir, file_string) ' does not exist in view_old_analysis.'])
end

oldfiglist = findobj(0,'-depth',1);

if strcmp(pstruc.analysis_type,'average')
    plot_twa(pstruc)
elseif strcmp(pstruc.analysis_type,'sensitivity')
    plot_sens(pstruc)
elseif strcmp(pstruc.analysis_type,'reaction frequency')
    plot_reaction_freq(pstruc)
elseif strcmp(pstruc.analysis_type,'cmpds plot')
    af_list = dir(fullfile(data_dir,'*.fig'));
    af_list = struct2cell(af_list);
    af_list = af_list(1,:)';
 
    for i=1 : size(af_list,1)
        file = fullfile(data_dir, af_list{i,:});
        open(file)
    end
end

newfiglist = findobj(0,'-depth',1);

newfigs = setxor(oldfiglist,newfiglist);


stubstr = get(handles.editoutstub,'String');
for i = 1:length(newfigs)
    set(0,'CurrentFigure',newfigs(i));
    hax = findobj(gca,'Type','Line');
    if ~isempty(hax)
        for j = 1:length(hax)
            xd = [];
            xd(:,1) = get(hax(j),'XData')';
            xd(:,2) = get(hax(j),'YData')';
%            savefilestr = [stubstr 'figure' num2str(newfigs(i)) '_plot' num2str(j) '.txt'];
%            savefile = fullfile(analysis_dir,savefilestr);
%            save(savefile,'xd','-ascii', '-double')
        end
    end



    hax = findobj(gca,'Type','Patch');
    if ~isempty(hax)
        for j = 1:length(hax)
            xd = [];
            xdt = get(hax(j),'XData');
            ydt = get(hax(j),'YData');
            for k = 1:size(xdt,2)
                xd(k,1) = mean(xdt(2:3,k));
                xd(k,2) = ydt(2,k);
            end
%            savefilestr = [stubstr 'figure' num2str(newfigs(i)) '_plot' num2str(j) '.txt'];
%            savefile = fullfile(analysis_dir,savefilestr);
%            save(savefile,'xd','-ascii', '-double')
        end
    end
end
    

%close(handles.figure1)
%choose_single_analysis(aod)



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

%file_choice = get(handles.choosedata_popup, 'Value');
%evaluate_file_choice(handles.figure1, handles, file_choice);


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


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

handles.closefigs = 1;
guidata(handles.figure1, handles);

close all

handles.closefigs = 0;
guidata(handles.figure1, handles);


% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure

if ~handles.closefigs
    delete(hObject);
end


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

% Hint: get(hObject,'Value') returns toggle state of saveraw_checkbox


function editoutstub_Callback(hObject, eventdata, handles)
% hObject    handle to editoutstub (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editoutstub as text
%        str2double(get(hObject,'String')) returns contents of editoutstub as a double


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

% Hint: edit 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


