WIP refactor and bug correction