#!/usr/bin/env bash
#
#   z80dasm-clean - clean up z80dasm ouput
#
#   This takes `z80dasm` output on stdin and cleans it up to look nicer
#   and be more usable with the t8dev assembly coding style. This assumes
#   the assembler (typically ASL) is configured to use $nnnn hex number
#   format, `db` and `dw` for defining words and bytes, and so on.
#
#   You may add an additional sed scripts to do further work by giving
#   it as an argument on a command line.
#
#   It requires GNU sed, mainly because BSD sed doesn't allow comments.
#
set -Eeuo pipefail

addsed=/dev/null
[[ $# -gt 0 ]] && { addsed="$1"; shift; }
[[ $# -gt 0 ]] && { echo 1>&2 "Only one arg permitted"; exit 2; }

sed -E -e '
        /^[^\t;].*:$/{N;s/\n//}     # join labels to next line
        s/l([0-9a-f]{4})h/unk\U\1/g # more readable label format
        s/sub_([0-9a-f]{4})h/sub_\U\1/g
        s/0x([0-9a-f]{4})/$\U\1/    # number format 0xnnnn → $NNNN
        s/0([0-9a-f]{4})h/$\U\1/    # number format 0nnnnh → $NNNN
        s/0([0-9a-f]{2})h/$\U\1/    # number format 0nnh → $NN
        s/\t[a-z][a-z] /&  /        # indent operand after 2-letter mnemonic
        s/\t[a-z]{3} /& /           # indent operand after 3-letter mnemonic
        s/^\t/\t    /               # indent non-label lines
        s/:\t/\t    /               # indent menmonic on label lines, remove :
        s/ defb / db    /           # ASL syntax
        s/ defw / dw    /           # ASL syntax
        ' -f "$addsed" \
    | sed -E -e 's/[ \t]+$//  # remove any trailing whitesapce' \
    | expand
#   Notes:
#   • Trailing whitespace removal is done as a separate command because
#     when incuded at the end of the original sed script it will not affect
#     lines that were split (e.g., to add a blank line after another).
