better prevention and error handling for TypeError in this complex function