changed logic to be safer