#!/usr/bin/python

import sys, getopt, random

def usage(err=""):
  if err != "":
    sys.stderr.write(err+'\n')
  sys.stderr.write("Usage: flashify <options> [infile [outfile]]\n")
  sys.stderr.write("Convert a binary file into a flash image\n")
  sys.stderr.write("    -s       Introduce single-bit errors\n")
  sys.stderr.write("    -d       Introduce double-bit errors\n")
  sys.stderr.write("    -p <num> Flash page size 'num' bytes\n")
  sys.exit(0)

global ECC_UNIT
ECC_UNIT=512
def computeEcc(buf):
  parity = [0]*12
  parity_p = [0]*12
  bits = [0]*8

  for count in xrange(0, ECC_UNIT): 
    for bitCount in xrange(0, 8):
      bits[bitCount] = (ord(buf[count]) & (1 << bitCount)) >> bitCount
    allBits = bits[0] ^ bits[1] ^ bits[2] ^ bits[3] ^ bits[4] ^ bits[5] ^ bits[6] ^ bits[7];

    parity[0] = parity[0] ^ bits[1] ^ bits[3] ^ bits[5] ^ bits[7];
    parity_p[0] = parity_p[0] ^ bits[0] ^ bits[2] ^ bits[4] ^ bits[6];
    parity[1] = parity[1] ^ bits[2] ^ bits[3] ^ bits[6] ^ bits[7];
    parity_p[1] = parity_p[1] ^ bits[0] ^ bits[1] ^ bits[4] ^ bits[5];
    parity[2] = parity[2] ^ bits[4] ^ bits[5] ^ bits[6] ^ bits[7];
    parity_p[2] = parity_p[2] ^ bits[0] ^ bits[1] ^ bits[2] ^ bits[3];

    for parityCount in xrange(3, 12):
      if (count >> (parityCount - 3)) & 1:
        parity[parityCount] = parity[parityCount] ^ allBits;
      else:
        parity_p[parityCount] = parity_p[parityCount] ^ allBits;

  ecc = 0
  for count in xrange(0, 12):
    ecc = ecc | ((parity[count] & 0x1) << (16 + count)) | \
                ((parity_p[count] & 0x1) << count)
  return ecc

try:
  ops, args = getopt.getopt(sys.argv[1:], "p:sd")
except getopt.GetoptError, reason:
  usage(str(reason))

input = sys.stdin
output = sys.stdout
if len(args) == 1:
  input = open(args[0])
elif len(args) == 2:
  input = open(args[0])
  output = open(args[1], "w")
elif len(args) > 2:
  usage("Too many arguments")

pageSize = 2048
spareSize = 64
errors = 0
for op, a in ops:
  if op == '-s':
    errors = 1
  elif op == '-d':
    errors = 2
  elif op == '-p':
    if a == "2048":
      pageSize = 2048
      spareSize = 64
    elif a == "512":
      pageSize = 512
      spareSize = 16
    else:
      usage("Unknown page size '%s'" % a)

chunk = input.read(pageSize)
while len(chunk) == pageSize:
  eccStr = ""
  for x in xrange(0, pageSize, ECC_UNIT):
    ecc = computeEcc(chunk[x:x+ECC_UNIT])
    eccStr = eccStr + chr((ecc >>  0) & 0xff)
    eccStr = eccStr + chr((ecc >>  8) & 0xff)
    eccStr = eccStr + chr((ecc >> 16) & 0xff)
    eccStr = eccStr + chr((ecc >> 24) & 0xff)
    for e in xrange(errors):
      if random.randint(0, 9) != 0:
        byte = random.randint(x, x+ECC_UNIT-1)
        chunk = chunk[:byte] + chr(ord(chunk[byte]) ^ (1 << random.randint(0, 7))) + chunk[byte+1:]
      else:
        byte = random.randint(4*x/ECC_UNIT, 4*x/ECC_UNIT+3)
        eccStr = eccStr[:byte] + chr(ord(eccStr[byte]) ^ (1 << random.randint(0, 7))) + eccStr[byte+1:]
  output.write(chunk)
  output.write(chr(0)*(spareSize-len(eccStr))+eccStr)
  chunk = input.read(pageSize)
