#include <cstring>
#include <except.h>
#include <unistd.h>

#ifdef __FreeBSD__
#include <floatingpoint.h>
#endif
#ifdef __NetBSD__
#include <machine/ieeefp.h>
#endif

#include <iostream>

using namespace std;

#include <qapp.h>
#include "genctl.h"
#include "recwnd.h"

void my_new_handler()
{
    cerr<<"ERROR: new failed"<<endl;
    exit(1);
}
void Usage()
{
    cerr<<"Usage: qtrecomp [config-file-name]"<<endl
	<<"   Without options: interactive mode"<<endl
	<<"   With one option: batch mode ( processes one file according to config options and exits )"<<endl;
}

struct ConsoleCallback: public IRecompressCallback
{
    int state;
    ConsoleCallback():state(0){}
    virtual void setNewState(double progress, double elapsed,
			     double estimated, int64_t filesize) {}
    virtual void setTotal(framepos_t vtotal, framepos_t atotal,
			  double vtime, double atime) {}
    virtual void addVideo(framepos_t vframe, size_t vsize, double vtime, bool keyframe) {}
    virtual void addAudio(framepos_t asample, size_t asize, double atime) {}
    virtual void finished() { state=1; }
};

int main(int argc, char** argv)
{
#if defined(__FreeBSD__) || defined(__NetBSD__)
	fpsetmask(fpgetmask() & ~(FP_X_DZ|FP_X_INV));
#endif
    set_new_handler(&my_new_handler);
    if (argc == 1)
    {
        try
	{
	    QApplication app(argc,argv);
    	    QtRecompressorCtl ctl;
	    ctl.show();
	    app.setMainWidget(&ctl);
	    app.exec();
	}
        catch(FatalError& e)
	{
	    e.PrintAll();
        }
    }
    else if (argc == 2)
    {
	if (strcmp(argv[1], "--help")!=0)
	{
	    ConsoleCallback ck;
	    RecKernel kernel;
	    kernel.loadConfig(argv[1]);
	    kernel.set_callback(&ck);
	    kernel.start_recompress();
	    while (!ck.state)
		sleep(1);
//	    RecWindow* wnd=new RecWindow(0, &kernel);
//	    wnd->show();
//	    app.setMainWidget(wnd);
//	    wnd->exec();
	}
	else
	    Usage();
    }
    else
	Usage();
    return 0;
}
