Add more assertions and error checks
Use errno instead of hardcoded ENOMEM