Added processing of error cases
Added documentation
Cleaned up code