#!/bin/env python

# start phase somewhere
p=False

# create varicode table
import varicode_table
varicode=varicode_table.build_vctable()

# clear byte out accumulator
out=[]

# open input and output files
tfh = open("text","r")
pskfh = open("psk","w")

# write some idle to sync first, current state of phase is False
# so last bit written must be 0, i.e., 0xAA (10101010)
for i in range(0,7):
  pskfh.write(chr(0xaa))

# start read loop
line = tfh.readline()

# do untill end of file
while line != '':
  # clean out varicode line buffer
  vline=[]
  # loop over line, lookup varicode for each char in input line, adding
  # between character spacing (00)
  for i in range(0, len(line)):
    vline+=varicode[ord(line[i])]+'00'

  # convert varicode to phase shifts
  for i in range(0,len(vline)):
    if vline[i]=='0':	# phase change
      p=not p
    if p==False: out+='0'
    else: out+='1'
    if len(out)==8: # do we have a full byte?
      c=128*int(out[0])+64*int(out[1])+32*int(out[2])+16*int(out[3])+8*int(out[4])+4*int(out[5])+2*int(out[6])+int(out[7])
      pskfh.write(chr(c))
      out=[]	# clear byte out, may have residual for next line if we reach
                # EOL before len(out)==8

  line = tfh.readline()	# next line

# clean up residual in 'out' if any
if len(out) != 0:
  for i in range(len(out),8):
    if out[i-1]=='0': out+='1'
    else: out+='0'
# then write it
  c=128*int(out[0])+64*int(out[1])+32*int(out[2])+16*int(out[3])+8*int(out[4])+4*int(out[5])+2*int(out[6])+int(out[7])
  pskfh.write(chr(c))

# phase of idle character depends on last bit of out
  if out[7]=='0': ic=0xaa
  else: ic = 0x55
else:
  ic = 0xaa

# and some idle
for i in range(0,7):
  pskfh.write(chr(ic))

# that should be all lines in file, close and exit
tfh.close()
pskfh.close()

