#!/opt/gnu/bin/perl

# Global variables

$tables_bin = '/usr/stsci/tables/bin/';
$fitsio = "${tables_bin}x_fitsio.e";

local ($input, $output);

# The main program loop

foreach $input (@ARGV) {
    next if $input =~ /\.[^c].d$/;	# skip if file is a datafile

    $output = &makeoutname ($input);
    &makefits ($input, $output);
}

exit (0);

# MAKEOUTNAME -- Create output fits file name from input name
#
# The output file name is genreated by taking the old extension, adding
# it to the filename separated by an undescore, and adding the new 
# extension ".fits".

sub makeoutname {
    local ($input) = @_;
    local ($output, $dot, $root, $ext);

    $dot = rindex ($input, ".");
    if ($dot <= 0) {
	print "Can't generate output name for $input\n";
	exit (1);
    }

    $root = substr ($input, 0, $dot);
    $ext = substr ($input, $dot+1);
    $ext = substr ($ext, 0, -1) . 'f' if &is_image ($input);

    $output = "${root}_${ext}.fits";
    return $output;
}

# IS_IMAGE -- Return 1 if file is an image, 0 otherwise
#
# The program determines if the file is an image by seeing if it starts 
# with "SIMPLE =".

sub is_image {
    local ($input) = @_;
    local ($buffer);

    unless (open (INPUT, $input)) {
	print "Can't open $input\n";
	exit (1);
    }

    $buffer = '';
    read (INPUT, $buffer, 9);
    close (INPUT);

    return ($buffer eq "SIMPLE  =")
}

# MAKEFITS -- A wrapper for the stsdas task stwfits
#
# The subroutine takes two arguments: the name of the input geis 
# and output fits file. It uses the global variable fitsio, which
# contains the full pathname of the executable containing stwfits

sub makefits {
    local ($input, $output) = @_;
    local ($parfile);

    # Create the pramaeter file for stwfits

    $parfile = "/tmp/loop$$.dpr";
    open (PARFILE, ">$parfile");

    print PARFILE <<EOQ;
stwfits.iraf_files = "$input"
stwfits.fits_files = "$output"
stwfits.newtape = no
stwfits.long_header = no
stwfits.short_header = yes
stwfits.format_file = "default"
stwfits.log_file = "none"
stwfits.bitpix = 0
stwfits.blocking_factor = 1
stwfits.extensions = no
stwfits.binary_tables = no
stwfits.gftoxdim = yes
stwfits.ieee = yes
stwfits.scale = yes
stwfits.autoscale = yes
stwfits.bscale = 1.
stwfits.bzero = 0.
stwfits.dadsfile = "null"
stwfits.dadsclas = "null"
stwfits.dadsdate = "null"
stwfits.Version = "21-Feb-1996"
stwfits.mode = "ql"
# EOF
EOQ

    close (PARFILE);

    # Run stwfits with the parameter file we have created

    system ($fitsio, 'stwfits', '@' . $parfile);
    unlink ($parfile);

    exit (1) unless -e $output;
}
