#!/usr/bin/env python3
#########################################################################
#  python script to rewrite the operational regular bulletin into web 
#    page format 
#
#  History:
#
#          Sep. 2022      Huang and Schnapp     - New script created
#
##########################################################################
import sys
import logging
from dataclasses import dataclass
import pandas as pd
from datetime import datetime

Arg  = sys.argv[1]
HH = Arg[8:10]
MM = Arg[10:12]

INFILE = sys.argv[2]
OUTFILE = sys.argv[3]

#f = open('lmp_lavtxt.t' + HH + MM +'z','r')
f = open(INFILE,'r')
bull = f.readlines()
f.close()

tbl = 'lmp_station.tbl'

#w = open('lavlamp_' + HH + MM + '.txt','w')
w = open(OUTFILE,'w')

def from_mos2ktbl(tbl):
    df = pd.read_csv(tbl, sep=':', usecols=[0,1,2,3,5,6,7,18],
            names=['call', 'link', 'name', 'state', 'elev', 'lat', 'lon', 'comment'], quoting=3)
            # quoting = 3 prevents unclosed quotes from blocking parse on sep and \n
    df['call'] = df['call'].str.strip()
#    df['lat'] = df['lat'].apply(south_to_negative)
#    df['lon'] = df['lon'].apply(west_to_negative)
    return df

stations = from_mos2ktbl(tbl) 
stations = stations.set_index('call')

print(stations)

'''
Write to the output file
'''

def writeStations(leadingStn,longname,Arg,w):
   YR = Arg[0:4]
   Mon = Arg[4:6]
   DY = Arg[6:8]
   HH = Arg[8:10]
   MM = Arg[10:12]
   
   Mon1 = Mon[0]
   if Mon1 == "0":
      Mon = " " + Mon[1]

   w.write(" " + leadingStn + "   " + longname + "  " + "GFS LAMP " + HH + MM + " UTC" + "  " + Mon + "/" + DY + "/" + YR +"\n")  

last_line_blank = False
for s in bull:
   if last_line_blank:
      call = s.split()[0]
      name = stations.loc[call]['name']
#      print(call)
 #     print(name)
  #    print(w)
      
      writeStations(call,name,Arg,w)
      last_line_blank = False
   else:
      w.write(s)
      if s.strip() == '':
         last_line_blank = True
 
w.close()