After much work, an neary functional version.
RAW codes are still shabby