Refactored map_foreach* functions.

Removed a lot of duplicated code.
Added some documentation & comments.