Make more resilient to error conditions and do some cleanup