First draft of refactor (untested)
Bug Fixes