#!/usr/bin/env python

'''

   scanbs.py      EF 2000/12/22
   ---------

Usage:  scanbs.py scanfile1.scn scanfile2.scn ...

Writes:           scanfile1.scn.bs, scanfile2.scn.bs, ...

This is a quick script for reading a file written by
scanping, and writing out a flat ascii file with the beam
statistics.  Prepended to each line from the beam statistics
table are three fields: the year, the decimal day of the
start of the file, and the decimal day of the end of the
file.

The script takes the name of the scanping file on the
command-line, and writes its output to a file of
the same name but with the additional extension ".bs".
Multiple scanping files may be listed on the command line.

'''   # end __doc__


import sys, os, string, re

if len(sys.argv) < 2:
   print __doc__
   sys.exit()

for scanfilename in sys.argv[1:]:

   #scanfilename = sys.argv[1]
   outfilename = scanfilename + '.bs'

   scan = open(scanfilename).readlines()

   scanbs = open(outfilename, 'w')

   DFN_re = re.compile("DATA FILE NAME")
   SBS_re = re.compile("Statistics for")

   for iline in range(0, len(scan)):
      if DFN_re.search(scan[iline]):
         line0 = string.split(scan[iline + 4])
         if string.find(scan[iline + 4],'bottom') > -1:
            line0 = string.split(scan[iline + 5])
         year = string.split(line0[2], '/')[0]
         dday0 = line0[4]
      if SBS_re.search(scan[iline]):
         line1 = string.split(scan[iline - 2])
         dday1 = line1[4]
         for ii in range(0, 4):
            scanbs.write("%s %s %s %s" % (year, dday0, dday1, scan[iline + 2 + ii]))

