% function H = drawhalfspace(A, b, sz, color, fill)
%
% Draw a halfspace or halfspaces given by inequalities
%   A*x + b >= 0
% SZ specifies scaling (should be at least sqrt(2) times as large as larger
%   axis length, defaults to 1)
% COLOR specifies color (defaults to blue)
% If FILL is [], draw only the line; otherwise, also draw shading to show
% which side of the constraint is infeasible.
%
% Return value H is a handle to the lines that bound the halfspaces

function h = drawhalfspace(A, b, sz, color, fill)

if (nargin < 3) sz = []; end
if (nargin < 4) color = []; end
if (nargin < 5) fill = 1; end

if (isempty(sz)) sz = 1; end
if (isempty(color)) color = [0 0 1]; end

for i = 1:size(A,1)
    pt = A(i,:);
    len = sqrt(sum(pt.^2));
    pt = -b(i) * A(i,:) / len^2;
    dir = A(i,:) * [0 1; -1 0];
    from = pt + sz*dir;
    to = pt - sz*dir;

    if (~isempty(fill))
        out = pt - sz * 1.414 * A(i,:)/len;
        patch([from(1) to(1) out(1)], [from(2), to(2), out(2)], color, 'LineStyle', 'none', 'FaceAlpha', [0.3]);
    end

    h = line([from(1) to(1)], [from(2) to(2)], 'LineWidth', 2, 'Color', color);
end
