Added code to handle non-blocking reads correctly. Better error handling
was also added.