Refactored, added writing to external file functionality