Break up into more functions, improve error handling