Added documentation and fixed some error handling