#!/usr/bin/perl

#####################################################
open(FILE, "./COLORLOOKUP.TXT");
while(<FILE>) {
    ($name, $code, $color) = split/\t/, $_; $color=~s/\s+$//;
    if ($code eq '') { $code = 'eng'; }
    $COLORHASH{$code} = $color;
}
close(FILE);
#####################################################

#$width=12288; $height=6144;
#$width=4000; $height=2000;
#$width=4096*3; $height=2048*3;
$width = $ARGV[0];
$height = $ARGV[1];
$bgcolor = $ARGV[2];
$infile = $ARGV[3];
$outfile = $ARGV[4];

if ($width < 500 || $height < 500) { print "FATAL: INVALID WIDTH/HEIGHT! Good settings are 4000x2000 or 12288x6144\n"; exit; }
if (length($bgcolor) < 6 || $bgcolor!~/^[A-F0-9]{6}$/) { print "FATAL: INVALID BACKGROUND COLOR! Specify as 6-digit HEX. Good settings are FFFFFF for white or 000000 for black backgrounds.\n"; exit; }
if (!-e "$infile") { print "FATAL: INPUT FILE DOES NOT EXIST!\n"; }
if ($outfile eq '') { print "FATAL: INVALID OUTPUT FILE!\n"; }

print "Generating DOT File...\n";
print "\tWidth: $width / Height: $height\n";
print "\tBackground: $bgcolor\n";
print "\tInput File: $infile\n";
print "\n";

open(OUTGV, ">$outfile.dot");
print OUTGV "strict graph converted {\n\tncorner0 [height=\"0.0\",width=\"0.0\",pos=\"0,0\",style=\"invis\"];\n\tnocorner1 [height=\"0.0\",width=\"0.0\",pos=\"$width,$height\",style=\"invis\"];\n";

open(FILE, $infile);
$NODEID = 0;
while(<FILE>) {
    ($lat, $long, $cnt, $lang) = split/,/, $_; $lang=~s/\s+$//; 
    $color = $COLORHASH{$lang};
    if ($cnt > 0 && $color ne '') {
        $plat = $lat; $plong = $long;
        $plat+=90; $plong+=180; #offset to 0,0 
        $plat=$plat*$height/180; $plong=$plong*$width/360; #norm to 100x100...
        $plat = sprintf("%0.4f", $plat); $plong = sprintf("%0.4f", $plong);
        print OUTGV "\tn$NODEID [height=\"0.01\",width=\"0.01\",pos=\"$plong,$plat\",style=\"filled\",shape=\"point\",color=\"${color}FF\",fontcolor=\"${color}FF\"];\n";
        $NODEID++;
    }
}
close(FILE);

print OUTGV "}\n";
close(OUTGV);

print "Rendering...\n";
print "CMD(neato -Gviewport=\"$width,$height\" -Gbgcolor=#000000 -n -Tpng $outfile.dot > $outfile.png)\n";
system("neato -Gviewport=\"$width,$height\" -Gbgcolor=#$bgcolor -n -Tpng $outfile.dot > $outfile.png");
#########################################################################
