#!/usr/bin/perl
# list_asteroids.pl
# Jure Skvarc, March 1999
# Using asteroid_server and fitsjd program list asteroids present in the given FITS
# images.  Assumes correct time and WCS coordinates
use IO::Socket;
use Getopt::Std;

$remote  = shift || die 'Host name missing!';
$user = shift || die 'User id missing!';
$mag = shift || die 'Magnitude limit missing!';
$port = 58972;
$iaddr = inet_aton($remote)               || die "no host: $remote";
$paddr = sockaddr_in($port, $iaddr);

#  Establish connection
$server = IO::Socket::INET->new(Proto => "tcp", 
				PeerAddr => $remote, 
				PeerPort => $port) 
    or die "Can't connect to asteroid server $remote";
print $server $user . "\0";
$hello = get_answer($server);
while ($name = shift) {
    $line = `fitsjd -j -w $name` || die "Error in $name";
    @args = split ' ', $line;
    shift @args;
    $newline = join(' ', @args);
    printf $server "fits $newline %f%c", $mag, '\0';
    $line = get_answer($server);
    @lines = split '\n', $line;
    for $a (@lines) {
	printf "%s:: $a\n", $name;
    }
}

close $server            || die "close: $!";
exit;


#  Receive an answer until the '\0' is received
sub get_answer

{
    my ($server) = @_;
    local $msk, $timeout = 30, $in = 1;
    local $a, $ans, $ans1;

    $ans = '';
    #  Prepare a bit mask for the select statement
    $msk = '';
    vec($msk, fileno($server), 1) = 1;
    while ($in) {
	#  Wait for data
	$a = select($msk, undef, undef, $timeout);
	if ($a > 0) {
	    sysread $server, $ans1, 1;
	    if ($ans1 eq "\0") {
		$in = 0;
	    }
	    else {
		$ans .= $ans1;
	    }
	}
	else {
	    $in = 0;
	}
    }
    return $ans;
}
