Improve robustness and simplify code