Merged Ismail's changes and fixed a bug in a loop.