Re-re-refactored, much smaller now.