refactor and change order of functions