Fixed numerous small bugs and fixed aliasing issue

Files were not being aliased correctly because of a closure
issue within a foreach loop. Solution was to move all code
that was previously inside of the foreach loop into a separate
function that was then called by the loop.