Code cleanup

Here is a patch performing minor code improvements (foreach loops, generics, unused imports, StringBuilders, etc)