Refractored the code to the controller. ref #4