Some major refactoring to make everything neater