#!/usr/bin/env python3
# morse - text to Morse code and back
# Usage: morse TEXT... | morse --decode CODE... | morse --file FILE
#   Letters, digits and common punctuation. Words are separated by " / ".
#   Input may also come from stdin.
import argparse, sys

MORSE = {
    "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.",
    "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..",
    "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.",
    "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-",
    "Y": "-.--", "Z": "--..",
    "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-",
    "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.",
    ".": ".-.-.-", ",": "--..--", "?": "..--..", "'": ".----.", "!": "-.-.--",
    "/": "-..-.", "(": "-.--.", ")": "-.--.-", "&": ".-...", ":": "---...",
    ";": "-.-.-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "_": "..--.-",
    '"': ".-..-.", "$": "...-..-", "@": ".--.-.",
}
REV = {v: k for k, v in MORSE.items()}

def encode(text):
    out = []
    for word in text.upper().split():
        out.append(" ".join(MORSE.get(ch, "?") for ch in word))
    return " / ".join(out)

def decode(code):
    out = []
    for word in code.strip().split(" / "):
        out.append("".join(REV.get(tok, "?") for tok in word.split()))
    return " ".join(out)

def selftest():
    assert encode("SOS") == "... --- ..."
    assert decode("... --- ...") == "SOS"
    assert encode("HELLO WORLD") == ".... . .-.. .-.. --- / .-- --- .-. .-.. -.."
    assert decode(encode("HELLO WORLD 123")) == "HELLO WORLD 123"
    assert encode("hi?") == ".... .. ..--.."
    print("morse selftest: ok (SOS, hello world, digits, punctuation, round-trip)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="morse",
        description="Text to Morse code and back.")
    p.add_argument("text", nargs="*", help="text to encode (or Morse to decode with --decode)")
    p.add_argument("--decode", "-d", action="store_true", help="decode Morse to text")
    p.add_argument("--file", "-f", help="read input from FILE instead of arguments")
    p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    if a.file:
        try:
            data = open(a.file).read()
        except OSError as e:
            print(f"morse: {e}", file=sys.stderr); return 2
    elif a.text:
        data = " ".join(a.text)
    elif not sys.stdin.isatty():
        data = sys.stdin.read()
    else:
        p.error("give TEXT, --file, or pipe input on stdin")
    data = data.strip("\n")
    print(decode(data) if a.decode else encode(data))
    return 0

if __name__ == "__main__":
    sys.exit(main())
