#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",
channels,bits_per_sample,sample_rate,total_pcm_frames;
OUTPUT "a TTA encoded file";
VAR channels "channels";
VAR bits_per_sample "bits-per-sample";
VAR sample_rate "sample rate";
VAR total_pcm_frames "total PCM frames";
VAR header_crc "header CRC";
VAR seektable_crc "seektable CRC";
VAR tta_file "TTA file";
VAR block_size "block size";
VAR pcm_frames "PCM frames";
VAR tta_frame "TTA frame";
VAR tta_frame_size "TTA frame size";
FUNC read_frame "read PCM frames from input";
FUNC encode_frame "encode frame" "tta:encode_frame";
/*write header*/;
bytes(84, 84, 65, 49) -> write 4 bytes;
1 -> write 16 unsigned;
channels -> write 16 unsigned;
bits_per_sample -> write 16 unsigned;
sample_rate -> write 32 unsigned;
total_pcm_frames -> write 32 unsigned;
header_crc <- calculate_crc();
header_crc -> write 32 unsigned;
;
/*write placeholder seektable*/;
for i <- 0 to ceil((total_pcm_frames * 245) / (sample_rate * 256)) {
    0 -> write 32 unsigned;
}
0 -> write 32 unsigned;
;
/*write TTA frames*/;
i <- 0;
pcm_frames,block_size <- read_frame(floor((sample_rate * 256) / 245));
while block_size > 0 {
   tta_frame[i],tta_frame_size[i] <- encode_frame(bits_per_sample,
                                                  channels,
                                                  block_size,
                                                  pcm_frames);
   tta_frame[i] -> write tta_frame_size[i] bytes;
   pcm_frames,block_size <- read_frame(floor((sample_rate * 256) / 245));
}
;
/*rewrite seektable with actual TTA frame sizes*/;
seek 0x16;
for i <- 0 to ceil((total_pcm_frames * 245) / (sample_rate * 256)) {
    tta_frame_size[i] -> write 32 unsigned;
}
seektable_crc <- calculate_crc();
seektable_crc -> write 32 unsigned;
;
return tta_file;
