fixed errors, some refactoring