moved out as much as possible of code from controller