#!/usr/bin/python

import slalib as S
import logging
import os
import os.path
import optparse
import sys

import MOPS.Utilities as Utilities

#------------------------------------------------------------------------------
# Entry point.
#------------------------------------------------------------------------------
def main(args=sys.argv[1:]):
    
    # Verify that an input file was specified
    if (len(args) < 2):
        parser.error('Input files were not specified.')
    # <-- end if
    
    # Get logger and set logging level. Typically set level to info.
    # Add null handler to logger to avoid the No handlers could be found
    # for logger XXX error if a handler is not found in a higher level logger
    global gLogger  
    gLogger = Utilities.getLogger('SLA', None)
    gLogger.setLevel(logging.DEBUG)
    
    # Verify that input file exists
    input_file = args[0]
    if (not os.path.exists(input_file)) :
        gLogger.error("SLATEST: %s does not exist!!" % (input_file))
        raise RuntimeError("SLATEST: %s does not exist!!" % (input_file))
    # <-- end if
    
    input_file2 = args[1]
    if (not os.path.exists(input_file2)) :
        gLogger.error("SLATEST: %s does not exist!!" % (input_file2))
        raise RuntimeError("SLATEST: %s does not exist!!" % (input_file2))
    # <-- end if
   
    res = []
    status = 0
    Deg2Rad = 0.01745329252
    gLogger.info("SLATEST: Opening %s" % (input_file))
    gLogger.info("SLATEST: Opening %s" % (input_file2))    
    try:
        fh = open(input_file, "r")
        fh2 = open(input_file2, "r")
        while True:
            line = fh.readline()
            line2 = fh2.readline()
            if len(line) == 0: # Zero length indicates EOF
                break
            # <-- end if

            # Parse the line for its orbital elements.
            cols = line.split(" ")
            ra = float(cols[0]) * Deg2Rad
            dec = float(cols[1]) * Deg2Rad

            cols2 = line2.split(" ")
            ra2 = float(cols2[0]) * Deg2Rad
            dec2 = float(cols2[1]) * Deg2Rad
            
            # Ask SLA lib for angular seperation between the two points.
            sep = S.sla_dsep(ra, dec, ra2, dec2)
            
            res.append(sep)
        # <-- end while
        fh.close()
        fh2.close()
        
        # Write out results        
        for sep in res :
            sys.stdout.write("%s\n" % (sep))
        # <-- end for
                    
    except Exception, e:
        gLogger.exception("SLATEST: %s" % (str(e)))
        sys.stderr.write(str(e))
        raise SystemExit(1)
    # <-- end try
# <-- end def

if __name__ == '__main__':
    sys.exit(main())
# <-- end if           