total refactor, modestly working