calculation bug fix and some refactoring