Refactored and made pep8-compliant