refactoring and general bug fixing