#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 "a signed residual",entropies,
u[i - 2], zeroes[i - 1], m[i - 1], offset[i - 1], add[i - 1], sign[i - 1];
OUTPUT zeroes[i],m[i],offset[i],add[i],sign[i],entropies,u[i - 1];
VAR zeroes "zeroes";
VAR residual "residual";
VAR offset "offset";
VAR add "add";
VAR sign "sign";
VAR entropies "entropies";
VAR undefined "undefined";
FUNC encode_residual "encode residual" "wavpack:encode_residual";
FUNC flush_residual "flush residual" "wavpack:flush_residual";
if (zeroes[i - 1] != undefined) and (m[i - 1] == undefined) /*in a block of zeroes*/ {
    if residual == 0 /*continue block of zeroes*/ {
        zeroes[i] <- zeroes[i - 1] + 1;
        m[i] <- m[i - 1];
        offset[i] <- offset[i - 1];
        add[i] <- add[i - 1];
        sign[i] <- sign[i - 1];
        u[i - 1] <- u[i - 2];
    } else /*end block of zeroes*/ {
        zeroes[i] <- zeroes[i - 1];
        m[i],offset[i],add[i],sign[i],entropies[c] <-
        encode_residual(residual, entropies[c]);
        u[i - 1] <- u[i - 2];
    }
} else /*not in a block of zeroes*/ {
    if residual == 0 /*start new block of zeroes*/ {
        zeroes[i] <- 1;
        m[i],offset[i],add[i],sign[i] <- undefined;
        u[i - 1] <- flush_residual(u[i - 2],
                                   zeroes[i - 1],
                                   m[i - 1],
                                   offset[i - 1],
                                   add[i - 1],
                                   sign[i - 1],
                                   0);
        entropies[0][0],entropies[0][1],entropies[0][2],
        entropies[1][0],entropies[1][1],entropies[1][2] <- 0;
    } else /*false alarm block of zeroes*/ {
        zeroes[i] <- 0;
        m[i],offset[i],add[i],sign[i],entropies[c] <-
        encode_residual(residual, entropies[c]);
        u[i - 1] <- flush_residual(u[i - 2],
                                   zeroes[i - 1],
                                   m[i - 1],
                                   offset[i - 1],
                                   add[i - 1],
                                   sign[i - 1],
                                   m[i]);
    }
}
return zeroes[i],m[i],offset[i],add[i],sign[i],entropies[c],u[i - 1];
