#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 channel of shifted PCM samples, sample count of channel, bits-per-sample, the size of uncompressed LSBs in bytes, a list of uncompressed LSBs; default block size from encoding parameters";
INPUT shifted,sample_count,bits_per_sample,
uncompressed_LSBs,LSB,encoding_parameters;
OUTPUT "non-interlaced frame, non-interlaced frame size";
VAR shifted "shifted";
VAR encoding_parameters "encoding parameters";
VAR LSB "LSB";
VAR uncompressed_LSBs "uncompressed LSBs";
VAR sample_count "sample count";
VAR bits_per_sample "bits-per-sample";
VAR block_size "block size";
VAR sample_size "sample size";
VAR QLP_coeff "QLP coefficient";
VAR QLP_coeff_count "QLP coefficient count";
VAR residual "residual block";
VAR residual_size "residual block size";
VAR compressed_frame "compressed frame";
VAR compressed_frame_size "compressed frame size";
FUNC compute_QLP_coeff "compute QLP coefficient and residual"
"alac:compute_qlp_coeffs";
FUNC write_subframe_header "write subframe header"
"alac:write_subframe_header";
block_size <- encoding_parameters;
sample_size <- bits_per_sample - (uncompressed_LSBs * 8);
0 -> write 16 unsigned /*unused*/;
if sample_count != block_size {
    1 -> write 1 unsigned /*has sample count*/;
    uncompressed_LSBs -> write 2 unsigned /*uncompressed LSBs*/;
    0 -> write 1 unsigned /*not compressed*/;
    sample_count -> write 32 unsigned;
} else {
    0 -> write 1 unsigned /*has sample count*/;
    uncompressed_LSBs -> write 2 unsigned /*uncompressed LSBs*/;
    0 -> write 1 unsigned /*not compressed*/;
}

0 -> write 8 unsigned /*interlacing shift*/;
0 -> write 8 unsigned /*interlacing leftweight*/;
;

QLP_coeff,QLP_coeff_count,residual,residual_size <-
compute_QLP_coeff(shifted,
                  sample_count,
                  sample_size,
                  encoding_parameters);

write_subframe_header(QLP_coeff,QLP_coeff_count);

if uncompressed_LSBs > 0 {
    for i <- 0 to sample_count * 1 {
        LSB[i] -> write (uncompressed_LSBs * 8) unsigned;
    }
}

residual -> write residual_size unsigned;
return compressed_frame,compressed_frame_size;
