/**************************************************************************

Example of IAviReadFile & IAviReadStream interface usage.
Copyright 2000 Eugene Kuznetsov (divx@euro.ru)

**************************************************************************/
#include <config.h>
#include <default.h>
#include <avifile.h>
#include <stdio.h>
#include <aviplay.h>
#include <except.h>
#include <version.h>
#include <iostream>

#define __MODULE__ "extractor"

using namespace std;

int main(int argc, char** argv)
{
    FILE* f=0;
    IAviReadFile* ac=0;
    IAviReadStream* as=0;
    uint8_t* zz=0;
    if (GetAvifileVersion()!=AVIFILE_VERSION)
    {
	cout<<"This binary was compiled for Avifile ver. "<<AVIFILE_VERSION<<", but the library is ver. "<<GetAvifileVersion()<<". Aborting."<<endl;
	return 0;
    }

    if (argc == 0)
    {
	fprintf(stderr, "Missing argument: filename\n");
	exit(0);
    }

    try
    {
	f = fopen("./log2.mp3", "wb");
	if (f == 0)
	    throw FATAL("Can't open ./log2.mp3 for writing");
	ac = CreateIAviReadFile(argv[1]);
	if (ac == 0)
	    throw FATAL("Can't read given file");

	as = ac->GetStream(0, AviStream::Audio);
	if (ac == 0)
	    throw FATAL("Stream doesn't contain audio stream");

	const int buffer_size = 20000;
	zz = new uint8_t[buffer_size];
	size_t samp_read, bytes_read;
	while (!as->Eof())
	{
	    as->ReadDirect(zz, buffer_size, buffer_size, samp_read, bytes_read);
	    fwrite(zz, bytes_read, 1, f);
	}
    }
    catch(FatalError& error)
    {
	error.Print();
    }
    if(f)fclose(f);
    if(ac)delete ac;
    if(zz)delete zz;
}
