## Copyright (C) 2017 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 PURPOSE. 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. If not, see .
## -*- texinfo -*-
## @deftypefn {} {@var{lat_o, lon_o} =} antipode (@var{lat_i}, @var{lon_i})
## @deftypefnx {} {@var{lat_o, lon_o} =} antipode (@var{lat_i}, @var{lon_i}, @var{unit})
## Compute antipode (opposite point on globe).
##
## @var{lat_i} and @var{lon_i} (numeric values) are input latitude and
## longitude, optionally vectors.
##
## Optional argument @var{unit} can be one of 'Degrees' or 'Radians') and
## can be used to specify the input units. Just one 'd' or 'r'
## (case-insensitive) will do.
##
## @end deftypefn
## Author: Philip Nienhuis
## Created: 2017-03-02
function [lato, lono] = antipode (lati, loni, unit="")
if (nargin < 2 || nargout < 2)
print_usage ();
elseif (! isnumeric (lati) || ! isnumeric (loni))
error ("antipode: numeric arguments expected for latitude and longitude\n");
elseif (! ischar (unit))
error ("antipode: character argument expected for lat/lon unit\n");
elseif (nargin > 3 && ! ismember (lower (unit(1)), {"d", "r"}))
error ("antipode: units must be one of 'Degrees' of 'Radians'");
endif
if (strncmpi (lower (unit), "r", 1))
convfac = 180.0 / pi;
lati *= convfac;
loni *= convfac;
endif
lato = -abs (180.0 - wrapTo360 (lati - 90.0)) + 90.0;
lono = wrapTo180 (loni + 180);
if (strncmpi (lower (unit), "r", 1))
lato /= convfac;
lono /= convfac;
endif
endfunction
%!test
%! [lato, lono] = antipode (90, 0);
%! assert ([lato, lono], [-90, 180], eps);
%!test
%! [lato, lono] = antipode (43, 15);
%! assert ([lato, lono], [-43, -165], eps);