Cleaned up code, factored out some code into additional methods.