Suggested improvements (crazy4cs and Euan T.) and an additional check added for performance