Code consolidation

Added foreach loop instead of a bunch of if statements , fixed some
comments, changed some function positions