## Copyright (C) 2019-2020 Philip Nienhuis
##
## 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 @var{phi} and @var{phi_2}.
##
## If phi_2 is larger than phi the value will be negative.
##
## If no spheroid is given the default is wgs84.
## The angleunit can be degrees or radians (the latter is default).
##
## 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 supplied by anonymous contributor, see:
## https://savannah.gnu.org/patch/index.php?9720

function s = meridianarc (phi, phi_2, spheroid="wgs84", angleUnit="radians")

  persistent intv = "-pi/2, pi/2";
  persistent degintv = "-90, 90";

  if (nargin < 2)
    print_usage ();
  endif

  if (strncmpi (lower (angleUnit), "d", 1) == 1)
    phi = deg2rad (phi);
    phi_2 = deg2rad (phi_2);
    intv = degintv;
  endif
  if (abs (phi) > pi / 2 || abs (phi_2) > pi / 2)
    error ("meridianarc: latitudes must lie in interval [%s]", intv);
  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))
    E = spheroid;
  elseif (ischar (spheroid))
    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)
%!error <latitudes> meridianarc (-2, 2)
%!error <latitudes> meridianarc (-91, 91, "", "d")

