#!/star/Perl/bin/perl
$baseDir   = "/thoth/www/wsa/tmp/MultiGetImage/";
$baseURL   = "http://surveys.roe.ac.uk/wsa/tmp/MultiGetImage/";
$fitsProg  = "/home/mar/webprogs/fitsandjpeg ";
$noPerPage = 20;
$noPerRow  = 4;
$maxSize   = 120;
$pageTop   =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"> <html> <head><title>WFCAM Science Archive</title><style type=\"text/css\">\n<!-- A { text-decoration: none} --> </style> </head><body>";
$pageBottom = "\n </body></html>";
$length     = @ARGV;
$file       = "";
$email      = "";
$band       = "";
$survey     = "";
$crossHair  = "y";
$email      = "";
$size       = "";
for ( my $i = 0 ; $i < $length ; $i++ ) {
	if ( $ARGV[$i] eq "-file" ) {
		$file = $ARGV[ $i + 1 ];
	}
	if ( $ARGV[$i] eq "-email" ) {
		$email = $ARGV[ $i + 1 ];
	}
	if ( $ARGV[$i] eq "-band" ) {
		$band = $ARGV[ $i + 1 ];
	}
	if ( $ARGV[$i] eq "-survey" ) {
		$survey = $ARGV[ $i + 1 ];
		$survey =~ s/_/ /g;
	}
	if ( $ARGV[$i] eq "-crossHair" ) {
		$crossHair = $ARGV[ $i + 1 ];
	}
	if ( $ARGV[$i] eq "-size" ) {
		$size = $ARGV[ $i + 1 ];
	    }
    }

$proc = int( rand 100 ) + 1;
print "$file \n";
print "$email \n";
$dirname = substr( $file, index( $file, "/upload" ) + 1, 64 );
$dirname =~ s/.res//;
$dirname = $dirname . "_" . $proc . "dir";

#print "$dirname \n";

$count = 0;
if ( -e $file ) {
	$fullPath = $baseDir . $dirname . "/";
	$fullURL  = $baseURL . $dirname . "/";
	mkdir( $fullPath, 0755 );

	#|| die "cannot create dir: $!";
	chdir($fullPath);
	$indexFile = $fullPath . "index.html";
	$indexURL  = $fullURL . "index.html";
	open( INDEX, "> $indexFile" );
	print INDEX "$pageTop";
	print INDEX "<h3>MultiGetImage Summary Page</h3> ";
	if ( $survey ne "" ) {
		print INDEX "<p>Survey: <b>$survey</b>";
	}
	if ( $band ne "" ) {
		print INDEX "<p>Waveband: <b>$band</b>";
	}
	if ( $size ne "" ) {
		print INDEX "<p>Size: <b>$size</b> arcmin";
	}

	$noImages = 0;
	open( RES, "< $file" );
	while (<RES>) {

		$count = $count + 1;
	}
	close(RES);
	if ( $count % $noPerPage == 0 ) {
		$noOfPages = $count / $noPerPage;
	}
	else {
		$noOfPages =
		  ( $count + $noPerPage - ( $count % $noPerPage ) ) / $noPerPage;
	}

	print INDEX "<p>HTML result pages. =&gt; \n";
	print INDEX &pageList($noOfPages);

	#   for ( my $i = 1 ; $i <= $noOfPages ; $i++ ) {
	#print INDEX " <a href=\"$i.html\">$i</a> \n";
	#}

	print "$noOfPages \n";

	$noLine = 0;
	$page   = 1;

	open( RES, "< $file" );
	while (<RES>) {
		$noLine = $noLine + 1;
		$line   = $_;
		chomp($line);
		$line =~ s/^\s+//;
		$line =~ s/\s+$//;
		@fields = split( /,/, $line );
		$ra     = $fields[0];
		$raH    = sprintf( "%02d", int( $ra / 15.0 ) );
		$raM    = sprintf( "%02d", int( ( $ra - ( $raH * 15.0 ) ) * 4.0 ) );
		$raS    = sprintf( "%04.1f",
			( $ra - ( $raH + $raM / 60.0 ) * 15.0 ) * 4.0 * 60.0 );

		if ( $raS >= 60.0 ) {
			$raS = sprintf( "%04.1f", $raS - 60.0 );
			$raM = sprintf( "%02d",   $raM + 1 );
		}
		if ( $raM >= 60 ) {
			$raM = sprintf( "%02d", $raM - 60 );
			$raH = sprintf( "%02d", $raH + 1 );
		}

		$dec  = $fields[1];
		$sign = "+";
		if ( $dec < 0 ) {
			$sign = "-";
		}
		$absDec = abs($dec);
		$decD   = sprintf( "%02d", int($absDec) );
		$decM   = sprintf( "%02d", int( ( $absDec - ($decD) ) * 60.0 ) );
		$decS   =
		  sprintf( "%02.0f", ( $absDec - ( $decD + $decM / 60.0 ) ) * 3600.0 );
		if ( $decS >= 60.0 ) {
			$decS = sprintf( "%02.0f", $decS - 60.0 );
			$decM = sprintf( "%02d",   $decM + 1 );
		}
		if ( $decM >= 60 ) {
			$decM = sprintf( "%02d", $decM - 60 );
			$decD = sprintf( "%02d", $decD + 1 );
		}

		$coordName = $raH . $raM . $raS . $sign . $decD . $decM . $decS;

		$mfFile = $fields[2];
		$mfID   = $fields[3];
		$filter = $fields[4];
		$ext    = $fields[5];
		$lowx   = $fields[6];
		$highx  = $fields[7];
		$lowy   = $fields[8];
		$highy  = $fields[9];
		$xpos   = $fields[10];
		$ypos   = $fields[11];
		$cd11   = $fields[12];
		$cd12   = $fields[13];
		$cd21   = $fields[14];
		$cd22   = $fields[15];
		$projp1 = $fields[16];
		$projp3 = $fields[17];
		$irot   = $fields[18];
		$iflip  = $fields[19];

		if ( ( $noLine - 1 ) % $noPerPage == 0 ) {
			$page = 1 + ( ( $noLine - 1 ) / $noPerPage );
			$open = defined fileno HTML;
			if ($open) {
				print HTML "</table>";
				print HTML "<br>page ", $page - 1,
				  " of <a href=\"$indexURL\">Summary</a> ";
				print HTML &pageList($noOfPages);

				print HTML $pageBottom;
				close(HTML);
			}
			$pageFile = "p" . sprintf( "%03d", $page ) . ".html";
			open( HTML, "> $pageFile" );
			print HTML $pageTop;
			print HTML "$survey $band <br>page ", $page,
			  " of <a href=\"$indexURL\">Summary</a> ";
			print HTML &pageList($noOfPages);

			print HTML "<p><table border=\"1\" cellpadding=\"0\">";
		}
		if ( ( $noLine - 1 ) % $noPerRow == 0 ) {
			print HTML "<tr>\n";
		}
		if ( -e $mfFile && ( $mfFile =~ /fit/ ) ) {

			$noImages = $noImages + 1;
			if ( $irot == 1 || $irot == 3 ) {
				$width  = $highy - $lowy + 1;
				$height = $highx - $lowx + 1;
			}
			else {
				$height = $highy - $lowy + 1;
				$width  = $highx - $lowx + 1;
			}
			$displaySize = $maxSize;

			if ( $height >= $width ) {
				if ( $height > $maxSize ) {
					$displaySize = $maxSize;
				}
				else {
					$displaySize = $height;
				}
				$displayTxt = " height=\"$displaySize\" ";
			}
			else {
				if ( $width > $maxSize ) {
					$displaySize = $maxSize;
				}
				else {
					$displaySize = $width;
				}
				$displayTxt = " width=\"$displaySize\" ";
			}

			$inFits =
			    $mfFile . "[" . $ext . "][" . $lowx . ":" . $highx . "," . $lowy
			  . ":"
			  . $highy . "]";

#$inFits="/disk01/wsa/ingest/fits/20041114/w20041114_01300_sf_st.fit[3][5895:6044,4618:4767]";
			$outFits = $noLine . "_" . $coordName . "_" . $band . ".fits.gz";
			$outJpg  = $noLine . ".jpg ";

			#$irot="1";
			#$xpos= "75.8";
			#$ypos= "50.3";

			$command = "nice "
			  . $fitsProg
			  . " -fits "
			  . $inFits
			  . " -outfits \\!"
			  . $outFits
			  . " -jpeg "
			  . $outJpg
			  . " -irot "
			  . $irot;

			#." -xpos ".$xpos." -ypos ".$ypos;

			if ( $crossHair eq "y" ) {
				$command = $command . " -xpos " . $xpos . " -ypos " . $ypos;
			}

			#print "$command \n";
			system("$command");

			print HTML
"<td align=\"center\" valign=\"top\"><font size=\"-1\">$noLine. mfID=$mfID<font><br><font size=\"-2\">RA/Dec</font><font size=\"-1\"> ",
			  sprintf( "%9.5f", $ra ), ",", sprintf( "%8.4f", $dec ),
			  "<br><a href=\"$fullURL$outFits\">", $coordName,
".fits.gz</a><br><a href=\"$fullURL$noLine.jpg\"><img alt=\"cut-out image\" src=\"$fullURL$noLine.jpg\" $displayTxt ></a></font></td> \n";
		}
		else {

			print HTML
"<td align=\"center\" valign=\"top\"><font size=\"-1\">$noLine. no match<br>RA/Dec ",
			  sprintf( "%9.5f", $ra ), ",", sprintf( "%8.4f", $dec ),
"<br>$coordName<br><img alt=\"null image\" src=\"http://surveys.roe.ac.uk/wsa/null.gif\" height=\"$maxSize\" width=\"$maxSize\" ></font></td> \n";

		}
	}
	print HTML "</table>";

	print HTML "<br>page ", $page, " of <a href=\"$indexURL\">Summary</a> ";
	print HTML &pageList($noOfPages);

	print HTML $pageBottom;
	close(HTML);
	print INDEX "<p>$noImages matching images found.<p>\n";
	$tarFile = "fits.tar";
	$pdfFile = "results.pdf";
	system("nice tar -cf $tarFile *.fits.gz");
	if ( -e $tarFile ) {
		print INDEX
"<a href=\"$fullURL$tarFile\"> Link to tar saveset of gzipped FITS images</a> <p>";
	}
	else {
		print INDEX "Unable to create tar file<p>\n";
	}

	$ENV{HTMLDOC_NOCGI} = 1;
	system(
"nice /home/mar/htmldoc-1.8.24/htmldoc/htmldoc --size a4 --webpage -f $pdfFile \*.html"
	);
	if ( -e $pdfFile ) {
		print INDEX
		  "<a href=\"$fullURL$pdfFile\">Link to PDF file of results.</a> <p>";
	}
	else {
		print INDEX "Unable to create PDF file<p>\n";
	}

	close(INDEX);

	if ( !open( MAIL, "| /usr/lib/sendmail -t" ) ) {
		print "error - couldn't send email\n";
	}
	else {
		print MAIL "To: $email\n";
		print MAIL "Subject: WSA MultiGetImage results\n";
		print MAIL "Bcc: mar\@roe.ac.uk\n";
		print MAIL "\n";

		print MAIL
		  "The results of your MultiGetImage request are available at: \n";
		print MAIL "$indexURL \n \n";
		print MAIL "The files will be deleted after 2 days. \n";
	}
	close(MAIL);

}

sub pageList {
	$number = $_[0];
	$retStr = "";
	for ( my $i = 1 ; $i <= $number ; $i++ ) {
		$htFile = "p" . sprintf( "%03d", $i ) . ".html";
		$retStr = $retStr . "<a href=\"$htFile\">$i</a> \n";
	}
	return $retStr;
}

