#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 "effective channel count, number of decorrelation terms, a decorrelation term per pass, a list of decorrelation terms per channel per pass";
OUTPUT "a decorrelation samples sub block, the sub block size";
VAR decorrelation_term_count "term count";
VAR decorrelation_terms "decorrelation terms";
VAR decorrelation_samples "decorrelation samples";
VAR effective_channels "effective channels";
VAR sub_block "sub block";
VAR sub_block_size "sub block size";
VAR encoded_samples "encoded samples";
FUNC encode_wv_log2 "encode wv_log2"
"wavpack:encode_wv_log2";
FUNC write_sub_block_header "write sub block header"
"wavpack:write_sub_block_header";
t <- 0 /*total encoded samples*/;
for p <- decorrelation_term_count downto 0 {
    if (17 <= decorrelation_terms[p] <= 18) {
        for c <- 0 to effective_channels {
            encoded_samples[t] <-
                encode_wv_log2(decorrelation_samples[p][c][0]);
            encoded_samples[t + 1] <-
                encode_wv_log2(decorrelation_samples[p][c][1]);
            t <- t + 2;
        }

    } elif (1 <= decorrelation_terms[p] <= 8) {
        for s <- 0 to decorrelation_terms[p] {
            for c <- 0 to effective_channels {
                encoded_samples[t] <-
                    encode_wv_log2(decorrelation_samples[p][c][s]);
                t <- t + 1;
            }
        }
    } elif (-3 <= decorrelation_terms[p] <= -1) {
        encoded_samples[t] <-
            encode_wv_log2(decorrelation_samples[p][0][0]);
        encoded_samples[t + 1] <-
            encode_wv_log2(decorrelation_samples[p][1][0]);
        t <- t + 2;
    }
}
write_sub_block_header(4, 0, t * 2);
for i <- 0 to t {
    encoded_samples[i] -> write 16 signed;
}
return sub_block,2 + (t * 2);
