## Copyright (C) 2018 Anonymous 
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or (at
## your option) any later version.
##
## This program is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSEll. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; see the file COPYING.  If not, see
## <http://www.gnu.org/licenses/>.

## -*- texinfo -*-
## @deftypefn  {Function File} {@var{s} =}  meridianarc (@var{phi}, @var{phi_2}, @var{spheroid} , @var{angleUnit}) 
## Returns the meridian arch length given two latitudes and a sphereoid.
## If phi_2 is larger than phi the value will be negative.
## If no sphereoid is given the default is wgs84
## The angles are assumed to be in radians.
##
## Examples
## Full options:
## @example
## s = meridianarc (0, 56, "int24", "degrees")
## => s =
## 6.2087e+06 
## @end example
## Short version:
## @example
## s = meridianarc (0, pi/4)
## => s =
## 4.9849e+06
## @end example
## If want different units:
## @example
## s = meridianarc (0, 56, referenceEllipsoid ("int24", "km"), "degrees")
## => s =
## 6208.7
## @end example
## @seealso{referenceEllipsoid} 
## @end deftypefn
function s = meridianarc (phi, phi_2, spheroid = "wgs84", angleUnit = "radians")

if nargin < 2
  print_usage ();
endif

if ( strncmpi (lower (angleUnit), "d", 1) == 1 )
  phi = deg2rad (phi);
  phi_2 = deg2rad (phi_2);
endif

if isempty (spheroid)
  spheroid = "wgs84";
end

## From: Algorithms for global positioning. Kai Borre and Gilbert Strang pg 373
## Note: Using integral instead of Taylor Expansion 
if ( isstruct (spheroid) == 1)
  E = spheroid;
elseif ( ischar (spheroid) == 1)
  E = referenceEllipsoid (spheroid);
else
  error (" meridianarc.m: spheroid must be a string or a stucture");
endif

e_sq = E.Eccentricity ^ 2;
F = @(x) ((1 - e_sq * sin(x) ^ 2) ^ (-3 / 2));
s = E.SemimajorAxis * (1 - e_sq) * quad ( F, phi, phi_2, 1.0e-12);


endfunction

%!test
%! s = meridianarc ( 0, 56, "int24", "degrees");
%! assert (s,6208700.08662672, 10e-6)

%!error <spheroid> meridianarc ( 0, pi/4, 7)
%!error <spheroid> meridianarc ( 0, pi/4, 7i)

