final refactor, updated with tweaks from production