Version 2 of function with additional error checking