#!/usr/bin/perl
# Parse the results of a query into Gaia database
#
# This version puts additional fields into the output file.
#  
#    MWR 1/23/2021
#
use POSIX;
use Scalar::Util qw(looks_like_number);

  $debug = 1;

  # this is the name of the "clean" datafile we'll create 
  #    and use for plotting
#  $clean_file = "./dr2_paragt100_extra.dat";
  $clean_file = "./dr2_paragt40_extra.dat";
  
  my($output_file, $term_options);

  ###################################################################################
  # Create a datafile which contains (B-R) color, apparent G mag, absolute G mag
  #    from the given datafile.

#  $gaia_file = "./dr2_paragt100.csv";
  $gaia_file = "./dr2_paragt40.csv";
  open(CLEAN_FILE, ">$clean_file") || die("can't create file $clean_file");
  open(GAIA_FILE, "$gaia_file") || die("can't open file $gaia_file");
  while (<GAIA_FILE>) {
    $line = $_;
    if ($line =~ /^#/) {
      next;
    }
    @words = split(/,/, $line);
    $id = $words[0];
    $ra = $words[5];
    $dec = $words[7];
    #  in milliarcsec
    $parallax = $words[9];
    #  in milliarcsec
    $parallax_error = $words[10];
    $g_mag = $words[50];
    $bp_minus_rp = $words[63];
    # check to see if the (Bp - Rp) value is an empty string; if so, ignore
    if (!(looks_like_number($bp_minus_rp))) {
      next;
    }
    $l = $words[73];
    $b = $words[74];
    $teff = $words[78];
    $a_g_val = $words[81];

    # compute distance in pc
    $dist = 1.0 / ($parallax * 0.001);

    # compute absolute g mag
    $abs_g_mag = $g_mag + 5.0 - 5.0*log10($dist);
    
    # compute a very approximate size
    $solar_lum = 1.99E30;
    $solar_abs_g = 4.8;
    $sigma = 5.67E-8;
    $solar_mult = 10.0**(0.4*($solar_abs_g - $abs_g_mag));
    $lum = $solar_lum*$solar_mult;
    $radius = sqrt( ($lum) / (4.0*3.14159*$sigma*($teff**4.0)) );

  
    printf CLEAN_FILE " para %8.2f  dist %8.2f  g %6.3f  (B-R) %6.3f  G %6.3f  Teff %7.0f  L %8.3e rad %8.3e RA %6.2f Dec %6.2f \n",
           $parallax, $dist, $g_mag, $bp_minus_rp, $abs_g_mag, $teff, $lum, $radius, $ra, $dec;



  }
  close(GAIA_FILE);
  close(CLEAN_FILE);


exit 0;
