First stab at rewrite, lots of TODOs left