Safeguards and fix

Added more safeguards and fixed one of the functions to have a more
consistent program flow