Moved code from main into separate functions