Bug fixing anf general refactoring