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

% Last Modified by GUIDE v2.5 25-Mar-2013 15:15:21

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




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

% Update handles structure
guidata(hObject, handles);

% get all the CONDOR MATLAB folders
directories = dir('CDML*');
% add them to combo box
for i = 1: length(directories)
   dirName = directories(i).name;
   CONDORMATLAB.MLAddFolder(dirName, handles);
end

% disable STOP button
set(handles.btnStop,'Enable','off'); 

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


% --- Outputs from this function are returned to the command line.
function varargout = ResumeGraphGUI_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 selection change in lbJobActivities.
function lbJobActivities_Callback(hObject, eventdata, handles)
% hObject    handle to lbJobActivities (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns lbJobActivities contents as cell array
%        contents{get(hObject,'Value')} returns selected item from lbJobActivities


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

% Hints: contents = cellstr(get(hObject,'String')) returns lbUserActivities contents as cell array
%        contents{get(hObject,'Value')} returns selected item from lbUserActivities


% --- Executes during object creation, after setting all properties.
function lbUserActivities_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lbUserActivities (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 btnExit.
function btnExit_Callback(hObject, eventdata, handles)
% hObject    handle to btnExit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    % resume application?
    choice = questdlg('Do you want to exit the application?', 'Warning', 'Yes', 'No', 'Yes');
        switch choice
            case 'Yes'
                close all;
            case 'No'
                % do nothing
                return;
        end

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

% Hints: contents = cellstr(get(hObject,'String')) returns cbTask contents as cell array
%        contents{get(hObject,'Value')} returns selected item from cbTask


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

% disable button Start
set(handles.btnStart,'Enable','off') ;
% enable button Stop
set(handles.btnStop,'Enable','on'); 

warning off;
global APP_RUN;
APP_RUN = true;

try    

    % get selected folder
    selectedIndex = get(handles.cbTask, 'Value');
    allItems = get(handles.cbTask, 'String');
    selectedDir = allItems{selectedIndex};
    % initialize all global params
    CONDORMATLAB.MLInitGlobalParams_ResumeGraph(selectedDir, handles);
    % save application settings information
    global TOTAL_POINTS;
    global MAX_POINT;
    global CHECK_POINT;
    global SETTING_FILE;
    global LOG_FILE;
    global JOB_LIST;
    global LOG_LAST_POS;
    global RUNTIMES;
    global FOLDER;
    global FUNCTION;

    % calculate total chunk
    TOTAL_CHUNK = 1;
    if(TOTAL_POINTS > MAX_POINT)
        TOTAL_CHUNK = 1 + ceil((TOTAL_POINTS - MAX_POINT) /  CHECK_POINT);
    end
    CURRENT_CHUNK = 1;


    % if this is submitted chunk
    if(CONDORMATLAB.ML_IsSubmittedChunk(CURRENT_CHUNK, FOLDER) == 1)
        % resume chunk 1
        [status, newJobList, logPos] = CONDORMATLAB.CD_ResumeJobsInChunk(CURRENT_CHUNK, LOG_FILE, FOLDER, handles);
        if(status == 1)
            return;
        end
        JOB_LIST = newJobList;
        LOG_LAST_POS(num2str(CURRENT_CHUNK)) = logPos;
        CURRENT_CHUNK = CURRENT_CHUNK + 1;
    else
        % sumbmit chunk 1
        [status, newJobList, logPos] = CONDORMATLAB.CDSubmitJobsInChunk(CURRENT_CHUNK, LOG_FILE, FUNCTION, FOLDER, handles);
        if(status == 1)
            return;
        end
        JOB_LIST = newJobList;
        LOG_LAST_POS(num2str(CURRENT_CHUNK)) = logPos;
        CURRENT_CHUNK = CURRENT_CHUNK + 1;
    end


    % go to the loop
    RUNTIMES_INDEX = 1;
    TOTAL_SO_FAR = 0;

    % draw graph
    graphHandle = figure('name', 'Graph2D');
    hold on;

    while(true)
       global APP_RUN;
       if(APP_RUN == false)
           break;
       end
       message = ['Total complete jobs: ', num2str(TOTAL_SO_FAR)];
       CONDORMATLAB.MLAddJobActivity(message, handles);
       % check all the log files we have currently
       [status, JOB_LIST, LOG_LAST_POS, RUNTIMES, RUNTIMES_INDEX] = CONDORMATLAB.CDCheckLogFiles(JOB_LIST, LOG_LAST_POS, RUNTIMES, RUNTIMES_INDEX, FOLDER);
       % draw graph
       [status, TOTAL_SO_FAR, terminatedJobs] = CONDORMATLAB.MLDrawCurrentData(JOB_LIST, TOTAL_POINTS, TOTAL_SO_FAR, graphHandle);


       % log file and remove complete jobs from JOB_LIST
       [status, JOB_LIST] = CONDORMATLAB.MLUpdateLogFiles(terminatedJobs, JOB_LIST, LOG_FILE, FOLDER);
       % check if number of jobs in JOB_LIST < MAX_POINT - CHECK_POINT
            if(JOB_LIST.Count < MAX_POINT - CHECK_POINT)
            % if YES
                % if the current chunk is not the last chunk
                if(CURRENT_CHUNK <= TOTAL_CHUNK)
                    % if this is submitted chunk
                    if(CONDORMATLAB.ML_IsSubmittedChunk(CURRENT_CHUNK, FOLDER) == 1)
                        % resume this chunk
                        [status, newJobList, logPos] = CONDORMATLAB.CD_ResumeJobsInChunk(CURRENT_CHUNK, LOG_FILE, FOLDER, handles);
                        if(status == 1)
                            break;
                        end
                         % update job list
                        JOB_LIST = [JOB_LIST; newJobList];
                        % update position in log file
                        LOG_LAST_POS(num2str(CURRENT_CHUNK)) = logPos;
                        CURRENT_CHUNK = CURRENT_CHUNK + 1;
                    else
                        % submit new chunk
                        [status, newJobList, logPos] = CONDORMATLAB.CDSubmitJobsInChunk(CURRENT_CHUNK, LOG_FILE, FUNCTION, FOLDER, handles);
                        if(status == 1)
                            break;
                        end

                        % update job list
                        JOB_LIST = [JOB_LIST; newJobList];
                        % update position in log file
                        LOG_LAST_POS(num2str(CURRENT_CHUNK)) = logPos;
                        CURRENT_CHUNK = CURRENT_CHUNK + 1;
                    end

                % else: if the number of jobs in JOB_LIST == 0, then finish the
                % while loop.
                else
                    if(JOB_LIST.Count == 0)
                        break;
                    end
                end
            end
            % if NO
                % do nothing 
       % pause the application a period of time (maybe 30s)
       pause(10);
    end




    message = ['Total complete jobs: ', num2str(TOTAL_SO_FAR)];
    CONDORMATLAB.MLAddJobActivity(message, handles);
    % display histogram
    CONDORMATLAB.MLDrawCompleteJobHistogram(RUNTIMES, RUNTIMES_INDEX, handles);
    % display statistical information
    CONDORMATLAB.MLDisplayInformation(TOTAL_CHUNK, LOG_FILE, FOLDER, handles);
    message = 'Done.';
    CONDORMATLAB.MLAddUserActivity(message, handles);
    message = 'Click on "Resume" to resume a task, or "EXIT" to exit application.';
    CONDORMATLAB.MLDisplayError(message, handles);

catch err
    
end
    
% disable button Start
set(handles.btnStart,'Enable','on') ;
% enable button Stop
set(handles.btnStop,'Enable','off'); 




% --- Executes on button press in btnStop.
function btnStop_Callback(hObject, eventdata, handles)
% hObject    handle to btnStop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global APP_RUN;
APP_RUN = false;
