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

% Last Modified by GUIDE v2.5 12-Feb-2013 16:57:24

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

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

% Update handles structure
guidata(hObject, handles);

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

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


% --- Outputs from this function are returned to the command line.
function varargout = DrawGraphGUI_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 txtStart_Callback(hObject, eventdata, handles)
% hObject    handle to txtStart (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 txtStart as text
%        str2double(get(hObject,'String')) returns contents of txtStart as a double


% --- Executes during object creation, after setting all properties.
function txtStart_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtStart (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 txtEnd_Callback(hObject, eventdata, handles)
% hObject    handle to txtEnd (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 txtEnd as text
%        str2double(get(hObject,'String')) returns contents of txtEnd as a double


% --- Executes during object creation, after setting all properties.
function txtEnd_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtEnd (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 txtNOP_Callback(hObject, eventdata, handles)
% hObject    handle to txtNOP (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 txtNOP as text
%        str2double(get(hObject,'String')) returns contents of txtNOP as a double


% --- Executes during object creation, after setting all properties.
function txtNOP_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtNOP (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 btnStart.
function btnStart_Callback(hObject, eventdata, handles)
% disable START button
set(handles.btnStart,'Enable','off');
% enable STOP button
set(handles.btnStop,'Enable','on'); 


warning off;

try
    
global APP_RUN;
APP_RUN = true;

% get start point
startPoint = get(handles.txtStart, 'string');
startPoint = str2double(char(startPoint));

% get end point
endPoint = get(handles.txtEnd, 'string');
endPoint = str2double(char(endPoint));

% get number of points
NoP = get(handles.txtNOP, 'string');
NoP = str2double(char(NoP));

% get function name
cusFunction = get(handles.txtFunction, 'string');
cusFunction = char(cusFunction);



% call DrawGraph function
DrawGraph(startPoint, endPoint, NoP, cusFunction, handles);
catch err
    
end

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



% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over btnStart.
function btnStart_ButtonDownFcn(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)
 

    
    
    


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


% --- Executes during object creation, after setting all properties.
function txtFunction_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtFunction (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 btnStop.
function btnStop_Callback(hObject, eventdata, handles)
global APP_RUN;
APP_RUN = false;


% --- EXIT APPLICATION -----%
function btnExit_Callback(hObject, eventdata, handles)

    % 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











function DrawGraph(XStart, XEnd, NumberOfPoints, cusFunction, handles)

% validate the input parameters
status = CONDORMATLAB.MLCheckInput(XStart, XEnd, NumberOfPoints, cusFunction, handles);
if(status == 1)
    return;
end

% initialize important global parameters
status = CONDORMATLAB.MLInitGlobalParams_DrawGraph(NumberOfPoints, handles);
if(status == 1)
    return;
end

% 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;
status = CONDORMATLAB.MLGenerateAppSettings(TOTAL_POINTS, MAX_POINT, CHECK_POINT, cusFunction, SETTING_FILE, FOLDER, handles);
if(status == 1)
    return;
end

% generate application log files
[status, TOTAL_CHUNK] = CONDORMATLAB.MLGenerateAllLogFiles(TOTAL_POINTS, MAX_POINT, CHECK_POINT, XStart, XEnd, LOG_FILE, FOLDER, handles);
if(status == 1)
    return;
end
drawnow;
% submit chunk 1
CURRENT_CHUNK = 1;
[status, newJobList, logPos] = CONDORMATLAB.CDSubmitJobsInChunk(CURRENT_CHUNK, LOG_FILE, cusFunction, FOLDER, handles);
if(status == 1)
    return;
end

JOB_LIST = newJobList;
LOG_LAST_POS(num2str(CURRENT_CHUNK)) = logPos;
CURRENT_CHUNK = CURRENT_CHUNK + 1;
% 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, submit new chunk
            if(CURRENT_CHUNK <= TOTAL_CHUNK)
                [status, newJobList, logPos] = CONDORMATLAB.CDSubmitJobsInChunk(CURRENT_CHUNK, LOG_FILE, cusFunction, 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: 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 "Start" to excute a new task, or "EXIT" to exit application.';
CONDORMATLAB.MLDisplayError(message, handles);



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