function [ alpha  F ] = ActualWingAngle( theta, V )
%This function computes the actual wing angle relative to the spine, give
%the incoming water direction relative to the spine.  
%This is done by balancing the fluids moment on the wing with the spring
%restoring force.
%Also computed and output is the force vector, component 1 is the force
%along the spine, and component 2 is the force normal to the spine.

persistent initial_value

if(isempty(initial_value))
    initial_value = 0;
end

% if(abs(theta) < 30)
%   initial_value = 0;
% else
%   inital_value = theta;
% end

 if(theta > 0)
   initial_value = 50;
 else
   initial_value = -50;
 end

F = zeros(3,1);

%allowable_alpha = [-30 10];  %Deployed
allowable_alpha = [-30 30]; 
%allowable_alpha = [-180 180];  %Deployed


fun = @(x) TotalMoment(x,theta,V);    % function of x alone
[alpha,fval,exitflag,output] = fzero(fun,initial_value);


if(exitflag ~= 1)
  disp(['Theta = ' num2str(theta)]);
  disp(['Alpha = ' num2str(alpha)]);
  disp(['exitflag = ' num2str(exitflag)]);
end


if(alpha < allowable_alpha(1))
    alpha = allowable_alpha(1);
end
if(alpha > allowable_alpha(2))
    alpha = allowable_alpha(2);
end  

initial_value = alpha;

F = HorzForce(alpha,theta);


[rho S Cp C ] = Constants();
C4 = C/4;

qinf = .5*rho*V.^2;

F0 = S*qinf*C;
M0 = S*qinf*C*C;

F(1) = F0*F(1);
F(2) = F0*F(2);
F(3) = M0*F(3) + F(1)*(C4-Cp)*sin(alpha*pi/180)  - F(2)*(C4-Cp)*cos(alpha*pi/180);  % <- Moment returned is moment about pivot point required to hold this orientation

%disp(['alpha = ' num2str(alpha)]);

end


