Cleaned up code, functionalized portions, and touched up error handling.