Added sanity check, error handling, and improved logic