Moved the main code to a separate function and added more comments.