Changes based on Leo's review including cleaner code, better error handling