#!/usr/bin/env perl

use 5.008;

use strict;
use warnings;

use Astro::App::Satpass2;
use Astro::Coord::ECI::Sun;
use Getopt::Long 2.33 qw{ :config auto_version };
use Pod::Usage;

our $VERSION = '0.057_01';

my %opt = (
    load	=> 'usual.tle',
);

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

my ( $name, @obs ) = @ARGV;

my $aas = Astro::App::Satpass2->new();

$aas->init( $opt{initfile} );

$opt{location}
    and $aas->dispatch( $opt{location} );

$aas->load( $opt{load} );

my $body;

{
    my @body = $aas->__choose( { bodies => 1 }, [ $name ] )
	or die "$name does not appear in $opt{load}\n";
    @body > 1
	and die "$name is not unique in $opt{load}\n";

    $body = $body[0];
}

my $sta;
unless( $sta = $body->get( 'station' ) ) {
    $sta = $aas->station();
    $body->set( station => $sta );
}

my $illum = $body->get( 'illum' )
    or die "Illuminating body not set on $name\n";

my $mag_adj = $illum->isa( 'Astro::Coord::ECI::Sun' ) ? 0 :
    $illum->magnitude() - Astro::Coord::ECI::Sun->MEAN_MAGNITUDE();

my $tp = $aas->get( 'time_parser' );

my $num = @obs / 2;
my $mag = 0;
while( @obs ) {
    my ( $time_string, $obs_mag ) = splice @obs, 0, 2;
    my $time = $tp->parse( $time_string );
    $body->universal( $time );
    my $range = ( $body->azel() )[2];

    # Compute the fraction of the satellite illuminated.
    my $frac_illum = ( 1 + cos( $body->angle( $illum, $sta ) ) ) / 2;

    # Finally we get to McCants' algorithm
    my $std_mag = $obs_mag - ( $mag_adj - 15.75 +
	2.5 * log( $range ** 2 / $frac_illum ) / log( 10 ) );

    $mag += $std_mag;
}

{
    local $\ = "\n";
    print $mag / $num;
}

__END__

=head1 TITLE

intrinsic-magnitude - Calculate intrinsic magnitude of a satellite

=head1 SYNOPSIS

 intrinsic-magnitude 48274 '2021-06-01 21:22:23' 1.5
 intrinsic-magnitude --help
 intrinsic-magnitude --version

=head1 OPTIONS

=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 calculates the intrinsic magnitude of a satellite given
the time and its apparant magnitude at that time as seen from the
observer's location.

=head1 AUTHOR

Thomas R. Wyant, III F<wyant at cpan dot org>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2021-2026 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 files F<LICENSE-Artistic> and F<LICENSE-GPL>.

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 :
