#!/usr/bin/perl -w

use DBI;
use Getopt::Long;
use Term::ReadKey;
use Math::Trig;
use Image::MetaData::JPEG;

$dbase    = "HiRISE";
$user     = "";
$pass     = "";
$host     = "pirldb.lpl.arizona.edu";
$ogrph    = 0;
$help     = 0;

$opt = GetOptions ("dbase|d=s"         => \$dbase,
                   "host=s"            => \$host,
                   "user|u=s"          => \$user,
                   "pass|p=s"          => \$pass,
                   "graphic|g"         => \$ogrph,
                   "help|h"            => \$help);

if (!$opt || $help) {
 print "\n";
 print "obs_geom.pl -dbase -host -user -pass -help -output \n";
 print "\n";
 print "  dbase|d    database to connect to (default is HiRISE)\n";
 print "  host       hostname where the database is stored (default is pirldb.lpl.arizona.edu)\n";
 print "  user|u     username to connect to database (not username associated with suggestions)\n";
 print "  pass|p     password to connect to database (program will prompt you if not provided here)\n";
 print "  graphic|g  Export shapefile in 'ographic latitudes\n";
 print "  help|h     print this help message\n";
 print "\n";
 print "This program produces an ESRI shapefile containing HiRISE observations.\n";
 print "It does this by reading the HiCAT database.";
 print "Questions? Contact: Shane Byrne - shane\@lpl.arizona.edu\n";
 die("\n");
}

if ($user eq '') {
 print "MySQL username: ";
 $user = <STDIN>;
 chomp $user;
}

if ($pass eq '') {
 print "MySQL password: ";
 ReadMode('noecho');
 $pass = ReadLine(0);
 chomp $pass;
 ReadMode('normal');
}

$dbh = DBI->connect("dbi:mysql:database=".$dbase.";host=".$host, $user, $pass);
$dbh->{RaiseError} = 1;
$dbh->{AutoCommit} = 1;


#$ff   = ((3396190.0/3376200.0)*(3396190.0/3376200.0));    # Flattening to convert ocentric lats to ographic
#$r2d  = 57.295779513082323;                               # Convert radians to degrees (180/pi)

$sqlcmd1 = "select PRODUCT_ID,LINE_SAMPLES,IMAGE_LINES,MAP_SCALE,SAMPLE_PROJECTION_OFFSET,LINE_PROJECTION_OFFSET from RDR_Products where abs(IMAGE_CENTER_LATITUDE) > 70 AND TARGET_NAME = 'MARS' ORDER BY PRODUCT_ID;";
print "Performing MySQL queries...\n";
@res = @{  $dbh->selectall_arrayref($sqlcmd1) };
print "Closing database connection...\n";
$dbh->disconnect;

print "Getting jpegs...\n";
open  LST, "> filelist";
foreach $j (@res) {
 @res2 = @{$j};
 $fname  = $res2[0].".browse.jpg";
 $rfname = "Extras/RDR/".substr($res2[0],0,3)."/ORB_".substr($res2[0],4,4)."00_".substr($res2[0],4,4)."99/".substr($res2[0],0,15)."/".$res2[0].".browse.jpg";
 if (!-e $fname) {print LST "$rfname\n"};
}
close LST;
system "rsync -vutz --no-relative --files-from=filelist shane\@hisync.lpl.arizona.edu::hirise_data .";
system "rm -rf filelist";


print "Writing world files...\n";
foreach $j (@res) {
 @res2 = @{$j};
 $fname  = $res2[0].".browse.jpg";
 $wname  = $res2[0].".browse.jgw";

 if (-e $fname) { 
  $image = new Image::MetaData::JPEG($fname);
  ($dim_x, $dim_y) = $image->get_dimensions();
 
  $scale = 0.5*(($res2[1]/$dim_x)*$res2[3] + ($res2[2]/$dim_y)*$res2[3]);
  $ulx   = -$res2[4]*$res2[3]  - 0.5*$res2[3] + 0.5*$scale ; #   This           minus sign is "wrong"... we're using the PDS standard rather than the ISIS standard
  $uly   =  $res2[5]*$res2[3]  + 0.5*$res2[3] - 0.5*$scale ; #   This lack of a minus sign is "wrong"... we're using the PDS standard rather than the ISIS standard
 
  open  PRJ, "> $wname";
  print PRJ "$scale\n";
  print PRJ "0.0\n";
  print PRJ "0.0\n";
  print PRJ "-$scale\n";
  print PRJ "$ulx\n";
  print PRJ "$uly\n\n";
  close PRJ;
 }
}


