1st pass rewrite

Old code too hard to understand / maintain...