Refactoring, bug fixes and stuff