heavy refactor for clarity