#!/usr/bin/env python3

import numpy as np
import argparse, os, struct

parser = argparse.ArgumentParser()
parser.add_argument('voltagefile', help="RFSOC Voltage Dump")
args = parser.parse_args()

inputfile = args.voltagefile

fpre, fext = os.path.splitext(inputfile)

if fext == "":
    outputfile = fpre + ".codif"
else:
    outputfile = fpre + ".out" + fext

print(inputfile, "->", outputfile)

fin = open(inputfile, "rb")

header = np.fromfile(fin, dtype = np.dtype('u8'), count=8)
fin.close()

frame = header[0] & np.uint64(0xFFFFFFFF)
seconds = (header[0]>>np.uint64(32)) & np.uint64(0x3FFFFFFF)
iscomplex = (header[0]>>np.uint64(62)) & np.uint64(0x1)
invalid = (header[0]>>np.uint64(63)) & np.uint64(0x1)

stationid = int(header[1] & np.uint64(0xFFFF))
representation = int((header[1]>>np.uint64(22)) & np.uint64(0xF))
epoch = int((header[1]>>np.uint64(26)) & np.uint64(0x3F))
framelength = int(((header[1]>>np.uint64(32)) & np.uint64(0xFFFFFF))) * 8
nbits = int(((header[1]>>np.uint64(56)) & np.uint64(0x1F)))
version = int(((header[1]>>np.uint64(61)) & np.uint64(0x7)))

groupid = int(header[2] & np.uint64(0xFFFF))
threadid = int((header[2]>>np.uint64(16)) & np.uint64(0xFFFF))
nchan = int(((header[2]>>np.uint64(32)) & np.uint64(0xFFFF))) + 1
blocklength = int((header[2]>>np.uint64(48)) & np.uint64(0xFFFF))

period = int((header[3]>>np.uint64(32)) & np.uint64(0xFFFF))

totalsamples = header[4]

sync = int((header[5]>>np.uint64(32)) & np.uint64(0xFFFFFFFF))

#print("frame: ", frame);
#print("seconds: ", seconds)
#print("invalid: ",invalid)
#print("complex: ", iscomplex)
#
#print("stationid:  ", stationid)
#print("repr: ", representation)
#print("epoch:  ", epoch)
#print("framelength:  ", framelength)
#print("nbits:  ", nbits)
#print("version:  ", version)
#
#print("groupid:  ", groupid)
#print("threadid:  ", threadid)
#print("nchan:  ", nchan)
#print("blocklength:  ", blocklength)
#
#print("period:  ", period)
#
#print("totalsamples:  ", totalsamples)
#
#print("sync: 0x{:08X}".format(sync))

framesamples = framelength//2 # 16 bit integers

with open(inputfile) as fin:
    with open(outputfile, "w") as fout:
        while True:
            header = np.fromfile(fin, dtype = np.dtype('u8'), count=8)
            if header.size==0: break
            data = np.fromfile(fin, dtype=np.dtype('int16'), count=framesamples)
            if data.size==0: break
            data[1::2] = - data[1::2]
            header.tofile(fout)
            data.tofile(fout)
