#!perl
use 5.010;
use strict;
use warnings;
use Getopt::Long;

# Compiles Meeus's table 37.A (Pluto, 1885 to 2099) from the Go port's
# pluto.go (github.com/soniakeys/meeus, MIT) into include/tks/tks_pluto37.h,
# with the file's own digits. Shipped so a reader can regenerate the table;
# never installed.
#
#     perl tools/plutocompile --go ../plan_time_keeper_sky/sources/meeus-pluto/pluto.go

my ($go, $out) = ('', 'include/tks/tks_pluto37.h');
GetOptions('go=s' => \$go, 'out=s' => \$out) or die "usage: plutocompile --go <pluto.go> [--out <header>]\n";
die "plutocompile: --go <pluto.go> is needed\n" unless $go;
open my $fh, '<', $go or die "plutocompile: $go: $!\n";
my $src = do { local $/; <$fh> };
my ($table) = $src =~ /var t37 = \[\]struct \{.*?\}\{\n(.*?)\n\}/s or die "plutocompile: no t37 table in $go\n";
my $num = qr/-?(?:\d+\.?\d*|\.\d+)/;
my @rows;
for my $line (split /\n/, $table) {
    next unless $line =~ /\S/;
    my @f = $line =~ /\{(.*)\}/ ? split(/\s*,\s*/, $1) : die "plutocompile: '$line'\n";
    die "plutocompile: '$line' has " . scalar(@f) . " fields\n" unless @f == 9 && !grep { !/^$num$/ } @f;
    s/^(-?)\./${1}0./ for @f;
    push @rows, \@f;
}
die "plutocompile: " . scalar(@rows) . " rows, not 43\n" unless @rows == 43;
open my $oh, '>', $out or die "plutocompile: $out: $!\n";
print $oh "#ifndef TKS_PLUTO37_H\n#define TKS_PLUTO37_H\n\n";
print $oh "/* Generated by tools/plutocompile from the Go port of Meeus (soniakeys/meeus,\n";
print $oh " * MIT), table 37.A: the multiples of J, S and P, then the sine and cosine\n";
print $oh " * coefficients of longitude and latitude (degrees) and radius (AU). Do not\n * edit: regenerate. */\n\n";
print $oh "static const double tks_pluto_37a[43][9] = {\n";
print $oh "    { ", join(', ', @$_), " },\n" for @rows;
print $oh "};\n\n#endif\n";
close $oh;
printf "%s: %d rows\n", $out, scalar @rows;
