A few structural changes to break down this script into easily manageable parts.

Because I heard that this is a good way to write shell scripts.