restructured code into a functions