Rewritten all from scratch so it doesn't use any regexes.