Refactor & fix bugs