% thetas = find_angle(d, opt)
% Find angles to hit a target at distance d in the ballistics problem.
% If the target is unreachable, give an error message.

function [thetas] = find_angle(d, opt)

% Fit a Chebyshev polynomial to the targeting behavior
[D,z] = cheb(20);
thetac = (z+1)*pi/4;
impactsc = 0*thetac;
for k = 1:length(thetac)-1
impactsc(k) = ftarget(thetac(k), opt);
end

% Find the farthest-traveling trajectory
zcrit = chebopt(impactsc);
topt = chebeval(thetac, zcrit);
xopt = chebeval(impactsc, zcrit);

% If we fall below that point, quit
if d > xopt, error('Target out of range'); end
g = @(z) chebeval(impactsc, z)-d;
zs = [ fzero(g, [-1,zcrit]); fzero(g, [zcrit,1]) ];
thetas = chebeval(thetac, zs);