Added processing of error cases. Cleaned up the code. Added docs