#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 u[i - 2],zeroes[i - 1],m[i - 1],offset[i - 1],add[i - 1],sign[i - 1],m[i];
OUTPUT u[i - 1];
VAR zeroes "zeroes";
VAR offset "offset";
VAR add "add";
VAR sign "sign";
VAR undefined "undefined";
FUNC write_egc "write Elias gamma code";
if zeroes[i - 1] != undefined {
    write_egc(zeroes[i - 1]);
}
if m[i - 1] == undefined {
    u[i - 1] <- undefined;
    return u[i - 1];
}
if (m[i - 1] > 0) and (m[i] > 0) /*determine unary value*/ {
    if (u[i - 2] == undefined) or (u[i - 2] % 2 == 0) {
        u[i - 1] <- (m[i - 1] * 2) + 1;
    } else {
        u[i - 1] <- (m[i - 1] * 2) - 1;
    }
} elif (m[i - 1] == 0) and (m[i] > 0) {
    if (u[i - 2] == undefined) or (u[i - 2] % 2 == 1) {
        u[i - 1] <- 1;
    } else {
        u[i - 1] <- undefined;
    }
} elif (m[i - 1] > 0) and (m[i] == 0) {
    if (u[i - 2] == undefined) or (u[i - 2] % 2 == 0) {
        u[i - 1] <- m[i - 1] * 2;
    } else {
        u[i - 1] <- (m[i - 1] - 1) * 2;
    }
} elif (m[i - 1] == 0) and (m[i] == 0) {
    if (u[i - 2] == undefined) or (u[i - 2] % 2 == 1) {
        u[i - 1] <- 0;
    } else {
        u[i - 1] <- undefined;
    }
}
if u[i - 1] != undefined /*write unary value*/ {
    if u[i - 1] < 16 {
        u[u - 1] -> write unary 0;
    } else {
        16 -> write unary 0;
        write_egc(u[i - 1] - 16);
    }
}
if add[i - 1] > 0 /*write non unary values*/ {
   p <- floor(log 2 {add[i - 1]});
   e <- 2 ^ {p + 1} - add[i - 1] - 1;
   if offset[i - 1] < e {
       offset[i - 1] -> write p unsigned;
   } else {
       floor((offset[i - 1] + e) / 2) -> write p unsigned;
       (offset[i - 1] + e) % 2 -> write 1 unsigned;
   }
}
sign[i - 1] -> write 1 unsigned /*write sign bit*/;
return u[i - 1];
