improved error handling, fixed some notices.