Refactored file handling, cleaned up and commented code.