#!/usr/bin/perl
#
# Given a spectrum from MCA in form
#
#       channel     counts
#
# convert the channel to energy, using my fit based on data 
# taken 9/26/2009.
#
#       energy (keV)  =  0.055161 * (channel)^(1.8845)
#
# Print to stdout lines like this:
#
#       channel     counts      energy_keV
#
# MWR 10/6/2009

$debug = 0;

# set this to 1 to add "#" markers to every line before 
#    Channel    Contents
#
$add_comment_char = 1;
$header_finished = 0;

$coeff = 0.055161;
$power = 1.8845;


while (<STDIN>) {
  $line = $_;
  $orig_line = $_;
  chomp($line);
  if ($line =~ /^#/) {
    printf "%s\n", $line;
    next;
  }
  $line = " " . $line;
  @words = split(/\s+/, $line);

  $channel = $words[1];
  $counts = $words[2];
  if ($debug > 0) {
   printf " channel ..%s.. counts ..%s.. \n", $channel, $counts;
  }

  if (($header_finished == 0) && ($add_comment_char == 1)) {
    if (($channel eq "Channel") && ($counts eq "Contents")) {
      if ($debug > 0) {
        printf " yup \n";
      }
      printf "# Channel Contents energy(keV)\n";
      $header_finished = 1;
      next;
    }
    else {
      printf "# %s", $orig_line;
      next;
    }
  }

  $energy = $coeff * ($channel**$power);
  printf "%6d %8d %10.5f \n", $channel, $counts, $energy;
}


exit 0;
