Made some loops more idiomatic (edited in line, haven't tested)