Refactored based on @jenius's suggestions