#! /usr/bin/env python

# This python script will read in ELS or SNG binary files and convert to a text file.
# One record per line, columns are the PDS Objects.
# output line ends with \t\n (rather than just \n) to match other example scripts.

from struct import unpack, calcsize

fid_i = open('SNG_200528400_U3.DAT','rb')  # Open input file, ELS or SNG
fid_o = open('output_python.txt','w')      # Open file for output

# Format of Binary Data in Input File
fmt_i = '>HHdBBHHHHHHHHHHHHH'  # the > means Big Endian, H = uint16, d = double, B = uint8

# Desired Format of Data in Output File
fmt_o = '%u\t%u\t%f\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t\n'

fmtsz = calcsize(fmt_i) # this should be 40 for SNG and ELS files

while True:
    entry = fid_i.read(fmtsz) # read file
    if not entry:
        break  # EOF yields null string, exit loop 
    data = unpack(fmt_i,entry)  # unpack the record using the defined input format
    fid_o.write(fmt_o%data)     # write to output file using the defined output format

fid_i.close() # close input file
fid_o.close() # close output file

