Big code refactor, and test refactor