major refactoring
fix some minor bugs