% ARCARROW - generate an arc shaped arrow for annotating plots
function arcarrow(xystart, xyend, radius, varargin)
global AMPRINT_FLAG;
global AM_small_arrowsize AM_ref_linewidth;

% Determine the aspect ratio of the axes (default = circle)
axisposn = get(gca, 'DataAspectRatio');
aspectratio = axisposn(1) / axisposn(2);
if (nargin > 3) 
  aspectratio = aspectratio * varargin{1};
end
rx = radius;
ry = radius / aspectratio;

% Scale the beginning and end points
q1 = [xystart(1), xystart(2)*aspectratio];
q2 = [xyend(1), xyend(2)*aspectratio];

% Figure out the center for the circle used to generate the arc
vecline = (q2 - q1) / norm(q2 - q1);
midpoint = (q1 + q2) / 2;
perpline = [vecline(2), -vecline(1)];

if (radius^2 - norm(q1-midpoint)^2 < 0)
  fprintf(2, 'arcarrow: radius is too small; aborting\n');
  return;
end;
length = sqrt(radius^2 - norm(q1-midpoint)^2);

center = midpoint - perpline * length * sign(radius);
angle = atan(((q2-center)*vecline') / ((q2-center)*perpline'));

% Rescale the coordinates to put back any eccentricity
center = [center(1), center(2)/aspectratio];
phi0 = atan2(perpline(2), perpline(1));

% Debugging plots
if (AMPRINT_FLAG == 0)
  plot([xystart(1), xyend(1)], [xystart(2), xyend(2)], 'x');
  hold on; plot([center(1)], [center(2)], 'o');
end

% Create the line for the arrow
for i = -50:50
  phi = i/50 * angle + phi0;
  X(i+51) = center(1) + rx*cos(phi);
  Y(i+51) = center(2) + ry*sin(phi);
end

% Generate the line on the plot
h = line(X, Y);
set(h, 'color', 'k', 'LineWidth', AM_ref_linewidth);

% Add an arrowhead
arrow([X(100), Y(100)], [X(101), Y(101)], AM_small_arrowsize);

return;

