#!/usr/bin/env python3
# Un-convert input from hexadecimal.
import argparse
import io
import re
import sys

parser = argparse.ArgumentParser()
parser.add_argument("-a", metavar="STRING", help="input text")
args = parser.parse_args()

if args.a is not None:
    input = io.StringIO(args.a)
else:
    input = sys.stdin

while hasattr(sys.stdout, "encoding"):
    sys.stdout = sys.stdout.detach()

carry = ""
while buf := input.read(4096):
    # "0x" stripping ought to only be applied to 1st line, but it's fine
    buf = re.sub(r"^0x", "", buf)
    buf = re.sub(r"\s+", "", buf)
    #buf = re.sub(r"[^0-9A-Fa-f]", "", buf)
    # After stripping whitespace, we might end up with an odd number of nibbles
    buf = carry + buf
    if len(buf) % 2:
        carry = buf[-1]
        buf = buf[:-1]
    else:
        carry = ""
    sys.stdout.write(bytes.fromhex(buf))
