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

% Last Modified by GUIDE v2.5 23-Aug-2012 10:02:46

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @QR_click_n_kill_OpeningFcn, ...
                   'gui_OutputFcn',  @QR_click_n_kill_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
end

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

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

% Update handles structure
guidata(hObject, handles);

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

% Preset radio button
global switcher 
switcher = 1; %Preset is HH.
global structure
structure = 0;

%%%% PRESETS FOR THE PUBLISH FEATURE %%%%
global A 
A = randi(5,5);
colourmatrix(handles.axes1,A,A);
[n,~] = size(A);
set(handles.edit1,'String','randi(5,5)');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end

% --- Outputs from this function are returned to the command line.
function varargout = QR_click_n_kill_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;
end

function killHH(row,col,handles)
global A;

row = int32(row);
col = int32(col);

[m,~] = size(A);

u=get_householder(row,col,A);
A=do_householder(u,A);

tol = 1e-12;
%Correct signs of zeros in A;
for i = 1:m;
   for j = 1:m;
       if abs(A(i,j)) < tol 
           A(i,j) = 0;
       end
   end
end

%Plot the matrix
colourmatrix(handles.axes1,A,A)
end

function killgiv(row,col,chosenrow,handles)
global A
tol = 10^(-12);

row = int32(row);
col = int32(col);

G = get_givens(row,col,A(row,col),chosenrow,A(chosenrow,col));
A = do_givens(G,row,chosenrow,A);

%Correct signs of zeros in A;
        for i = 1:size(A);
            for j = 1:size(A);
               if abs(A(i,j)) < tol 
                   A(i,j) = 0;
               end
            end
        end
colourmatrix(handles.axes1,A,A)
end

function[A] = matrix_bwrg(M,Q,tol)
%M must be a square matrix.
[n,~] = size(M);

A=zeros(n);

for i = 1:n;
    for j = 1:n;
        if abs(M(i,j) - Q(i,j)) >  tol
           A(i,j) = 0.5;
        else
            if abs(M(i,j)) < tol;
                A(i,j) = 1;
            else
                A(i,j) = 0;
            end
        end
    end
end

end
        
function colourmatrix(ax,mat,matprevious)
[n,~] = size(mat);
global tol
global structure

for i = 1:size(mat);
    for j = 1:size(mat);
        if abs(mat(i,j)) < tol
            mat(i,j) = abs(mat(i,j));
        end
    end
end

textStrings = num2str(mat(:),'%0.1f'); % Create strings from matrix values 
textStrings = strtrim(cellstr(textStrings)); % Remove any space padding 

B = matrix_bwrg(mat,matprevious,tol);

h=imshow(B,[0 1],'Parent',ax);            % Plot the image 
set(h,'HitTest','off');

if structure == 0
    [x,y] = meshgrid(1:n);   % Create x and y coordinates for the strings 


    hStrings = text(x(:),y(:),textStrings(:),...      % Plot the strings 
                    'HorizontalAlignment','center',...
                    'Parent',ax,...
                    'FontUnits','Normalized',...
                    'HitTest','off');

    textColors = repmat(B(:)==0,1,3); % Choose white or black for the 
                                      % text color of the strings so 
                                      % they can be easily seen over 
                                      % the background color 
    % The trick: first compare with zero to flip 1 to 0, 0 and 0.5 to 1.
    % Then repeat value 3 times horizonally to get a color.
    
    set(hStrings,{'Color'},num2cell(textColors,2)); % Change text colors
end
set(ax,'XTick',[],...  % Change the axes tick marks 
       'YTick',[]);
axis(ax,'image');

end

% --- Executes on mouse press over figure background.
function figure1_ButtonDownFcn(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)
global switcher;
global A;

[n,~]=size(A);

ud=get(handles.edit1,'UserData');
if(ud.valid)
    % Householder
    if switcher == 1;
        [x_user, y_user] = ginput(1);

        col = round(x_user);
        row = round(y_user);
        
        if( row>=1 && row<=n && col>=1 && col<=n) % check valid click
            killHH(row,col,handles);
        end

    % Givens
    elseif switcher == 2;
        [x_user, y_user] = ginput(1);
        col = round(x_user);
        row = round(y_user);
        [~, chosenrow] = ginput(1);
        chosenrow = round(chosenrow);
        if( row ~= chosenrow && ... % check valid click
                row>=1 && row<=n && col>=1 && col<=n && ...
                chosenrow >=1 && chosenrow <=n)
            killgiv(row,col,chosenrow,handles);
        end
    end
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
end


% --- Executes when selected object is changed in uipanel1.
function uipanel1_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in uipanel1 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)
global switcher;

switch get(eventdata.NewValue,'Tag') % Get Tag of selected object. 
    case 'radioHH' 
       switcher = 1;
    case 'radioGivens' 
       switcher = 2;
    otherwise 
        % Do nothing.         
end 
end


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

global A

try
    str = get(hObject,'String');
    B = str2num(str);
    [n,m] = size(B);
    assert(n==m && n>=2 && n <= 50 && ndims(B)==2 && isreal(B),...
    'A must be a real square matrix of size at least 2 and at most 50');
    A=B; % all appears to be well    
    colourmatrix(handles.axes1,A,A);
        
    ud=get(hObject,'UserData');
    ud.valid=1;
    set(hObject,'UserData',ud);
catch err
    ud=get(hObject,'UserData');
    ud.valid=0;
    set(hObject,'UserData',ud);
    h=msgbox(err.message,'Error','error','modal');
    waitfor(h);
end

end

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

ud=get(hObject,'UserData');
ud.valid=1; % assume initial data is valid
set(hObject,'UserData',ud);
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); 
end


% --- Executes on button press in checkbox1.
function checkbox1_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox1 (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 checkbox1
global structure
global A

ud=get(handles.edit1,'UserData');
if(ud.valid);
    structure = get(hObject,'value');
    colourmatrix(handles.axes1,A,A);
end
end
