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

% Last Modified by GUIDE v2.5 27-Oct-2015 16:10:07
% We got to change the working directory.
% B = which('POP.m');
% B = B(1:end-5);
% cd(B);

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

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

% Print logos in the boxes
B = which('POP.m');
B = strsplit(B,'\POP.m');

% pwd
imshow([B{1},'.\Figures\logo_Imperial.png'],'parent',handles.logo_left);
imshow([B{1},'.\Figures\logo_TAMU.png'],'parent',handles.logo_right);
imshow([B{1},'.\Figures\ProblemFormulation.png'],'parent',handles.Solver_ProblemFormulation);
set(handles.Solver_ProblemFormulation,'xtick',[],'ytick',[])

% Define graphics-handles
handles.WelcomeScreen = {'Welcome_Initial','Solver_PushButton_Initial',...
    'Library_PushButton_Initial','Generator_PushButton_Initial'};

handles.SolverText = {'Solver_Top_Text','Solver_ProblemFormulation','Solver_Options',...
    'Solver_SolveProblem','Solver_ProblemSelection','Solver_ExportMFile',...
    'Solver_SelectedProblem_Info','Solver_PostProcessing_Text','Solver_Plotting','Solver_Display'};

handles.LibraryText = {'Library_Top_Text','Library_ProblemSelection',...
    'Library_ProblemSpecifications','Library_ProblemText','Library_ProblemFound',...
    'Library_mpLP','Library_mpQP','Library_mpMILP','Library_mpMIQP',...
    'Library_NumberParameters_Text','Library_NumberParameters',...
    'Library_NumberInequality_Text','Library_NumberInequality',...
    'Library_NumberCRs_Text','Library_NumberCRs',...
    'Library_NumberContinuous_Text','Library_NumberContinuous',...
    'Library_NumberBinary_Text','Library_NumberBinary',...
    'Library_ExportProblems','Library_ProblemStatistics','Library_TestSetSelection'};

handles.GeneratorText = {'Generator_Top_Text','Generator_ProblemClass',...
    'Generator_ProblemSize','Generator_GenerateProblem','Generator_ExportMFile',...
    'Generator_Options'};

% Update handles structure
guidata(hObject, handles);

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


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

list_fields = [handles.WelcomeScreen, handles.LibraryText, handles.GeneratorText];

for k = 1:length(list_fields)
    set(handles.(list_fields{k}),'Visible','Off');
end

for k = 1:length(handles.SolverText)
    set(handles.(handles.SolverText{k}),'Visible','On');
end
set(handles.Solver_ProblemFormulation,'Visible','Off');
set(handles.Solver_PostProcessing_Text,'Visible','Off');
set(handles.Solver_Plotting,'Visible','Off');
set(handles.Solver_Display,'Visible','Off');
set(findobj(handles.Solver_ProblemFormulation,'Type','image'), 'Visible', 'on')

% Get the contents of the workspace
Wspace = evalin('base','who');

Wspace = [{'Select problem from workspace';'---------------'}; Wspace];

% Give this content to the menu
set(handles.Solver_ProblemSelection,'String',Wspace);

guidata(hObject, handles);


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

list_fields = [handles.WelcomeScreen, handles.SolverText, handles.GeneratorText];

for k = 1:length(list_fields)
    set(handles.(list_fields{k}),'Visible','Off');
end
set(findobj(handles.Solver_ProblemFormulation,'Type','image'), 'Visible', 'off')

for k = 1:length(handles.LibraryText)
    set(handles.(handles.LibraryText{k}),'Visible','On');
end

handles = findProblemDynamicDisplay(hObject, handles);

% Define the problem set folders
B = which('POP.m');
B = strsplit(B,'\POP.m');
listing = dir([B{1},'\Library']);
entries = find([listing.('isdir')]==1);
entries([1,2]) = []; % These are . and ..

Wspace = {'Specify test set';'---------------';'all (default)'};

for k = 1:length(entries)
    Wspace = [Wspace;listing(entries(k)).name];
end

% Give this content to the menu
set(handles.Library_TestSetSelection,'String',Wspace);

guidata(hObject, handles);


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

list_fields = [handles.WelcomeScreen, handles.SolverText, handles.LibraryText];

for k = 1:length(list_fields)
    set(handles.(list_fields{k}),'Visible','Off');
end
set(findobj(handles.Solver_ProblemFormulation,'Type','image'), 'Visible', 'off')

for k = 1:length(handles.GeneratorText)
    set(handles.(handles.GeneratorText{k}),'Visible','On');
end
val_mpMILP = get(handles.Generator_mpMILP,'Value');
val_mpMIQP = get(handles.Generator_mpMILP,'Value');
if ~(val_mpMILP == 1 || val_mpMIQP == 1)
    lisi = {'Generator_BinarySize','Generator_Binary','Generator_ShiftY','Generator_BorderY'};
    for j = 1:length(lisi)
        set(handles.(lisi{j}),'Visible','Off');
    end
end
guidata(hObject, handles);


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

% Taken from MATLAB website
choice = questdlg('Got a problem or comment? Would like to contact us?', ...
    'Help', 'Open User Manual','Email us at paroc@tamu.edu','Visit paroc.tamu.edu','Open User Manual');

% Handle response
switch choice
    case 'Open User Manual'
        winopen('UserManual.pdf')
    case 'Email Us'
        web mailto:paroc@tamu.edu
    case 'Visit our website'
        web('http://paroc.tamu.edu','-browser')
end



% --------------------------------------------------------------------
function About_Menu_Callback(hObject, eventdata, handles)
% hObject    handle to About_Menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
B = which('POP.m');
B = strsplit(B,'\POP.m');
cdata = imread([B{1},'.\Figures\logo_PAROC.png']);
h = msgbox({'Version: 1.5','','This software is part of the PAROC software platform.',...
    'More information can be found at paroc.tamu.edu',...
    '','Developed in the group of Prof. Pistikopoulos by: Richard Oberdieck,',...
    'Nikolaos A. Diangelakis, Martina Wittmann-Hohlbein, Nikolaos A.',...
    'Bozinis, Maria M. Papathanasiou, Ioana Nascu, Muxin Sun,'...
    'Styliani Avraamidou, Efstratios N. Pistikopoulos'},...
    'About','custom',cdata);
set(h,'color','w');%it changes the backgrounde color to white;

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

Solver_Menu_Callback(hObject, eventdata, handles)


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

Library_Menu_Callback(hObject, eventdata, handles)


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

Generator_Menu_Callback(hObject, eventdata, handles)


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


% Generate appropriate option set
CreateOptionSet(handles);
B = which('POP.m');
B = strsplit(B,'\POP.m');
sv = cd;

if isempty(handles.Solver_ProblemClass)
    errordlg('Please specify a problem','No problem specified');
    guidata(hObject, handles);
    return
else
    val = get(handles.Solver_ProblemSelection,'Value');
    item = get(handles.Solver_ProblemSelection,'String');
    problem = evalin('base',item{val});
    
    try
        % Start the solver
        if length(handles.Solver_ProblemClass) == 6
            % Necessary if GAMS is used for MINLP, due to Syntax
            cd([B{1},'\Files']);
            [Solution,Time] = mpMIQP(problem);
            cd(sv);
            FeasibleSet = [];
        elseif length(handles.Solver_ProblemClass) == 4
            [Solution,Time,FeasibleSet] = mpQP(problem);
        else
            prompt = {'Enter name of the library:'};
            dlg_title = 'Name of the library';
            num_lines = 1;
            def = {'ProblemLibrary'};
            answer = inputdlg(prompt,dlg_title,num_lines,def);
            if isempty(answer)
                return
            end
            answer = answer{1};
            % Define the name of the problem folder. The size of x, y and t is
            % fixed
            strr = [answer,'_'];
            
            % Search through the directory to find the right index
            listing = dir([B{1},'\Library']);
            listing(1:2) = [];
            lcl = arrayfun(@(x) x.isdir == 1, listing);
            flter = arrayfun(@(x) x.name, listing(lcl), 'UniformOutput',false);
            index = 1 + sum(strncmp(flter,strr,length(strr)));
            ind = sprintf('%02d',index);
            
            strr = [strr,ind];
            mkdir([B{1},'Library\',strr]);
            cdd = cd;
            cd([B{1},'Library\',strr]);
            All_problem = problem;
            clear problem
            
            for t = 1:length(All_problem)
                if ~isfield(All_problem,'E') || isempty(All_problem(t).E)
                    if ~isfield(All_problem,'Q') || isempty(All_problem(t).Q) || ...
                            max(abs(All_problem(t).Q(:))) < 1e-2
                        Class = 'mpLP';
                    else
                        Class = 'mpQP';
                    end
                else
                    if ~isfield(All_problem,'Q') || isempty(All_problem(t).Q) || ...
                            max(abs(All_problem(t).Q(:))) < 1e-2
                        Class = 'mpMILP';
                    else
                        Class = 'mpMIQP';
                    end
                end
                
                len = length(Class);
                if len == 4
                    stri = [Class,'_',num2str(size(All_problem(t).F,2)),'x',...
                        num2str(size(All_problem(t).A,1)),'x',num2str(size(All_problem(t).A,2)),'x0x0_'];
                else
                    stri = [Class,'_',num2str(size(All_problem(t).F,2)),'x',...
                        num2str(size(All_problem(t).A,1)),'x',num2str(size(All_problem(t).A,2)),...
                        'x',num2str(size(All_problem(t).E,2)),'x0_'];
                end
                leno = length(stri);
                
                % Search through the directory to find the right index
                listing = dir;
                index = 1;
                for k = 1:(length(listing) - 2) % The first two entries are always . and ..
                    leng = fprintf(listing(k+2).name);
                    if leng >= leno && strcmp(listing(k+2).name(1:leno),stri);
                        index = index + 1;
                    end
                end
                
                ind = sprintf('%02d',index);
                stri = [stri,ind];
                problem = All_problem(t);
                clc
                
                save(stri,'problem');
            end
            
            LibraryGeneration([B{1},'\Library\',strr]);
            cd(cdd);
            msgbox('The library was successfully created.','Success');
            return
        end
        
    catch
        errordlg('The problem could not be solved, and an error occured. Please contact paroc@tamu.edu');
        guidata(hObject, handles);
        return
    end
end

if isempty(Solution)
    msgbox('The problem was infeasible','Success');
else
    
    clear Results
    Results.problem = problem;
    Results.Solution = Solution;
    Results.Time = Time;
    if ~isempty(FeasibleSet)
        Results.FeasibleSet = FeasibleSet;
    end
    
    % Export to workspace
    assignin('base','Results',Results);
    
    % Taken from MATLAB website
    choice = questdlg({'The problem was successfully solved, and the data is available in the workspace under ''Results''. The problem statistics are as follows:',...
        '----------------------------------------------',...
        ['Continuous variables: ',num2str(size(problem.A,2))],...
        ['Binary variables: ',num2str(size(problem.Q,1)-size(problem.A,2))],...
        ['Parameters: ',num2str(size(problem.F,2))],...
        ['Inequality Constraints: ',num2str(size(problem.A,1))],...
        ['Equality Constraints: ',num2str(size(problem.Aeq,1))],...
        ['Critical regions: ',num2str(length(Solution))],...
        ['Solution time: ',num2str(Time.Total),' s'],...
        '----------------------------------------------',...
        'Would you like to perform any post-processing steps?'}, ...
        'Post-Processing', 'Plotting','Display Solution','Save Problem and Solution','Plotting');
    
    % Handle response
    switch choice
        case 'Plotting'
            choice2 = questdlg('What plot-type would you like to display?', ...
                'Plotting', 'Critical Regions and Objective Function','Critical Regions','Objective Function',...
                'Critical Regions and Objective Function');
            
            if ~isempty(choice2)
                if size(Solution(1).CR.A,2) > 2
                    x = Chebyshev(Solution(1).CR.A,Solution(1).CR.b);
                    str = num2str(x(3:end)');
                    str_cmb = {'[NaN, NaN, ',str,']'};
                    fix = inputdlg('Indicate which parameters should be fixed:',...
                        'Fixing of parameters', [1 50],str_cmb);
                    tfixed = str2num(fix{:});
                else
                    tfixed = [NaN NaN];
                end
                
                switch choice2
                    case 'Critical Regions and Objective Function'
                        PlotSolution(Solution,tfixed');
                    case 'Critical Regions'
                        PlotSolution(Solution,tfixed','CR');
                    case 'Objective Function'
                        PlotSolution(Solution,tfixed','OBJ');
                end
            end
            
        case 'Display Solution'
            DisplaySolution(Solution);
        case 'Save Problem and Solution'
            strc = ['Problem_',item{val}];
            Data.Problem = problem;
            Data.Solution = Solution;
            Data.Solver = 'POP v1.5';
            Data.options = OptionSet;
            save(strc,'Data');
            str = ['The file was successfully stored under the name ''',strc,'.m'''];
            msgbox(str,'Success');
    end
end
% Get the contents of the workspace
Wspace = evalin('base','who');

Wspace = [{'Select problem from workspace';'---------------'}; Wspace];

% Give this content to the menu
set(handles.Solver_ProblemSelection,'String',Wspace);

guidata(hObject, handles);


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

valu = get(hObject,'Value');
lis = {'Solver_Tolerance','Solver_TimeMax','Solver_BigM','Solver_LPSolver',...
    'Solver_QPSolver','Solver_SaveProblem','Solver_GlobalSolver','Solver_Comparison',...
    'Solver_Progress'};
if valu == 1
    for k=1:length(lis)
        set(handles.(lis{k}),'Visible','Off');
    end
else
    for k=1:length(lis)
        set(handles.(lis{k}),'Visible','On');
    end
    
    if length(handles.Solver_ProblemClass) == 4
        set(handles.Solver_GlobalSolver,'Visible','Off');
        set(handles.Solver_Comparison,'Visible','Off');
        %         set(handles.Solver_Progress,'String',{'Progress Bar','------','Off','mpQP'});
    else
        %         set(handles.Solver_Progress,'String',{'Progress Bar','------','Off','mpQP','mpMIQP'});
    end
end

guidata(hObject, handles);



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


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


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


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


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


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


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


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


% --- Executes during object creation, after setting all properties.
function Solver_TimeMax_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Solver_TimeMax (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 Solver_LPSolver.
function Solver_LPSolver_Callback(hObject, eventdata, handles)
% hObject    handle to Solver_LPSolver (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 Solver_LPSolver contents as cell array
%        contents{get(hObject,'Value')} returns selected item from Solver_LPSolver


% --- Executes during object creation, after setting all properties.
function Solver_LPSolver_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Solver_LPSolver (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 selection change in Solver_QPSolver.
function Solver_QPSolver_Callback(hObject, eventdata, handles)
% hObject    handle to Solver_QPSolver (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 Solver_QPSolver contents as cell array
%        contents{get(hObject,'Value')} returns selected item from Solver_QPSolver


% --- Executes during object creation, after setting all properties.
function Solver_QPSolver_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Solver_QPSolver (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 selection change in Solver_GlobalSolver.
function Solver_GlobalSolver_Callback(hObject, eventdata, handles)
% hObject    handle to Solver_GlobalSolver (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 Solver_GlobalSolver contents as cell array
%        contents{get(hObject,'Value')} returns selected item from Solver_GlobalSolver


% --- Executes during object creation, after setting all properties.
function Solver_GlobalSolver_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Solver_GlobalSolver (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 selection change in Solver_mpMIQPSolver.
function Solver_mpMIQPSolver_Callback(hObject, eventdata, handles)
% hObject    handle to Solver_mpMIQPSolver (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 Solver_mpMIQPSolver contents as cell array
%        contents{get(hObject,'Value')} returns selected item from Solver_mpMIQPSolver


% --- Executes during object creation, after setting all properties.
function Solver_mpMIQPSolver_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Solver_mpMIQPSolver (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 selection change in Solver_UpperBound.
function Solver_UpperBound_Callback(hObject, eventdata, handles)
% hObject    handle to Solver_UpperBound (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 Solver_UpperBound contents as cell array
%        contents{get(hObject,'Value')} returns selected item from Solver_UpperBound


% --- Executes during object creation, after setting all properties.
function Solver_UpperBound_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Solver_UpperBound (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 selection change in Solver_Comparison.
function Solver_Comparison_Callback(hObject, eventdata, handles)
% hObject    handle to Solver_Comparison (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 Solver_Comparison contents as cell array
%        contents{get(hObject,'Value')} returns selected item from Solver_Comparison


% --- Executes during object creation, after setting all properties.
function Solver_Comparison_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Solver_Comparison (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 selection change in Solver_ProblemSelection.
function Solver_ProblemSelection_Callback(hObject, eventdata, handles)
% hObject    handle to Solver_ProblemSelection (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 Solver_ProblemSelection contents as cell array
%        contents{get(hObject,'Value')} returns selected item from Solver_ProblemSelection

% Get which problem was selected. If no valid one was selected
items = get(hObject,'String');
index_selected = get(hObject,'Value');
handles.Solver_ProblemClass = [];
set(handles.Solver_SolveProblem,'String','Solve Problem');
set(handles.Solver_ExportMFile,'Visible','On');
B = which('POP.m');
B = strsplit(B,'\POP.m');

% The first two entries are only decoration
if index_selected > 2
    item_selected = items{index_selected};
    mpPProblem = evalin('base',item_selected);
    
    lis_check = {'A','b','F','CRA','CRb'};
    handles.ValidProblem = true;
    if ~isstruct(mpPProblem)
        set(handles.Solver_SelectedProblem_Info,'String','Not a struct, please select an appropriate problem');
        handles.ValidProblem = false;
        imshow([B{1},'\Figures\ProblemFormulation.png'],'parent',handles.Solver_ProblemFormulation);
        set(handles.Solver_SolveProblem,'Visible','On');
        set(handles.Solver_ExportMFile,'Visible','On');
        set(handles.Solver_Options,'Visible','On');
        set(handles.Solver_PostProcessing_Text,'Visible','Off');
        set(handles.Solver_Plotting,'Visible','Off');
        set(handles.Solver_Display,'Visible','Off');
    else
        if isfield(mpPProblem,'Solution')
            if  ~isfield(mpPProblem,'CR') && isfield(mpPProblem,'problem')
                mpPProblem = mpPProblem.Solution;
            end
            str = 'You have selected the solution to a mp-P problem';
            set(handles.Solver_SelectedProblem_Info,'String',str);
            set(handles.Solver_SolveProblem,'Visible','Off');
            set(handles.Solver_ExportMFile,'Visible','Off');
            set(handles.Solver_Options,'Visible','Off');
            set(handles.Solver_PostProcessing_Text,'Visible','On');
            set(handles.Solver_Plotting,'Visible','On');
            set(handles.Solver_Display,'Visible','On');
            
            % Output stats
            message = sprintf('----------------------------------------------\n');
            message = sprintf('%sNumber of Parameters: %d\n',message,size(mpPProblem(1).CR.A,2));
            message = sprintf('%sNumber of Continuous Variables: %d\n',message,size(mpPProblem(1).Solution.X,1));
            if isfield(mpPProblem,'Integer')
                message = sprintf('%sNumber of Binary Variables: %d\n',...
                    message,length(mpPProblem(1).Solution.Y));
            end
            message = sprintf('%sNumber of Critical Regions: %d\n',message,...
                length(mpPProblem));
            message = sprintf('%s----------------------------------------------\n',message);
            
            set(handles.Solver_PostProcessing_Text,'String',message);
            imshow([B{1},'\Figures\Solution-Example.png'],'parent',handles.Solver_ProblemFormulation);
            guidata(hObject, handles);
            return
        else
            set(handles.Solver_SolveProblem,'Visible','On');
            set(handles.Solver_ExportMFile,'Visible','On');
            set(handles.Solver_Options,'Visible','On');
            set(handles.Solver_PostProcessing_Text,'Visible','Off');
            set(handles.Solver_Plotting,'Visible','Off');
            set(handles.Solver_Display,'Visible','Off');
            
            for t = 1:length(lis_check)
                if ~isfield(mpPProblem,lis_check{t})
                    str = ['The field ''',lis_check{t},''' is missing from the problem formulation, please add!'];
                    set(handles.Solver_SelectedProblem_Info,'String',str);
                    handles.ValidProblem = false;
                    imshow([B{1},'.\Figures\ProblemFormulation.png'],'parent',handles.Solver_ProblemFormulation);
                    break
                end
            end
        end
    end
    
    if handles.ValidProblem
        if length(mpPProblem) > 1
            str = ['The currently selected problem is an array of ',num2str(length(mpPProblem)),' problems.'];
            set(handles.Solver_SelectedProblem_Info,'String',str);
            set(handles.Solver_SolveProblem,'String','Generate Problem Library');
            set(handles.Solver_ExportMFile,'Visible','Off');
            handles.Solver_ProblemClass = 'Array';
            imshow([B{1},'\Figures\ProblemFormulation.png'],'parent',handles.Solver_ProblemFormulation);
            guidata(hObject, handles);
            return
        end
        [mpPProblem,ok] = ProblemSet(mpPProblem);
        if ~ok
            set(handles.Solver_SelectedProblem_Info,'String','The problem formulation contains an error, please check.');
            handles.ValidProblem = false;
            imshow([B{1},'\Figures\ProblemFormulation.png'],'parent',handles.Solver_ProblemFormulation);
            set(handles.Solver_SolveProblem,'Visible','On');
            set(handles.Solver_ExportMFile,'Visible','On');
            set(handles.Solver_Options,'Visible','On');
            set(handles.Solver_PostProcessing_Text,'Visible','Off');
            set(handles.Solver_Plotting,'Visible','Off');
            set(handles.Solver_Display,'Visible','Off');
            return
        end
        
        if isfield(mpPProblem,'E')
            valu = get(handles.Solver_DefaultOptions,'Value');
            if valu == 0
                lis = {'Solver_GlobalSolver','Solver_Comparison'};
                for k=1:length(lis)
                    set(handles.(lis{k}),'Visible','On');
                end
            end
            if ~isfield(mpPProblem,'Q') || isempty(mpPProblem.Q) || ...
                    max(abs(mpPProblem.Q(:))) < 1e-4
                str = sprintf('The currently selected problem is a mp-MILP.\n');
                imshow([B{1},'\Figures\ProblemFormulation_mpMILP.png'],'parent',handles.Solver_ProblemFormulation);
                handles.Solver_ProblemClass = 'mpMILP';
            else
                str = sprintf('The currently selected problem is a mp-MIQP.\n');
                imshow([B{1},'\Figures\ProblemFormulation.png'],'parent',handles.Solver_ProblemFormulation);
                handles.Solver_ProblemClass = 'mpMIQP';
            end
        else
            lis = {'Solver_GlobalSolver','Solver_Comparison'};
            for k=1:length(lis)
                set(handles.(lis{k}),'Visible','Off');
            end
            
            if ~isfield(mpPProblem,'Q') || isempty(mpPProblem.Q) || ...
                    max(abs(mpPProblem.Q(:))) < 1e-4
                str = sprintf('The currently selected problem is a mp-LP.\n');
                imshow([B{1},'\Figures\ProblemFormulation_mpLP.png'],'parent',handles.Solver_ProblemFormulation);
                handles.Solver_ProblemClass = 'mpLP';
            else
                str = sprintf('The currently selected problem is a mp-QP.\n');
                imshow([B{1},'\Figures\ProblemFormulation_mpQP.png'],'parent',handles.Solver_ProblemFormulation);
                handles.Solver_ProblemClass = 'mpQP';
            end
        end
        % Output stats
        str = sprintf('%s\n',str);
        str = sprintf('%sNumber of Continuous Variables: %d\n',str,size(mpPProblem.A,2));
        if isfield(mpPProblem,'E')
            str = sprintf('%sNumber of Binary Variables: %d\n',...
                str,size(mpPProblem.A,2));
        end
        str = sprintf('%sNumber of Parameters: %d\n',str,size(mpPProblem.F,2));
        str = sprintf('%sNumber of Inequality Constraints: %d\n',str,size(mpPProblem.A,1));
        str = sprintf('%sNumber of Equality Constraints: %d\n',str,size(mpPProblem.Aeq,1));
        set(handles.Solver_SelectedProblem_Info,'String',str);
    end
else
    set(handles.Solver_SelectedProblem_Info,'String','Currently no problem selected');
    imshow([B{1},'\Figures\ProblemFormulation.png'],'parent',handles.Solver_ProblemFormulation);
end

guidata(hObject, handles);

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

% Get the contents of the workspace
Wspace = evalin('base','who');

Wspace = [{'Select problem from workspace';'---------------'}; Wspace];

% Give this content to the menu
set(hObject,'String',Wspace);
handles.Solver_ProblemClass = [];

guidata(hObject, handles);


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

B = which('POP.m');
B = strsplit(B,'\POP.m');

% Ask the user for a name
prompt = {'Enter name of .m file:'};
dlg_title = 'Name of .m file';
num_lines = 1;
def = {'Example'};
answer = inputdlg(prompt,dlg_title,num_lines,def);
if isempty(answer)
    return
end
answer = answer{1};

if ~strcmp(answer(end-1:end),'.m')
    answer = [answer,'.m'];
end

% Open the file
fid = fopen(answer,'w');

% Write the beginning
fprintf(fid,'%%==========================================================================\n');
fprintf(fid,['%% File Name     : <',answer,'>\n']);
fprintf(fid,'%% Description   : This file was automatically created by POP.\n');
fprintf(fid,'%%--------------------------------------------------------------------------\n');
fprintf(fid,'%% Author        : Richard Oberdieck, Nikolaos A. Diangelakis\n');
fprintf(fid,'%% Office        : Engineering Research Building, Texas A&M University\n');
fprintf(fid,'%% Mail          : paroc@tamu.edu\n');
fprintf(fid,'%%--------------------------------------------------------------------------\n');
fprintf(fid,'%% Generation date | Author  | Description\n');
fprintf(fid,'%%-----------------+---------+----------------------------------------------\n');
fprintf(fid,['%% ',date,'     | None    | Automatically generated version\n']);
fprintf(fid,'%%==========================================================================\n');
fprintf(fid,'\n');

% Add the correct path
fprintf(fid,['addpath(genpath(''',B{1},'.\Files''));\n']);
fprintf(fid,'\n');

% Load the problem
if isempty(handles.Solver_ProblemClass)
    fprintf(fid,'%% Please specify a problem using\n');
    fprintf(fid,'%% problem = ');
    msgbox('No problem has been specified, please add in the script manually.','Problem specification');
    fprintf(fid,'\n');
else
    val = get(handles.Solver_ProblemSelection,'Value');
    item = get(handles.Solver_ProblemSelection,'String');
    name = item{val};
    
    fprintf(fid, ['problem = ',name,';\n']);
    
    fprintf(fid,'\n');
    
    % Start the solver
    if length(handles.Solver_ProblemClass) == 6
        fprintf(fid,'Solution = mpMIQP(problem);\n');
    else
        fprintf(fid,'Solution = mpQP(problem);\n');
    end
end
fclose(fid);

CreateOptionSet(handles);

msgbox('File successfully created! The file ''OptionSet.m'' has been updated.','Export successful');


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


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

B = which('POP.m');
B = strsplit(B,'\POP.m');

handles = findProblemDynamicDisplay(hObject, handles);

% Ask the user for a name
prompt = {'Enter name of .mat file:'};
dlg_title = 'Name of .mat file';
num_lines = 1;
def = {'Problem Storage'};
answer = inputdlg(prompt,dlg_title,num_lines,def);
if isempty(answer)
    return
end
answer = answer{1};

if strcmp(answer(end-3:end),'.mat')
    answer(end-3:end) = [];
end


temp = handles.ProblemDirection;
if isempty(temp)
    warndlg('Please specify a problem','No problem specified');
    return
end
listing = fieldnames(temp);

% Initialization
store.problem = [];
store.stats = [];
count = 1;

for i = 1:length(listing)
    cll = temp.(listing{i});
    for k = 1:length(cll)
        % Load the problem
        str = [B{1},'\Library\',listing{i},'\',cll{k},'.mat'];
        data = load(str);
        
        % Store in store
        store(count).problem = data.problem;
        if isfield(data,'stats')
            store(count).stats = data.stats;
        else
            store(count).stats = 'Statistical information not available';
        end
        
        count = count + 1;
    end
end

save(answer,'store');
msgbox(['The problems have been successfully exported to ''',answer,'.mat'''],'Success');


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

handles = findProblemDynamicDisplay(hObject, handles);

% All the info is already here
temp = handles.ProblemStatistics;

% Check for all nonzero entries
test = all(temp == 0,1);
xdim = 5 - sum(test);

xlab = {'Number of Parameters','Number of Inequality Constraints',...
    'Number of Continuous Variables','Number of Binary Variables','Number of Critical Regions'};

figure
i = 1;

for t = 1:length(xlab)
    if sum(temp(~isnan(temp(:,t)),t)) > 0
        %          keyboard
        subplot(1,xdim,i)
        
        hist(temp(:,t));%,(max(temp(:,t)) - min(temp(:,t))));
        xlabel(xlab{t});
        ylabel('Count');
        i = i + 1;
    end
end
suptitle('Problem Statistics');

% Construct a questdlg with three options
choice = questdlg('Would you to export the problem statistic information?', ...
    'Export','Yes','No','No');
% Handle response
switch choice
    case 'Yes'
        % Ask the user for a name
        prompt = {'Enter name of .mat file:'};
        dlg_title = 'Name of .mat file';
        num_lines = 1;
        def = {'Problem Statistic Storage'};
        answer = inputdlg(prompt,dlg_title,num_lines,def);
        answer = answer{1};
        
        if strcmp(answer(end-3:end),'.mat')
            answer(end-3:end) = [];
        end
        
        save(answer,'temp');
        
        msgbox(['The problem statistics have been successfully exported to ''',answer,'.mat'''],'Success');
end



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

handles = findProblemDynamicDisplay(hObject, handles);

guidata(hObject, handles);


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

handles = findProblemDynamicDisplay(hObject, handles);

guidata(hObject, handles);


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

handles = findProblemDynamicDisplay(hObject, handles);

guidata(hObject, handles);


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

handles = findProblemDynamicDisplay(hObject, handles);

guidata(hObject, handles);



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

handles = findProblemDynamicDisplay(hObject, handles);

guidata(hObject, handles);


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

handles = findProblemDynamicDisplay(hObject, handles);

guidata(hObject, handles);


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

handles = findProblemDynamicDisplay(hObject, handles);

guidata(hObject, handles);


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

handles = findProblemDynamicDisplay(hObject, handles);

guidata(hObject, handles);


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

handles = findProblemDynamicDisplay(hObject, handles);

guidata(hObject, handles);


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

B = which('POP.m');
B = strsplit(B,'\POP.m');

problems = [];
if get(handles.Library_mpLP,'Value') == 1
    problems = [problems; {'mpLP'}];
end
if get(handles.Library_mpQP,'Value') == 1
    problems = [problems; {'mpQP'}];
end
if get(handles.Library_mpMILP,'Value') == 1
    problems = [problems; {'mpMILP'}];
end
if get(handles.Library_mpMIQP,'Value') == 1
    problems = [problems; {'mpMIQP'}];
end

if ~isempty(problems)
    % Stage one: the problem classes
    problem_class = char(problems);
    
    fields = {'Parameters','Inequality','Continuous','Binary','CRs'};
    list(length(fields)).val = [];
    for j = 1:length(fields)
        str = ['Library_Number',fields{j}];
        getit = str2num(get(handles.(str),'String'));
        list(j).val = getit;
    end
    
    % Detect the length of the entries of problem_class. This is needed for the
    % comparison later
    len = zeros(size(problem_class,1),1);
    for k = 1:size(problem_class,1)
        j = find(isspace(problem_class(k,:)),1);
        if isempty(j)
            len(k) = size(problem_class(k,:),2);
        else
            len(k) = j - 1;
        end
    end
    
    % As there might be different directories: we have to do this first
    valu_dir = get(handles.Library_TestSetSelection,'Value');
    
    % The first three entries denote 'all'. Note that dir_search is a cell with
    % multiple entries. Technically we could also enable the option of
    % selecting which directories to search in. But this is not the aim of this
    % one.
    if valu_dir <= 3
        item_dir = textscan(genpath([B{1},'\Library']),'%s','delimiter',';');
        dir_search = item_dir{1};
    else
        item_dir = get(handles.Library_TestSetSelection,'String');
        dir_search = item_dir(valu_dir);
        dir_search = {[B{1},'Library\',dir_search{1}]};
    end
    
    all_cand = [];
    all_Data = [];
    all_direc = [];
    
    for t = 1:length(dir_search)
        
        % Get the list of names, transform it into a cell. This is easier to
        % scroll through
        listing = dir(dir_search{t});
        candidates = cell(length(listing) - sum([listing.('isdir')]),1);
        Data = zeros(length(candidates),5); % To store the data for further evaluation
        
        entries = find([listing.('isdir')]==0);
        
        for k = 1:(length(listing) - sum([listing.('isdir')]))
            
            candidates{k} = listing(entries(k)).name;
            % Eliminate the ending
            candidates{k} = candidates{k}(1:(end-4));
            
            % In addition, extract the information about the number of parameters
            % etc. while we are at it. This is not very efficient (due to the
            % nested for-loop). But I am not sure how to do it in a more efficient
            % manner!
            for j = 1:size(problem_class,1)
                if strncmp(problem_class(j,:), candidates{k}, len(j));
                    val = num2str(len(j)+1);
                    str = ['%*',val,'c%f%*c%f%*c%f%*c%f%*c%f'];
                    
                    dat = sscanf(candidates{k},str);
                    if length(dat) == 4 || dat(5) == 0
                        dat(5) = NaN;
                    end
                    
                    Data(k,:) = dat';
                    break
                end
            end
        end
        
        % The general idea of the algorithm is to eliminate all the elements from
        % the candidate cell-array that are not fitting.
        
        %% Start with the problem class
        ind = [];
        for k = 1:size(problem_class,1)
            TF = strncmp(problem_class(k,:), candidates, len(k));
            if isempty(ind)
                ind = TF;
            else
                ind = bsxfun(@or, ind, TF);
            end
        end
        
        % Remove candidates that do not fit the profile
        candidates(~ind) = [];
        Data(~ind,:) = [];
        
        %% Check the numerical values
        % This assignment is done in order to be more efficient. Instead of writing
        % the same code for 4 different things (par, con, cv, bv), we just loop
        % through them, since at the end the operation we perform are always the
        % same.
        
        % The structure of the numerical values is always assumed to be [1xp
        % double]!
        
        for i = 1:length(list)
            % First check whether we should take that part into account
            if ~isempty(list(i).val)
                % Check whether they match somewhere
                ind = bsxfun(@eq, Data(:,i), list(i).val);
                
                % If they do (this is the reason for the 'any'), keep candidate
                ind = any(ind == 1,2);
                
                % Delete the parts that do not match
                candidates(~ind) = [];
                Data(~ind,:) = [];
            end
        end
        
        all_Data = [all_Data;Data];
        all_cand = [all_cand;candidates];
        
        if ~isempty(Data)
            C = strsplit(dir_search{t},'\');
            all_direc.(C{end}) = candidates;
        end
        
    end
    
    handles.ProblemDirection = all_direc;
    handles.ProblemStatistics = all_Data;
    set(handles.Library_ProblemFound,'String',all_cand);
else
    handles.ProblemDirection = [];
    handles.ProblemStatistics = [];
    set(handles.Library_ProblemFound,'String',[]);
end

guidata(hObject, handles);


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


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

valu = get(hObject,'Value');
lis = {'Generator_LowerBound','Generator_UpperBound','Generator_ConstraintFactor',...
    'Generator_RangeValue','Generator_BorderX','Generator_ShiftX','Generator_BorderY',...
    'Generator_ShiftY','Generator_ShiftTheta','Generator_BorderTheta','Generator_SaveProblem',...
    'Generator_LibraryGeneration'};

if valu == 1
    for k=1:length(lis)
        set(handles.(lis{k}),'Visible','Off');
    end
else
    for k=1:length(lis)
        set(handles.(lis{k}),'Visible','On');
    end
    
    % Understand which box is ticked
    
    val_mpMILP = get(handles.Generator_mpMILP,'Value');
    val_mpMIQP = get(handles.Generator_mpMILP,'Value');
    if ~(val_mpMILP == 1 || val_mpMIQP == 1)
        set(handles.Generator_BorderY,'Visible','Off');
        set(handles.Generator_ShiftY,'Visible','Off');
    end
end
guidata(hObject, handles);



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


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


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


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


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


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


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


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


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


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


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


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


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


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

% valu = get(hObject,'Value');
%
% if valu == 1
%     lis = {'Generator_mpQP','Generator_mpMIQP','Generator_mpMILP'};
%     for j = 1:length(lis)
%         set(handles.(lis{j}),'Value',0);
%     end
%     lisi = {'Generator_BinarySize','Generator_Binary'};
%     for j = 1:length(lisi)
%         set(handles.(lisi{j}),'Visible','Off');
%     end
%
%     vall = get(handles.Generator_DefaultOptions,'Value');
%     if vall == 0
%         set(handles.Generator_BorderY,'Visible','Off');
%         set(handles.Generator_ShiftY,'Visible','Off');
%     end
% end

% Update handles structure
guidata(hObject, handles);


% --- Executes on button press in Generator_mpQP.
function Generator_mpQP_Callback(hObject, eventdata, handles)
% hObject    handle to Generator_mpQP (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 Generator_mpQP
%
% valu = get(hObject,'Value');
%
% if valu == 1
%     lis = {'Generator_mpMIQP','Generator_mpMILP','Generator_mpLP'};
%     for j = 1:length(lis)
%         set(handles.(lis{j}),'Value',0);
%     end
%     lisi = {'Generator_BinarySize','Generator_Binary'};
%     for j = 1:length(lisi)
%         set(handles.(lisi{j}),'Visible','Off');
%     end
%
%     vall = get(handles.Generator_DefaultOptions,'Value');
%     if vall == 0
%         set(handles.Generator_BorderY,'Visible','Off');
%         set(handles.Generator_ShiftY,'Visible','Off');
%     end
% end

% Update handles structure
guidata(hObject, handles);


% --- Executes on button press in Generator_mpMILP.
function Generator_mpMILP_Callback(hObject, eventdata, handles)
% hObject    handle to Generator_mpMILP (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 Generator_mpMILP
%
valu = get(hObject,'Value');
val_mpMIQP = get(handles.Generator_mpMIQP,'Value');

if valu == 1 || val_mpMIQP == 1
    lisi = {'Generator_BinarySize','Generator_Binary'};
    for j = 1:length(lisi)
        set(handles.(lisi{j}),'Visible','On');
    end
    
    vall = get(handles.Generator_DefaultOptions,'Value');
    if vall == 0
        set(handles.Generator_BorderY,'Visible','On');
        set(handles.Generator_ShiftY,'Visible','On');
    end
else
    lisi = {'Generator_BinarySize','Generator_Binary'};
    for j = 1:length(lisi)
        set(handles.(lisi{j}),'Visible','Off');
    end
    
    vall = get(handles.Generator_DefaultOptions,'Value');
    if vall == 0
        set(handles.Generator_BorderY,'Visible','Off');
        set(handles.Generator_ShiftY,'Visible','Off');
    end
end

% Update handles structure
guidata(hObject, handles);


% --- Executes on button press in Generator_mpMIQP.
function Generator_mpMIQP_Callback(hObject, eventdata, handles)
% hObject    handle to Generator_mpMIQP (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 Generator_mpMIQP
%
valu = get(hObject,'Value');
val_mpMILP = get(handles.Generator_mpMILP,'Value');

if valu == 1 || val_mpMILP == 1
    lisi = {'Generator_BinarySize','Generator_Binary'};
    for j = 1:length(lisi)
        set(handles.(lisi{j}),'Visible','On');
    end
    
    vall = get(handles.Generator_DefaultOptions,'Value');
    if vall == 0
        set(handles.Generator_BorderY,'Visible','On');
        set(handles.Generator_ShiftY,'Visible','On');
    end
else
    lisi = {'Generator_BinarySize','Generator_Binary'};
    for j = 1:length(lisi)
        set(handles.(lisi{j}),'Visible','Off');
    end
    
    vall = get(handles.Generator_DefaultOptions,'Value');
    if vall == 0
        set(handles.Generator_BorderY,'Visible','Off');
        set(handles.Generator_ShiftY,'Visible','Off');
    end
end

% Update handles structure
guidata(hObject, handles);



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

B = which('POP.m');
B = strsplit(B,'\POP.m');

prompt = {'Enter name of variable name:'};
dlg_title = 'Name of variable name file';
num_lines = 1;
def = {'RandomProblem'};
answer = inputdlg(prompt,dlg_title,num_lines,def);
if isempty(answer)
    return
end
answer = answer{1};
if ~isvarname(answer)
    errordlg('Please specify a valid variable name','Invalid variable name');
    return
end

lis = {'Generator_mpLP','Generator_mpQP','Generator_mpMILP','Generator_mpMIQP'};
Class = [];
for i = 1:length(lis)
    visi = get(handles.(lis{i}),'Value');
    if visi == 1
        temp = lis{i};
        Class = [Class, {temp(11:end)}];
    end
end

temp = get(handles.Generator_Binary,'String');
temp_num = str2num(temp);
if ~isempty(temp_num)
    Size.y = temp_num;
end

temp = get(handles.Generator_Continuous,'String');
temp_num = str2num(temp);
if ~isempty(temp_num)
    Size.x = temp_num;
end

temp = get(handles.Generator_Parameters,'String');
temp_num = str2num(temp);
if ~isempty(temp_num)
    Size.t = temp_num;
end

% Specify the options
val = get(handles.Generator_DefaultOptions,'Value');

if ~exist('Size','var')
    Size = [];  % Everything is randomly generated
end

if val == 0
    lst = {'BorderTheta','BorderX','BorderY','LibraryGeneration'...
        'LowerBound','RangeValue','ShiftTheta','ShiftX','ShiftY','UpperBound'};
    List_Fields = {'TBorder','XBorder','YBorder','ProblemNumber',...
        'LowerBound','RangeValue','TShift','XShift','YShift','UpperBound'};
    
    options = struct;
    for i = 1:length(lst)
        temp = ['Generator_',lst{i}];
        valu = get(handles.(temp),'String');
        entry = str2double(valu);
        if ~isnan(entry)
            options.(List_Fields{i}) = entry;
        end
    end
    
    % Special cases for number of constraints and save button
    valu = get(handles.Generator_ConstraintFactor,'String');
    entry = str2num(valu);
    if ~isempty(entry)
        Size.m = entry;
    end
    
    val_save = get(handles.Generator_SaveProblem,'Value');
    if val_save == 1
        options.Save = 'On';
    end
    
    if ~exist('Size','var')
        Size = [];  % Everything is randomly generated
    end
    
    if isfield(options,'Save') && strcmp(options.Save,'On')
        problem = ProblemGenerator(Class,Size,options);
    else
        problem = ProblemGenerator(Class,Size,options);
    end
else
    problem = ProblemGenerator(Class,Size);
end

assignin('base',answer,problem)

msgbox(['The problem has been successfully created and is now available in the workspace with the name ''',answer,'''.'],'Success');


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

B = which('POP.m');
B = strsplit(B,'\POP.m');

lis = {'Generator_mpLP','Generator_mpQP','Generator_mpMILP','Generator_mpMIQP'};
Class = [];
for i = 1:length(lis)
    visi = get(handles.(lis{i}),'Value');
    if visi == 1
        temp = lis{i};
        Class = [Class, ', ''',temp(11:end),''''];
    end
end

% Ask the user for a name
prompt = {'Enter name of .m file:'};
dlg_title = 'Name of .m file';
num_lines = 1;
def = {'Example'};
answer = inputdlg(prompt,dlg_title,num_lines,def);
answer = answer{1};

if ~strcmp(answer(end-1:end),'.m')
    answer = [answer,'.m'];
end

% Open the file
fid = fopen(answer,'w');

% Write the beginning
fprintf(fid,'%%==========================================================================\n');
fprintf(fid,['%% File Name     : <',answer,'>\n']);
fprintf(fid,'%% Description   : This file was automatically created by POP.\n');
fprintf(fid,'%%--------------------------------------------------------------------------\n');
fprintf(fid,'%% Author        : Richard Oberdieck, Nikolaos A. Diangelakis\n');
fprintf(fid,'%% Office        : Engineering Research Building, Texas A&M University\n');
fprintf(fid,'%% Mail          : paroc@tamu.edu\n');
fprintf(fid,'%%--------------------------------------------------------------------------\n');
fprintf(fid,'%% Generation date | Author  | Description\n');
fprintf(fid,'%%-----------------+---------+----------------------------------------------\n');
fprintf(fid,['%% ',date,'     | None    | Automatically generated version\n']);
fprintf(fid,'%%==========================================================================\n');
fprintf(fid,'\n');

% Add the correct path
fprintf(fid,['addpath(genpath(''',B{1},'\Files''));\n']);
fprintf(fid,'\n');

if ~isempty(Class);
    if length(Class) == 1
        fprintf(fid,['Class = ''',Class,''';\n']);
    else
        fprintf(fid,['Class = ''{',Class,'};\n']);
    end
end

temp = get(handles.Generator_Binary,'String');
if ~isempty(str2num(temp))
    fprintf(fid,['Size.y = ',temp,';\n']);
end

temp = get(handles.Generator_Continuous,'String');
if ~isempty(str2num(temp))
    fprintf(fid,['Size.x = ',temp,';\n']);
end

temp = get(handles.Generator_Parameters,'String');
if ~isempty(str2num(temp))
    fprintf(fid,['Size.t = ',temp,';\n']);
end

% Specify the options
val = get(handles.Generator_DefaultOptions,'Value');

if val == 0
    
    % Special cases for number of constraints and save button
    valu = get(handles.Generator_ConstraintFactor,'String');
    if ~isempty(str2num(valu))
        fprintf(fid,['Size.m = ',valu,';\n']);
    end
    
    fprintf(fid,'\n');
    
    lst = {'BorderTheta','BorderX','BorderY','LowerBound','RangeValue',...
        'ShiftTheta','ShiftX','ShiftY','UpperBound'};
    List_Fields = {'TBorder','XBorder','YBorder','LowerBound','RangeValue',...
        'TShift','XShift','YShift','UpperBound'};
    
    for i = 1:length(lst)
        temp = ['Generator_',lst{i}];
        valu = get(handles.(temp),'String');
        entry = str2num(valu);
        if ~isnan(entry)
            fprintf(fid,['options.',List_Fields{i},' = ',valu,';\n']);
        end
    end
    
    val_save = get(handles.Generator_SaveProblem,'Value');
    if val_save == 1
        fprintf(fid,'options.Save = ''On'';\n');
    end
    
    fprintf(fid,'\n');
    fprintf(fid,'problem = ProblemGenerator(Class,Size,options);\n');
else
    fprintf(fid,'\n');
    fprintf(fid,'problem = ProblemGenerator(Class,Size);\n');
end

fclose(fid);

msgbox(['The file ''',answer,''' has been successfully created!'],'Success');



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

findProblemDynamicDisplay(hObject, handles);

guidata(hObject, handles);



% --- Executes during object creation, after setting all properties.
function Library_TestSetSelection_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Library_TestSetSelection (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
B = which('POP.m');
B = strsplit(B,'\POP.m');

% Get the contents of the workspace
listing = dir([B{1},'\Library']);
entries = find([listing.('isdir')]==1);
entries([1,2]) = []; % These are . and ..

Wspace = {'Specify test set';'---------------';'all (default)'};

for k = 1:length(entries)
    Wspace = [Wspace;listing(entries(k)).name];
end

% Give this content to the menu
set(hObject,'String',Wspace);

guidata(hObject, handles);

function CreateOptionSet(handles)

B = which('POP.m');
B = strsplit(B,'\POP.m');

valu = get(handles.Solver_DefaultOptions,'Value');
if valu == 1
    copyfile([B{1},'\Files\OptionSet_Default.m'],[B{1},'\Files\OptionSet.m']);
else
    fid = fopen([B{1},'\Files\OptionSet.m'],'w');
    
    % Write the beginning
    fprintf(fid,'%%==========================================================================\n');
    fprintf(fid,'%% File Name     : <OptionSet.m>\n');
    fprintf(fid,'%% Usage         : options = OptionSet\n');
    fprintf(fid,'%% Description   : This file was automatically created by POP.\n');
    fprintf(fid,'%% \n');
    fprintf(fid,'%% This function contains the options set when the problem was exported. If\n');
    fprintf(fid,'%% the user would like to change these options, he or she is kindly referred\n');
    fprintf(fid,'%% to the user manual, where all the options are listed.\n');
    fprintf(fid,'%%--------------------------------------------------------------------------\n');
    fprintf(fid,'%% Author        : Richard Oberdieck, Nikolaos A. Diangelakis\n');
    fprintf(fid,'%% Office        : Engineering Research Building, Texas A&M University\n');
    fprintf(fid,'%% Mail          : paroc@tamu.edu\n');
    fprintf(fid,'%%--------------------------------------------------------------------------\n');
    fprintf(fid,'%% Generation date | Author  | Description\n');
    fprintf(fid,'%%-----------------+---------+----------------------------------------------\n');
    fprintf(fid,['%% ',date,'     | None    | Automatically generated version\n']);
    fprintf(fid,'%%==========================================================================\n');
    fprintf(fid,'\n');
    fprintf(fid,'function options = OptionSet');
    fprintf(fid,'\n');
    
    % Get the default options
    options = OptionSet_Default;
    
    % LP Solver
    val = get(handles.Solver_LPSolver,'Value');
    str = get(handles.Solver_LPSolver,'String');
    if val > 2
        valu = str{val};
    else
        if exist('cplexlp','file')
            valu = 'CPLEX';
        else
            valu = 'MATLAB';
        end
    end
    valu = ['''',valu,''''];
    fprintf(fid,['options.LPSolver = ',valu,';\n']);
    fprintf(fid,['options.QPSolver = ',valu,';\n']);
    
    % QP Solver
    val = get(handles.Solver_QPSolver,'Value');
    str = get(handles.Solver_QPSolver,'String');
    if val > 2
        valu = str{val};
    else
        valu = 'Graph';
    end
    valu = ['''',valu,''''];
    fprintf(fid,['options.mpSolver = ',valu,';\n']);
    
    % Not part of options in GUI
    fprintf(fid,'options.SolutionStyle = ''full'';\n');
    
    % Tolerance
    val = get(handles.Solver_Tolerance,'String');
    entry = str2double(val);
    if isnan(entry)
        val = num2str(options.tolerance);
    end
    fprintf(fid,['options.tolerance = ',val,';\n']);
    
    % Not part of options in GUI
    fprintf(fid,'options.MinimalStep = 1000;\n');
    fprintf(fid,'options.Step = 10;\n');
    
    % Time Max
    val = get(handles.Solver_TimeMax,'String');
    entry = str2double(val);
    if isnan(entry)
        val = num2str(options.TimeMax);
    end
    fprintf(fid,['options.TimeMax = ',val,';\n']);
    
    % Big M formulation
    val = get(handles.Solver_BigM,'String');
    entry = str2double(val);
    if isnan(entry)
        val = num2str(options.BigM);
    end
    fprintf(fid,['options.BigM = ',val,';\n']);
    
    % Global Solver
    val = get(handles.Solver_GlobalSolver,'Value');
    str = get(handles.Solver_GlobalSolver,'String');
    if val > 2
        valu = str{val};
    else
        if exist('cplexmilp','file')
            valu = 'CPLEX';
        else
            valu = 'MATLAB';
        end
    end
    valu = ['''',valu,''''];
    fprintf(fid,['options.GlobalSolver = ',valu,';\n']);
    
    % Comparison
    val = get(handles.Solver_Comparison,'Value');
    str = get(handles.Solver_Comparison,'String');
    if val > 2
        valu = str{val};
    else
        valu = 'None';
    end
    valu = ['''',valu,''''];
    fprintf(fid,['options.Comparison = ',valu,';\n']);
    
    % Not part of options in GUI
    fprintf(fid,'options.DeltaSolver = ''Approximate'';\n');
    
    % Progress bar
    val = get(handles.Solver_QPSolver,'Value');
    if val == 4
        if handles.Solver_ProblemClass == 6
            valu = 'mpMIQP';
        else
            valu = 'mpQP';
        end
    else
        valu = 'Off';
    end
    valu = ['''',valu,''''];
    fprintf(fid,['options.Progress = ',valu,';\n']);
    
    fprintf(fid,'end');
    fclose(fid);
end



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




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


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


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


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

items = get(handles.Solver_ProblemSelection,'String');
index_selected = get(handles.Solver_ProblemSelection,'Value');
item_selected = items{index_selected};
Solution = evalin('base',item_selected);
if isfield(Solution,'problem')
    Solution = Solution.Solution;
end

choice2 = questdlg('What plot-type would you like to display?', ...
    'Plotting', 'Critical Regions and Objective Function','Critical Regions','Objective Function',...
    'Critical Regions and Objective Function');

if ~isempty(choice2)
    if size(Solution(1).CR.A,2) > 2
        x = Chebyshev(Solution(1).CR.A,Solution(1).CR.b);
        str = num2str(x(3:end)');
        str_cmb = {'[NaN, NaN, ',str,']'};
        fix = inputdlg('Indicate which parameters should be fixed:',...
            'Fixing of parameters', [1 50],str_cmb);
        tfixed = str2num(fix{:});
    else
        tfixed = [NaN NaN];
    end
    
    switch choice2
        case 'Critical Regions and Objective Function'
            PlotSolution(Solution,tfixed');
        case 'Critical Regions'
            PlotSolution(Solution,tfixed','CR');
        case 'Objective Function'
            PlotSolution(Solution,tfixed','OBJ');
    end
end


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

items = get(handles.Solver_ProblemSelection,'String');
index_selected = get(handles.Solver_ProblemSelection,'Value');
item_selected = items{index_selected};
Solution = evalin('base',item_selected);
if isfield(Solution,'problem');
    Solution = Solution.Solution;
end

DisplaySolution(Solution);
