Did some major code refactoring to fix bugs