Fix #257 and fix #258 issues and some refactoring