Finish up: bug fixing, refactoring