updated code to make more robust