Moved code from controllers to models