Made code slightly more robust