Bug fix and better error handling