Cleanup and improved error checks