Code clean up, moving code into separate functions