I'd create a model for most of this, instead of shoving it into the controller. That way we can unit test them independently.