#!/usr/bin/perl -w
# The -w switch produces some lovely diagnostics.
#------------------------------------------------------------------------------#
#                                                                              #
#                 Instituto de Astrofisica de Canarias                         #
#                    Software Department                                       #
#------------------------------------------------------------------------------#

#-- start of module header information -----------------------------------------
#
# COMPONENT:
#   $Id: lsamp_slit.pl,v 1.0 2005/03/11 12:00:44 hmoreno Exp $
#   post_mult
#
#
# HISTORY:
#   $Log: lsamp_slit.pl,v $
#   Imported using TkCVS
#
#   Version  Date     Author      Description
#
#   1.0      050706   J. Acosta    Original code.
#
#
#
#
# TYPE:
#
#    PERL script
#
#
# PURPOSE:
#
#   Move a star along the slit in order to determine spectral distortion. 
#  
#
# Usage:
#
#   lsamp_slit <exposure_time(s)> <title>
#       -npts= number of points to obtain an exposure along the slit
#
#   The optional arguments have the following default values:
#    nrun  = 1
#
#
#
# PORTABILITY:
#
#    PERL script
#
#
# DESCRIPTION:
#
#  This script implements
#
#
# DEPENDENCIES
#
#    This script requires the following environmental variables to be set:
#
#     OBSSYS     - specifies path to top of WHT release tree.
#     IRCAMERA   - name of camera to make de observation (ingrid/liris)
#
#    Uses the following components of other subsystems:
#
#        cmd        - to move the telescope to a new nod point
#
#        multrun    - to take exposures
#
#
#    - Previously the Observation system  should have been started.
#    - The WHT TCS should be online.
#    - The TCS should be pointing at the source object.
#
#
#-- end of module header information ------------------------------------------#

#-- Main Script ---------------------------------------------------------------#

#----------------------------------------------------------------------#
#  Function name : main                                                #
#                                                                      #
#  Arguments     : argv[1] - exposure time                             #
#                  argv[2] - title                                     #
#                                                                      #
#  Returned      : $status = 0  - Success                              #
#                          = -1 - Error                                #
#                                                                      #
#  Description   : Execute lsamp_slit                                  #
#                                                                      #
#----------------------------------------------------------------------#

#
# The following variables are used by this script:
#
#   database_dir  - Directory holding data files
#   num_runs      - Number of MULTRUNS (for a single RUN must be equal to 1)
#   title         - holds title input by observer
#   DEBUG        - Activate/Des-activate debug mode


#
#   Add module to find user defined packages
#
use FindBin;
use lib $FindBin::Bin;

# 
#  Add module to parse command arguments 
#
use Getopt::Long;

#
#  Add Perl interface module to UNIX syslog(3) call
#
use Sys::Syslog;

#
#   Add module to obtain TCS info 
#   Import Subroutines Get_ApNomXY 
#
use GetTCSInfo qw(Get_ApNomXY); 
#
# 
#  Add module to take exposure subroutines
use GuideExpos qw(Take_exposure MoveTel DefAper);
#
# Register Catch interrupt catcher rutine
#
   $SIG{'INT'} = 'my_sigint_catcher';
#
# Log commad issued message.
#
  syslog( 'debug', "DEBUG: Command issued: $0 @ARGV\n");

#
#  Set default values for command-line options
#
  $num_runs = 1;
  $DEBUG = 0;
  $mct = 11;
  # define starting position in pixel
  $lyini = 40.;  
  # define interval  in pixel
  $lyfin = 980.; 
  $yref = 400.;  # the targets are usually centered at pixel (xx,400)
  
   

#   
#  Analyse command-line options
#
    GetOptions (
      'bottom|bot=i' => \$lyini,
      'top|top=i' => \$lyfin,
      'refpos|ref=i' => \$yref,
      'npts|np=i' => \$mct,
      'debug!' => \$DEBUG ) or goto ERR_BADUSE;   

#
# Check for correct number of  mandatory command-line arguments
# ( a minimum of 3 should be entered )
#

   if ( @ARGV < 2  ) {   
       goto ERR_BADUSE;
   }

#
# Assign passed arguments to shell variables
# 
   $exp_time   = $ARGV[0];
   $title      = $ARGV[1];

   $deltay = ($lyfin - $lyini) / ($mct - 1); 


# do not perform buffering IO in STDOUT and STDERR.
   select (STDOUT);
   $| = 1;
   select (STDERR);
   $| = 1;  
   

   print "\n======================================\n";
   print "     lsamp_slit script started.";
   print "\n======================================\n\n";
   
   print "Exposition time      = $exp_time sec\n";   
   print "Title                = $title\n\n";         

#      
#  Define program constat values 
#     
   $pixscal = 0.25;
   $delaytime = 5;
   $apsetA = 3; 
   $clean_imgs = 0;


######################################################################
#  1.- Verify if Apertures have been defined
#
#      If not, probably the lacq_mask program has not been executed
#      Therefore terminate giving the observer the appropiate message
#
######################################################################
   if ($DEBUG !=1)  {
      unless (@apnom_point = &Get_ApNomXY()) {goto ERR_GETTCSPOS_FAILED};
                       
      if ( (abs($apnom_point[0]) <= 0.000001 )
	            && (abs($apnom_point[1]) <= 0.000001) ) {
          print "\aSTARTING OFFSET HAS NOT BEEN DEFINED! !!!\a\a\n" ;
	  print "\nMust run the lacq_mask script to define it.\n\n ";
	  goto ERR_NOT_APERTURE; 
      } 		    	       	
   }
         
   
######################################################################
# 2.- Calculate relative positions   
#
######################################################################

   &calc_slitoffsets;

######################################################################
# 3.- Command telescope
#
######################################################################

   &point_telescope;
 

# 
# If execution reached here there were no errors. Inform the user and exit
#
   print "Script complete. No errors.\n";
   syslog( 'debug', "DEBUG $0 script complete. No errors.\n"); 
   system("audioplay", "-v", "99", "/wht/etc/sounds/doorbell.au");
        
   exit ;
 
 
#- SUB ROUTINES --------------------------------------------------------------#


#--------------------------------------------------------------------#
# Subroutine    : calc_slitoffsets                                   #
#                                                                    #
# Passed        : none                                               #
#                                                                    #
# Returned      : Calcule reference relative slit positions          #
#                                                                    #
# Description   :  calculate $offset[]                               #
#                                                                    #
#--------------------------------------------------------------------#
sub calc_slitoffsets {
   undef @offsets;
   
   for ($i=0; $i <$mct; $i++){
      $offsets[2*$i] = 0;
      $offsets[2*$i+1] = $lyini + $deltay * $i -$yref ;
      if ($DEBUG == 1) {
         print "  DEBUG:: offsety $offsets[2*$i+1] \n";
 
       }
   }
   
}

#-------------------------------------------------------------------#
# Subroutine   : point_telescope                                    #
#                                                                   #
# Passed       : <compl_title> = $_[0]                              #
#                                                                   #
# Returned     : 0 if succed, -1 otherwise                          #
#                                                                   #
# Description  : Moves the TCS using apertures                      #
#-------------------------------------------------------------------#
sub point_telescope {   
       
   for ($i=0; $i <$mct; $i++){
       $apx = $offsets[2*$i] * $pixscal;
       $apy = -$offsets[2*$i+1] * $pixscal ;
       if ($DEBUG != 1) {
          if (DefAper($apsetA , $apx, $apy) == -1 ) {goto ERR_SET_APER};

	  if (MoveTel("GOAPER", $apsetA) == -1 ) {goto ERR_GO_APER};
       }
       else {
          print "  DEBUG:: Aperture $apsetA:  xoffset=$apx  yoffset=$apy \n";
	  print "  DEBUG:: Moving telescope to aperture $apsetA \n";
       }
       
       sleep $delaytime;
       
#       take_exposure("Sl-$i/$mct: $title");
       if ($DEBUG != 1) {
           if ( &Take_exposure($num_runs, $exp_time, $clean_imgs, 
                 "Sl-$i/$mct:$title") ) {goto ERR_TAKE_EXPOSURE};
       } else {
	  print 
	  "  DEBUG:: Take Exposure: $num_runs, $exp_time, $clean_imgs, S($i+1)/$mct:$title\n";             
       }
	        
  }

   #Send back to aperture 0
   if ($DEBUG != 1) {
       # resetting aperture 0 to (0,0) (comenta JAP: no es necesario y ademas
       #  puede dar errores si se repite el comando)
       #if (DefAper(0 , 0, 0) == -1 ) {goto ERR_SET_APER};
       
       if (MoveTel("GOAPER", 0) == -1 ) {goto ERR_GO_APER};
   }
   else {
      print "  DEBUG:: Resetting aperture 0 to (0,0)\n";
      print "  DEBUG:: Moving telescope to aperture 0 \n";
   }
   
     
}


sub my_sigint_catcher {
   syslog( 'debug', "DEBUG: Command $0 failed!. Script aborted by user.\n");	
   die("\n Script aborted by user.\n");
}


#- Script exception handlers -------------------------------------------------#
   
ERR_BADUSE:

   print "\nERROR: Invalid command line arguments.\nUsage is:\n";
   syslog( 'debug', "DEBUG: Command $0 failed. Invalid cmd line args.\n");	         
   die ("      lsamp_slit <exposure_time(s)> <title> 
          [-npts=int] [-refpos=int] [-top=int] [-bottom=int]\n
          DEFAULT_VALUES:
          \t -npts=11 (number of points along the slit)\n");
 
ERR_EXIST_SLFILE: 
   syslog( 'debug', "DEBUG: Script failed. $slit_file_name file does not exist.\n");
   die ("\nERROR: $slit_file_name file does not exist \n"); 
   
ERR_LOAD_SLFILE:
   syslog( 'debug', "DEBUG: Script failed. Invalid file ($slit_file_name) format.\n");
   die ("\nERROR: Invalid format of $slit_file_name file\n");
     
ERR_SET_APER:
   syslog( 'debug', "DEBUG: Script failed. Couldn't enter APERTURE to TCS\n");
   die ("\nERROR: Script failed. Couldn't enter APERTURE to telescope.\n");

ERR_GO_APER:
   syslog( 'debug', "DEBUG: Script failed. Couldn't move to defined APERTURE.\n");
   die ("\nERROR: Script failed. TCS Couldn't move to defined APERTURE.\n");
   
ERR_RUN_FAILED: 
   syslog( 'debug', "DEBUG: Script failed. The DAS 'run' command failed.\n");
   die ("\nERROR: Script failed. The DAS 'run' command failed\n");
   
ERR_MULTRUN_FAILED: 
   syslog( 'debug', "DEBUG: Script failed. The DAS 'multrun' command failed.\n");
   die ("\nERROR: Script failed. The DAS multrun command failed\n");

ERR_GETTCSPOS_FAILED:
   syslog( 'debug', "DEBUG: Script failed. Couldn't obtain (TCS.xApNom,TCS.yApNom).\n");
   die("\nERROR: Script failed. Couldn't obtain (TCS.xApNom,TCS.yApNom).\n");

ERR_NOT_APERTURE:
   syslog( 'debug', "DEBUG: Script failed. xApNom, yApNom not defined.\n");
   die("\nERROR: Script failed. xApNom, yApNom not defined. \n");
    
ERR_TAKE_EXPOSURE: 
  syslog( 'debug', "DEBUG: Command $0 failed. The DAS run cmd command failed.\n");
   die ("\nERROR: Script failed. The DAS run cmd command failed\n");  
