function value = elliptic_inc_pia ( phi, n, a )

%*****************************************************************************80
%
%% ELLIPTIC_INC_PIA evaluates the incomplete elliptic integral Pi(PHI,N,A).
%
%  Discussion:
%
%    This is one form of what is sometimes called the incomplete elliptic
%    integral of the third kind.
%
%    The function is defined by the formula:
%
%      Pi(PHI,N,A) = integral ( 0 <= T <= PHI )
%        dT / (1 - N sin^2(T) ) sqrt ( 1 - sin^2(A*pi/180) * sin ( T )^2 )
%
%    In MATLAB, the function can be evaluated by:
%
%      ellipticPi(n,phi,sin^2(a*pi/180))
%
%    The value is computed using Carlson elliptic integrals:
%
%      Pi(phi,n,a) = sin(phi) RF ( cos^2(phi), 1 - sin^2(a*pi/180) sin^2(phi), 1 ) 
%        + 1/3 n sin^3(phi) RJ ( cos^2(phi), 1 - sin^2(a*pi/180) sin^2(phi), 1, 1 - n sin^2(phi) )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 June 2018
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real PHI, N, A, the arguments.
%    0 <= PHI <= PI/2.
%         N   <= 1 / sin^2 ( PHI )
%    0 <= abs ( sin(A*pi/180) ) <= 1 / abs(sin ( PHI ))
%
%    Output, real VALUE, the function value.
%
  k = sin ( a * pi / 180 );

  sp = sin ( phi );
  cp = cos ( phi );

  x = cp ^ 2;
  y = ( 1.0 - k * sp ) * ( 1.0 + k * sp );
  z = 1.0;
  p = 1.0 - n * sp ^ 2;
  errtol = 1.0E-03;

  [ value1, ierr ] = rf ( x, y, z, errtol );
  if ( ierr ~= 0 )
    fprintf ( 1, 'ELLIPTIC_INC_PIA - Fatal error!\n' );
    fprintf ( 1, '  RF returned IERR = %d\n', ierr );
    error ( 'ELLIPTIC_INC_PIA - Fatal error!' );
    return
  end

  [ value2, ierr ] = rj ( x, y, z, p, errtol );
  if ( ierr ~= 0 )
    fprintf ( 1, 'ELLIPTIC_INC_PIA - Fatal error!\n' );
    fprintf ( 1, '  RJ returned IERR = %d\n', ierr );
    error ( 'ELLIPTIC_INC_PIA - Fatal error!' );
    return
  end

  value = sp * value1 + n * sp ^ 3 * value2 / 3.0;

  return
end
