wip: refactor, fix bugs, add comments