Refactoring hairy controller. Looks much nicer now