fix few bugs and make some refactoring