refactoring, and some bugs addressed