Foreach loops are now managed, also ensured control groups are closed by eof.
Reorganised control flow management, removed extraneous code.