Fixing some errors when multiple foreach performed and adding unit tests.