Improved error handling. Added documentation