use one loop to encode