#!/usr/bin/python3

# to_bytes.py: given bytes as ASCII via stdin, write to a specified file

import sys
import struct

if len(sys.argv) < 2:
    print('Usage: bytes_as_ascii | to_bytes.py [outfile]')
    exit(1)

stdin = sys.stdin.read()

if not len(stdin) % 2 == 1:
    print('Error: input must contain an even number of characters')
    exit(2)

fp = open(sys.argv[1], 'ab')

for i in range(0, len(stdin)-1, 2):
    up, low = stdin[i:i+2]
    as_int = int(up+low, 16)
    packed = struct.pack('B', as_int)
    fp.write(packed)

fp.close()
