added error handling and minor style changes