#!/usr/bin/perl
#
# Create an ASCII text spectrum from data in an SDSS spectrum.
#
# MWR 8/23/2008

use POSIX;

$debug = 0;


# contains spectrum of object, one line per element
$infile = "spSpec-52000-0474-626_t0.txt";
$coeff0 = 3.5811;
$coeff1 = 1.000E-4;
$num_bin = 3831;
$temp1 = "make_spec.1.tmp";
$temp2 = "make_spec.2.tmp";

# first, we take the input file, which was saved from the FITS spectrum
#    via "fv".  The input file has all the values on a single line,
#    each value quoted and separated by commas, like this:
#
#         "50.74560","50.79490","48.51600","46.23270" ....
#
# We first split it up into individual numbers, one per line,
#    with no quotation marks.
#
$cmd = "sed -e 's/\"/ /g' $infile > $temp1";
exec_cmd($cmd);
$cmd = "sed -e 's/\,/\\n/g' $temp1 > $temp2";
exec_cmd($cmd);


# now we work on the cleaned-up version of the spectrum, currently in temp2

$num_val = 0;
open(INFILE, "$temp2") || die("can't open file $temp2");
while (<INFILE>) {
  $line = " " . $_;
  chomp($line);
  if ($debug > 0) {
    printf " next line is ..%s.. \n", $line;
  }
  @words = split(/\s+/, $line);
  $spec_val[$num_val] = $words[1];
  if ($debug > 0) {
    printf " spec_val number %6d is %12.5f \n", $num_val, $spec_val[$num_val];
  }
  $num_val++;
}
close(INFILE);
if ($num_val != $num_bin) {
  printf STDERR " num_bin %6d but num_val %6d \n", $num_bin, $num_val;
 #  exit(1);
}

for ($i = 0; $i < $num_val; $i++) {

  $arg = $coeff0 + $i*$coeff1;
  $lam = pow(10.0, $arg);
#  printf "  i %6d  lam %12.1f spec %12.5e \n", $i, $lam, $spec_val[$i];
  printf "%-12.1f %12.5e \n", $lam, $spec_val[$i];

}




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);
}


