Cleaned up the code and commented relevant parts.