Made code more robust for handling unexpected situations