You may consider making this a function in the controller since it's so complex.