changed code to be more robust