Convert sections of the script to functions

Converted sections of the script to functions where appropiate.