#!/opt/gnu/bin/perl
#
# roll_entry.cgi
# Generate the html page for HST nominal roll calculation and display.
# S.J.Hulbert 14Jul99 v1.0

BEGIN
{
  unshift (@INC, "/data/garnet2/httpd/cgi-bin/SJH/perl5/");
  unshift (@INC, "/data/garnet2/httpd/cgi-bin/SJH/perl5/5.00502/sun4-solaris");
  unshift (@INC, "/data/garnet2/httpd/cgi-bin/SJH/perl5/site_perl/5.005/sun4-solaris");
  unshift (@INC, "/data/garnet2/httpd/cgi-bin/SJH/perl5/site_perl/5.005");
}

use CGI;

$REF = '/data/pongo5/SSD/SSD_WWW/TMP/';
$HREF = 'http://garnet.stsci.edu/ssd/TMP/';

# First get the parameters passed into the script
# Use the CGI module to parse the CGI form submission.
#
my $query = new CGI;
my $frmt = &trim($query->param('frmt'));
my $start = &trim($query->param('start'));
my $end = &trim($query->param('end'));
my $ra = &trim($query->param('ra'));
my $dec = &trim($query->param('dec'));
my $freeform = &trim($query->param('freeform'));

# parse input and check for validity
($errmsg, *starts, *ends, *ras, *decs)  = &parsecheck($frmt, $start, $end, $ra, $dec, $freeform);

# Print the header and beginning html for the result page.
#
print $query->header(-type => 'text/html');
print $query->start_html(-title => "HST Nominal Roll");

if (!($errmsg)) {

  # In this case we have data passed in from the form.
  # so run the processing scripts
  (*xvalues, *rax, *decx, *nominal, *lolim, *hilim) = &proc_in(\@starts, \@ends, \@ras, \@decs);
  ($tablename, $giffilename) = &proc_plot(\@xvalues, \@rax, \@decx, \@nominal, \@lolim, \@hilim);
  $tablename =~ s/$REF/$HREF/;
  $giffilename =~ s/$REF/$HREF/;

  print "<CENTER><FONT SIZE=+1>HST Nominal Roll Results<BR><BR><BR>";
  print "<IMG WIDTH=501 HEIGHT=301 ";
  print "SRC=\"$giffilename\"> <BR><BR></CENTER>";
  print "<CENTER><a href=\"$tablename\"><FONT SIZE=+1>Tabular Results</a><BR>";
  print "</CENTER>";

} else {

  # In this case, no data or incorrectly formatted data have been passed to the script
  # Print message explaining problem
  #
  print "<center><FONT SIZE=+2>HST Nominal Roll Calculator</FONT></center><BR>";

  # print the error message
  print "$errmsg";

}

# Now print the html form at the bottom of the page.
# We always append this form to anything we print out.
#
print "<FORM METHOD=POST ACTION=\"roll_entry.cgi?";
print "frmt=$frmt&start=$start&end=$end&ra=$ra&dec=$dec&freeform=$freeform\">";

print <<EOF;
<center>
<table width=525 border=0 cellpadding=2 cellspacing=0>
<tr>
<td><IMG SRC="http://garnet.stsci.edu/ssd/1_tr.gif" WIDTH=25 HEIGHT=1></td>
<td><IMG SRC="http://garnet.stsci.edu/ssd/1_tr.gif" WIDTH=125 HEIGHT=1></td>
<td><IMG SRC="http://garnet.stsci.edu/ssd/1_tr.gif" WIDTH=125 HEIGHT=1></td>
<td><IMG SRC="http://garnet.stsci.edu/ssd/1_tr.gif" WIDTH=125 HEIGHT=1></td>
<td><IMG SRC="http://garnet.stsci.edu/ssd/1_tr.gif" WIDTH=125 HEIGHT=1></td>

<tr>
<td valign=top><INPUT TYPE=radio NAME=frmt VALUE=fixed CHECKED></td>
<td colspan=4><strong>Single Target Position</strong></td>
</tr>
<tr>
<td></td>
<td align=left> Target RA<br><font size="-1"><em>hh:mm:ss.ss</em></font></td>
<td align=left> Target DEC<br><font size="-1"><em>(-)dd:mm:ss.s</em></font></td>
<td align=left>Start Date<br><font size="-1"><em>mm/dd/yyyy</em></font></td>
<td align=left>End Date<br><font size="-1"><em>mm/dd/yyyy</em></font></td>
</tr>
<tr>
<td></td>
<td><INPUT TYPE=text NAME=ra SIZE=14> </td>
<td><INPUT TYPE=text NAME=dec SIZE=14></td>
<td><INPUT TYPE=text NAME=start SIZE=14></td>
<td><INPUT TYPE=text NAME=end SIZE=14></td>
</tr>
<tr>
<td valign=top><INPUT TYPE=radio NAME=frmt VALUE=free></td>
<td colspan=4><strong>Multiple Target Positions</strong><br>
<font size="-1"><em>hh:mm:ss.ss  (-)dd:mm:ss.s  mm/dd/yyyy</em></font>
</td>
</tr>
<tr>
<td></td>
<td colspan=4><TEXTAREA NAME=freeform COLS=60 ROWS=5></TEXTAREA></td>
</tr>
<tr>
<td></td>
<td></td>
<td align=RIGHT><INPUT TYPE="submit" VALUE="Calculate"></td>
<td align=LEFT><INPUT TYPE="reset" VALUE="Reset"></td>
<td></td>
</tr>
<tr>
<td></td>
<td colspan=4>
<strong>Instructions:</strong><BR>
<UL>
<LI>Select the Single Target Position Form to calculate the roll angle
of a single target position over a range of dates. 
</LI>
<LI> Select the Multiple Target Positions Form to calculate the roll angle of
a series of target positions on specific dates. This form is provided to  
facilitate calculations  of nominal roll angles for moving targets. 
</LI>
<LI>
Enter the relevant target position and date information for your target(s) and submit using the <strong>Calculate</strong> button.
</LI>
</UL>
<BR>
</td>
</tr>
</table>
</center>
</FORM>
</BODY>
</HTML>

EOF

#
#
sub proc_in {

  use GD;
  use GIFgraph::points;
  use Date::Calc(qw(Delta_Days Add_Delta_Days));
  use CGI;
  use Math::Trig;

  local (*starts, *ends, *ras, *decs) = @_;

  # perform all calculations
  foreach $i (0 .. $#starts) {
    my @xv = &proc_xval($starts[$i], $ends[$i]);
    push @xvalues, @xv;
    (*nominal, *lolim, *hilim) = &proc_roll();
    push @nominal_all, @nominal;
    push @lolim_all, @lolim;
    push @hilim_all, @hilim;
    foreach $j (0 .. $#nominal) {
      push @rax, $ras[$i];
      push @decx, $decs[$i];
    }
  }

return (\@xvalues, \@rax, \@decx, \@nominal_all, \@lolim_all, \@hilim_all);

}


#--------------------------------
#
sub proc_xval {

(my $start, my $end) = @_;


# JD2000.0
$REF_DATE = '01/01/2000';

# Calculate the number of days between the start and end date
#
$days = datediff(parsedate($start),
                    parsedate($end));


# Calculate the number of days between reference date and the start date
#
$refdiff = datediff(parsedate($REF_DATE), parsedate($start)) - 0.5;


# The xvalues list contains all of the numbers of the days within the
# start to end range. Use the daterange funtion described below to
# return all the days between two dates. This handles situations where
# the range spans a month or year border.
#
my @xvalues = daterange(parsedate($start),$days);

return @xvalues;

}

#--------------------------------
#
sub proc_roll {

my (@nominal, @lolim, @hilim);


# Now we can calculate nominal roll for the given date range.
#
(*beta, *t_opt) = &calculate_angles();

# set limits base on sun angle == 180 - beta
# sun angle   	off-nominal	plot action
#----------     ------------
# <50		not available	don't plot nominal roll
# 50-<90	5		plot nominal roll +/-5
# 90-<178	30		plot nominal roll +/-30
# 178-180	limited		plot nominal roll +/-all

for $i (0 .. $#beta) {
  $sunangle = 180. - $beta[$i];
  if ($sunangle < 50) {
    $nominal[$i] = -999;
    $lolim[$i] = -999;
    $hilim[$i] = -999;
  } elsif ($sunangle < 90) {
    $nominal[$i] = $t_opt[$i];
    $lolim[$i] = $t_opt[$i] - 5.0;
    $hilim[$i] = $t_opt[$i] + 5.0;
  } elsif ($sunangle < 178) {
    $nominal[$i] = $t_opt[$i];
    $lolim[$i] = $t_opt[$i] - 30.0;
    $hilim[$i] = $t_opt[$i] + 30.0;
  } else {
    $nominal[$i] = $t_opt[$i];
    $lolim[$i] = $t_opt[$i] - 90.0;
    $hilim[$i] = $t_opt[$i] + 90.0;
  }
}

# go back and force range to 0 - 360
foreach $i (0 .. $#lolim) {
  if ($nominal[$i] != -999) {
    $lolim[$i] = $lolim[$i] + 360.0 if ($lolim[$i] < 0.);
    $hilim[$i] = $hilim[$i] - 360.0 if ($hilim[$i] > 360.);
  }
}

return (\@nominal, \@lolim, \@hilim);

}


#--------------------------------
#
sub proc_plot {

use FileHandle;

local (*xvalues, *rax, *decx, *nominal, *lolim, *hilim) = @_;

# Organize the data in a form that we can pass to a plotting routine...
#
my @data = (\@xvalues,
            \@nominal,
            \@lolim,
            \@hilim,
           );


# The 'legend' is the set of labels for the various data sets
#
my @legend = ("HST Nominal Roll", "Off-Nominal Lower Limit", "Off-Nominal Upper Limit");

# Create a new bar graph
#
my $graph = new GIFgraph::points(501,301);

# misc. calculation to make pretty axis labels
$totdays = datediff(parsedate($xvalues[0]), parsedate($xvalues[$#xvalues]));
if ($totdays < @xvalues) {
  $nskip = int $totdays / 7;
} else {
  $nskip = int @xvalues / 7;
}

# fix is ugly...
if ($#ras == 0) {
  $ttl = "Single Position: RA=$ras[0] DEC=$decs[0]";
} else {
  $ttl = "Multiple Positions: RA=$ras[0] DEC=$decs[0], ...";
}

# Set the attributes for the graph
#
$graph->set(x_label           => 'Date',            
            x_label_skip      => $nskip,
            x_label_position  => 0.5,
            y_label           => 'Position Angle E of N (degrees)',
            y_min_value       => '0',
            y_max_value       => '360',
            y_tick_number     => '18',
            title             => $ttl,
            markers           => [3,9,9],
            dclrs             => ['green','blue','blue'],

         );

# Add the legend to the graph
#
$graph->set_legend(@legend);

# Draw the graph 
#
my $giffilename = mktmpfn().'.gif';
$graph->plot_to_gif($giffilename, \@data);

# Write the table
my $tablename = mktmpfn();
open TBLNM, ">$tablename";
format HEADER =
                          HST Nominal Roll Results

                                               Nominal      Lower      Upper
       Date             RA            DEC         Roll      Limit      Limit
 mm/dd/yyyy    hh:mm:ss.ss  (-)dd:mm:ss.s     deg EofN   deg EofN   deg EofN
 ----------    -----------  -------------     --------   --------   --------
