Convert most of the code to use for-each loops