#!/usr/bin/perl
#get_elevation.pl -- Assigns elevations to MOLA tracks. Elevations are obtained from an 
#external MOLA xyz file, which must be sorted appropriately, and duplicates must be eliminated. 

use Getopt::Std;
getopts('a:b:');

$usage = "get_elevation.pl -a <MOLA xy track file> -b <MOLA xyz data file>";

if (! ($opt_a && $opt_b )) { die "\nUsage: $usage\n\n"; }

open(TRACKFILE,"$opt_a") || die "Could not open track file.\n";

open(DATAFILE,"$opt_b") || die "Could not open data file.\n";

while(<TRACKFILE>) {

  $line = $_;
  if ( $line =~ /^(\S+)\s+(\S+)\s+/ ) {
   #Grab the first two columns of data

     $longitude = $1;
     $latitude = $2;

     $match = 0;
     while ( $match == 0 )  {
        $line2 = <DATAFILE>;
        if ( $line2 =~ /^(\S+)\s+(\S+)\s+(\S+)\s/ ) {
           $longitude2 = $1;
           $latitude2 = $2;
           $topography2 = $3;


           #Check if the coordinates of the raw data matched the coordinates of the smoothed data
           if ( ( $longitude == $longitude2) && ( $latitude == $latitude2 ) ) {
              $match = 1;

              print "$longitude2\t$latitude2\t$topography2\n";
           }
        }
     }
  }
}

