fixes #129 #119 and add code refactoring