Edited as per Hound's suggestions for improving code quality.