#!/usr/bin/env perl

use 5.006002;

use strict;
use warnings;

use Astro::Coord::ECI;
use Astro::Coord::ECI::Utils qw{ deg2rad rad2deg };
use Getopt::Long 2.33 qw{ :config auto_version };
use Pod::Usage;

our $VERSION = '0.133';

my %opt = (
    precision	=> $Astro::Coord::ECI::DEFAULT_MAIDENHEAD_PRECISION,
);

GetOptions( \%opt,
    qw{ precision=i },
    help => sub { pod2usage( { -verbose => 2 } ) },
) and @ARGV or pod2usage( { -verbose => 0 } );

my $fmt = "%.$opt{precision}f %.$opt{precision}f\n";

my $eci = Astro::Coord::ECI->new();

while ( @ARGV ) {
    if ( $ARGV[0] =~ m/ \A [[:alpha:]] /smx ) {
	$eci->maidenhead( shift @ARGV );
	my ( $lat, $lon ) = map { rad2deg( $_ ) } $eci->geodetic();
	printf $fmt, $lat, $lon;
    } else {
	my ( $lat, $lon ) = map { deg2rad( $_ ) } splice @ARGV, 0, 2;
	$eci->geodetic( $lat, $lon, 0 );
	print( ( $eci->maidenhead( $opt{precision} ) )[0], "\n" );
    }

}

__END__

=head1 TITLE

maidenhead - Convert positions to and from the Maidenhead Locator System

=head1 SYNOPSIS

 maidenhead -- 38.896 -77.042
 maidenhead FM18lv
 maidenhead -help
 maidenhead -version

=head1 OPTIONS

=head2 -precision

 -precision=3

This option specifies the precision of the output. This is the number of
pairs of characters for Maidenhead locators, or decimal places for
degrees of latitude and longitude.

The default is the value of
C<$Astro::Coord::ECI::DEFAULT_MAIDENHEAD_PRECISION>.

=head2 -help

This option displays the documentation for this script. The script then
exits.

=head2 -version

This option displays the version of this script. The script then exits.

=head1 DETAILS

This Perl script converts between degrees of latitude and longitude and
Maidenhead Locator grid specifications. Positions to convert are given
as command-line arguments.

Any command-line argument that begins with a letter is assumed to be a
Maidenhead Locator, and converted to degrees of latitude and longitude.

Any other command-line argument is assumed to be degrees of latitude,
with south being negative. The following argument is taken as degrees of
longitude east of Greenwich, England, with west being negative. The pair
is converted into a Maidenhead Locator.

Output is to standard out.

=head1 AUTHOR

Tom Wyant (wyant at cpan dot org)

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2018-2025 by Thomas R. Wyant, III

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl 5.10.0. For more details, see the full text
of the licenses in the directory LICENSES.

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.

=cut

# ex: set textwidth=72 :
