Refactor code to fix various problems. #45, #46. Closes #44