Refactored out some stuff from controller to libraries