Mapping function could be more elegant. See here for an alternative - possibly nicer - implementation.