#!/usr/bin/perl
#
# Calculate absolute magnitudes for stars in the CLEA 
#   stellar spectral classification lab, in "CLASSIFY.KEY" file
#

use POSIX;

# uncertainty in parallax, milliarcsec (assumed same for all stars)
$px_uncert = 1.0;


#$infile = "./clea_key.dat";
$infile = "./foo5";
open(INFILE, $infile) || die("can't open file $infile");
while (<INFILE>) {

  $line = $_;
  if ($line =~ /^#/) {
    next;
  }
  $line = " " . $line;
  @words = split(/\s+/, $line);
  $name = $words[1];
  $spec = $words[2]; 
  $lum = $words[3];
  if (0 == 1) {
    $px_mas = $words[4];
    $vmag = $words[7];
    $bv = $words[9];
  }
  else {
    $px_mas = $words[5];
    $bmag = $words[6];
    $vmag = $words[7];
    $bv = $bmag - $vmag;
  }

  # printf "%20s %8.3f %8.3f \n", $name, $bmag, $vmag;

  if ($px_mas <= 0) {
    next;
  }

  # best distance
  $dist_pc = 1000.0/$px_mas;
  $m_minus_M = 5.0*(log($dist_pc)/log(10.0)) - 5.0;
  $abs_mag = $vmag - $m_minus_M;

  # min distance
  $min_px_mas = $px_mas + $px_uncert;
  $min_dist_pc = 1000.0/$min_px_mas;
  $min_m_minus_M = 5.0*(log($min_dist_pc)/log(10.0)) - 5.0;
  $min_abs_mag = $vmag - $min_m_minus_M;

  # max distance
  $max_px_mas = $px_mas - $px_uncert;
  if ($max_px_mas <= 0.0) {
    $max_px_mas = 0.1;
  }
  $max_dist_pc = 1000.0/$max_px_mas;
  $max_m_minus_M = 5.0*(log($max_dist_pc)/log(10.0)) - 5.0;
  $max_abs_mag = $vmag - $max_m_minus_M;

  # convert the spectral type to a numerical value
  #    letter O -> 10
  #           B -> 20
  #           A -> 30 
  #      etc.
  $letter = substr($spec, 0, 1);
  if ($letter eq "O") {
    $tens = 10;
  }
  if ($letter eq "B") {
    $tens = 20;
  }
  if ($letter eq "A") {
    $tens = 30;
  }
  if ($letter eq "F") {
    $tens = 40;
  }
  if ($letter eq "G") {
    $tens = 50;
  }
  if ($letter eq "K") {
    $tens = 60;
  }
  if ($letter eq "M") {
    $tens = 70;
  }
  $number = substr($spec, 1, 1);
  $spec_num = $tens + $number;
  
  

    
   printf "%10s %7s %4s %6.1f %6.1f %6.2f %8.3f %8.3f %8.3f %8.3f %6.3f %5d \n", 
          $name, $spec, $lum, $px_mas, $dist_pc, $m_minus_M, $vmag, $abs_mag,
          $min_abs_mag, $max_abs_mag, $bv, $spec_num;


}
close(INFILE);

exit 0;
