Better error handling

Several improvements in error handling; minor code clean-up and fixes