Corrected exit condition in encoding process