Some loops were inside another loop where they needn't be. I don't think functionality is affected, but this should be cleaner and faster.