#This work is licensed under the
#Creative Commons Attribution-Share Alike 3.0 United States License.
#To view a copy of this license, visit
#http://creativecommons.org/licenses/by-sa/3.0/us/ or send a letter to
#Creative Commons,
#171 Second Street, Suite 300,
#San Francisco, California, 94105, USA.

INPUT "an unsigned residual value",kappa,sample_size;
OUTPUT "an encoded residual";
VAR residual "residual";
VAR sample_size "sample size";
VAR MSB "MSB";
VAR LSB "LSB";
VAR encoded_residual "encoded residual";
MSB <- residual / (2 ^ kappa - 1);
LSB <- residual % (2 ^ kappa - 1);
if MSB > 8 {
    511 -> write 9 unsigned /*escape unary value*/;
    residual -> write sample_size unsigned;
} else {
    MSB -> write unary 0;
    if kappa > 1 {
        if LSB > 0 {
            (LSB + 1) -> write kappa unsigned;
        } else {
            0 -> write (kappa - 1) unsigned;
        }
    }
}
return encoded_residual;