Refactor. Change function order to more logical