Significantly more error handling added.