Major refactor and bug fixes