Refactor API code and fix invalid input handling

Simplify the code and add additional checks for invalid input.

Change-Id: Ic1fe978730af7715c72f58cd7af46ab753e614e8