Lots of reorganization to make the code cleaner