Added slightly modified version with better error checking.