Refactor functions to handle invalid input arguments and remove redundancy