Adapted for multiple destinations.
Added comments and changed var names for clarity.
Fixed merge conflicts.