#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 "signed PCM samples",block_size,initial_history,history_multiplier,
maximum_k,interlacing_shift,leftweight_min,leftweight_max;
OUTPUT "an encoded mdat atom";
VAR encoding_parameters "encoding parameters";
VAR block_size "block size";
VAR initial_history "initial history";
VAR history_multiplier "history multiplier";
VAR maximum_k "maximum K";
VAR interlacing_shift "interlacing shift";
VAR leftweight_min "minimum leftweight";
VAR leftweight_max "maximum leftweight";
VAR pcm_data "PCM data";
VAR pcm_frames "PCM frames";
VAR bits_per_sample "bits-per-sample";
VAR channel_count "channel count";
VAR total_mdat_bytes "total mdat bytes";
VAR alac_frame "ALAC frame";
VAR alac_frame_length "ALAC frame length";
VAR mdat_atom "mdat atom";
FUNC read_frame "read PCM frames from input";
FUNC encode_frameset "encode ALAC framest" "alac:encode_frameset";
FUNC return_to_start "return to start of mdat atom";
encoding_parameters <-
block_size,
initial_history,
history_multiplier,
maximum_k,
interlacing_shift,
leftweight_min,
leftweight_max;
total_mdat_bytes <- 8;
total_mdat_bytes -> write 32 unsigned /*placeholder length*/;
bytes(109, 100, 97, 116) -> write 4 bytes /*atom name*/;
pcm_data,pcm_frames <- read_frame(block_size);
while pcm_frames > 0 {
    alac_frame,alac_frame_length <- encode_frameset(
       pcm_data,
       pcm_frames,
       bits_per_sample,
       channel_count,
       encoding_parameters);
    alac_frame -> write alac_frame_length bytes;
    total_mdat_bytes <- total_mdat_bytes + alac_frame_length;
    pcm_data,pcm_frames <- read_frame(block_size);
}
return_to_start();
total_mdat_bytes <- 8;
total_mdat_bytes -> write 32 unsigned;
return mdat_atom;
