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

% Last Modified by GUIDE v2.5 26-Mar-2013 15:02:41

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @mydialog2_OpeningFcn, ...
                   'gui_OutputFcn',  @mydialog2_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{:});
    %[varargout{1:5}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before mydialog2 is made visible.
function mydialog2_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 mydialog2 (see VARARGIN)

% Choose default command line output for mydialog2
handles.output = 'Yes';

varargin = varargin{1};

handles.C = varargin{1};
handles.d = varargin{2};
handles.L = varargin{3};

handles.preferenceAlgo = varargin{4};
handles.preferenceMethod = varargin{5};
handles.bq = varargin{6};
handles.dimensions = size(handles.L,2);

%handles.workingd = [];
%handles.workingC = [];
%handles.workingAlgo = [];
%handles.workingMethod = [];

handles.ok = false; % dialog wird nur gestartet wenn Konfiguration nicht funktioniert

%[handles.d,handles.L] =  redefineDimensions(handles.d,handles.L,handles.bq); %sortiert L (und d) anders

handles.workingd = handles.d;
handles.workingC = handles.C;
handles.workingAlgo = handles.preferenceAlgo;
handles.workingMethod = handles.preferenceMethod;

    
%S = calcPolytopeSP(handles.workingC,handles.workingd,handles.workingAlgo,handles.workingMethod,zeros(size(handles.L,2),1),[],[]);
%if performeSPTest(S,handles.L)
%    handles.ok = true;
%    set(handles.proceed,'Enable','on'); 
    
%end;    

% Update handles structure
guidata(hObject, handles);

% Insert custom Title and Text if specified by the user
% Hint: when choosing keywords, be sure they are not easily confused 
% with existing figure properties.  See the output of set(figure) for
% a list of figure properties.
if(nargin > 3)
    for index = 1:2:(nargin-3),
        if nargin-3==index, break, end
        switch lower(varargin{index})
         case 'title'
          set(hObject, 'Name', varargin{index+1});
         case 'string'
          set(handles.text1, 'String', varargin{index+1});
        end
    end
end

% Determine the position of the dialog - centered on the callback figure
% if available, else, centered on the screen
FigPos=get(0,'DefaultFigurePosition');
OldUnits = get(hObject, 'Units');
set(hObject, 'Units', 'pixels');
OldPos = get(hObject,'Position');
FigWidth = OldPos(3);
FigHeight = OldPos(4);
if isempty(gcbf)
    ScreenUnits=get(0,'Units');
    set(0,'Units','pixels');
    ScreenSize=get(0,'ScreenSize');
    set(0,'Units',ScreenUnits);

    FigPos(1)=1/2*(ScreenSize(3)-FigWidth);
    FigPos(2)=2/3*(ScreenSize(4)-FigHeight);
else
    GCBFOldUnits = get(gcbf,'Units');
    set(gcbf,'Units','pixels');
    GCBFPos = get(gcbf,'Position');
    set(gcbf,'Units',GCBFOldUnits);
    FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ...
                   (GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2];
end
FigPos(3:4)=[FigWidth FigHeight];
set(hObject, 'Position', FigPos);
set(hObject, 'Units', OldUnits);

% Make the GUI modal
set(handles.figure1,'WindowStyle','modal')

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

% --- Outputs from this function are returned to the command line.
function varargout = mydialog2_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.ok;
varargout{2} = handles.workingd;
varargout{3} = handles.workingC;
varargout{4} = handles.workingAlgo;
varargout{5} = handles.workingMethod;

varargout = {varargout};

% The figure can be deleted now
delete(handles.figure1);

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

handles.output = get(hObject,'String');
%mydialog2_OutputFcn(hObject, eventdata, handles);

% Update handles structure
guidata(hObject, handles);

% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);

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

handles.output = get(hObject,'String');

% Update handles structure
guidata(hObject, handles);

warning('The result may be inaccurate or invalid !');
%pause on;
%pause();

% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);


% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if isequal(get(hObject, 'waitstatus'), 'waiting')
    % The GUI is still in UIWAIT, us UIRESUME
    uiresume(hObject);
else
    % The GUI is no longer waiting, just close it
    delete(hObject);
end


% --- Executes on key press over figure1 with no controls selected.
function figure1_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Check for "enter" or "escape"
if isequal(get(hObject,'CurrentKey'),'escape')
    % User said no by hitting escape
    handles.output = 'No';
    
    % Update handles structure
    guidata(hObject, handles);
    
    uiresume(handles.figure1);
end    
    
if isequal(get(hObject,'CurrentKey'),'return')
    uiresume(handles.figure1);
end    


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


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

contents = cellstr(get(hObject,'String'));
if strcmp('linprog',contents{get(hObject,'Value')})
    choices{1} = 'LargeScale';
    choices{2} = 'MediumScale';
    choices{3} = 'Simplex';
elseif strcmp('fmincon',contents{get(hObject,'Value')})
    choices{1} = 'active-set';
    choices{2} = 'interior-point';
    choices{3} = 'trust-region-reflective';
    choices{4} = 'sqp';
elseif strcmp('mpt',contents{get(hObject,'Value')})
    choices{1} = 'CDD Dual Simplex';
    choices{2} = 'CDD Ciss-Cross';
    choices{3} = 'GLPK';
    choices{4} = 'SeDuMi';
elseif strcmp('cvx',contents{get(hObject,'Value')})
    choices{1} = ' ';
end;
set(handles.optalgo,'String',choices);
set(handles.optalgo,'Value',1);

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

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



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

input = get(hObject,'String');
[x, input] = checkDoubleInput(0,Inf,input);
if x
    
    handles.workingd = handles.d + input;
    S = calcPolytopeSP(handles.workingC,handles.workingd,handles.workingAlgo,handles.workingMethod,zeros(handles.dimensions,1),[],[]);

    if get(handles.autochose,'Value')
        [algorithm,method,success] = autochose(handles.workingC,handles.workingd,handles.L);
        if success
            handles.workingAlgo = algorithm;
            handles.workingMethod = method;
            handles.ok = true;
            set(handles.proceed,'Enable','on');
        end;
    else
        handles = test(handles,S);
    end;
else
    msgbox('The input should be a double value between 0 and Inf!','Invalid Input','error');
    set(hObject,'String','0');
end;

guidata(hObject,handles);



function [handles] = test(handles,S)
if performeSPTest(S,handles.L);
    set(handles.proceed,'Enable','on');
    handles.ok = true;
      
else
    set(handles.proceed,'Enable','off');
    handles.ok = false;
end;


% --- Executes during object creation, after setting all properties.
function relaxvalue_CreateFcn(hObject, eventdata, handles)
% hObject    handle to relaxvalue (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 autochose.
function autochose_Callback(hObject, eventdata, handles)
% hObject    handle to autochose (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 autochose
if get(hObject,'Value')
    set(handles.optmethod,'Enable','off');
    set(handles.optalgo,'Enable','off');
    set(handles.apply,'Enable','off');
    
    [algorithm,method,success] = autochose(handles.workingC,handles.workingd,handles.L);
    if success
        handles.workingAlgo = algorithm;
        handles.workingMethod = method;
        handles.ok = true;
        set(handles.proceed,'Enable','on');
    else
        set(handles.proceed,'Enable','off');
        fprintf('No working algorithm found. Please try to losen the constraints.\n');
    end;
    
else
    set(handles.autochose,'Value',0);
    set(handles.optmethod,'Enable','on');
    set(handles.optalgo,'Enable','on');
    set(handles.apply,'Enable','on');
end;

guidata(hObject,handles);

function [algorithm,method,abort] = autochose(C,d,L)
method = {'linprog','fmincon','mpt','cvx'};

algo{1} = {'MediumScale','Simplex','LargeScale'};
algo{2} = {'active-set','interior-point','trust-region-reflective','sqp'};
algo{3} = {'CDD Criss-Cross','CDD Dual Simplex','GLPK','SeDuMi'};
algo{4} = {''};

% automatische Suche
    abort = false;
    
    for i=1:1:size(method,2)
        
        algos = algo{i};
        
        for j=1:1:size(algo{i},2)
            nextX0 = calcPolytopeSP(C,d,algos{j},method{i},zeros(size(C,2),1),[],[]);
            fprintf('   test: %s with %s ... \n',method{i},algos{j});
            if performeSPTest(nextX0,L)
                
                algorithm = algos{j};
                method = method{i};
                
                fprintf('Working configuration found !\n');
                
                abort = true;
                break;
            end;
        end;
        
        if abort
            break;
        end;
        
    end;
    
    if ~abort %no working configuration found
        algorithm = [];
        method = [];
    end;



% --- Executes on button press in reconstruct.
function reconstruct_Callback(hObject, eventdata, handles)
% hObject    handle to reconstruct (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 reconstruct
%if get(hObject,'Value')
%    S = calcPolytopeSP(handles.C,d,handles.preferenceAlgo,handles.preferenceMethod,zeros(size(handles.L,2),1),[],[]);
%    handles.ok = performeSPTest(S,handles.L);
%    
%    if handles.ok
%        set(handles.proceed,'Enable','on');
%    else
%        set(handles.proceed,'Enable','off');
%    end;
%end;


% --- Executes on button press in checkbox3.
function checkbox3_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox3 (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 checkbox3
if get(hObject,'Value')
    
    set(handles.panel_relax,'Visible','on');
else
    set(handles.panel_relax,'Visible','off');
    set(handles.relaxvalue,'String','0');
    handles.workingd = handles.d;
end;
guidata(hObject,handles);


% --- Executes on button press in checkbox4.
function checkbox4_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox4 (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 checkbox4
if get(hObject,'Value')
    
    set(handles.panel_chose,'Visible','on');
    
    contents = cellstr(get(handles.optalgo,'String'));
    handles.workingAlgo = contents{get(handles.optalgo,'Value')};
    contents = cellstr(get(handles.optmethod,'String'));
    handles.workingMethod = contents{get(handles.optmethod,'Value')};
else
    set(handles.panel_chose,'Visible','off');

    handles.workingAlgo = handles.preferenceAlgo;
    handles.workingMethod = handles.preferenceMethod;
end;


% --- Executes during object creation, after setting all properties.
function figure1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called
%set(handles.relaxvalue,'String','0');


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


contents = cellstr(get(handles.optalgo,'String'));
handles.workingAlgo = contents{get(handles.optalgo,'Value')};
contents = cellstr(get(handles.optmethod,'String'));
handles.workingMethod = contents{get(handles.optmethod,'Value')};

S = calcPolytopeSP(handles.workingC,handles.workingd,handles.workingAlgo,handles.workingMethod,zeros(handles.dimensions,1),[],[]);
handles = test(handles,S);

guidata(hObject,handles);
