Refactor, fix minor bugs