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

% Last Modified by GUIDE v2.5 30-Aug-2007 09:10:12

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

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

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes plot_from_data 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)
    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 plot_from_data.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');
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 '_analysis'];
%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


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)

if length(run_info.param_sets) < 1
    numruns = run_info.num_runs;
else
    pset = run_info.param_sets(handles.pset_choice);
    numruns = pset.numruns;
end
set(handles.firstruntext, 'String', '1')
set(handles.firstrunedit, 'String', '1')
set(handles.lastruntext, 'String', num2str(numruns))
set(handles.lastrunedit, 'String', num2str(numruns))


[temp,idxs] = sortrows(lower(plot_info.monitor_cmpds));
handles.cmpdlist = plot_info.monitor_cmpds(idxs);
numcmpds = length(handles.cmpdlist);

handles.calist = [];
handles.cplist = [];

% initialize with plot_info plot groupings if available
if isfield(plot_info,'plot_cmpds') && ~isempty(plot_info.plot_cmpds)
    numfigs = length(plot_info.plot_cmpds);
    fig_num = 0;
    for i = 1:numfigs
        if ~isempty(plot_info.plot_cmpds{i})
            move_cmpd = [];
            numcmpds_thisplot = length(plot_info.plot_cmpds{i});
            for j = 1:numcmpds_thisplot
                idx_cmpd = find(strcmp(handles.cmpdlist,plot_info.plot_cmpds{i}(j)));
                if ~isempty(idx_cmpd)
                    move_cmpd = [move_cmpd idx_cmpd];
                end
            end
            if ~isempty(move_cmpd)
                fig_num = fig_num + 1;
                fig_list{fig_num} = num2str(fig_num);
                keep = [1:numcmpds];
                keep(move_cmpd) = [];
                handles.calist{fig_num} = handles.cmpdlist(keep);
                handles.cplist{fig_num} = handles.cmpdlist(move_cmpd);
            end
            
        end
    end
    fig_list{fig_num+1} = num2str(fig_num+1);
    set(handles.fignumpopup, 'Value', 1);
    set(handles.fignumpopup, 'String', fig_list);
    handles.calist{fig_num+1} = handles.cmpdlist;
    handles.cplist{fig_num+1} = [];
    set(handles.cmpdavail, 'String', handles.calist{1}, 'Value', 1)
    set(handles.cmpdplot, 'String', handles.cplist{1}, 'Value', 1)

%    handles.lastfig = 1;
    
    if fig_num > 0
        handles.grouping_choice = 1;
        set(handles.fignumpopup,'Enable','on');
%        set(handles.radiosepfigs,'Value',0);
        set(handles.radiogrpplots,'Value',1);
        set(handles.gobutton, 'Enable', 'on');
        set(handles.button_runbatch, 'Enable', 'on');
    else
%        set(handles.cmpdavail, 'String', handles.cmpdlist, 'Value', 1)
%        set(handles.cmpdplot, 'String', [], 'Value', 1)
        handles.grouping_choice = 0;
        set(handles.fignumpopup,'Enable','off');
        set(handles.gobutton, 'Enable', 'off');
        set(handles.button_runbatch, 'Enable', 'off');
    end
    
else
    fig_list{1} = '1';
    set(handles.fignumpopup, 'Value', 1);
    set(handles.fignumpopup, 'String', fig_list);
%    handles.lastfig = 1;
    set(handles.cmpdavail, 'String', handles.cmpdlist, 'Value', 1)

    handles.grouping_choice = 0;
    set(handles.fignumpopup,'Enable','off');
    set(handles.gobutton, 'Enable', 'off');
    set(handles.button_runbatch, 'Enable', 'off');
end

handles.lastfig = 1;

handles.closefigs = 0;


guidata(fig_handle, handles)

% --- Outputs from this function are returned to the command line.
function varargout = plot_from_data_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')
        if isempty(get(handles.cmpdplot,'String'))
            figlist = get(handles.fignumpopup,'String');
            numfigs = length(figlist);
%            figlist = [figlist;num2str(numfigs+1)];
            figlist{numfigs+1} = num2str(numfigs+1);
            set(handles.fignumpopup,'String',figlist);
            handles.calist{numfigs+1} = handles.cmpdlist;
            handles.cplist{numfigs+1} = [];
        end
        switch_cmpdlist(handles, 'cmpdavail', 'cmpdplot',0);
        handles.calist{handles.lastfig} = get(handles.cmpdavail,'String');
        handles.cplist{handles.lastfig} = get(handles.cmpdplot,'String');
        guidata(handles.figure1,handles);
        
        set(handles.gobutton, 'Enable', 'on');
        set(handles.button_runbatch, 'Enable', 'on');
    end
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);
        handles.calist{handles.lastfig} = get(handles.cmpdavail,'String');
        handles.cplist{handles.lastfig} = get(handles.cmpdplot,'String');
        guidata(handles.figure1,handles);
        if isempty(get(handles.cmpdplot,'String'))
            figlist = get(handles.fignumpopup,'String');
            numfigs = length(figlist);
            keep = [1:handles.lastfig-1 handles.lastfig+1:numfigs];
            handles.calist = handles.calist(keep);
            handles.cplist = handles.cplist(keep);
            if numfigs > 1
                figlist = figlist(1:numfigs-1);
                set(handles.fignumpopup,'String',figlist);
            end
            change_fignum(handles,numfigs-1)
        end
        if get(handles.fignumpopup, 'Value') == 1 & isempty(get(handles.cmpdplot, 'String'))
            set(handles.gobutton, 'Enable','off');
            set(handles.button_runbatch, 'Enable', 'off');
        end
    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'))
    if isempty(get(handles.cmpdplot,'String'))
        figlist = get(handles.fignumpopup,'String');
        numfigs = length(figlist);
%        figlist = [figlist;num2str(numfigs+1)];
            figlist{numfigs+1} = num2str(numfigs+1);
        set(handles.fignumpopup,'String',figlist);
        handles.calist{numfigs+1} = handles.cmpdlist;
        handles.cplist{numfigs+1} = [];
    end
    switch_cmpdlist(handles, 'cmpdavail', 'cmpdplot',0);
    handles.calist{handles.lastfig} = get(handles.cmpdavail,'String');
    handles.cplist{handles.lastfig} = get(handles.cmpdplot,'String');
    guidata(handles.figure1,handles);
    set(handles.gobutton, 'Enable', 'on');
    set(handles.button_runbatch, '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);
    handles.calist{handles.lastfig} = get(handles.cmpdavail,'String');
    handles.cplist{handles.lastfig} = get(handles.cmpdplot,'String');
    guidata(handles.figure1,handles);
    if isempty(get(handles.cmpdplot,'String'))
        figlist = get(handles.fignumpopup,'String');
        numfigs = length(figlist);
        keep = [1:handles.lastfig-1 handles.lastfig+1:numfigs];
        handles.calist = handles.calist(keep);
        handles.cplist = handles.cplist(keep);
        if numfigs > 1
            figlist = figlist(1:numfigs-1);
            set(handles.fignumpopup,'String',figlist);
        end
        change_fignum(handles,numfigs-1)

        if get(handles.fignumpopup, 'Value') == 1 & isempty(get(handles.cmpdplot, 'String'))
            set(handles.gobutton, 'Enable','off');
            set(handles.button_runbatch, 'Enable', 'off');
        end
        
    end
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));
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));
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.analysis_dir = handles.analysis_dir;
twa.pset_choice = handles.pset_choice;

close(handles.figure1)

if strcmp(handles.param_string,'none')
%    aod.analysis_dir = twa.analysis_dir;
    analyze_olddata(twa)
else
    choose_pset_for_plot(twa)
end


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

handles.use_batch = 0;
run(handles);
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'))
    if isempty(get(handles.cmpdplot,'String'))
        figlist = get(handles.fignumpopup,'String');
        numfigs = length(figlist);
%        figlist = [figlist;num2str(numfigs+1)];
            figlist{numfigs+1} = num2str(numfigs+1);
        set(handles.fignumpopup,'String',figlist);
        handles.calist{numfigs+1} = handles.cmpdlist;
        handles.cplist{numfigs+1} = [];
    end
    switch_cmpdlist(handles, 'cmpdavail', 'cmpdplot',1);
    handles.calist{handles.lastfig} = get(handles.cmpdavail,'String');
    handles.cplist{handles.lastfig} = get(handles.cmpdplot,'String');
    guidata(handles.figure1,handles);
    set(handles.gobutton, 'Enable', 'on');
    set(handles.button_runbatch, '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);
    handles.calist{handles.lastfig} = get(handles.cmpdavail,'String');
    handles.cplist{handles.lastfig} = get(handles.cmpdplot,'String');
    guidata(handles.figure1,handles);
    figlist = get(handles.fignumpopup,'String');
    numfigs = length(figlist);
    keep = [1:handles.lastfig-1 handles.lastfig+1:numfigs];
    handles.calist = handles.calist(keep);
    handles.cplist = handles.cplist(keep);
    if numfigs > 1
        figlist = figlist(1:numfigs-1);
        set(handles.fignumpopup,'String',figlist);
    end
    change_fignum(handles,numfigs-1)
    
    if get(handles.fignumpopup, 'Value') == 1 & isempty(get(handles.cmpdplot, 'String'))
        set(handles.gobutton, 'Enable','off');
        set(handles.button_runbatch, 'Enable', 'off');
    end
    
end

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


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

newfignum = get(handles.fignumpopup,'Value');
change_fignum(handles,newfignum)


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function change_fignum(handles, newfignum)


handles.lastfig = newfignum;

set(handles.cmpdavail,'String',handles.calist{handles.lastfig},'Value',1)
set(handles.cmpdplot,'String',handles.cplist{handles.lastfig},'Value',1)

set(handles.fignumpopup,'Value',newfignum);

guidata(handles.figure1, handles)

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

function firstrunedit_Callback(hObject, eventdata, handles)
% hObject    handle to firstrunedit (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 firstrunedit as text
%        str2double(get(hObject,'String')) returns contents of firstrunedit as a double
if str2num(get(handles.firstrunedit,'String')) < 1
    set(handles.firstrunedit, 'String', '1')
end
if str2num(get(handles.firstrunedit,'String')) > str2num(get(handles.lastruntext,'String'))
    set(handles.firstrunedit, 'String', get(handles.lastruntext,'String'))
    set(handles.lastrunedit, 'String', get(handles.lastruntext,'String'))
elseif str2num(get(handles.firstrunedit,'String')) > str2num(get(handles.lastrunedit,'String'))
    set(handles.lastrunedit, 'String', get(handles.firstrunedit,'String'))
end


% --- Executes during object creation, after setting all properties.
function firstrunedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to firstrunedit (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 lastrunedit_Callback(hObject, eventdata, handles)
% hObject    handle to lastrunedit (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 lastrunedit as text
%        str2double(get(hObject,'String')) returns contents of lastrunedit as a double
if str2num(get(handles.lastrunedit,'String')) > str2num(get(handles.lastruntext,'String'))
    set(handles.lastrunedit, 'String', get(handles.lastruntext,'String'))
end
if str2num(get(handles.lastrunedit,'String')) < 1
    set(handles.firstrunedit, 'String', '1')
    set(handles.lastrunedit, 'String', '1')
elseif str2num(get(handles.lastrunedit,'String')) < str2num(get(handles.firstrunedit,'String'))
    set(handles.firstrunedit, 'String', get(handles.lastrunedit,'String'))
end

% --- Executes during object creation, after setting all properties.
function lastrunedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lastrunedit (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 button press in clear_plots.
function clear_plots_Callback(hObject, eventdata, handles)
% hObject    handle to clear_plots (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.calist = [];
handles.cplist = [];

fig_list{1} = '1';
set(handles.fignumpopup, 'Value', 1);
set(handles.fignumpopup, 'String', fig_list);
handles.lastfig = 1;

set(handles.cmpdavail, 'String', handles.cmpdlist, 'Value', 1)
set(handles.cmpdplot, 'String', [], 'Value', 1)

handles.calist{1} = handles.cmpdlist;
handles.cplist{1} = [];

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

guidata(handles.figure1, handles);


% --- Executes on button press in closefigsbutton.
function closefigsbutton_Callback(hObject, eventdata, handles)
% hObject    handle to closefigsbutton (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 radiosepfigs.
function radiosepfigs_Callback(hObject, eventdata, handles)
% hObject    handle to radiosepfigs (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 radiosepfigs
        handles.grouping_choice = 0;
        set(handles.fignumpopup,'Enable','off');
        
        % clear the plot grouping info, but can keep the current selections
        % for plotting
        handles.calist = [];
        handles.cplist = [];
        handles.calist{1} = get(handles.cmpdavail,'String');
        handles.cplist{1} = get(handles.cmpdplot,'String');
        
        fig_list = [];
        fig_list{1} = '1';
        if ~isempty(get(handles.cmpdplot,'String'))
            fig_list{2} = '2';
            handles.calist{2} = handles.cmpdlist;
            handles.cplist{2} = [];
        end
        set(handles.fignumpopup, 'Value', 1);
        set(handles.fignumpopup, 'String', fig_list);
        handles.lastfig = 1;
        set(handles.radiogrpplots, 'Value', 0);
  
        guidata(handles.figure1, handles);


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

        handles.grouping_choice = 1;
        set(handles.fignumpopup,'Enable','on');
        set(handles.radiosepfigs, 'Value', 0);

        guidata(handles.figure1, handles);


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

%   save_defaults
code_dir = pwd;

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

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.checkboxsave, 'Value', 1);
handles.use_batch = 1;

    if ispc
        run(handles);
        run_analysis;
    else
        global BATCH
       GUI_batch_script;
       uiwait(GUI_batch_script);
       run(handles);
       batch_file = create_batch_analysis_LSF(BATCH);
       
       comm = ['bsub < ',batch_file, ' &'];
       system(comm);

    end
      warndlg(' Batch job has been submitted ...','Batch message');
      
      
% ******************************************************************
 function run(handles)

pfd.savefigs = get(handles.checkboxsave,'Value');
pfd.plotcmpds = handles.cplist;
pfd.cmpdgrp = handles.grouping_choice;
pfd.use_batch = handles.use_batch;

pfd.data_file = get(handles.datafiletext, 'String');
pfd.data_dir = handles.data_dir;
%twa.analysis_dir = get(handles.outdirtext, 'String');
pfd.analysis_dir = handles.analysis_dir;


%twa.analysis_file = get(handles.outfileedit, 'String');
pfd.param_string = handles.param_string;
%twa.cmpds = get(handles.cmpdplot, 'String');
pfd.timestart = str2double(get(handles.avgstartedit, 'String'));
pfd.timeend = str2double(get(handles.avgendedit, 'String'));
pfd.firstrun = str2double(get(handles.firstrunedit, 'String'));
pfd.lastrun = str2double(get(handles.lastrunedit, 'String'));

%make_time_plots(pfd);
analysis_type = 'make_time_plots';
write_analysis_parms (analysis_type,pfd);

        

