function [mgn,x] = leftsin (x, opts, output_mgn)
%LEFTSIN  The Sin target in Caprile'02 and Merler'04.
%
%   Y = LEFTSIN(X) gives output (1/-1) of the Sin target.
%   Y = LEFTSIN(X, [2 3]) also specifies a=2 and w=3.
%
%   MGN = LEFTSIN(X, [2 3], true) gives the signed margin.

if nargin < 3, output_mgn = false; end
if nargin < 2, opts = []; end
opts = options([2 3], opts);
a = opts(1); w = opts(2);

if length(x) == 1, %% Generate random inputs
    assert(x == round(x));
    x = rand(x,2)*2-1;
    x(:,1) = x(:,1)*10; x(:,2) = x(:,2)*4.8;
end

mgn = zeros(size(x,1),1);
if output_mgn
    for i = 1:size(x,1)
        mgn(i) = sinmgn(x(i,1:2), a, w);
    end
else
    idx = find(x(:,1) < 0);
    mgn(idx) = a*sin(w*x(idx));
    mgn = sign(x(:,2) - mgn);
end


function mgn = sinmgn (x, a, w)
y = x(2); x = x(1);

d1 = abs(y);
if x < 0, d1 = sqrt(x^2+y^2); end

[tm,d2,flg] = fminbnd(@(t) (x-t).^2+(y-a*sin(w*t)).^2, ...
                      min(0,x-pi/w), min(0,x+pi/w), ...
                      optimset('TolX', 1e-6));

b = 0;
if x < 0, b = a*sin(w*x); end
mgn = sign(y-b) * min(d1,d2);
