Refined some fuctions and moved out from controller to class.