Пример #1
0
bool Game::init(const mkString& cmd_line)
{
    rtti::TypeManager::getInstance().finishTypeRegistration();

    m_presetMgr = new rtti::PresetMgr;
    m_presetMgr->init();

    parseCmdLine(cmd_line);
    initRendering();
    initInput();
    initPhysics();

#ifdef ENABLE_BULLET_DEBUG_DRAW
    g_debugPhysicsDrawer = new BtOgre::DebugDrawer(m_ogreSceneMgr->getRootSceneNode(), m_physicsWorld);
    m_physicsWorld->setDebugDrawer(g_debugPhysicsDrawer);
#endif

    m_actorControllerFactory = new ActorControllerFactory;

    m_level = new Level();
    if (!m_level->load("data/levels/" + m_levelName + ".json"))
        return false;

    m_freelook = m_startWithFreelook;

	//Set Player conflict side to Neutral
	m_level->getPlayer()->setConflictSide(EConflictSide::Unknown);
    return true;
}
Пример #2
0
int main(int argc, char** argv)
{
    std::vector<std::string> inputFile;
    std::string              outputDir;
    int                      opts;
    int                      verbosity;

#ifdef use_cpp11
    // handle errors by exiting
    spv::spirvbin_t::registerErrorHandler(errHandler);

    // Log messages to std::cout
    spv::spirvbin_t::registerLogHandler(logHandler);
#endif

    if (argc < 2)
        usage(argv[0]);

    parseCmdLine(argc, argv, inputFile, outputDir, opts, verbosity);

    if (outputDir.empty())
        usage(argv[0], "Output directory required");

    std::string errmsg;

    // Main operations: read, remap, and write.
    execute(inputFile, outputDir, opts, verbosity);

    // If we get here, everything went OK!  Nothing more to be done.
}
Пример #3
0
void parseCmdLine(LPSTR lpCmdLine, int *argc, char **argv[]) {
	if (lpCmdLine && *lpCmdLine) {
		size_t len = 0;
		int c = *argc;
		char* del = 0;
		if(*lpCmdLine == 0x20) {
			// blank space:
			lpCmdLine++;
			len = strspn(lpCmdLine," ");
		} else {
			// space, quote or zero delimited argument:
			len		= *lpCmdLine=='"'
					? strcspn(++lpCmdLine,del="\"")
					: strcspn(lpCmdLine,del=" ");
			if (len>0) {
				*argv = realloc(*argv,(c+1)*sizeof(char*));
				(*argv)[c] = malloc(len+1);
				(*argv)[c][len] = 0;
				strncpy((*argv)[c],lpCmdLine,len);
				c++;
			}
			if (del[0]=='"' && lpCmdLine[len]!=0) lpCmdLine++;
		}
		*argc = c;
		lpCmdLine += len;
		parseCmdLine(lpCmdLine,argc,argv);
	}
}
HRESULT OGLTest::Init(HINSTANCE hInstance,
                      LPSTR lpCmdLine,
                      int nCmdShow)
{
    parseCmdLine(lpCmdLine);

    HRESULT hr = initWindow(hInstance, nCmdShow);
    if (SUCCEEDED(hr))
    {
        mpRender = CreateRender(miRenderId);
        if (mpRender)
        {
            hr = initOGL();
            if (SUCCEEDED(hr))
            {
                setCurrentGLCtx(mhGLRC);

                hr = mpRender->InitRender();
                if (FAILED(hr))
                {
                    TestShowError(hr, "InitRender");
                }

                setCurrentGLCtx(NULL);
            }
        }
        else
        {
            hr = E_FAIL;
        }
    }

    return hr;
}
Пример #5
0
int main(int argc, String argv[]) {
  /* Handle a plea for help */
  if (argc == 1) {
    printUsage(argv[0]);
    exit(1);
  }

  /* Parse xPL & program command line parms */
  if (!xPL_parseCommonArgs(&argc, argv, FALSE)) exit(1);
  if (!parseCmdLine(&argc, argv)) exit(1);

  /* Ensure we have a class */
  if ((msgSchemaClass == NULL) || (msgSchemaType == NULL)) {
    fprintf(stderr, "The -c schema class.type is REQUIRED\n");
    exit(1);
  }

  /* Start xPL up */
  if (!xPL_initialize(xPL_getParsedConnectionType())) {
    fprintf(stderr, "Unable to start xPL");
    exit(1);
  }

  /* Parse the source */
  if (!parseSourceIdent()) exit(1);

  /* Parse the target */
  if (!parseTargetIdent()) exit(1);

  /* Send the message */
  if (!sendMessage(argc, argv)) exit(1);
  return 0;
}
Пример #6
0
NmAnalyzerParams::NmAnalyzerParams(int argc, char** argv)
{
	if(!parseCmdLine(argc,argv,*this))
	{
		*this = DefaultParams;
	}
}
Пример #7
0
int main (int argc, char* const argv[]) 
{
	init();
	
	if (argc == 1 && usage())
		return 0;
	if (parseCmdLine(argc, argv) != 0)
		return 0;
	if (optShowHelp && showHelp())
		return 0;
	if (optShowVersion && showVersion())
		return 0;
    
    curl_global_init(CURL_GLOBAL_ALL);
	
	for (int i = 0; i < optFiles.size(); i++)
	{
		std::string processed = processImage(optFiles[i], optImageSize);
		if (processed == "") 
			continue;
		
		if (processed != optFiles[i])
			tempFiles.push_back(processed);
		
        std::string err;
		std::string output = uploadImage(processed.c_str(), err);
		if (!userOutput(output) || err.length() > 0)
			fprintf(stderr, "Upload failed for %s.\n%s\n", optFiles[i].c_str(), err.c_str());
	}
	
	for (int i = 0; i < tempFiles.size(); i++)
		remove(tempFiles[i].c_str());
	
    return 0;
}
Пример #8
0
int main(int argc, char *argv[]) {
  int error = EXIT_SUCCESS;
  cmdLineParameters params;

  openlogex(argv[0],LOG_CONS|LOG_PERROR|LOG_PID,LOG_USER);
  /* set default values */
  params.facility = LOG_USER;
  params.stdOutLogLevel = LOG_INFO;
  params.stdErrLogLevel = LOG_ERR;
  params.options = LOG_PID;
#ifdef _DEBUG_
  params.options |= LOG_CONS|LOG_PERROR;
#endif
  params.cmdLine[0] = '\0';

  error = parseCmdLine(argc,argv,&params);
  if (EXIT_SUCCESS == error) {
     if (optind < argc) {
        syslogproc(argv[optind],argv+optind,params.options,params.facility,params.stdOutLogLevel,params.stdErrLogLevel);
     } else {
       printHelp(NULL);
     }
  }
  closelogex();
  return error;
}
Пример #9
0
    int start(int argc, char** argv) {
        MPI::Init(argc, argv);

        comm = MPI::COMM_WORLD;

        currentRank = comm.Get_rank();
        currentSize = comm.Get_size();

        peerCount = currentSize - 1;

        if (currentSize<2) {
            std::cerr << ("At least 2 peers may instantiated and work properly!\n") << std::endl;
            return -2;
        }

        options.parseCmdLine(argc, argv);

        if (currentRank == 0)
            rootComputing();
        else
            peerComputing();

        MPI::Finalize();
        return 0;
    }
Пример #10
0
/*
 * WinMain - main entry point
 */
int WINMAINENTRY WinMain( HINSTANCE currinst, HINSTANCE previnst,
                          LPSTR cmdline, int cmdshow )
{
    MSG         msg;

    cmdline = cmdline;
#if defined( __NT__ ) && !defined( __WATCOMC__ )
    _argc = __argc;
    _argv = __argv;
#endif
    WRInit();

    if( _argc > 1 ) {
        parseArgs( _argc, _argv );
    }

    if( !imgEditInit( currinst, previnst, cmdshow ) ) {
        if( ImgedIsDDE ) {
            IEDDEDumpConversation( currinst );
        }
        return( 0 );
    }

    if( ImgedIsDDE ) {
        if( IEDDEStart( currinst ) ) {
            if( !IEDDEStartConversation() ) {
                WImgEditError( WIE_DDE_INIT_FAILED, NULL );
                PostMessage( HMainWindow, WM_CLOSE, (WPARAM)1, 0 );
            }
        } else {
            WImgEditError( WIE_DDE_INIT_FAILED, NULL );
            PostMessage( HMainWindow, WM_CLOSE, (WPARAM)1, 0 );
        }
    }

    IEEnableMenuInput( TRUE );

    if( _argc > 1 ) {
        parseCmdLine( _argc, _argv );
    }

    while( GetMessage( &msg, (HWND)NULL, 0, 0 ) ) {
        if( !TranslateMDISysAccel( ClientWindow, &msg ) &&
            !TranslateAccelerator( HMainWindow, hAccel, &msg ) ) {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
    }

    if( ImgedIsDDE ) {
        IEDDEEndConversation();
        IEDDEEnd();
    }

    imgEditFini();
    WRFini();
    return( 1 );

} /* WinMain */
Пример #11
0
int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

#ifdef Q_OS_MACX
  // connect to plugins directory
  app.setLibraryPaths(app.applicationDirPath() + "/../PlugIns");
#endif

  parseCmdLine(argc, argv);

  initGlobals();
  Clipboard::create();
  PointSetStyles::create();
  DefaultSettings::create();

  DefaultSettings& rSettings = DefaultSettings::instance();
  if (rSettings.getWindowMainFontOverride())
  {
    app.setFont(QFont(rSettings.getWindowMainFontName(),
      rSettings.getWindowMainFontSize()));
  }

  QTranslator tor (0);
  // set the location where your .qm files are in load() below as the last parameter instead of "."
  // for development, use "/" to use the english original as
  // .qm files are stored in the base project directory.
  tor.load (QString("digitizer.") + QTextCodec::locale(), ".");
  app.installTranslator (&tor);

  DigitMain digitizer(cmdExport);
  qApp->setMainWidget(&digitizer);

  digitizer.show();

  if (!cmdImport.isEmpty())
	{
    if (cmdXYAxes)
		{
      digitizer.importImageFile(cmdImport, cmdXMinG, cmdXMaxG, cmdYMinG, cmdYMaxG);
		}
    else
		{
      digitizer.importImageFile(cmdImport);
		}
	}

  if (!cmdOpen.isEmpty())
    digitizer.openDocumentFile (cmdOpen);

  return app.exec();
}
Пример #12
0
int ExternalApplication::run( const uni_char *argument, int fd, const char* encoding )
{
	uni_char **argv = parseCmdLine( m_cmdline, argument );
	if (!argv || !argv[0] || !argv[0][0] )
	{
		errno = ENOENT;
		return -1;
	}

	int result = run(argv, fd, spawn, encoding );
	deleteArray(argv);
	return result;
}
Пример #13
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    parseCmdLine(app.arguments());
    QTranslator translator;
    if (!translator.load("yagf_" + QLocale::system().name(), "/usr/local/share/yagf/translations"))
        translator.load("yagf_" + QLocale::system().name(), "/usr/share/yagf/translations");
    app.installTranslator(&translator);
    QTranslator translator2;
    translator2.load("qt_" + QLocale::system().name(), "/usr/share/qt4/translations");
    app.installTranslator(&translator2);
    MainForm window;
    window.show();
    return app.exec();
}
Пример #14
0
/**
 * Main routine for all processors.
 *
 * Parse the command-line arguments for census options, then determine
 * whether we are controller or slave and run a specialised main routine
 * accordingly.
 */
int main(int argc, char* argv[]) {
    MPI_Init(&argc, &argv);

    // Which processor are we?
    int rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    // Extract census options.
    int retVal = parseCmdLine(argc, (const char**)argv, (rank == 0));

    if (retVal == 0) {
        // No breakage yet.  Controller or slave?
        if (rank == 0) {
            // We're the controller.
            // How many processors in total?
            int size;
            MPI_Comm_size(MPI_COMM_WORLD, &size);

            if (size <= 1) {
                std::cerr << "ERROR: At least two processors are required "
                    "(one controller and one slave).\n";
                retVal = 1;
            } else {
                nSlaves = size - 1;
                if (dim2)
                    retVal = mainController<Dim2Params>();
                else if (dim4)
                    retVal = mainController<Dim4Params>();
                else
                    retVal = mainController<Dim3Params>();
            }
        } else {
            // We're one of many slaves.
            if (dim2)
                retVal = mainSlave<Dim2Params>();
            else if (dim4)
                retVal = mainSlave<Dim4Params>();
            else
                retVal = mainSlave<Dim3Params>();
        }
    }

    MPI_Finalize();
    return retVal;
}
Пример #15
0
int main(int argc, char *argv[]) {

	initConfig();
	if (!parseCmdLine(argc, argv))
		goto exit;

	if (estgbconf.isSingleton) {
		switch (checkSingleton()) {
		case 0:
			break; // No another instance found, continue to work
		case 1:
			goto exit;
			// Found another instance of bot, exiting
		case 2:
			printf("Error open PID file for singleton check\n");
			goto exit;
			// Something goes wrong, exiting
		}

	}

	if (!globalInit())
		goto exit;

	if (estgbconf.isDaemonize)
		daemon(0, 0);

	if (estgbconf.needUnescape) {
		estgbconf.text = zc_unescape(estgbconf.text);
		estgbconf.comment = zc_unescape(estgbconf.comment);
	}

	if (estgbconf.isScan >= 0) {
		scan();
		goto exit;
	}

	if (estgbconf.isWildcard)
		sendMultiple();
	else
		sendSingle();

	exit: freeConfig();
	return 0;
}
Пример #16
0
int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	int result;

	// parse command line:
	int argc = 0;
	char** argv = 0;
	parseCmdLine(GetCommandLine(),&argc,&argv);

	// call the main function:
	result = boot_main(argc, argv);

	// clean up parsed arguments:
	while(argc) free(argv[--argc]);
	free(argv);

	// dispatch result:
	return result;
}
Пример #17
0
bool CDaemon::run(int argc,char** argv){
    parseCmdLine(argc,argv);
    m_pName = strrchr(argv[0],'/');
    m_pName != NULL ? m_pName += 1 : m_pName = argv[0];

    HISI i=m_hisOptVal.find('k');
    if (i!=m_hisOptVal.end()){
        if (i->second=="start"){
            return start();
        }else if(i->second=="stop"){
            return stop();
        }else if(i->second=="restart"){
            if(stop()){
                return start();
            }
            return false;
        }
    }
    return true;
}
Пример #18
0
int main(int argc, char** argv) {
	init();

	CmdArgs* args = parseCmdLine(argc, argv);
	if (!args) {
		writeLog(LOG_QUIET, L"Oops, invalid or not enough arguments. Try 'zbspac help' for command syntax.");
		deleteCmdArgs(args);
		return EXIT_FAILURE;
	}

	setLogLevel(argLogLevel(args));
	bool result;

	switch (argCmdType(args)) {
	case CMD_PACK:
		result = processPackCmd(args);
		break;
	case CMD_PACK_BFE:
		result = processPackBfeCmd(args);
		break;
	case CMD_UNPACK:
		result = processUnpackCmd(args);
		break;
	case CMD_PACK_SCRIPT:
		result = processPackScriptCmd(args);
	break;
	case CMD_UNPACK_SCRIPT:
		result = processUnpackScriptCmd(args);
		break;
	case CMD_ABOUT:
		result = processAboutCmd(args);
		break;
	case CMD_HELP:
	default:
		result = processHelpCmd(args);
		break;
	}
	deleteCmdArgs(args);

	return result ? EXIT_SUCCESS : EXIT_FAILURE;
}
Пример #19
0
//
// 执行命令行
//
void executeCmdLine(const char* cmdLine)
{
	assert(cmdLine != NULL);

	char cmd[MAX_CMD_LEN];
	char args[MAX_ARG_LEN];

	parseCmdLine(cmdLine, cmd, args);

	int index = -1;
	ErrorType err = queryCmd(cmd, &index);
	switch(err)
	{
	case NoErr:
		cmdLineTable[index].handlerFunc(args);
		break;
	case NoMatchingCmd:
		break;
	}
	return;
}
Пример #20
0
void configure(int arg_num, char *arg_vet[]) {

    bool config_found = false;

    for (int i = 1; i < arg_num; i++) {
	    if (!strcmp(arg_vet[i], "-help")) {
            showHelp(arg_vet[0]);
            exit(0);
        }
    }

    for (int i = 1; i < arg_num; i++) {
	    if (!strcmp(arg_vet[i], "-config")) {
            GlobalParams::config_filename = arg_vet[++i];
            config_found = true;
            break;
        }
    }

    if (!config_found)
    {
        std::ifstream infile(CONFIG_FILENAME);
        if (infile.good())
            GlobalParams::config_filename = CONFIG_FILENAME;
        else
        {
            cerr << "No YAML configuration file found!\n Use -config to load examples from config_examples folder" << endl;
            exit(0);
        }
    }

    loadConfiguration();
    parseCmdLine(arg_num, arg_vet);

    checkConfiguration();

    // Show configuration
    if (GlobalParams::verbose_mode > VERBOSE_OFF)
        showConfig();
}
Пример #21
0
/*
 * main - main entry point for PM
 */
int main( int argc, char *argv[] )
{
    HMQ         hmq;
    QMSG        qmsg;
    HAB         hab;

    hab = WinInitialize( 0 );
    if(!hab) {
        DosBeep(BEEP_WARN_FREQ, BEEP_WARN_DUR);
        DosExit(EXIT_PROCESS, RETURN_ERROR);
    }

    hmq = WinCreateMsgQueue( hab, 0 );
    if(!hmq) {
        DosBeep(BEEP_WARN_FREQ, BEEP_WARN_DUR);
        WinTerminate(hab);
        DosExit(EXIT_PROCESS, RETURN_ERROR);
    }

    if( !imgEditInit( hab ) ) {
        DosBeep(BEEP_WARN_FREQ, BEEP_WARN_DUR);
        WinTerminate(hab);
        DosExit(EXIT_PROCESS, RETURN_ERROR);
    }

    IEEnableMenuInput( TRUE );

    if( argc > 1 ) {
        parseCmdLine( argc, argv );
    }

    while ( WinGetMsg(hab, &qmsg, 0, 0, 0) ) {
        WinDispatchMsg( hab, &qmsg );
    }

    imgeditFini( hmq );

    return 0;
} /* main */
Пример #22
0
int main(int argc, String argv[]) {

	/* Parse command line parms */
	if (!xPL_parseCommonArgs(&argc, argv, FALSE)) {
		exit(1);
	}

	/* Start xPL up */
	if (!xPL_initialize(xPL_getParsedConnectionType())) {
		fprintf(stderr, "Unable to start xPL");
		exit(1);
	}
	
	/* Parse Hub command arguments */
	if (!parseCmdLine(&argc, argv)) {
		printUsage(argv[0]);
		exit(1);
	}

	if (daemonMode) {
		switch (fork()) {
			case 0: /* child */
				/* No io in child mode */
				close(fileno(stdin));
				close(fileno(stdout));
				close(fileno(stderr));
				setpgrp();

				startServer();
				break;
			case -1: /* error */
				fprintf(stderr, "Unable to spawn daemon, %s (%d)\n", strerror(errno), errno);
				exit(1);
		}
	} else {
		startServer();
	}
	return 0;
}
Пример #23
0
int main(int argc, char *argv[]) 
{
  char cmd_buff[1024];
  char *pinput;
  char *fname = argv[1];
  char *mode = "r";
  FILE *f= fopen(fname, mode);
  cmd_line *c, *backup;
  char* extra_buff;
  char* test = malloc(sizeof(char)*514);
  char buf[1024];

  if(argv[2] != NULL){ /*if trying to run batch with 2 filenames*/                                                
    err();
    exit(0);
  }

  if(f == NULL){ /*if read is invalid*/
    err();
    exit(0);
  }
  dw = getcwd(buf, 1024); /*for global var accessible to function calls*/
  while (1) {
    /*INTERACTIVE MODE*/
    if(argv[1] == NULL){ 
      myPrint("myshell> ");
      pinput = fgets(cmd_buff, 100, stdin);
      c = parseCmdLine(cmd_buff);
      backup = c;
      while(backup != NULL){
        processCmd(backup->c);
        backup = backup->next;
      }
    /*BATCH MODE*/ 
    }  else if(argv[1] != NULL){
      memset(cmd_buff,'\0',514);
      pinput = fgets(cmd_buff, 514, f);
      
      if (!pinput) { /*invalid fgets*/
        exit(0);
      }

      if((extra_buff = strstr(cmd_buff,"\n"))!=NULL) {/*check if whole command has been taken in*/
        if (check_space(cmd_buff)==0) /*if all blank spaces, don't print*/
          continue;
        else {
      myPrint(cmd_buff); /*print command*/
      collapsed_str(cmd_buff,test); 
      /*CATCH ERRORS RIGHT AWAY*/
      if(exception1(test)==1){
        err();
      }
      else if(exception2(test)==1) {
        err();
      }
      else if(exception3(test)==1) {
        continue;
      }
      /*PARSE*/
      else {
        c = parseCmdLine(cmd_buff);
        backup = c;
        while(backup != NULL){
          processCmd(backup->c);
          
          backup = backup->next;
        }
        free_cmdline(c);
      }
    }
      }
      /*COMMAND TOO LONG*/
      if(extra_buff==NULL) {
        myPrint(cmd_buff);

        while(fgets(cmd_buff,1024,f)!=NULL) {/*keep getting more chars while you can*/
          if((strlen(cmd_buff)<1023) || cmd_buff[1022]=='\n') { /*if new one is shorter than max, break*/
            myPrint(cmd_buff);
            memset(cmd_buff, '\0', 1024);
            break;
          }
          else 
            myPrint(cmd_buff); /*else keep getting*/
          memset(cmd_buff, '\0', 1024);
        }
    err();
      }
      
    }
  }
  free(test);   
fclose(f);
return 0;
}
Пример #24
0
//Main program entry point
int main(int argc, char** argv)
{
    g_bProgressOverwrite = false;
    g_iNumThreads = 0;
    DWORD iTicks = GetTickCount();	//Store the starting number of milliseconds

    vfs.Prepare();

    //read in the resource names to unpack
    initResMap();
    initSoundManifest();
    parseCmdLine(argc,argv);

    if(argc < 2)
    {
        cout << "Usage: liDecompress [filename1] [filename2] ... [filenameN]" << endl;
        return 0;
    }

    for(int iArg = 1; iArg < argc; iArg++)
    {
        if(argv[iArg][0] == '-')	//Skip over commandline switches
            continue;
        cout << endl << "Unpacking resource blob file " << argv[iArg] << endl;

        FILE* f = fopen(argv[iArg], "rb");
        if(f == NULL)
        {
            cout << "Unable to open file " << argv[iArg] << endl;
            continue;
        }

        blobHeader bH;
        if(fread((void*)&bH, 1, sizeof(blobHeader), f) != sizeof(blobHeader))
        {
            cout << "Error reading number of resources in file " << argv[iArg] << endl;
            fclose(f);
            continue;
        }

        list<resourceHeader> lResourceHeaders;

        for(int i = 0; i < bH.numItems; i++)
        {
            resourceHeader rH;
            size_t sizeRead = fread((void*)&rH, 1, sizeof(resourceHeader), f);
            if(sizeRead != sizeof(resourceHeader))
            {
                cout << "Read " << sizeRead << " bytes, which differs from resource header size " << sizeof(resourceHeader) << endl;
                fclose(f);
                continue;
            }
            lResourceHeaders.push_back(rH);
        }

        //Create list file with all the files that were in this .pak
        string sPakListFilename = "";
        for(int i = strlen(argv[iArg])-1; i >= 0; i--)
        {
            if(argv[iArg][i] == '\\' ||
                    argv[iArg][i] == '/')
                break;
            sPakListFilename.insert(sPakListFilename.begin(), argv[iArg][i]);
        }
        sPakListFilename += ".filelist.txt";
        ofstream oPakList(sPakListFilename.c_str());

        //Iterate through these items, splitting them out of the file and creating new files out of each
        cout << "Extracting files..." << endl;
        for(list<resourceHeader>::iterator i = lResourceHeaders.begin(); i != lResourceHeaders.end(); i++)
        {
            ThreadConvertHelper dh;
            makeFolder(i->id);
            const wchar_t* cName = getName(i->id);
            oPakList << ws2s(cName) << endl;
            fseek(f, i->offset, SEEK_SET);
            dh.sFilename = cName;
            if(i->flags == FLAG_ZLIBCOMPRESSED)
            {
                compressedHeader cH;
                if(fread((void*)&cH, 1, sizeof(compressedHeader), f) != sizeof(compressedHeader))
                {
                    cout << "Error reading compressed header." << endl;
                    fclose(f);
                    continue;
                }

                uint32_t size = cH.compressedSizeBytes;

                uint8_t* buf = (uint8_t*)malloc(size);
                size_t sizeRead = fread((void*)buf, 1, size, f);
                if(sizeRead != size)
                {
                    cout << "Error reading compressed data. Size: " << size << " read: " << sizeRead << endl;
                    fclose(f);
                    free(buf);
                    continue;
                }
                dh.data.data = buf;
                dh.data.compressedSize = cH.compressedSizeBytes;
                dh.data.decompressedSize = cH.uncompressedSizeBytes;
                dh.bCompressed = true;
            }
            else if(i->flags == FLAG_NOCOMPRESSION)
            {
                uint8_t* buf = (uint8_t*)malloc(i->size);

                if(fread((void*)buf, 1, i->size, f) != i->size)
                {
                    cout << "Error reading non-compressed data." << endl;
                    fclose(f);
                    free(buf);
                    continue;
                }
                dh.data.data = buf;
                dh.data.compressedSize = dh.data.decompressedSize = i->size;
                dh.bCompressed = false;
            }
            else
                cout << "Invalid resource flag " << i->flags << endl;

            g_lThreadedResources.push_back(dh);

        }

        threadedDecompress();

        fclose(f);
        oPakList.close();
    }
    cout << "\rDone.                                " << endl;

    iTicks = GetTickCount() - iTicks;
    float iSeconds = (float)iTicks / 1000.0;	//Get seconds elapsed
    int iMinutes = iSeconds / 60;
    iSeconds -= iMinutes * 60;

    cout << "Time elapsed: " << iMinutes << " min, " << iSeconds << " sec" << endl;
    //system("PAUSE");

    return 0;
}
Пример #25
0
/*
 * main function - executes ecerything and runs in infinite loop until stopped via CTRL+C
 */
int main(void){
	//Initialize current time for Session-start
	time(&now);
	//Get the username and capitalize it.
	username = getlogin();
  	username[0] = toupper(username[0]);

  	//prints a one-time welcome message
	promptWelcomeMsg();

	//Handle CTRL+C and CTRL+Z 'manually'.
	//The strategy basically is: Do nothing for the parent process when there is a child-process
	signal(SIGINT, interruptHandler);
	signal(SIGTSTP, tstpHandler);

	//initializes variables for reading line and prompt-message
	char *line;
	char mashPrompt[LINE_LENGTH + 3];

	//set 'cwd' to the current work directory and set prompt-message
	setCwd();
	snprintf(mashPrompt, sizeof(mashPrompt), "%s >> ", cwd);

	//reads lines until EOF is detected, using the GNU readline library
	while((line = readline(mashPrompt)) != NULL){
		int status;

        //If user presses enter without any character ignore the command
        if (line[0] != 0){
        	//saving commant to history, using GNU readline library
        	add_history(line);
        }else{
        	continue;
        }

		//Forking the child process, which then handles the read line, as well as error handling.
		if ((childPID=fork())==0){
			//For child-process only; parses and executes command
			//printf("\nChild Process with %u started. Parent Process ID: %u \n", getpid(), getppid());
    		parseCmdLine(line);
		}else if(childPID == -1){
			//Failure, no child process is created
			fprintf(stderr, "Unfortunately there was a little mess-up, %s\n", username);
		}else{
			//For parent-process: Waits on child
			pid_t result = waitpid(childPID, &status, WUNTRACED);
			if (result == -1) {
				//waitpid was not succesfull
				fprintf(stderr, "Something under the hood went terribly wrong. Just try again, %s", username);
			} else {
				//Everything succesfully executed; Set childPID to -1, 
				//so signal-handler functions know there is no child-process running
				childPID = -1;
				free(line);
			}
		}
		//Theoretically to check if the user has changed directory. Since cd isn't built in yet, doesn't really have a function
		setCwd();
		snprintf(mashPrompt, sizeof(mashPrompt), "%s >> ", cwd);
	}
	return EXIT_SUCCESS;
}
Пример #26
0
int main( int argc, char* argv[] )
{
    std::set_terminate(&terminateHandler);
    try {
        if( !parseCmdLine( argc, argv ) ) {
            return EXIT_SUCCESS;
        }
        SDL_Init( SDL_INIT_EVERYTHING );
        light4cxx::Logger::root()->info( L4CXX_LOCATION, "Trying to load '%s'", config::filename );
        ppp::AbstractModule::Ptr module;
        try {
            module = ppp::PluginRegistry::tryLoad( config::filename, 44100, config::maxRepeat, config::interpolation );
            if( !module ) {
                light4cxx::Logger::root()->error( L4CXX_LOCATION, "Failed to load '%s'", config::filename );
                return EXIT_FAILURE;
            }
        }
        catch( ... ) {
            light4cxx::Logger::root()->fatal( L4CXX_LOCATION, "Exception on module loading: %s", boost::current_exception_diagnostic_information() );
            std::cout << std::flush;
            std::cerr << "The message above means that PPPlay encountered a severe problem it\n"
                      << "could not handle gracefully. Please report this problem to the developers at:\n"
                      << "    http://sourceforge.net/p/peepeeplayer/tickets/\n"
                      << "If possible, please add the file you tried to play, as this seems to be the\n"
                      << "root of all evil, as well as the message above. Thank you!"
                      << std::endl;
            return EXIT_FAILURE;
        }
        if( !config::noGUI ) {
            light4cxx::Logger::root()->debug( L4CXX_LOCATION, "Initializing SDL Screen: %s", PACKAGE_STRING );
            dosScreen.reset( new ppg::SDLScreen( 80, 25, PACKAGE_STRING ) );
            dosScreen->setAutoDelete( false );
            dosScreen->show();
        }
        if( config::outputFilename.empty() ) {
            light4cxx::Logger::root()->info( L4CXX_LOCATION, "Init Audio" );
            output.reset( new SDLAudioOutput( module ) );
            if( !output->init( 44100 ) ) {
                light4cxx::Logger::root()->fatal( L4CXX_LOCATION, "Audio Init failed" );
                return EXIT_FAILURE;
            }
            output->play();
            if( dosScreen ) {
                uiMain = new UIMain( dosScreen.get(), module, output );
            }
            SDL_Event event;
            while( output ) {
                if( output->errorCode() == AbstractAudioOutput::InputDry ) {
                    light4cxx::Logger::root()->debug( L4CXX_LOCATION, "Input is dry, trying to jump to the next song" );
                    if( !module->jumpNextSong() ) {
                        light4cxx::Logger::root()->debug( L4CXX_LOCATION, "Jump failed, quitting" );
                        output.reset();
                        break;
                    }
                    module->setPaused( false );
                    output->play();
                    continue;
                }
                else if( output->errorCode() != AbstractAudioOutput::NoError ) {
                    light4cxx::Logger::root()->debug( L4CXX_LOCATION, "Input has error, quitting" );
                    output.reset();
                    break;
                }
                if( output && uiMain ) {
                    uiMain->setFft( reinterpret_cast<SDLAudioOutput*>( output.get() )->leftFft(), reinterpret_cast<SDLAudioOutput*>( output.get() )->rightFft() );
                }
                if( !SDL_PollEvent( &event ) ) {
                    std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
                    continue;
                }
                if( event.type == SDL_KEYDOWN ) {
                    switch( event.key.keysym.sym ) {
                        case SDLK_ESCAPE:
                            output.reset();
                            break;
                        case SDLK_SPACE:
                            if( output->playing() ) {
                                output->pause();
                            }
                            else if( output->paused() ) {
                                output->play();
                            }
                            break;
                        case SDLK_END:
                            if( !module->jumpNextSong() )
                                output.reset();
                            break;
                        case SDLK_HOME:
                            module->jumpPrevSong();
                            break;
                        case SDLK_PAGEDOWN:
                            if( !module->jumpNextOrder() ) {
                                if( !module->jumpNextSong() )
                                    output.reset();
                            }
                            break;
                        case SDLK_PAGEUP:
                            module->jumpPrevOrder();
                            break;
                        default:
                            break;
                    }
                }
                else if( !config::noGUI && event.type == SDL_MOUSEMOTION ) {
                    dosScreen->onMouseMove( event.motion.x / 8, event.motion.y / 16 );
                }
                else if( event.type == SDL_QUIT ) {
                    output.reset();
                }
            }
            if( output )
                output.reset();
        }
        else if( boost::iends_with( config::outputFilename, ".wav" ) ) {
            light4cxx::Logger::root()->info( L4CXX_LOCATION, "QuickWAV Output Mode" );
            if( config::outputFilename.empty() ) {
                config::outputFilename = config::filename + ".wav";
            }
            WavAudioOutput* wavout = new WavAudioOutput( module, config::outputFilename );
            output.reset( wavout );
            if( 0 == wavout->init( 44100 ) ) {
                if( wavout->errorCode() == AbstractAudioOutput::OutputUnavailable ) {
                    light4cxx::Logger::root()->error( L4CXX_LOCATION, "Maybe cannot create WAV File" );
                }
                else {
                    light4cxx::Logger::root()->error( L4CXX_LOCATION, "WAV initialization error: '%d'", wavout->errorCode() );
                }
                return EXIT_FAILURE;
            }
            if( dosScreen ) {
                uiMain = new UIMain( dosScreen.get(), module, output );
            }
            output->play();
            int secs = module->length() / module->frequency();
            boost::progress_display progress( module->length(), std::cout, stringFmt( "QuickWAV: %s (%dm%02ds)\n", config::filename, secs / 60, secs % 60 ) );
            while( output->playing() ) {
                std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
                progress += std::const_pointer_cast<const ppp::AbstractModule>( module )->state().playedFrames - progress.count();
            }
            output.reset();
        }
#ifdef WITH_MP3LAME
        else if( boost::iends_with( config::outputFilename, ".mp3" ) ) {
            light4cxx::Logger::root()->info( L4CXX_LOCATION, "QuickMP3 Output Mode" );
            if( config::outputFilename.empty() ) {
                config::outputFilename = config::filename + ".mp3";
            }
            MP3AudioOutput* mp3out = new MP3AudioOutput( module, config::outputFilename );
            output.reset( mp3out );
            mp3out->setID3( boost::trim_copy( module->metaInfo().title ), PACKAGE_STRING, std::const_pointer_cast<const ppp::AbstractModule>( module )->metaInfo().trackerInfo );
            if( 0 == mp3out->init( 44100 ) ) {
                if( mp3out->errorCode() == AbstractAudioOutput::OutputUnavailable ) {
                    light4cxx::Logger::root()->error( L4CXX_LOCATION, "LAME unavailable: Maybe cannot create MP3 File" );
                }
                else {
                    light4cxx::Logger::root()->error( L4CXX_LOCATION, "LAME initialization error: '%d'", mp3out->errorCode() );
                }
                return EXIT_FAILURE;
            }
            if( dosScreen ) {
                uiMain = new UIMain( dosScreen.get(), module, output );
            }
            output->play();
            int secs = module->length() / module->frequency();
            boost::progress_display progress( module->length(), std::cout, stringFmt( "QuickMP3: %s (%dm%02ds)\n", config::filename, secs / 60, secs % 60 ) );
            while( output->playing() ) {
                std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
                progress += std::const_pointer_cast<const ppp::AbstractModule>( module )->state().playedFrames - progress.count();
            }
            output.reset();
        }
#endif
#ifdef WITH_OGG
        else if( boost::iends_with( config::outputFilename, ".ogg" ) ) {
            light4cxx::Logger::root()->info( L4CXX_LOCATION, "QuickOGG Output Mode" );
            if( config::outputFilename.empty() ) {
                config::outputFilename = config::filename + ".ogg";
            }
            OggAudioOutput* oggOut = new OggAudioOutput( module, config::outputFilename );
            output.reset( oggOut );
            oggOut->setMeta( boost::trim_copy( module->metaInfo().title ), PACKAGE_STRING, std::const_pointer_cast<const ppp::AbstractModule>( module )->metaInfo().trackerInfo );
            if( 0 == oggOut->init( 44100 ) ) {
                if( oggOut->errorCode() == AbstractAudioOutput::OutputUnavailable ) {
                    light4cxx::Logger::root()->error( L4CXX_LOCATION, "OGG unavailable: Maybe cannot create OGG File" );
                }
                else {
                    light4cxx::Logger::root()->error( L4CXX_LOCATION, "OGG initialization error: '%d'", oggOut->errorCode() );
                }
                return EXIT_FAILURE;
            }
            if( dosScreen ) {
                uiMain = new UIMain( dosScreen.get(), module, output );
            }
            output->play();
            int secs = module->length() / module->frequency();
            boost::progress_display progress( module->length(), std::cout, stringFmt( "QuickOGG: %s (%dm%02ds)\n", config::filename, secs / 60, secs % 60 ) );
            while( output->playing() ) {
                std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
                progress += std::const_pointer_cast<const ppp::AbstractModule>( module )->state().playedFrames - progress.count();
            }
            output.reset();
        }
#endif
    }
    catch( ... ) {
        light4cxx::Logger::root()->fatal( L4CXX_LOCATION, stringFmt( "Main (end): %s", boost::current_exception_diagnostic_information() ) );
        std::cout << std::flush;
        std::cerr << "The message above means that PPPlay encountered a problem which\n"
                  << "was so terrible that, despite all taken care, caused it to die.\n"
                  << "To help PPPlay learn to handle this problem, please submit\n"
                  << "a bug report to:\n"
                  << "    http://sourceforge.net/p/peepeeplayer/tickets/\n"
                  << "If possible, please add the file you tried to play and the message above,\n"
                  << "so the authors can examine and hopefully solve the mystery. Thank you!"
                  << std::endl;
        return EXIT_FAILURE;
    }
    dosScreen.reset();
    return EXIT_SUCCESS;
}
Пример #27
0
int main(int argc, char* argv[]) {

		int err=parseCmdLine(argc, argv);
		if (err>0){
		   std::cout<<"Wrong command line argument: \""<<argv[err]<<'\"'<<std::endl;
		   printHelp();
		   exit(-1);
		}

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

		t_function funct(SHA1);
		t_cipher alg(parseCipherAlgorithm());

		int keylength(0), blocksize(0);

		switch (alg){
		  case AES:  
			  keylength = CryptoPP::AES::DEFAULT_KEYLENGTH; 
			  blocksize = CryptoPP::AES::BLOCKSIZE; 
			  break;
		  case GOST_28147_89 :
			  keylength = CryptoPP::GOST::DEFAULT_KEYLENGTH; 
			  blocksize = CryptoPP::GOST::BLOCKSIZE; 
			  break;
		}
		
		securityInfo sec(keylength,blocksize);
		sec.setPassword(cmdkey[key_pass].value);


		CipherMode *pCipherMode(NULL);


		t_mode mode(parseCipherMode());
		switch (mode){
		case	ECB : pCipherMode = new ECBCipherMode(alg); break;
		case    CBC : pCipherMode = new CBCCipherMode(alg); break; 
		case    CFB : pCipherMode = new CFBCipherMode(alg); break; 
		//case    OFB : pCipherMode = new OFBCipherMode(alg); break;

		}

	
		pCipherMode->AttachSecurityInfo(&sec);

		IOData data;


		if (cmdkey[key_enc].wasUsed) {
		   //Encryption
		   data.loadPlainText(cmdkey[key_inp].value);
		   pCipherMode->Encrypt(data);
		   data.saveBinary(cmdkey[key_out].value,sec,alg,mode,funct);
		}
		if (cmdkey[key_dec].wasUsed){
		   //Decryption
           data.loadBinary(cmdkey[key_inp].value,sec,alg,mode,funct);

		   pCipherMode->Decrypt(data);
		   data.savePlainText(cmdkey[key_out].value);
		}


		delete pCipherMode;

		/*system("pause");*/
return 0;
}
Пример #28
0
int _tmain (int argc, _TCHAR **argv)
{

  for (int i = 0; i < argc; ++i)
  {
      out << argv[i] << std::endl;
  }

  if (argc < 2)
  {
    showHelp ();
    return (0);
  }

  params_t params;

  if (!parseCmdLine (argc - 1, argv + 1, &params))
  {
    if (otUnknown == params.opType) 
    {
      out << _T (" : unknown operation") << std::endl;
    }
    else
    {
      out << _T ("bad command line") << std::endl;
    }
    return (-1);
  }

  if (FAILED (initLicensing (AppInfo, params.basesPaths, CLicensingPolicy::cmKeyOnly))) 
  {
    return (-1);
  }

//  synchronizeKeys (AppInfo, KeyFile1, 0);

#if defined (_WIN32)
  SetThreadLocale (MAKELCID (MAKELANGID (LANG_ENGLISH, SUBLANG_NEUTRAL), SORT_DEFAULT));
  CComLib comLib;
#endif

  switch(params.opType) 
  {
    case otKeyReg             : 
    case otKeyRegAdd          : regKey (params.keyFileName, params.keyAddMode); break;
    case otKeyRevoke          : revokeKey (params.serialNumber); break;
    case otCheckActiveKey     :	checkActiveKey (); break;
    case otKeyFileInfo        : keyFileInfo (params.keyFileName); break;
    case otViewInstalledKeys  : viewInstalledKeys (); break;
    case otViewBlacklist      : viewBlacklist (params.blacklistName); break;
    case otCheckAgainstBlacklist: checkAgainstBlackList (params.blacklistName.c_str ()); break;
    case otCheckKeyBlacklist  : checKeyBlacklist (params.keyFileName, params.blacklistName); break;
    case otCheckKeyFile       : 
    case otCheckKeyFileAdd    : 
        checkKeyFile (params.keyFileName, params.keyAddMode); break;
    default                   : break;
  }

//  recreateTest (AppInfo, params.basesPaths, CLicensingPolicy::cmFullCheck);

  return (0);

}
Пример #29
0
void
simbatch_init(int *argc, char **argv)
{
    const char *config_file;    
    const char *deployment_file;
    const char *request = "/config/global/file[@type=\"deployment\"]/text()";
    //const char *req = "/platform_description/process[@function=\"SB_batch\"]";
    
    if (parseCmdLine(*argc, argv)) {
        xbt_die("Error parsing command line");
    }
    config_file = getParam(argv, "-f");
    
#ifdef VERBOSE
    {
        int i = 0;
        fprintf(stderr, "*** Global init ***\n");
        fprintf(stderr, "DIET MODE %s\n", (DIET_MODE)? "enabled": "disable");
        fprintf(stderr, "DIET FILE %s\n", (DIET_FILE)? DIET_FILE: "disable");
        for (i=0; i<4; ++i)
            fprintf(stderr, "DIET_PARAM[%d] = %lu\n", i, DIET_PARAM[i]);
        fprintf(stderr, "Loading config file %s... ", config_file);
    }
#endif
	
    config = config_load(config_file);
    if (!config) {
#ifdef VERBOSE
        fprintf(stderr, "failed\n");
        fprintf(stderr, "Usage : %s -f simbatch_config.xml\n", argv[0]);
#endif
        free(config);
        xbt_die("Cant'load config file");
    }
    
#ifdef VERBOSE
    fprintf(stderr, "ok\n");
    fprintf(stderr, "Check batch deployed and batch defined... ");
#endif
    
    nbBatch = config_get_nb_nodes("/config/batch");
    deployment_file = config_get_value(request);
    
    /* 
     * A bit dirty - I need just one value in the deployment file 
     * So i do a context switch instead of changing my functions
     *//*
    {
        config_t * config_backup = config;
	
        config = config_load(deployment_file);
        if (!config) {
#ifdef VERBOSE 
            fprintf(stderr, "failed\n");
#endif
            free(config_backup);
            xbt_die("Cant'load deployment file");
        }
	
        nbBatchDeployed = config_get_nb_nodes(req);
        free(config);
        config = config_backup;
    }
    
    if (nbBatchDeployed != nbBatch) {
#ifdef VERBOSE
        fprintf(stderr, "failed\n");
#endif
        free(config);
        xbt_die("Batch deployed are not equal to batch defined");
    }
    
#ifdef VERBOSE
    fprintf(stderr, "ok\n");
    
    if (nbBatch <= 0)
        fprintf(stderr, "Warning no batch used\n");
    
    fprintf(stderr, "Number of batch defined  : %d\n", nbBatch);
#endif
    */
    book_of_plugin = xbt_dict_new(); 
    
#ifdef LOG
    book_of_log = xbt_dict_new();
    config_init_log_file();
#endif
    
}
Пример #30
0
int main(int argc, char *argv[]) {

	struct addrinfo hints, *res, *src=NULL;
	int r;
	int sock, output_fd;
	union {
		struct group_req gr;
		struct group_source_req gsr;
	} gr;
	int ifid, level;
	int ssm = 0;
	int on = 1;
	int first = 1;

	parseCmdLine(argc, argv);


	if (conf_output) {
		output_fd = open(conf_output, O_WRONLY | O_CREAT | O_TRUNC, 0755);
		free(conf_output);
		conf_output = NULL;
	} else {
		output_fd = fileno(stdout);
		if (isatty(output_fd)) {
			logger(LOG_ERROR, "Output should be redirected. Not writing any data.\n");
			output_fd = open("/dev/null", O_WRONLY);
		}
	}
	if (output_fd < 0) {
		logger(LOG_FATAL, "Cannot open output file: %s\n",
				strerror(errno));
		exit(EXIT_FAILURE);
	}


	memset(&hints, 0, sizeof(hints));
	hints.ai_family = conf_family;
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_flags = AI_PASSIVE;
	r = getaddrinfo(conf_IP, conf_port, &hints, &res);
	free(conf_IP); conf_IP=NULL;
	free(conf_port); conf_port=NULL;
	if (r) {
		logger(LOG_FATAL, "Getaddrinfo failed: %s\n",
				gai_strerror(r));
		exit(EXIT_FAILURE);
	}
	if (res->ai_next != NULL) {
		logger(LOG_ERROR, "The multicast address is ambiguous!\n");
	}

	sock = socket(res->ai_family, res->ai_socktype, 
	              res->ai_protocol);
	r = setsockopt(sock, SOL_SOCKET,
	               SO_REUSEADDR, &on, sizeof(on));
	if (r) {
		logger(LOG_ERROR, "SO_REUSEADDR "
		"failed: %s\n", strerror(errno));
	}
	r = bind(sock,(struct sockaddr *) res->ai_addr, res->ai_addrlen);
	if (r) {
		logger(LOG_FATAL, "Cannot bind: %s\n",
		       strerror(errno));
		exit(EXIT_FAILURE);
	}


	/** SSM Case */
	if (conf_source) {
		memset(&hints, 0, sizeof(hints));
		hints.ai_family = conf_family;
		r = getaddrinfo(conf_source, NULL, &hints, &src);
		free(conf_source); conf_source=NULL;
		if (r) {
			logger(LOG_FATAL, "Source getaddrinfo failed: %s. Ignoring.\n",
					gai_strerror(r));
			ssm = 0;
		} else {
			if (res->ai_next != NULL) {
				logger(LOG_ERROR,
				"The source address is ambiguous!\n");
			}
			memcpy(&(gr.gsr.gsr_source), src->ai_addr,
				min(sizeof(gr.gsr.gsr_source), src->ai_addrlen));
			ssm = 1;
			freeaddrinfo(src); src=NULL;
		}
	}

	/** Interface Case */
	if (conf_interface) {
		ifid = if_nametoindex(conf_interface);
		if (ifid == 0) {
			logger(LOG_ERROR, "Interface %s not found. Ignoring\n",
					conf_interface);
		}
		free(conf_interface); conf_interface=NULL;
	} else {
		ifid = 0;
	}

	switch (res->ai_family) {
		case AF_INET:
			level = SOL_IP;
			break;
			
		case AF_INET6:
			level = SOL_IPV6;
			if ( ((const struct sockaddr_in6 *)
				(res->ai_addr))->sin6_scope_id != 0) {
				if (ifid != 0) {
					logger(LOG_ERROR, 
						"Interface id overriden "
						"by scoped IPv6 address.\n");
				}
				ifid = ((const struct sockaddr_in6 *)
						(res->ai_addr))->sin6_scope_id;
			}
			break;
		default:
			logger(LOG_ERROR, "Address family does not support mcast.\n");
			exit(EXIT_FAILURE);
	}			 

	if (ssm) {
		memcpy(&(gr.gsr.gsr_group), res->ai_addr,
			min(sizeof(gr.gsr.gsr_group), res->ai_addrlen));
		gr.gsr.gsr_interface = ifid;
		r = setsockopt(sock, level,
			MCAST_JOIN_SOURCE_GROUP, &(gr.gsr), sizeof(gr.gsr));
	} else {
		memcpy(&(gr.gr.gr_group), res->ai_addr,
			min(sizeof(gr.gr.gr_group), res->ai_addrlen));
		gr.gr.gr_interface = ifid;
		r = setsockopt(sock, level,
			MCAST_JOIN_GROUP, &(gr.gr), sizeof(gr.gr));
	}

	if (r) {
		logger(LOG_ERROR, "Cannot join mcast group: %s\n",
				strerror(errno));
		/*Fallback to protocol-specific API*/
		if (fallback(sock, ssm, ssm? (void*)&(gr.gsr):(void*)&(gr.gr))){
			logger(LOG_FATAL, "Fallback failed.\n");
			exit(EXIT_FAILURE);
		}
		logger(LOG_ERROR, "Fallback succeded.\n");
	}
	freeaddrinfo(res); res= NULL;

	/** Joined. Let's forward traffic. */
	logger(LOG_DEBUG, "Joined. Waiting for data...\n");

	while(1) {
		uint8_t buf[UDPBUFLEN];
		int payloadstart, payloadlength;
		uint16_t seqn, oldseqn;

		r = recv(sock, buf, sizeof(buf), 0);
		if (r < 0){
			logger(LOG_FATAL,"Recv() failed: %s\n",
			       strerror(errno));
			exit(EXIT_FAILURE);
		}
		if (first) {
			logger(LOG_INFO, "First packet received. Good.\n");
		}
		if (first && !conf_udponly &&
			(r < 12 || (buf[0]&0xC0) != 0x80)) {
			logger(LOG_ERROR, "First packet is not RTP, "
					"switching to UDP mode.\n");
			conf_udponly = 1;
		}
		if (!conf_udponly) {
			if (r < 12 || (buf[0]&0xC0) != 0x80) { 
				/*malformed RTP/UDP/IP packet*/
				logger(LOG_INFO,"Malformed RTP packet received\n");
				continue;
			}
	
			payloadstart = 12; /* basic RTP header length */
			if (buf[0]&0x0F) {
				payloadstart += (buf[0]&0x0F) * 4; /*CRSC headers*/
				logger(LOG_DEBUG, "CRSC header found\n");
			}
			if (buf[0]&0x10) { /*Extension header*/
				payloadstart += 4 + 4*ntohs(*((uint16_t *)(buf+payloadstart+2)));
				logger(LOG_DEBUG, "Extension header found\n");
			}
			payloadlength = r - payloadstart;
			if (buf[0]&0x20) { /*Padding*/
				payloadlength -= buf[r];
				logger(LOG_DEBUG, "Padding found\n");
				/*last octet indicate padding length*/
			}
			if(payloadlength<0) {
				logger(LOG_INFO,"Malformed RTP packet received\n");
				continue;
			}
			seqn = ntohs(*((uint16_t *)(buf+2)));
			if (!first && seqn==oldseqn) {
				logger(LOG_INFO,"Duplicated RTP packet "
					"received (seqn %d)\n", seqn);
				continue;
			}
			if (!first && (seqn != ((oldseqn+1)&0xFFFF))) {
				logger(LOG_INFO,"Congestion - expected %d, "
					"received %d\n", (oldseqn+1)&0xFFFF, seqn);
			}
			oldseqn=seqn;
		} else {
			payloadstart = 0;
			payloadlength = r;
		}

		first=0;
		while (payloadlength>0) {
			r = write(output_fd, buf+payloadstart, payloadlength);
			if (r<0) {
				logger(LOG_FATAL, "Write failed: %s\n",
						strerror(errno));
				exit(EXIT_FAILURE);
			}
			if (r != payloadlength) {
				logger(LOG_DEBUG, "Not all data written -"
				       " requested %d, written %d\n",
				       payloadlength, r);
			}
			payloadstart += r;
			payloadlength -= r;
		}
	}

	/* should never reach here */
	return 0;
}