revised code based on Josh's comment