#!/star/Perl/bin/perl
use File::Basename;
use CGI;
use DirHandle;
use Image::Size;
use Scalar::Util qw(looks_like_number);
use Fcntl ':flock';
use Cwd;
use File::Copy;

require 'cgiSubs.pl';
require 'server.pl';


#$okKml=&do_kml("514_307_10_172c","0_12_27574_20_n",749,749);

#print "$okKml \n";
#	      exit;

sub do_kml {
$|=1;

my $colourDir=$_[0]; #"3236_784_8_14c"; #"4042_729_4_7c"; # 3236_784_8_14c";
my $jpgBase=$_[1]; #"0_12_27574_20_n";#"0_12_28861_20_n"; #0_12_27574_20_n";
my $jpgSizeX=$_[2]; #749;
my $jpgSizeY=$_[3]; #749;

my $colourPath=$TMPWEB."colour/".$colourDir;
my $cwd= getcwd;

my $maxPixelArea=4096*4096;
my $regionate=0;
my $isOK=1;

if ($jpgSizeX * $jpgSizeY > $maxPixelArea) {
    $regionate=1;
}

my $convertCmd="/usr/bin/convert ";
my $zipCmd="/usr/bin/zip -r -q -1 ";

my $urlRef=$BASEWWWURL."tmp/colour/".$colourDir."/";

my $jpegFile=$jpgBase.".jpg";
my $pngFile=$jpgBase.".png";
my $warpedFile=$jpgBase."_w.png";
my $kmlFile=$jpgBase.".kml";
my $kmlTitle=$jpgBase;
my $tileDir=$jpgBase."Tiles";
my $kmlEnd=$jpgBase.".end";
my $kmzFile=$jpgBase.".kmz";

#print "$cwd \n $colourPath\n";

chdir  $colourPath;

unless (-e $jpegFile){
    return "";
} 

print "<!-- creating png file -->\n";


unless (-e $pngFile){
$outConvert=`nice $convertCmd  -quality 1 $jpegFile $pngFile`;
}

#system ("nice $convertCmd  -quality 1 $jpegFile $pngFile");

my $wcs2kmlCmd="/home/mar/usr/bin/wcs2kml --ground_overlay_name=$kmlTitle --copy_input_size=true --fitsfile=G.fits --imagefile=$pngFile --outfile=$warpedFile --kmlfile=$kmlFile";

if ($regionate == 1){
    $wcs2kmlCmd=$wcs2kmlCmd." --regionate=true --regionate_dir $tileDir ";
}

print "<!-- creating kml file -->\n";

unless (-e $kmlEnd) {
$outKml=`nice $wcs2kmlCmd`;
}


open (ENDKML,">$kmlEnd");
close(ENDKML);

print "<!-- creating zip file -->\n";

if ($regionate == 0){

$zipCmd=$zipCmd." $kmzFile $kmlFile $warpedFile";
}
else {
$zipCmd=$zipCmd." $kmzFile $kmlFile $tileDir";
 chmod (0775,$tileDir);
}

$zipOut=`$zipCmd`;

my $zipUrl=$urlRef.$kmzFile;

#print "$zipUrl\n";

#
#
#print "<!-- editing kml file(s) -->\n";
#
#opendir (DIR, "./"); 
#while( ($locname = readdir(DIR))){
#next unless $locname =~ /.kml$/ &&  $locname !~ /_url.kml$/;
#$urlname=$locname;
#$urlname=~ s/\.kml$/_url.kml/; 
#copy($locname,$urlname) 
#}
#closedir(DIR);

#opendir (DIR, "./$tileDir/"); 
#while( ($locname = readdir(DIR))){
#next unless $locname =~ /.kml$/ &&  $locname !~ /_url.kml$/;
#$urlname=$locname;
#$urlname=~ s/\.kml$/_url.kml/; 
##print("$locname\n $urlname\n");
#copy("$tileDir/$locname","$tileDir/$urlname") 
#}
#closedir(DIR);



#local @ARGV = grep -f, <*_url.kml>;
#
#$^I = '';
#
#while (<>) {
#s/<href>/<href>$urlRef/g;
#s/.kml</_url.kml</g;
#print;
#}


#local @ARGV = grep -f, <$tileDir/*_url.kml>;
#
#$^I = '';
#
#$urlRef=$urlRef.$tileDir."/";
#while (<>) {
#s/<href>/<href>$urlRef/g;
#s/.kml</_url.kml</g;
#print;
#}
#print "end\n";

if (-e $kmzFile){
return $kmzFile;
}
else {
    return "";
}
}




