Bug fixing and general refactoring