#!/usr/bin/env python3

import argparse, sys, re
from astropy import units as u
from astropy.coordinates import Angle

parser = argparse.ArgumentParser()
#parser.add_argument('-d', '--doublesideband', '-doublesideband', help="Double sideband", action="store_true")
#parser.add_argument('-p', '--plot', '-plot', help="Plot results", action="store_true")
#parser.add_argument('-azel', '--azel', help="Output AzEl", action="store_true")
parser.add_argument('horizons', help="Horizons output")
parser.add_argument('freq', help="Transmit Frequency (MHz)", type=float)

args = parser.parse_args()

filename = args.horizons

reSOE = re.compile("\$\$SOE")
reEOE = re.compile("\$\$EOE")
reCutoff = re.compile(".*Elevation Cut-off Requested")
reTableFormat = re.compile("Table format")

C = 299792458 # Speed of light

count = -1

def findColumn(name, values):
  for i, value in enumerate(values):
    if value==name:
      return(i)
  raise ValueError("Failed to find '{}' in {}".format(name,values))

sched = []

with open(filename, "r") as h:
  foundSOE = False
  foundEOE = False
  foundHeader = False
  for l in h:
    line = l.strip()

    if reTableFormat.match(line):
        count = 2
    elif reSOE.match(line):
        foundSOE = True
        break

    if count==0:
      columns = [x.strip() for x in line.split(",")]
    if count>=0:  count -= 1

  if not foundSOE:
    print('Failed to fine "$$SOE" section')
    sys.exit(1)

  iDate = findColumn('Date__(UT)__HR:MN:SS', columns)
  iDop = findColumn('deldot', columns) # km/s

  for l in h:
    line = l.strip()
    if line == "": continue
    if reCutoff.match(line): continue

    if reEOE.match(line):
        foundEOE = True
        break

    data = [x.strip() for x in line.split(",")]
    sched.append([data[iDate],data[iDop]])
    
  if not foundSOE:
    print('Failed to find "$$EOE"')
    sys.exit(1)

months = {
    'Jan': "01",
    'Feb': "02",
    'Mar': "03",
    'Apr': "04",
    'May': "05",
    'Jun': "06",
    'Jul': "07",
    'Aug': "08",
    'Sep': "09", 
    'Oct': "10",
    'Nov': "11",
    'Dec': "12"
}

for s in sched:
    date = s[0]
    Dop = s[1]

    (d, t) = date.split()
    (y, m, day) = d.split("-")
    m = months[m]

    obsFreq = args.freq * (1 - float(Dop)*1e3/C)

    print("{}-{}-{}T{} {:.6f}".format(y, m, day, t, obsFreq))


