use Tie::IxHash;
use File::Basename;
tie %paramVal, "Tie::IxHash"; # keeps order of insertion in hash



$wgetCmd="/usr/bin/wget ";    # path of your systems wget 

$coordFile=$ARGV[0];
$suppliedBand=$ARGV[1];

# form values

$paramVal{"archive"}="VSA";
$paramVal{"database"}="VVVDR5"; # database 
$paramVal{"programmeID"}="120"; # 120=VVV
$paramVal{"band__1"}="$suppliedBand"; # Z,Y,J,H,Ks
$paramVal{"userX"}="1.0"; # size arcmin

$paramVal{"idPresent"}="noID";
$paramVal{"email"}="";
$paramVal{"email1"}="";
$paramVal{"crossHair"}="n";
$paramVal{"mode"}="wget";


$numCoords=500;                       # number of coords in a loop 


$fileExtension="tmp.wget";                # extension used to search output


print "File extension $fileExtension \n";


$boundary="--FILEUPLOAD";           # separator

$loopCount=0;

$i=0;

open (COORDS,"<$coordFile");

$loop=0;


while (!eof(COORDS)) {
    $paramVal{"startID"}=$numCoords*$loop;
    $loop++;
    $uploadFile="upload_".$loop.".txt";
    $outFile="out_".$loop.".txt";
    print $uploadFile, "\n";
    open (UP,">$uploadFile");

    while (($param, $value) = each(%paramVal)){
        if ($param=~ /band__/) {
	    $param="band";
	}
	print UP "$boundary\n";
	print UP "Content-Disposition: form-data; name=\"$param\"\n\n";
	print UP "$value \n";
    }

    print UP "$boundary\n";
    print UP "Content-Disposition: form-data; name=\"fileName\"; filename=\"$uploadFile\" Content-Type: text/plain\n\n";

    $i=0;
    while ( $i < $numCoords && defined($line=<COORDS>)) {
	$i++;
	chomp($line);
#	print "$numCoords here \n";
	print UP $line,"\n";
    }


    
    print UP "\n$boundary--\n";
    close(UP);
        system ("$wgetCmd  --header=\"Content-Type: multipart/form-data;  boundary=FILEUPLOAD\" --post-file $uploadFile http://horus.roe.ac.uk:8080/vdfs/MultiGetImage -O $outFile");


    open (OUT,"<$outFile");
    $found=0;

    while (<OUT>){
	$record=$_;
	if ($found==0){
	    if ($record =~ /$fileExtension/){
		$endPos=index($record,$fileExtension);
		$strtPos=rindex(substr($record,0,$endPos),"http");
		$fileURL=substr($record,$strtPos,$endPos-$strtPos+length($fileExtension));
                print "$record \n";
		print "$endPos $strtPos downloading  $fileURL file\n";
                $dlFile= $loop."_wget.sh";
                $offset=($loop-1)*$numCoords;
		system ("$wgetCmd $fileURL -O $dlFile");
		$found=1;
	    }
	}
    }
close (OUT);
    print "Start sleep \n";
    sleep (3);
print "End sleep \n";
}

close (COORDS)

