Tidy and re-sync

Various bug fixes and refactoring - re-sync with Wonderflux latest commit.