Added input validity checks, bug fix