#!/usr/bin/perl
##########################################
# Skvbatch is a front end to webquery 
# to return FITS files from SkyView from 
# the command line.
#
# Calling sequence and parameter information
# can be found on the SkyView web site:
#     https://skyview.gsfc.nasa.gov/batchpage.html
#
# This software is in the public domain and may be used
# for any purposes without restriction.
##########################################

# Loop over the argument list  to see
# if file has been defined 
$i=0;
foreach (@ARGV) {
   last if (/^file=/i);
   $i++;
}
# if a filename has been specified, make it the filename
# and splice it out of the argument list
$filename = splice(@ARGV,$i,1);

# Loop over the argument list  to see
# if host has been defined 
$i=0;
foreach (@ARGV) {
   last if (/^host=/i);
   $i++;
}
# if a host has been specified, make it the host
# and splice it out of the argument list
$hostname = splice(@ARGV,$i,1);
   ($key,$host) = split('=',$hostname);
if ($host !~ /\w/) {
   $host="skyview.gsfc.nasa.gov";
}

# Loop over the argument list  to see
# if url has been defined 
$i=0;
foreach (@ARGV) {
   last if (/^url=/i);
   $i++;
}
# if a url has been specified, make it the url
# and splice it out of the argument list
$urlname = splice(@ARGV,$i,1);
($key,$url) = split('=',$urlname);
if ($url !~ /\w/) {
   $url="/current/cgi/pskcall";
}


# Read in the argument list and put the
# values in quotes
$new = 'webquery url="' .$url . '" host="' .$host .'" ' . '\'' . join('\' \'',@ARGV) . '\'';

# Exexcute webquery
@arr = `$new`;

# Put all the blocks togehter
$data = join('',@arr);

# Read past the HTTP header to get to the real data
# this is a kludge such that this works with the NCSA and APACHE
# web servers
if (index($data,"\n\r\n") == -1) {
    $locat = index($data, "\n\n") + 2;
} else {
    $locat = index($data, "\n\r\n") + 3;
}

if ($locat == 1) {$locat = 0;}
			       
# Either write to a file or standard output
if (length($filename)) {
   # get the filename from the argument
   ($key,$truename) = split('=',$filename);

   # Open the file
   open(WWWOUT,">$truename");

   # Print out only from SIMPLE on
   print(WWWOUT substr($data, $locat));
} else {
   # Print to standard outuput
   print substr($data, $locat);
}

# And that's all there is