%This function is called by afga.m

function [g_out, alpha] = afga_step(g_in, g0, del_lam)

cgin = cos(g_in);
sgin = sin(g_in);
cg0 = cos(g0);
sg0 = sin(g0);
cg0minus = cos(g0 - g_in);
sg0minus = sin(g0 - g_in);
clam = cos(del_lam);
slam = sin(del_lam);
rjs = cg0*cgin + sg0*sgin*clam;

angle_rjs = atan2(sqrt(1-rjs^2), rjs);
dg = -g0 + g_in + angle_rjs;
g_out = g_in - dg;

%alpha = asin(slam)*sgin)/sin(angle_rjs))
%this expression for alpha only works sometimes, because
%x and pi - x both have same sine 

x = sin(dg)*(cgin*sgin*(1-clam) + sg0minus*rjs) + cos(dg)*(cgin^2 +sgin^2*clam - cg0minus*rjs);
y = sin(g0 -g_in + dg)*sgin*slam;
alpha = atan2(y,x);
