Major bug fix and refactor