A little restructuring and some error handling