#!/usr/bin/perl 

#
# Flexure Estimator for MAESTRO
# 
#  JB, June 15, 2011
#  
#  Usage:
#    perl flexure.pl dec HA
#
#  Input:  dec = declination of target 
#          HA  = HA of target at start of exposure
#
#  Returns:  Number of binned pixel shift for next 2 hours, 
#            Assumes binning of 3 in dispersion direction, 
#                    binning of 2 in spatial direction 
#           

use Math::Trig

print "\n";
if ($#ARGV != 1) {
 print "usage: perl flexure.pl dec HA \n";
 exit;
}

$dec = $ARGV[0];
$HA0  = $ARGV[1];

# Latitude of the MMT is +31d 41' 19.6"
$dobs = 31.688778 * 3.14159 / 180.;

# Declination of object 
$decrad = $dec * 3.14159 / 180.;

# HA of start of observation 
$HA0rad = $HA0*15.*3.14159/180.;

print "MAESTRO Flexure Estimate";
print "\n";
print "\n";
print "Target Declination = ",$dec, " degrees";
print "\n";
print "\n";
print "Hour Angle, Airmass, Pixel shift per half hour in \n";
print "                     Dispersion, Spatial Directions:";
print "\n";

# Do first HA  

$cosa= cos($dobs)*cos($HA0rad)*cos($decrad);
$cosa=$cosa + sin($dobs)*sin($decrad);

$am=1./$cosa;

$el=90.-rad2deg(acos($cosa));

$disp=0.1125*$el - 10.25;
$spa = 0.3425*$el - 28.55;

# Divide by binning

$disp = $disp / 3.0;
$spa = $spa / 2.0;

$disp0=$disp;
$disp = 0.; 
$spa0 = $spa;
$spa = 0.;

$HA = $HA0;

printf   "   %.3f    %.3f    %.3f     %.3f ", $HA, $am, $disp, $spa;
print "\n";

$HArad = $HA0rad;

# Start loop for next 4 hours

for ($count=0; $count <8; $count=$count+1) {

$HArad=$HArad + 0.5*15.*3.14159/180.;
$HA=$HA+0.5;

$cosa= cos($dobs)*cos($HArad)*cos($decrad);
$cosa=$cosa + sin($dobs)*sin($decrad);

$am=1./$cosa;

$el=90.-rad2deg(acos($cosa));

$disp=0.1125*$el - 10.25;
$spa = 0.3425*$el - 28.55;

# Divide by binning

$disp = $disp / 3.0;
$spa = $spa / 2.0;

# Get sign of change right
#
if ($HA0rad ge $HArad) {
$dispdiff = $disp0-$disp; 
$spadiff  = $spa0 - $spa;
}

if ($HA0rad lt $HArad) {

$dispdiff = $disp - $disp0;
$spadiff = $spa - $spa0;
}

$disp0 = $disp;
$spa0 = $spa;
$HA0rad = $HArad;

printf   "   %.3f    %.3f    %.3f     %.3f ", $HA, $am, $dispdiff, $spadiff;
print "\n";

}
print "\n";

