/*
 * DMLib
 * -- Wav file writing
 * Programmed and designed by Matti 'ccr' Hamalainen
 * (C) Copyright 2012 Tecnic Software productions (TNSP)
 */
#include "dmwav.h"
#include "dmfile.h"


BOOL dmWriteWAVChunk(FILE * f, DMWaveChunk *ch)
{
    return dm_fwrite_str(f, ch->chunkID, 4) && dm_fwrite_le32(f, ch->chunkSize);
}


void dmMakeWAVChunk(DMWaveChunk *ch, const char *chunkID, const Uint32 chunkSize)
{
    memcpy(&(ch->chunkID), (const void *) chunkID, 4);
    ch->chunkSize = chunkSize;
}


void dmWriteWAVHeader(FILE *outFile, int sampBits, int sampFreq, int sampChn, size_t sampLen)
{
    DMWaveFile wav;
    
    // PCM WAVE chunk
    dmMakeWAVChunk(&wav.chFormat, DM_WAVE_FMT_ID, (2 + 2 + 4 + 4 + 2 + 2));

    wav.wFormatTag = DM_WAVE_FORMAT_PCM;
    wav.nChannels = sampChn;
    wav.nSamplesPerSec = sampFreq;
    wav.nAvgBytesPerSec = (sampBits * sampChn * sampFreq) / 8;
    wav.nBlockAlign = (sampBits * sampChn) / 8;
    wav.wBitsPerSample = sampBits;

    // Data chunk
    dmMakeWAVChunk(&wav.chData, DM_WAVE_DATA_ID, (sampLen * wav.nBlockAlign));

    // RIFF header
    memcpy(&wav.riffID, (const void *) DM_WAVE_RIFF_ID, 4);
    memcpy(&wav.riffType, (const void *) DM_WAVE_WAVE_ID, 4);
    wav.fileSize = ((4 + 4 + 4) + wav.chFormat.chunkSize + wav.chData.chunkSize);

    // Write header
    dm_fwrite_str(outFile, wav.riffID, sizeof(wav.riffID));
    dm_fwrite_le32(outFile, wav.fileSize);
    
    dm_fwrite_str(outFile, wav.riffType, sizeof(wav.riffType));
    dmWriteWAVChunk(outFile, &wav.chFormat);
    
    dm_fwrite_le16(outFile, wav.wFormatTag);
    dm_fwrite_le16(outFile, wav.nChannels);
    dm_fwrite_le32(outFile, wav.nSamplesPerSec);
    dm_fwrite_le32(outFile, wav.nAvgBytesPerSec);
    dm_fwrite_le16(outFile, wav.nBlockAlign);
    dm_fwrite_le16(outFile, wav.wBitsPerSample);
    
    dmWriteWAVChunk(outFile, &wav.chData);
}
