#!/usr/bin/env perl
use Cwd; $currdir=cwd; $|=1;
use threads; use threads::shared; my @tiles:shared;
$tileside=4000;
$tilebuffer=2;
$pixelsize=0.00025;

### USER INPUT ################################################
$endyear=2023;
$source="$currdir/source_tiles";
$output="$currdir/processed_tiles";
$maskpath="C:/GLAD_1.1/Models/SERVIR_Mekong_datamask";
$wetlandpath="C:/GLAD_1.1/Models/SERVIR_Mekong_wetland";
$ogr="C:/Program Files/QGIS 3.34.2/OSGeo4w.bat";
$threads=10;
###############################################################

########## Check name of the tile list
open (DAT, "tiles.txt") or die "ERROR: no tiles.txt"; @tiles=<DAT>; close (DAT); foreach (@tiles) {chomp;}
######################################

$tool="$currdir/process_tile.exe"; if (!-e $tool){die "$tool not found\n";}
mkdir ("$output");
$taskcount=@tiles;

for($threadID=1;$threadID<=$threads;$threadID++){push @ClassThreads, threads->create(\&Process);} 
foreach $thread (@ClassThreads)  {$thread->join();} @ClassThreads=();
system "del processed_tiles\\*.img";

sub Process {
while ($tile = shift(@tiles)){
if ($tile eq ""){die;}
$taskcount2=@tiles; $perc=int(100-$taskcount2/$taskcount*100); print "\rProcessed:$perc\%\tTile:$tile\t";
$x1=substr $tile,0,3; $sx=substr $tile,3,1; if ($sx eq "W"){$centerx=($x1+0.5)*-1;} else {$centerx=$x1+0.5;}
$y1=substr $tile,5,2; $sy=substr $tile,7,1; if ($sy eq "S"){$centery=($y1+0.5)*-1;} else {$centery=$y1+0.5;}
$ulxtile=$centerx-0.5-$tilebuffer*$pixelsize;
$ulytile=$centery+0.5+$tilebuffer*$pixelsize;
$lrxtile=$centerx+0.5+$tilebuffer*$pixelsize;
$lrytile=$centery-0.5-$tilebuffer*$pixelsize;

system("$tool $tile $endyear $source $output $ulxtile $ulytile $maskpath $wetlandpath");

open (BAT, ">temp_batch$threadID.bat");
for ($year=2000; $year<=$endyear; $year++){
	print BAT "gdal_translate -of GTiff -co COMPRESS=LZW $output/TCC_$year\_$tile.img $output/TCC_$year\_$tile.tif\n";
	print BAT "gdal_translate -of GTiff -co COMPRESS=LZW $output/TCH_$year\_$tile.img $output/TCH_$year\_$tile.tif\n";
	print BAT "gdal_translate -of GTiff -co COMPRESS=LZW $output/Loss_$year\_$tile.img $output/Loss_$year\_$tile.tif\n";
}
close (BAT);
readpipe "\"$ogr\" temp_batch$threadID.bat >nul 2>&1";
sleep(10);
system "del temp_batch$threadID.bat";
}
}
