Improved the code from David's suggestions.