Used some more AWK to make this slightly less horrible. Would like to rewrite in AWK entirely, if possible.