#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 "\"mdat\" atom data",channel_count,decoding_parameters;
OUTPUT "1 or 2 decoded channels of PCM data",sample_count;
VAR decoding_parameters "decoding parameters";
VAR bits_per_sample "bits-per-sample";
VAR channel_count "channel count";
VAR has_sample_count "has sample count";
VAR uncompressed_LSBs "uncompressed LSBs";
VAR not_uncompressed "not uncompressed";
VAR sample_count "sample count";
VAR samples_per_frame "samples-per-frame";
VAR channel "channel";
FUNC decode_compressed_frame "decode compressed frame" "alac:decode_compressed_frame";
bits_per_sample,
samples_per_frame <- decoding_parameters;
skip 16;
has_sample_count <- read 1 unsigned;
uncompressed_LSBs <- read 2 unsigned;
not_uncompressed <- read 1 unsigned;
if has_sample_count == 0 {
    sample_count <- samples_per_frame;
} else {
    sample_count <- read 32 unsigned;
}
if not_uncompressed == 1 /*uncompressed frame*/ {
    for i <- 0 to sample_count {
        for c <- 0 to channel_count {
            channel[c][i] <- read (bits_per_sample) signed;
        }
    }
} else {
    channel <- decode_compressed_frame(sample_count,
                                       channel_count,
                                       bits_per_sample,
                                       uncompressed_LSBs,
                                       decoding_parameters);
}
return channel,sample_count;
