Refactor to simplify logic. Also fix bug causing panics that occur in tests