#!/usr/bin/perl
#
# Analyze datafiles from Gaia which contain information on stars
#    in pencil beams located in different directions.
#
# MWR 8/8/2025

$debug = 1;

$infile = "./gaia_reg_a3.csv";


# list_columns($infile);



# compute distance (pc), absolute magnitude for each star, print a new line
#   with just a few bits of interesting info
calc_abs_mag($infile);


exit 0;



#########################################################
# SUBROUTINE: list_columns
#
# DESCRIPTION: List the contents of the columns, using first line
#              in the given datafile.  
#
# USAGE:      list_columns   infile
#
#         where
#              infile                is name of the file to describe
#
# RETURNS:    nothing
#
sub list_columns {

  my($infile, @words, $line, $i);

  $infile = $_[0];

		  # figure out which column has which data
		  open(INFILE, "$infile") || die("can't open file $infile");
		  while (<INFILE>) {
			 $line = $_;
			 @words = split(/,/, $line);
			 for ($i = 0; $i <= $#words; $i++) {
				printf " words [%2d] = ..%s.. \n", $i, $words[$i];
			 }
			 last;
		  }
		  close(INFILE);

  return;
}





#########################################################
# SUBROUTINE: calc_abs_mag
#
# DESCRIPTION: For each star, compute distance and absolute mag,
#              print one line with interesting info
#
# USAGE:      calc_abs_mag   infile
#
#         where
#              infile                is name of the file to describe
#
# RETURNS:    nothing
#
sub calc_abs_mag {

  my($infile, @words, $line, $i);
  my($dist, $abs_mag);

  $infile = $_[0];

		  # figure out which column has which data
		  open(INFILE, "$infile") || die("can't open file $infile");
		  while (<INFILE>) {
			 $line = $_;
          if ($line =~ /^#/) {
            next;
          }
			 @words = split(/,/, $line);

          $parallax = $words[4];
          $parallax_over_error = $words[5];
          $app_g_mag = $words[9];
          $bp_rp = $words[10];
          $distance_gspphot = $words[24];

          if ($parallax <= 0.0) {
            next;
          }
          if ($parallax_over_error < 10.0) {
            next;
          }

          # choose stars in a narrow color range
          $color = 0.7;
          $d_color = 0.1;
          if (($bp_rp < $color - $d_color) || ($bp_rp > $color + $d_color)) {
            next;
          }

          $distance = 1000.0 / $parallax;
          $abs_g_mag = $app_g_mag - (5.0*(log($distance)/log(10.0))) + 5.0;

          printf " app_g %6.3f bp_rp %6.3f  abs %6.3f  dist %6.1f %6.1f \n",
                 $app_g_mag, $bp_rp, $abs_g_mag, $distance, $distance_gspphot;

		  }
		  close(INFILE);

  return;
}


