Refactored some python code, and added comments