#!/usr/bin/perl
#
# Break the big table of exoplanets into smaller files
#   based on the discovery method
#
# MWR 6/28/2016

$debug = 1;

$infile = "planet_table.csv";

split_file($infile, "Transit", "planet_table.transit.csv", 0);
split_file($infile, "Astrometry", "planet_table.astrometry.csv", 0);
split_file($infile, "Imaging", "planet_table.imaging.csv", 0);
split_file($infile, "Microlensing", "planet_table.microlens.csv", 0);
split_file($infile, "Orbital Brightness Modulation", "planet_table.modulation.csv", 0);
split_file($infile, "Pulsar Timing", "planet_table.pulsar.csv", 0);
split_file($infile, "Radial Velocity", "planet_table.rv.csv", 0);
split_file($infile, "Eclipse Timing Variations", "planet_table.timing.csv", 0);
split_file($infile, "Pulsation Timing Variations", "planet_table.timing.csv", 1);
split_file($infile, "Transit Timing Variations", "planet_table.timing.csv", 1);


exit 0;


####################################################################
# PROCEDURE: split_file 
# 
# DESCRIPTION: Pick selected lines from the given file
#              and copy them into the output file.
#              If the 'append_flag' argument is 1, then append to the
#              given file.
#
# RETURNS:     0      if all goes well
#              1      if an error occurs
#
sub split_file {


  $infile = $_[0];
  $type = $_[1];
  $outfile = $_[2];
  $append_flag = $_[3];

  if ($append_flag == 0) {
    open(OUTFILE, ">$outfile") || die("split_file: can't open file $outfile");
  } else {
    open(OUTFILE, ">>$outfile") || die("split_file: can't open file $outfile");
  }
  open(INFILE, "$infile") || die("split_file: can't open file $infile");
  while (<INFILE>) {
    $line = $_;
    if ($line =~ /^#/) {
      next;
    }
    @words = split(/,/, $line);
    if ($words[3] eq $type) {
      printf OUTFILE "%s", $line;
    }

  }
  close(INFILE);
  close(OUTFILE);

  return(0);
}
