Make API more robust.

It crashed on certain faulty inputs