Improve robustness and add tests.