inline void Assembler::emit_int32(int x) {
  check_delay();
  AbstractAssembler::emit_int32(x);
}
int main (int argc, char ** argv)
{
    int opts = 0;
    int delay = 8000;
    short volume = 4;

    // Get the arguments
    while((opts = getopt(argc, argv,"d:v: tt")) != -1)
    {
        if (opts == 'd')
        {
            delay = atoi(optarg);
        }
        else if (opts == 'v')
        {
            volume = atoi(optarg);
        }
    }

    // Make sure delay is not negative
    // Make sure volume scale is at least 1
    check_delay(&delay);
    check_volume(&volume);

    // Open the files in binary mode to read, or write
    FILE *source = fopen(argv[optind], "rb");
    FILE *dest = fopen(argv[optind+1], "wb");

    // Handle incorrect source file input
    check_source(&source);

    // READ header from source - first 44 bytes as 11 ints
    int header[11] = {0};
    fread(header, sizeof(int), 11, source);

    // Change file size in the header
    header[1] += delay*2;
    header[10] += delay*2;

    // WRITE header to output file
    fwrite(header, sizeof(int), 11, dest);

    // Allocate mem to store delay number of shorts
    short *buffer;
    buffer = malloc((sizeof(short) * delay));

    // Copy samples before DELAY num of samples into buffer
    fseek(source, 44, SEEK_SET); // 44 bytes from start of file
    fread(buffer, sizeof(short), delay, source);


    // START READING THE SAMPLES ONE AT A TIME.
    fseek(source, 44, SEEK_SET); // 44 bytes from start of file
    short smp = 0; // This will hold the sample being read
    int s = 0; // Keeps track of the NUMBER OF samples read

    while (fread(&smp, sizeof(short), 1, source))
    {
        if (s < delay)
        {
            // If not at sample number DELAY yet, just write as they are...
            fwrite(&smp, sizeof(short), 1, dest);
        }
        else
        {
            // At sample number DELAY, write mixed in buffer[0] scaled by volume
            short temp = smp + (buffer[0] / volume);
            fwrite(&temp, sizeof(short), 1, dest);
        }

        // START OF BUFFER CODE
        // Append smp to the buffer AFTER "popping it"
        int i = 0;
        for (i = 0; i < delay-1; i++)
        {
            buffer[i] = buffer[i+1];
        }
        buffer[delay-1] = smp;
        // EOF BUFFER CODE

        s++; // Increment the number of samples
    }

    // Write the rest of the buffer scaled by volume to dest
    int i = 0;
    for (i = 0; i < delay; i++)
    {
        buffer[i] /= volume;
    }

    fwrite(buffer, sizeof(short), delay, dest);

    return 0;
}