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

% Last Modified by GUIDE v2.5 22-Aug-2012 12:32:32

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

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


% UIWAIT makes QR_hex_GUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
A = rand(20);

% Find max evalue of A and print it in relevant string
d = eig(A);
set(handles.listbox2,'String',num2str(sortrows(d),3));

% stop button flag
ud=get(handles.stop_button,'UserData');
ud.wasPressed=0;
set(handles.stop_button,'UserData',ud);

set(handles.figure1,'CurrentAxes',handles.axes1);
axis equal;

[n,m] = size(A);
xlim([-1, (n+1)]);
ylim([-1, (n+1)]);


% PRESETS FOR MATLAB PUBLISH - TO BE DELETED ONCE GUI IS ON WEB
hex_matrix(A,max(max(abs(A))),0,handles);

% Update handles structure
guidata(hObject, handles);




% --- Outputs from this function are returned to the command line.
function varargout = QR_hex_GUI_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 edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (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 edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double
set(handles.listbox2,'String','');
set(handles.first_entry_value,'String','');
set(handles.last_entry_value,'String','');

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

% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (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
set(hObject,'String','40');

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

try
    n_iter = str2double(get(handles.edit2,'String'));
    A = eval(get(handles.edit1,'String'));
    [n,m] = size(A);
    assert(n > 1 && m > 1 && n == m && ndims(A)==2,...
        'A must be a square matrix of size at least 2');
    assert( ~isnan(n_iter) && n_iter >= 0 && (floor(n_iter) == n_iter)...
        && isreal(n),...
        'The number of iterations must be a non-negative integer.')

    % Find max evalue of A and print it in relevant string
    d = eig(A);
    set(handles.listbox2,'String',num2str(sortrows(d),3));
    set(handles.first_entry_value,'String','');
    set(handles.last_entry_value,'String','');

    set(handles.first_entry_value,'String','');
    set(handles.last_entry_value,'String','')
    
    xlim([-1, (n+1)]);
    ylim([-1, (n+1)]);
    
    ud=get(handles.stop_button,'UserData');
    ud.wasPressed=0;
    set(handles.stop_button,'UserData',ud);

    set(handles.edit1,'Enable','off');
    set(handles.edit2,'Enable','off');
    set(handles.start_button,'Enable','off');
    set(handles.start_button,'String','Wait...');
    set(handles.popupmenu1,'Enable','off');
    set(handles.it_no,'String','0');
    QR_alg(A,n_iter,handles);
    set(handles.popupmenu1,'Enable','on');
    set(handles.start_button,'String','Start!');
    set(handles.start_button,'Enable','on');
    set(handles.popupmenu1,'Value',1);
    set(handles.edit2,'Enable','on');
    set(handles.edit1,'Enable','on');
    
    guidata(hObject,handles);
catch err
    if(strcmp(err.identifier,'MATLAB:class:InvalidHandle'))
        if( ishandle(hObject) ) % otherwise we know the problem!
            rethrow(err);
        end
    else
        h=msgbox(err.message,'Incorrect Input','Error','modal');
        waitfor(h);
    end
end

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

% Hint: place code in OpeningFcn to populate axes1
axis off


% --- Executes on button press in stop_button.
function stop_button_Callback(hObject, eventdata, handles)
% hObject    handle to stop_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ud=get(hObject,'UserData');
ud.wasPressed=1;
set(hObject,'UserData',ud);
guidata(hObject,handles);

function M = randS( n ) % random symmetric matrix
M=rand(n);
M=triu(M)+triu(M,1)';

function M = randSPD( n ) % random symmetric pos def matrix
M=rand(n);
M=M'*M;

function QR_alg(A, n_iter,handles)
%n_iter is the number of iterations.
val = max(max(abs(A)));

hex_matrix(A,val,0,handles);
for t = 1:n_iter;
    [Q,R] = qr(A);
    A = R*Q;
    
    % error checking and drawing code
    if ~hex_matrix(A,val,t,handles)
        break;
    end
    % ----
end 

function draw_pol(x,y,a,val, handles)
d_max = 1;
fac = 0.8*min(a/val,d_max);
t = (1/6:1/6:1)'*2*pi;
x_ver = x + fac*cos(t);
y_ver = y + fac*sin(t);

% Color
u = a/val;
if u > 1
    u = 1;
end

tol = 0.01; % how small before we don't draw any more?
if(u>tol)
    % Method 2 of coloring %
    
    % note: the CurrentAxes have been set in the GUI OpeningFcn
    fill(x_ver,y_ver,sqrt(u)*[u 1 u]); 
end

function [exitcode] = hex_matrix(A,val,count,handles)
nf=isnan(max(max(abs(A)))); % nans?
ud=get(handles.stop_button,'UserData');
sf=ud.wasPressed; % stop button pressed flag

if( sf || nf );
    exitcode=0; %failure
    return;
else
    set(handles.it_no,'String',count);
    [n ~] = size(A);
    set(handles.first_entry_value,'String',sprintf('%.3g',A(1,1)));
    set(handles.last_entry_value,'String',sprintf('%.3g',A(n,n)));
    cla

    hold on
    for t = 1:n;
        for j = 1:n;
            draw_pol(t,j,abs(A(n-j+1,t)),val,handles);
        end
    end
    drawnow;
    exitcode=1; % success
    return;
end



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


% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (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 popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1
index = get(hObject,'Value');
switch index
    case 1 
    
    case 2
    % User selected the first item: Upper Hessenberg
    % Generate random upper Hessenberg matrix
    set(handles.edit1,'String','triu(rand(20),-1)');
    

    case 3
    % User selected the second item: Symmetric
    % Generate random symmetric matrix
    set(handles.edit1,'String','randS(20)');
end

if( index == 2 || index == 3 )
    cla(handles.axes1);
    set(handles.listbox2,'String','');
    set(handles.first_entry_value,'String','');
    set(handles.last_entry_value,'String','');
end


% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (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 during object creation, after setting all properties.
function last_entry_value_CreateFcn(hObject, eventdata, handles)
% hObject    handle to last_entry_value (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


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


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