Improved error handling

Bug fixes