bug fix and some refactoring of logic