#!/usr/bin/perl
# convert mpcorb.dat on stdin to minorpl.edb on stdout.
#
# actually, only those asteroids that might ever be brighter than dimmag are
# sent to stdout; the others are saved in minorpl_dim.edb.
#
# mpcorb.dat is a service of the Minor Planet Center,
# http://cfa-www.harvard.edu/cfa/ps/mpc.html.
#
# This script is Copyright (c) 1999 Elwood Downey
# 16 Mar 1999: first draft
# 17 Mar 1999: change output filename

# mimic RCS version
$ver = '$Revision: 1.2 $';
$ver =~ s/\$//g;

# setup mag and filename
$dimmag = 13;			# set to dimmest mag to be sent to stdout
$dimfn = "minorpl_dim.edb";	# name of file for dim asteroids

# build some common boilerplate
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime;
$year += 1900;
$mon += 1;
$when = "# Processed $year-$mon-$mday $hour:$min:$sec UTC\n";
$from = "# Data is from ftp://cfa-ftp.harvard.edu/pub/MPCORB/MPCORB.DAT\n";
$what = "# Generated by mpcorb2edb.pl $ver by Elwood Downey\n";

# open the dim file
open (DIM, ">$dimfn") || die "Can not create $dimfn\n";

# add boilerplate to each file
print DIM "# Asteroids never brighter than $dimmag.\n";
print DIM $from;
print DIM $what;
print DIM $when;

print "# Asteroids ever brighter than $dimmag.\n";
print $from;
print $what;
print $when;

# process each mpcorb.dat entry
while (<STDIN>) {
    chomp();
    if (/^-----------/) {
	$sawstart = 1;
	next;
    }
    next unless ($sawstart);

    # build the name
    $name = substr ($_, 166);
    $name =~ s/\(//g;
    $name =~ s/\)//g;
    $name =~ s/^ *//;
    $name =~ s/ *$//;
    next if ($name eq "");

    # gather the orbital params
    $i = &s(60,68) +  0;
    $O = &s(49,57) +  0;
    $o = &s(38,46) +  0;
    $a = &s(93,103) + 0;
    $e = &s(71,79) +  0;
    $M = &s(27,35) +  0;
    $H = &s(9,13) +   0;
    $G = &s(15,19) +  0;

    $cent = &s(21,21);
    $TY = &s(22,23) + 0;
    $TY += 1800 if ($cent =~ /I/i);
    $TY += 1900 if ($cent =~ /J/i);
    $TY += 2000 if ($cent =~ /K/i);
    $TM = &mpcdecode (&s(24,24)) + 0;
    $TD = &mpcdecode (&s(25,25)) + 0;

    # decide whether it's ever bright
    $per = $a*(1 - $e);
    $aph = $a*(1 + $e);
    if ($per < 1.1 && $aph > .9) {
	$fd = STDOUT;	# might be in the back yard some day :-)
    } else {
	$maxmag = $H + 5*&log10($per*&absv($per-1));
	$fd = $maxmag > $dimmag ? DIM : STDOUT;
    }

    # print
    print $fd "$name";
    print $fd ",e,$i,$O,$o,$a,0,$e,$M,$TM/$TD/$TY,2000.0,$H,$G\n";
}

# like substr($_,first,last), but one-based.
sub s {
    substr ($_, $_[0]-1, $_[1]-$_[0]+1);
}

# return log base 10
sub log10 {
    .43429*log($_[0]);
}

# return absolute value
sub absv {
    $_[0] < 0 ? -$_[0] : $_[0];
}

# return decoded value
sub mpcdecode {
    my $x = $_[0];
    $x =~ /\d/ ? $x : sprintf "%d", 10 + ord ($x) - ord ("A");
}

# For RCS Only -- Do Not Edit
# @(#) $RCSfile: mpcorb2edb.pl,v $ $Date: 1999/03/16 16:27:58 $ $Revision: 1.2 $ $Name:  $
