#!/usr/bin/perl
#
# Convert the given Vazquez FITS image to 16-bit integer format,
#    dividing all pixel values by 2 (so that the max pixel value
#    is 32768, not 65536).
#
# Usage:  perl convert_int16.pl file.fits 
#
# MWR 11/22/2011
#
# Adapted for spiff.rit.edu.  It probably helps to run the HEAINIT
#    script before using this script.
#
# MWR 6/27/2016
#
# Adapted for use with HST images of NGC 4125
#
# MWR 8/25/2016

$debug = 1;

# we multiply all pixel values by this factor
$mul_factor = 500;

if ($#ARGV != 0) {
  printf "usage: perl convert_hst_int16.pl file.fit \n";
  exit(1);
}

$image = $ARGV[0];

# we divide all pixel values by this constant before converting
$ops_multiply = "*";

$ftools_dir = "/home/richmond/junk/hea/heasoft-6.21/x86_64-unknown-linux-gnu-libc2.23/bin";

$temp_file = "convert_int16.tmp";
$temp_file2 = "convert_int16_2.tmp";
$outfile = $image;
$outfile =~ s/.fits\[1\]/.fts/;


# first, we scale the image
$cmd = sprintf "%s/fcarith ", $ftools_dir;
$cmd .= sprintf " infile=%s ", $image;
$cmd .= sprintf " const=%s ", $mul_factor;
$cmd .= sprintf " outfil=%s ", $temp_file;
$cmd .= sprintf " ops=%s ", $ops_multiply;
$cmd .= sprintf " clobber=yes ";
$ret = exec_cmd($cmd);



# clip image to no pixels outside valid 16-bit integer range
$cmd = sprintf "%s/fimgtrim ", $ftools_dir;
$cmd .= sprintf " infile=%s ", $temp_file;
$cmd .= sprintf " outfile=%s ", $temp_file2;
$cmd .= sprintf " threshlo=-32767 ";
$cmd .= sprintf " const_lo=-32767 ";
$cmd .= sprintf " threshup=32767 ";
$cmd .= sprintf " const_up=32767 ";
$cmd .= sprintf " clobber=yes ";
$ret = exec_cmd($cmd);




# now, convert to 16-bit integer
#    change the file's extension to ".fts" as a sign
$cmd = sprintf "%s/chimgtyp ", $ftools_dir;
$cmd .= sprintf " infile=%s ", $temp_file2;
$cmd .= sprintf " outfile=%s ", $outfile;
$cmd .= sprintf " datatype=short ";
$cmd .= sprintf " Inull=0 ";
$cmd .= sprintf " clobber=yes ";
$ret = exec_cmd($cmd);

exit 0;

# add two COMMENT lines to header describing the change
$datestr = `date`;
chomp($datestr);
$cmd = sprintf "comment $outfile ";
$cmd .= " 'divided by $div_factor on $datestr ' ";
$ret = exec_cmd($cmd);
$cmd = sprintf "comment $outfile ";
$cmd .= " 'converted to 16-bit integer formate on $datestr ' ";
$ret = exec_cmd($cmd);

if ($debug == 0) {
  unlink($temp_file);
  unlink($temp_file2);
}


printf "%s OK \n", $outfile;

exit 0;







##############################################################################
# PROCEDURE: exec_cmd
#
# DESCRIPTION: Execute the given shell command line.  If the $debug flag
#              is set, we print to stdout the command line, and
#              also print out the result string.
#
# RETURNS:
#              the result of the command
#
#
sub exec_cmd {

  my($cmd, $ret);

  $cmd = $_[0];

  if ($debug > 0) {
    printf "cmd is ..$cmd.. \n";
  }
  $ret = `$cmd`;
  if ($debug > 0) {
    printf "ret is ..$ret.. \n";
  }

  return($ret);
}


