Code cleaning

Converted most of the file into a new function to make it easier to
manage and read.