use Math::Round;
open (SPLATDAT, "splat_data.txt") or die "Can't open spat_data.txt! \n";
open (SPLATXY,">splat_xy.txt") or die "Can't open splat_xy.txt! \n";

print "Rounding coordinates to 3 second intervals... \n";
$idx = 1;
while (<SPLATDAT>) {
  $temp = $_;
  @splatline = split /,\s/, $temp;
  $splatline[0] = $splatline[0]*1200;
  $splatline[0] = round($splatline[0]);
  $splatline[1] = $splatline[1]*1200;
  $splatline[1] = round($splatline[1]);
  $splatline[4] =~ s/\s.//;
  if ($idx > 2) { 
     $temp = $splatline[0]." ".$splatline[1]." ".$splatline[4];
     }
  elsif ($idx == 1) {
     $temp="0000000,  ".$_;
     }
  else {
     $temp="0000001,  ".$_;
  };
  print SPLATXY $temp;
        $idx++;
};
print $idx." records processed. \n";
close SPLATDAT;
close SPLATXY;
print "Sorting SPLAT xy file...\n";
system "sort /home/dl2/splat/data/splat_xy.txt > sorted_splat_xy.txt";

open (SITE, "sorted_splat_xy.txt") or die "Can't open spat_xy.txt! \n";
open (CLEAN,">clean_xy.txt") or die "Can't open clean_xy.txt! \n";

print "Cleaning duplicates from sorted SPLAT xy file...\n";

# Read the processed SPLAT text files 
# Get corner coordinates from site files
@corners = split /,\s/, <SITE>;
$lonmax1 = 1200 * $corners[1];
$lonmin1 = 1200 * $corners[2];
print '  longitude 1 = '."$lonmin1".' to '."$lonmax1"."\n";
@corners = split /,\s/, <SITE>;
$latmax1 = 1200 * $corners[1];
$latmin1 = 1200 * $corners[2];
$height1 = $ymax1 - $ymin1;
print '  latitude 1 = '."$latmin1".' to '."$latmax1"."\n";
print CLEAN '0000000,   '.($lonmax1 / 1200).', '.($lonmin1 / 1200).'  ; max_west, min_west'."\n";
print CLEAN '0000001,   '.($latmax1 / 1200).', '.($latmin1 / 1200).'    ; max_north, min_north'."\n";
$oldlon = 0;
$oldlat = 0;
$duplicate = 0;
$dupflag = 0;

while (<SITE>) {
   $temp = $_;
   @data = split /\s/, $temp;
   $lat = $data[0];
   $lon = $data[1];
   $fs = $data[2];
   if (($lon == $oldlon) && ($lat == $oldlat)) {
#      $duplicate=$duplicate + 1;
#      print "Duplicate longitude "."$lon"."  Duplicate total "."$duplicate"."  Latitude "."$lat"."\n";
      $lonpr = $lon+1;
      $datatemp = "$lat $lonpr $fs";
      $noprint = 1;
      }
   elsif (($lon == ($oldlon + 1)) && ($oldlat == $lat)) {
      $noprint = 0;
      $datatemp = "";
      }
   elsif(($lon == ($oldlon + 2)) && ($oldlat == $lat)) {
#      $lon = $lon+1;
      if ($datatemp) {print CLEAN $datatemp."\n";}; 
      $datatemp = "";
      $noprint = 0;
      $duplicate=$duplicate + 1;
      print "Duplicate longitude "."$lon"."  Duplicate total "."$duplicate"."  Latitude "."$lat"." else-if \n";
      }
   else {
      $noprint = 0;
   };
  $dataout = "$lat $lon $fs";
#   if (($lon < $oldlon) && ($lat == $oldlat)) {$dupflag = 1;};
  $oldlon = $lon;
  $oldlat = $lat;
  unless ($noprint) {
     print CLEAN $dataout."\n";
     };
   };
close SITE;
close CLEAN;
exit;



 