Improved implementation and added error handling code.