Refactoring, minor bugs fixed