refactor and bug fix

Refactor and bug fixes.