Refactor into functions, allow importing as a module
Handle errors when file open fails