Fixed some duplicate code and reordered things