#! /usr/bin/env python3

import os
import sys
import signal
import hashlib
import logging
import argparse

parser = argparse.ArgumentParser(description=sys.argv[0])
parser.add_argument('filename', help='Name of file to read')
parser.add_argument('-m', '--md5', action='store_true', help='Calculate MD5 checksum')
parser.add_argument('-v', '--verbose', action='count', help='Enable debugging')
args = parser.parse_args()

logging.basicConfig(format='%(asctime)s %(levelname)s %(pathname)s:%(lineno)d %(msg)s')
log = logging.getLogger()
log.setLevel(logging.WARNING - (args.verbose or 0)*10)

signal.signal(signal.SIGPIPE, lambda signum, stack_frame: exit(0))

md5 = None
if args.md5:
  md5 = hashlib.md5()

if os.path.exists(args.filename):
  if not os.path.isdir(args.filename):
    stream = open(args.filename, 'r' if sys.version_info.major == 2 else 'rb')
    log.info('{args.filename!r} opened'.format(**locals()))
    pos = 0
    while True:
      c = stream.read(1)
      if c:
        log.info('read: {c!r}'.format(**locals()))
        if args.md5:
          md5.update(c)
        hex = ord(c)
        if sys.version_info.major == 3:
          c = c.decode('cp437')
        print('{pos:8} 0x{hex:02x} {c!r}'.format(**locals()))
        pos += 1
      else:
        break
    if args.md5:
      print('md5: {}'.format(md5.hexdigest()))
    stream.close()
  else:
    parser.error('Cannot read: {args.filename!r}'.format(**locals()))
else:
  parser.error('Cannot find: {args.filename!r}'.format(**locals()))
