Added correct error handling, improved performance.