#!/usr/bin/perl
#
# Compute the fraction of objects within bins by magnitude
#   which satisfy some criteria
#
# MWR 8/18/2006
use POSIX;

$debug = 0;

$infile = "./sxds_locus_class.dat";

# 5 = V mag
$mag_col = 5;

# morphological score = col 19, color score = col 24
$morph_col = 19;
$color_col = 24;
# morph score >= 5 of 10 means low-quality star, >= 9 of 10 means high-quality
# color score >= 0.50 of 1.0 means low-qual star, >= 0.9 of 1.0 means high
$morph_crit_value = 9;
$color_crit_value = 0.9;

$start_mag = 0.0;
$end_mag = 33.0;
$mag_bin_size = 1.0;


$line_count = 0;
open(INFILE, "$infile") || die("can't open file $infile");
while (<INFILE>) {
  $line = $_;
  if ($line =~ /^#/) {
    next;
  }
  $line = " " . $line;

  if ($debug > 0) {
    printf "%s", $line;
  }

  @words = split(/\s+/, $line);
  $mag = $words[$mag_col];
  $mag_bin = int(($mag - $start_mag)/$mag_bin_size);
  if ($debug > 0) {
    printf "  mag %6.3f  bin %6d \n", $mag, $mag_bin;
  }

  $morph_value = $words[$morph_col];
  $color_value = $words[$color_col];

  if (($morph_value >= $morph_crit_value) && 
           ($color_value >= $color_crit_value)) {
    $star_count[$mag_bin]++;
  }
  $total_count[$mag_bin]++;
  if ($debug > 0) {
    printf "  line %6d  bin %6d  val %6.2f star_count %6d  total_count %6d \n",
        $line_count, $mag_bin, $other_value,
        $star_count[$mag_bin], $total_count[$mag_bin];
  }

  $line_count++;
 
  if (1 == 0) {
    if ($line_count > 100) {
      last;
    }
  }

}
close(INFILE);


for ($i = $start_mag; $i <= $end_mag; $i++) {
  if ($total_count[$i] > 0) {
    $star_frac = ($star_count[$i] + 0.0)/($total_count[$i] + 0.0);
  }
  else {
    $star_frac = 0.0;
  }

  printf "  mag %6.3f  star %6d  other %6d   star frac = %6.3f \n",
            $i, $star_count[$i], $total_count[$i], $star_frac;
}

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


