function [y,z] = tangram (z, opts, output_mgn)
%TANGRAM  A multiclass problem based on the tangram.
%
%   Y = TANGRAM(X) gives the labels (1..7) or 0 (out of the boundary).
%   X: each line is a point
%
%   [Y,X] = TANGRAM(N) generates N random X and their labels Y.
%
%   TANGRAM('plot') plots the 7 tangram pieces in color.

if nargin < 3, output_mgn = false; end
assert(~output_mgn); % not ready for the margin yet

tg{1} = [0 1 1; 2 2 1];
tg{2} = [1 2 2 1; 2 2 1 1];
tg{3} = [2 3 2; 2 2 1];
tg{4} = [3 4 3 2; 2 2 1 1];
tg{5} = [1 3 2; 1 1 0];
tg{6} = [0 2 0; 2 0 0];
tg{7} = [4 4 2; 2 0 0];

% color from wikipedia.com/tangram
clr = [238,149,197; 164,149,189; 246,242,32; 238,60,98; ...
       246,202,49; 106,190,213; 205,230,148] / 255;

if nargin < 1
    y = tg; z = clr; % give out the internal settings
    return;
end

if isstr(z) && strcmp(z, 'plot')
    plot_blocks(tg, clr);
    return;
end

if length(z) == 1, %% Generate random inputs
    assert(z == round(z));
    z = rand(z,2);
    z(:,1) = z(:,1)*4; z(:,2) = z(:,2)*2;
end

y = zeros(size(z,1), 1);
for i = 1:length(tg)
    idx = find(y == 0);
    in = in_block(tg{i}', z(idx,:));
    y(idx(in)) = i;
end
if any(y == 0)
    warning('Some inputs are out of the boundary (labeled 0).');
end


function plot_blocks (blk, clr)
hold on; axis equal; axis off;
for i = 1:length(blk)
    x = blk{i}(1,:); y = blk{i}(2,:);
    h = patch([x x(1)], [y y(1)], clr(i,:));
    set(h, 'EdgeColor', 'k', 'LineWidth', 0.01);
    text(mean(x), mean(y), int2str(i));
end


function in = in_block (pz, z)
% pz: p*2, p is the # of nodes/edges, clock-wise
dpz = diff(pz([1:end,1],:), 1, 1);
coef = dpz * [0 -1; 1 0];
bias = sum(coef .* pz, 2);
n = size(z, 1);
in = all([coef -bias] * [z ones(n,1)]' > -2*eps, 1);
