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

% Last Modified by GUIDE v2.5 17-Aug-2006 10:34:38

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @sens_analysis_OpeningFcn, ...
                   'gui_OutputFcn',  @sens_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 sens_analysis is made visible.
function sens_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 sens_analysis (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

init_gui(hObject, handles, nargin, varargin)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function init_gui(fig_handle, handles, nargin, varargin)
if nargin == 4
    set(handles.datafiletext, 'String', varargin{1}{1}.data_file)
    set(handles.outdirtext, 'String', varargin{1}{1}.analysis_dir)
    handles.data_dir = varargin{1}{1}.data_dir;
    handles.param_string = varargin{1}{1}.param_string;
    handles.pset_choice = varargin{1}{1}.pset_choice;
    handles.analysis_choice = varargin{1}{1}.analysis_choice;

   %   handles.analysis_dir = varargin{1}{1}.analysis_dir;
%   guidata(fig_handle, handles)
else
    error('Incorrect number of arguments to sens_analysis.m')
end

file_string = get(handles.datafiletext, 'String');

elf = findstr(file_string,'_eventlog_1');
pf = findstr(file_string,'_parsed_1');
df = findstr(file_string,'_data_1');
if ~isempty(pf)
    name_core = file_string(1:pf(1)-1);
    datafile_name = [name_core '_rundata.mat'];
elseif ~isempty(elf)
    name_core = file_string(1:elf(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

outfile_temp = [name_core '_bnsan'];
set(handles.outfileedit, 'String', outfile_temp)


datafile_wpath = fullfile(handles.data_dir, datafile_name);
if exist(datafile_wpath,'file')
    load(datafile_wpath, 'run_info', 'plot_info')
    handles.run_info = run_info;
%    guidata(fig_handle, handles)
else
    error([datafile_wpath ' does not exist.  If the data file choice was a parsed file, the corresponding _data_ file must also exist.'])
end

pset_num = str2num(handles.param_string);
pset = handles.run_info.param_sets(pset_num);

set(handles.perturbedname, 'String', pset.perturbed_param);

% find all parameter sets that are a part of this set_group
grpname = pset.set_group;
grplist = [];
for i = 1:length(run_info.param_sets)
    if strcmp(grpname,run_info.param_sets(i).set_group)
        grplist = [grplist i];
    end
end
handles.grplist = grplist;     

set(handles.setgrplist, 'String', num2str(grplist));

% calculate the percent change in the perturbed param for display
if length(grplist) > 2
    warning('The number of parameter sets found with the same set_group name when attempting a sensitivity analysis was greater than 2.  The first 2 will be used.')
end
if length(grplist) >= 2
    pset = run_info.param_sets(grplist(1));
    pertname = pset.perturbed_param;
    val1 = [];
    for i = 1:length(pset.newinitcmpds)
        if strcmp(pset.newinitcmpds(i).name,pertname)
            val1 = pset.newinitcmpds(i).val;
        end
    end
    for i = 1:length(pset.newrateparms)
        if strcmp(pset.newrateparms(i).name,pertname)
            val1 = pset.newrateparms(i).val;
        end
    end
    if isempty(val1)
        error('There is a problem with the parameter sets file.  The named perturbed_param does not have an altered value.');
    end
    pset = run_info.param_sets(grplist(2));
    val2 = [];
    for i = 1:length(pset.newinitcmpds)
        if strcmp(pset.newinitcmpds(i).name,pertname)
            val2 = pset.newinitcmpds(i).val;
        end
    end
    for i = 1:length(pset.newrateparms)
        if strcmp(pset.newrateparms(i).name,pertname)
            val2 = pset.newrateparms(i).val;
        end
    end
    if isempty(val2)
        error('There is a problem with the parameter sets file.  The named perturbed_param does not have an altered value.');
    end
    
    handles.val1 = val1;
    handles.val2 = val2;
    
    pertpercent = abs(val1 - val2) * 200 / (val1 + val2);
    
elseif length(grplist <2)
    error('The number of parameter sets found with the same set_group name when attempting a sensitivity analysis was less than 2.')
end

set(handles.perturbedpercent, 'String', num2str(pertpercent));

set(handles.simstarttext, 'String', run_info.time_start)
set(handles.avgstartedit, 'String', run_info.time_start)
set(handles.simendtext, 'String', run_info.time_end)
set(handles.avgendedit, 'String', run_info.time_end)


[temp,idxs] = sortrows(lower(plot_info.monitor_cmpds));
cmpdlist = plot_info.monitor_cmpds(idxs);
    
set(handles.cmpdavail, 'String', cmpdlist, 'Value', 1)

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

guidata(fig_handle, handles)

% --- Outputs from this function are returned to the command line.
function varargout = sens_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;



function avgstartedit_Callback(hObject, eventdata, handles)
% hObject    handle to avgstartedit (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 avgstartedit as text
%        str2double(get(hObject,'String')) returns contents of avgstartedit as a double
tempsval = str2num(get(handles.avgstartedit,'String'));
endval = str2num(get(handles.avgendedit,'String'));
if tempsval < handles.run_info.time_start
    set(handles.avgstartedit, 'String', handles.run_info.time_start)
elseif tempsval > endval
    set(handles.avgstartedit, 'String', endval)
end


% --- Executes during object creation, after setting all properties.
function avgstartedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to avgstartedit (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



function avgendedit_Callback(hObject, eventdata, handles)
% hObject    handle to avgendedit (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 avgendedit as text
%        str2double(get(hObject,'String')) returns contents of avgendedit as a double
tempeval = str2num(get(handles.avgendedit,'String'));
startval = str2num(get(handles.avgstartedit,'String'));
if tempeval > handles.run_info.time_end
    set(handles.avgendedit, 'String', handles.run_info.time_end)
elseif tempeval < startval
    set(handles.avgendedit, 'String', startval)
end


% --- Executes during object creation, after setting all properties.
function avgendedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to avgendedit (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


% --- Executes on selection change in cmpdavail.
function cmpdavail_Callback(hObject, eventdata, handles)
% hObject    handle to cmpdavail (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 cmpdavail contents as cell array
%        contents{get(hObject,'Value')} returns selected item from cmpdavail

if ~isempty(get(handles.cmpdavail,'String'))
    if strcmp(get(handles.figure1,'SelectionType'),'open')
        switch_cmpdlist(handles, 'cmpdavail', 'cmpdplot',0);
    end
    set(handles.gobutton, 'Enable', 'on');
end

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

% Hint: listbox 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 selection change in cmpdplot.
function cmpdplot_Callback(hObject, eventdata, handles)
% hObject    handle to cmpdplot (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 cmpdplot contents as cell array
%        contents{get(hObject,'Value')} returns selected item from cmpdplot

if ~isempty(get(handles.cmpdplot,'String'))
    if strcmp(get(handles.figure1,'SelectionType'),'open')
        switch_cmpdlist(handles, 'cmpdplot', 'cmpdavail',0);
    end
    if isempty(get(handles.cmpdplot,'String'))
        set(handles.gobutton, 'Enable', 'off');
    end
end

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

% Hint: listbox 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 addcmpdbutton.
function addcmpdbutton_Callback(hObject, eventdata, handles)
% hObject    handle to addcmpdbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if ~isempty(get(handles.cmpdavail,'String'))
    switch_cmpdlist(handles, 'cmpdavail', 'cmpdplot',0);
    set(handles.gobutton, 'Enable', 'on');
end

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

if ~isempty(get(handles.cmpdplot,'String'))
    switch_cmpdlist(handles, 'cmpdplot', 'cmpdavail',0);
    if isempty(get(handles.cmpdplot,'String'))
        set(handles.gobutton, 'Enable', 'off');
    end
end

function outfileedit_Callback(hObject, eventdata, handles)
% hObject    handle to outfileedit (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 outfileedit as text
%        str2double(get(hObject,'String')) returns contents of outfileedit as a double

outfile_temp = get(handles.outfileedit, 'String');
af = findstr(outfile_temp,'_bnsan');
if isempty(af)
    outfile_temp = [outfile_temp '_bnsan'];
end
set(handles.outfileedit, 'String', outfile_temp);


% --- Executes during object creation, after setting all properties.
function outfileedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to outfileedit (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

    

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function switch_cmpdlist(handles, oldlist, newlist, switchall)

old_hndl = eval(['handles.' oldlist]);
new_hndl = eval(['handles.' newlist]);

cmpdlist = get(old_hndl,'String');

if switchall
    cmpdlistn = get(new_hndl,'String');
    newval = get(new_hndl,'Val');
    cmpdlistn = [cmpdlistn;cmpdlist];
    [temp,idxs] = sortrows(lower(cmpdlistn));
    cmpdlistn = cmpdlistn(idxs);
    
    set(old_hndl, 'String',[],'Value',1);
    set(new_hndl, 'String',cmpdlistn,'Value',find(idxs == newval,1));
else

    cmpdsel = get(old_hndl, 'Value');
    cmpdstring = cmpdlist{cmpdsel};

    numplot = length(cmpdlist);
    if cmpdsel == 1
        keep = [2:numplot];
        newsel = 1;
    elseif cmpdsel == numplot
        keep = [1:numplot-1];
        newsel = numplot-1;
    else
        keep = [1:cmpdsel-1 cmpdsel+1:numplot];
        newsel = cmpdsel;
    end

    cmpdlist = cmpdlist(keep);

    set(old_hndl, 'String',cmpdlist);
    set(old_hndl, 'Value',newsel);

    cmpdlist = get(new_hndl,'String');
    newval = get(new_hndl,'Val');
    cmpdlist = [cmpdlist;{cmpdstring}];
    [temp,idxs] = sortrows(lower(cmpdlist));
    cmpdlist = cmpdlist(idxs);

    set(new_hndl, 'String',cmpdlist,'Value',find(idxs == newval,1));
end



% --- 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(handles.figure1)

% --- 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)
twa.data_file = get(handles.datafiletext, 'String');
twa.data_dir = handles.data_dir;
twa.analysis_dir = get(handles.outdirtext, 'String');
twa.pset_choice = handles.pset_choice;
twa.analysis_choice = handles.analysis_choice;
%twa.analysis_dir = handles.analysis_dir;

close(handles.figure1)
choose_single_analysis(twa)


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

twa.data_file = get(handles.datafiletext, 'String');
twa.data_dir = handles.data_dir;
twa.analysis_dir = get(handles.outdirtext, 'String');
twa.analysis_file = get(handles.outfileedit, 'String');
%twa.param_string = handles.param_string;
twa.cmpds = get(handles.cmpdplot, 'String');
twa.timestart = str2double(get(handles.avgstartedit, 'String'));
twa.timeend = str2double(get(handles.avgendedit, 'String'));
twa.grplist = handles.grplist;
twa.val1 = handles.val1;
twa.val2 = handles.val2;
twa.pertname = get(handles.perturbedname, 'String');
twa.plotfreq = get(handles.checkboxfreq, 'Value');

analysis_type = 'sens_calc';
write_analysis_parms (analysis_type,twa);
run_analysis;

% --- Executes on button press in addallcmpdbutton.
function addallcmpdbutton_Callback(hObject, eventdata, handles)
% hObject    handle to addallcmpdbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if ~isempty(get(handles.cmpdavail,'String'))
    switch_cmpdlist(handles, 'cmpdavail', 'cmpdplot',1);
    set(handles.gobutton, 'Enable', 'on');
end

% --- Executes on button press in removeallcmpdbutton.
function removeallcmpdbutton_Callback(hObject, eventdata, handles)
% hObject    handle to removeallcmpdbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if ~isempty(get(handles.cmpdplot,'String'))
    switch_cmpdlist(handles, 'cmpdplot', 'cmpdavail',1);
    set(handles.gobutton, 'Enable', 'off');
end

% --- Executes on button press in checkboxfreq.
function checkboxfreq_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxhist (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 checkboxhist



