fixed bug and some refactoring