示例#1
0
assoc_options_t *new_assoc_cli_options(void) {
    assoc_options_t *options = (assoc_options_t*) malloc (sizeof(assoc_options_t));
    options->num_options = NUM_ASSOC_OPTIONS;
    options->chisq = arg_lit0(NULL, "chisq", "Chi-square association test");
    options->fisher = arg_lit0(NULL, "fisher", "Fisher's exact test");
    return options;
}
示例#2
0
stats_options_t *new_stats_cli_options() {
    stats_options_t *options = (stats_options_t*) malloc (sizeof(stats_options_t));
    options->sample_stats = arg_lit0(NULL, "samples", "Get statistics about samples");
    options->variant_stats = arg_lit0(NULL, "variants", "Get statistics about variants, both per variant and per file (default)");
    options->num_options = NUM_STATS_OPTIONS;
    return options;
}
示例#3
0
int main (int argc, char **argv) {

  void *argtable[] = {
    help = arg_lit0("h","help","print this screen"),
    verbose = arg_lit0("v","verbose","tell me everything"),
    fsyslog = arg_lit0(NULL,"syslog","use syslog"),
    cachepath = arg_file1(NULL,NULL,"cachepath","directory or .cdb database file"),
    netaddress0 = arg_file1(NULL,NULL,"read_address","zmq read network address"),
    netaddress1 = arg_file1(NULL,NULL,"write_address","zmq write network address"),
    end = arg_end(20),
  };
  
  int32_t nerrors = arg_parse(argc,argv,argtable);
  
  if (help->count) {
    
    fprintf(stdout,"tmpcache %s - version 0\n",__FUNCTION__);
    arg_print_syntaxv(stdout,argtable,"\n\n");
    arg_print_glossary (stdout,argtable,"%-25s %s\n");
   
    goto finish;
  }

  if (verbose->count) {

    fprintf(stdout,"tmpcache host - version 0\n");
    int32_t major,minor,patch;
    zmq_version (&major,&minor,&patch);
    fprintf(stdout,"compiled with zmq support %d.%d.%d\n",major,minor,patch);

    goto finish;
  }

  if (nerrors) {
    
    arg_print_errors (stdout,end,"");
    arg_print_syntaxv(stdout,argtable,"\n\n");
    goto finish;
  }

 
  u_term = 0;
  signal (SIGINT,signalhandler);
  signal (SIGTERM,signalhandler);

  if (fsyslog->count)
    openlog (NULL,LOG_PID|LOG_NDELAY,LOG_USER);

  void *read (void *arg) {

    tc_readconfig_t *config = (tc_readconfig_t *)arg;

    if (fsyslog->count)
      syslog (LOG_INFO,"reading cache from %s @ %s",btocstr(config->cachepath),btocstr(config->address));
    
    tc_readfromcache (config);
    
    if (fsyslog->count)
      syslog (LOG_INFO,"closing cache %s @ %s for reading",btocstr(config->cachepath),btocstr(config->address));     
  }
示例#4
0
gwas_options_t *new_gwas_cli_options(void) {
    gwas_options_t *options = (gwas_options_t*) malloc (sizeof(gwas_options_t));
    options->num_options = NUM_GWAS_OPTIONS;
    options->assoc = arg_lit0(NULL, "assoc", "Basic case/control association test");
    options->fisher = arg_lit0(NULL, "fisher", "Fisher's exact test");
    options->tdt = arg_lit0(NULL, "tdt", "Transmission disequilibrium test");
    return options;
}
示例#5
0
merge_options_t *new_merge_cli_options() {
    merge_options_t *options = (merge_options_t*) malloc (sizeof(merge_options_t));
    options->num_options = NUM_MERGE_OPTIONS;
    options->input_files = arg_str1(NULL, "vcf-list", NULL, "List of comma-separated input VCF files");
    options->missing_mode = arg_str0(NULL, "missing-mode", NULL, "How to fill missing genotypes (missing = ./., reference = 0/0)");
    options->info_fields = arg_str0(NULL, "info-fields", NULL, "Information to generate in the new INFO column");
    options->copy_filter = arg_lit0(NULL, "copy-filter", "Whether to copy the FILTER column from the original files into the samples");
    options->copy_info = arg_lit0(NULL, "copy-info", "Whether to copy the INFO column from the original files into the samples");
    return options;
}
示例#6
0
void parse_command_line(int argc, char* argv[])
{
    // if the parsing of the arguments was unsuccessful
    int nerrors;

    // Define argument table structs
    python_folder = arg_file0 ( NULL, "py-folder", "<path to file>", "Path to folder (relative or absolute) that contains python script (default: lpfw-pygui)" );
    log_debug = arg_int0 ( NULL, "log-debug", "<1/0 for yes/no>", "Enable debug messages logging" );

    struct arg_lit *help = arg_lit0 ( NULL, "help", "Display this help screen" );
    struct arg_lit *version = arg_lit0 ( NULL, "version", "Display the current version" );
    struct arg_end *end = arg_end ( 10 );
    void *argtable[] = {python_folder, log_debug, help, version, end};

    // Set default values
    char *python_folder_pointer = malloc(strlen("lpfw-pygui")+1);
    strcpy (python_folder_pointer, "lpfw-pygui");
    python_folder->filename[0] = python_folder_pointer;

    * ( log_debug->ival ) = 0;

    if ( arg_nullcheck ( argtable ) != 0 )
      {
	printf ( "Error: insufficient memory\n" );
	exit(0);
      }

    nerrors = arg_parse ( argc, argv, argtable );

    if ( nerrors == 0 )
      {
	if ( help->count == 1 )
	  {
	    printf ( "Leopard Flower frontend :\n Syntax and help:\n" );
	    arg_print_glossary ( stdout, argtable, "%-43s %s\n" );
	    exit (0);
	  }
	else if ( version->count == 1 )
	  {
	    printf ( "%s\n", VERSION );
	    exit (0);
	  }
    }
    else if ( nerrors > 0 )
      {
	arg_print_errors ( stdout, end, "Leopard Flower frontend" );
	printf ( "Leopard Flower frontend:\n Syntax and help:\n" );
	arg_print_glossary ( stdout, argtable, "%-43s %s\n" );
	exit (1);
      }

    // Free memory - don't do this cause args needed later on
    //  arg_freetable(argtable, sizeof (argtable) / sizeof (argtable[0]));
}
示例#7
0
void register_ethernet()
{
    eth_event_group = xEventGroupCreate();
    tcpip_adapter_init();
    ESP_ERROR_CHECK(esp_event_loop_init(eth_event_handler, NULL));

    eth_config_t config = DEFAULT_ETHERNET_PHY_CONFIG;
    config.phy_addr = CONFIG_PHY_ADDRESS;
    config.gpio_config = eth_gpio_config_rmii;
    config.tcpip_input = tcpip_adapter_eth_input;
    config.clock_mode = CONFIG_PHY_CLOCK_MODE;
#ifdef CONFIG_PHY_USE_POWER_PIN
    /* Replace the default 'power enable' function with an example-specific one
     that toggles a power GPIO. */
    config.phy_power_enable = phy_device_power_enable_via_gpio;
#endif

    ESP_ERROR_CHECK(esp_eth_init(&config));

    eth_control_args.control = arg_str1(NULL, NULL, "<start|stop|info>", "Start/Stop Ethernet or Get info of Ethernet");
    eth_control_args.end = arg_end(1);
    const esp_console_cmd_t cmd = {
        .command = "ethernet",
        .help = "Control Ethernet interface",
        .hint = NULL,
        .func = eth_cmd_control,
        .argtable = &eth_control_args
    };
    ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));

    iperf_args.ip = arg_str0("c", "client", "<ip>",
                             "run in client mode, connecting to <host>");
    iperf_args.server = arg_lit0("s", "server", "run in server mode");
    iperf_args.udp = arg_lit0("u", "udp", "use UDP rather than TCP");
    iperf_args.port = arg_int0("p", "port", "<port>",
                               "server port to listen on/connect to");
    iperf_args.interval = arg_int0("i", "interval", "<interval>",
                                   "seconds between periodic bandwidth reports");
    iperf_args.time = arg_int0("t", "time", "<time>", "time in seconds to transmit for (default 10 secs)");
    iperf_args.abort = arg_lit0("a", "abort", "abort running iperf");
    iperf_args.end = arg_end(1);
    const esp_console_cmd_t iperf_cmd = {
        .command = "iperf",
        .help = "iperf command",
        .hint = NULL,
        .func = &eth_cmd_iperf,
        .argtable = &iperf_args
    };
    ESP_ERROR_CHECK(esp_console_cmd_register(&iperf_cmd));
}
示例#8
0
bool Application::initArgtable()
{
  const char* progname = "revisor";
  struct arg_str* l   = arg_str0("l", NULL, "<interface>",   "Interface to listen, default '127.0.0.1'");
  struct arg_int* p   = arg_int0("p", NULL, "<port number>", "Port to listen, default 8080");
  struct arg_lit* h   = arg_lit0("h", "help",                "This help message");
  struct arg_end* end = arg_end(20);
  void *argtable[]  = {l, p, h, end};

  int nerrors = arg_parse(argc, argv, argtable);

  // special case: '--help' takes precedence over error reporting
  if (h->count > 0) {
    printf("Usage: %s", progname);
    arg_print_syntax(stdout, argtable, "\n");
    arg_print_glossary(stdout, argtable, "  %-25s %s\n");
    return false;
  }

  if (nerrors > 0) {
    arg_print_errors(stdout, end, progname);
    return false;
  }

  if (l->count > 0) {
    listeningInterface = l->sval[0];
  }

  if (p->count > 0) {
    portNumber = *p->ival;
  }

  arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
  return true;
}
示例#9
0
int main(int argc, char **argv)
    {
    struct arg_xxx  *scalar  = arg_xxx1(NULL, NULL, "<scalar>",            0.0, 1.0, "<double> value in range [0.0, 1.0]");
    struct arg_xxx  *x       = arg_xxx0("x",  NULL, "<double>",           -1.0, 1.0, "x coeff in range [-1.0, 1.0]");
    struct arg_xxx  *y       = arg_xxxn("y",  NULL, "<double>", 0,argc+2,  0.5, 0.9, "y coeff in range [0.5, 0.9]");
    struct arg_lit  *help    = arg_lit0(NULL,"help",                                 "print this help and exit");
    struct arg_end  *end     = arg_end(20);
    void* argtable[] = {scalar,x,y,help,end};
    const char* progname = "argcustom";
    int nerrors;
    int exitcode=0;
    int i;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",progname);
        exitcode=1;
        goto exit;
        }

    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
        {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout,argtable,"\n");
        printf("This program demonstrates the use of the argtable2 library\n");
        printf("for parsing command line arguments.\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        exitcode=0;
        goto exit;
        }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
        {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,progname);
        printf("Try '%s --help' for more information.\n",progname);
        exitcode=1;
        goto exit;
        }

    /* only get here is command line arguments were parsed sucessfully */
    printf("scalar = %f\n", scalar->data[0]);
    if (x->count > 0)
        printf("x = %f\n", x->data[0]);
    for (i=0; i<y->count; i++)
        printf("y[%d] = %f\n", i, y->data[i]);

    exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return exitcode;
    }
示例#10
0
static
int dslink_parse_opts(int argc,
                      char **argv,
                      DSLinkConfig *config) {
    int ret = 0;
    struct arg_lit *help;
    struct arg_str *broker, *log;
    struct arg_end *end;

    void *argTable[] = {
        help = arg_lit0("h", "help", "Displays this help menu"),
        broker = arg_str1("b", "broker", "url", "Sets the broker URL to connect to"),
        log = arg_str0("l", "log", "log type", "Sets the logging level"),
        end = arg_end(5)
    };

    if (arg_nullcheck(argTable) != 0) {
        return DSLINK_ALLOC_ERR;
    }

    int errs = arg_parse(argc, argv, argTable);

    if (help->count > 0) {
        printf("Usage: <opts>\n");
        arg_print_glossary(stdout, argTable, " %-25s %s\n");
        ret = 1;
        goto exit;
    }

    if (errs > 0) {
        dslink_print_help();
        arg_print_errors(stdout, end, ":");
        ret = 1;
        goto exit;
    }

    config->broker_url = broker->sval[0];

    if (log->count > 0) {
        char lvl[8];
        const char *src = log->sval[0];
        size_t len = strlen(src);
        if (len > sizeof(lvl)) {
            len = sizeof(lvl);
        }
        memcpy(lvl, src, len);
        if (dslink_log_set_lvl(lvl, len) != 0) {
            printf("Invalid log level: %s\n", lvl);
            dslink_print_help();
            ret = 1;
            goto exit;
        }
    }

exit:
    arg_freetable(argTable, sizeof(argTable) / sizeof(argTable[0]));
    return ret;
}
示例#11
0
int main(int argc, char * argv[]) {
    void* argtable[] = {
                input = arg_filen(   "i",   "input",              "<string>", 0, 100,    "input file")
        ,  o_validate = arg_strn(   "v",  "validate",     "<string>",         0, 10,   "validate operations")
        ,         o_h = arg_file0(   NULL,  "output-h",           "<string>",            "output h file dir")
        ,     o_lib_c = arg_file0(   NULL,  "output-lib-c",       "<string>",            "output c lib file")
        , o_lib_c_arg = arg_str0(   NULL,  "output-lib-c-arg",    "<string>",            "output c lib file")
        ,   o_lib_bin = arg_file0(   NULL,  "output-lib-bin",     "<string>",            "output c lib file")
        ,        help = arg_lit0(   NULL,  "help",                                   "print this help and exit")
        ,         end = arg_end(20)
    };

    struct error_monitor em_buf;
    error_monitor_t em;
    int rv;
    int nerrors;

    cpe_error_monitor_init(&em_buf, cpe_error_log_to_consol, 0);
    em = &em_buf;

    rv = -1;

    if (arg_nullcheck(argtable) != 0) {
        CPE_ERROR(em, "init arg table fail!");
        goto exit;
    }

    nerrors = arg_parse(argc,argv,argtable);

    if (help->count > 0) {
        printf("Usage: %s", argv[0]);
        arg_print_syntax(stdout,argtable,"\n");
        rv = 0;
        goto exit;
    }

    if (nerrors > 0) {
        arg_print_errors(stdout, end, argv[0]);
        printf("Try '%s --help' for more information.\n", argv[0]);
        goto exit;
    }

    rv = tools_main(em);

exit:
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));

    return rv;
}
示例#12
0
int main(int argc, char *argv[])
{
    /* the global arg_xxx structs are initialised within the argtable */
    void *argtable[] = {
        help    = arg_lit0(NULL, "help", "display this help and exit"),
        version = arg_lit0(NULL, "version", "display version info and exit"),
        a       = arg_lit0("a", NULL,"the -a option"),
        b       = arg_lit0("b", NULL, "the -b option"),
        c       = arg_lit0("c", NULL, "the -c option"),
        scal    = arg_int0(NULL, "scalar", "<n>", "foo value"),
        verb    = arg_lit0("v", "verbose", "verbose output"),
        o       = arg_file0("o", NULL, "myfile", "output file"),
        file    = arg_filen(NULL, NULL, "<file>", 0, 100, "input files"),
        end     = arg_end(20),
    };

    int exitcode = 0;
    char progname[] = "testargtable3.exe";

    int nerrors;
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
    {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("List information about the FILE(s) "
               "(the current directory by default).\n\n");
        arg_print_glossary(stdout, argtable, "  %-25s %s\n");
        exitcode = 0;
        goto exit;
    }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
    {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        exitcode = 1;
        goto exit;
    }

exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return exitcode;
}
int
main(int argc, char **argv)
{
    struct arg_int *channels  = arg_int0("c", "channels", "<n>", "define number of channels (default is 1)");
    struct arg_int *subscribers  = arg_int0("s", "subscribers", "<n>", "define number of subscribers (default is 1)");

    struct arg_str *server_name = arg_str0("S", "server", "<hostname>", "server hostname where messages will be published (default is \"127.0.0.1\")");
    struct arg_int *server_port = arg_int0("P", "port", "<n>", "server port where messages will be published (default is 9080)");

    struct arg_int *timeout = arg_int0(NULL, "timeout", "<n>", "timeout when waiting events on communication to the server (default is 1000)");
    struct arg_int *verbose = arg_int0("v", "verbose", "<n>", "increase output messages detail (0 (default) - no messages, 1 - info messages, 2 - debug messages, 3 - trace messages");

    struct arg_lit *help    = arg_lit0(NULL, "help", "print this help and exit");
    struct arg_lit *version = arg_lit0(NULL, "version", "print version information and exit");
    struct arg_end *end     = arg_end(20);

    void* argtable[] = { channels, subscribers, server_name, server_port, timeout, verbose, help, version, end };

    const char* progname = "subscriber";
    int nerrors;
    int exitcode = EXIT_SUCCESS;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0) {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n", progname);
        exitcode = EXIT_FAILURE;
        goto exit;
    }

    /* set any command line default values prior to parsing */
    subscribers->ival[0] = DEFAULT_CONCURRENT_CONN;
    channels->ival[0] = DEFAULT_NUM_CHANNELS;
    server_name->sval[0] = DEFAULT_SERVER_HOSTNAME;
    server_port->ival[0] = DEFAULT_SERVER_PORT;
    timeout->ival[0] = DEFAULT_TIMEOUT;
    verbose->ival[0] = 0;

    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc, argv, argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0) {
        printf(DESCRIPTION_SUBSCRIBER, progname, VERSION, COPYRIGHT);
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_glossary(stdout, argtable, "  %-25s %s\n");
        exitcode = EXIT_SUCCESS;
        goto exit;
    }

    /* special case: '--version' takes precedence error reporting */
    if (version->count > 0) {
        printf(DESCRIPTION_SUBSCRIBER, progname, VERSION, COPYRIGHT);
        exitcode = EXIT_SUCCESS;
        goto exit;
    }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0) {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        exitcode = EXIT_FAILURE;
        goto exit;
    }

    verbose_messages = verbose->ival[0];

    /* normal case: take the command line options at face value */
    exitcode = main_program(channels->ival[0], subscribers->ival[0], server_name->sval[0], server_port->ival[0], timeout->ival[0]);

exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));

    return exitcode;
}
int UHD_SAFE_MAIN(int argc, char *argv[]){
    
    uhd::set_thread_priority_safe(); 
   
    size_t rxshm_size, txshm_size;

    bool mimic_active;
    float mimic_delay;

    unsigned int iSide, iSwing; // often used loop variables

    int32_t rx_worker_status = 0; 
    int32_t clrfreq_rx_worker_status = 0; 
    int32_t mute_output = 0; // used if rx_worker error happends

    int32_t rx_stream_reset_count = 0;
    int32_t rx_stream_error_count = 0;

    std::vector<sem_t>  sem_rx_vec(nSwings), sem_tx_vec(nSwings);

    std::vector<uint32_t> state_vec(nSwings, ST_INIT);
    uint32_t swing; // = SWING0;
    
    size_t nSamples_rx, nSamples_tx_pulse, nSamples_pause_after_rx, nSamples_auto_clear_freq, nSamples_rx_total;
    size_t auto_clear_freq_available = 0;


    uint32_t npulses, nerrors;
    ssize_t cmd_status;
    uint32_t usrp_driver_base_port, ip_part;

    int32_t connect_retrys = MAX_SOCKET_RETRYS; 
    int32_t sockopt;
    struct sockaddr_in sockaddr;
    struct sockaddr_storage client_addr;
    socklen_t addr_size;
    uint32_t exit_driver = 0;

    uint32_t tx_worker_active;

    uhd::time_spec_t start_time, rx_start_time;

    // vector of all pulse start times over an integration period
    std::vector<uhd::time_spec_t> pulse_time_offsets;
    // vector of the sample index of pulse start times over an integration period
    std::vector<uint64_t> pulse_sample_idx_offsets;

    boost::thread_group uhd_threads;
    boost::thread_group clrfreq_threads;

    // process config file for port and SHM sizes
    DEBUG_PRINT("USRP_DRIVER starting to read driver_config.ini\n");
    boost::property_tree::ptree pt;
    boost::property_tree::ini_parser::read_ini("../driver_config.ini", pt);

  //  DEBUG_PRINT("USRP_DRIVER reading rxshm_size\n");
  //  std::cout << pt.get<std::string>("shm_settings.rxshm_size") << '\n';
    rxshm_size = std::stoi(pt.get<std::string>("shm_settings.rxshm_size"));
 
  //  DEBUG_PRINT("USRP_DRIVER reading txshm_size\n");
    txshm_size = std::stoi(pt.get<std::string>("shm_settings.txshm_size"));

    usrp_driver_base_port = std::stoi(pt.get<std::string>("network_settings.USRPDriverPort"));
    
    boost::property_tree::ptree pt_array;
    DEBUG_PRINT("USRP_DRIVER starting to read array_config.ini\n");
    boost::property_tree::ini_parser::read_ini("../array_config.ini", pt_array);
    mimic_active = std::stof(pt_array.get<std::string>("mimic.mimic_active")) != 0;
    mimic_delay  = std::stof(pt_array.get<std::string>("mimic.mimic_delay"));
    fprintf(stderr, "read from ini: mimic_active=%d, mimic_delay=%f\n", mimic_active, mimic_delay);

    init_all_dirs();

    // TODO also read usrp_config.ini and get antenna and side information from it. remove antenna input argument. 

    // process command line arguments
    struct arg_lit  *al_help   = arg_lit0(NULL, "help", "Prints help information and then exits");
//    struct arg_int  *ai_ant    = arg_intn("a", "antenna", NULL, 1, 2, "Antenna position index for the USRP"); 
    struct arg_int  *ai_ant_a          = arg_int0("a", "antennaA", NULL, "Antenna position index for the USRP on side A"); 
    struct arg_int  *ai_ant_b          = arg_int0("b", "antennaB", NULL, "Antenna position index for the USRP on side B"); 
    struct arg_str  *as_host           = arg_str0("h", "host", NULL, "Hostname or IP address of USRP to control (e.g usrp1)"); 
    struct arg_lit  *al_intclk         = arg_lit0("i", "intclk", "Select internal clock (default is external)"); 
    struct arg_lit  *al_interferometer = arg_lit0("x", "interferometer", "Disable tx_worker for interferometer antennas"); 
    struct arg_end  *ae_argend         = arg_end(ARG_MAXERRORS);
    void* argtable[] = {al_help, ai_ant_a, ai_ant_b, as_host, al_intclk, al_interferometer, ae_argend};
    
    double txrate, rxrate, txfreq, rxfreq;
    double txrate_new, rxrate_new, txfreq_new, rxfreq_new;

    DEBUG_PRINT("usrp_driver debug mode enabled\n");

    if (SUPRESS_UHD_PRINTS) {
        uhd::msg::register_handler(&uhd_term_message_handler);
    }

    nerrors = arg_parse(argc,argv,argtable);
    if (nerrors > 0) {
        arg_print_errors(stdout,ae_argend,"usrp_driver");
        exit(1);
    }
    if (argc == 1) {
        printf("No arguments found, try running again with --help for more information.\n");
        exit(1);
    }
    if(al_help->count > 0) {
        printf("Usage: ");
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0]));
        return 0;
    }
   
    unsigned int nSides =  ai_ant_a->count + ai_ant_b->count; 
    if( nSides == 0 ) {
        printf("No antenna index, exiting...");
        return 0;
    }
    
    if(as_host->sval == NULL) {
        printf("Missing usrp host command line argument, exiting...");
        return 0;
    }

    std::vector<int> antennaVector(nSides);
    std::vector<uint64_t> channel_numbers;
    // both sides
    if( nSides == 2 ) {
        DEBUG_PRINT("Setting side A: ant_idx %d\n",ai_ant_a->ival[0]);
        antennaVector[0] = ai_ant_a->ival[0];
        channel_numbers.push_back(0);

        DEBUG_PRINT("Setting side B: ant_idx %d\n",ai_ant_b->ival[0]);
        antennaVector[1] = ai_ant_b->ival[0];
        channel_numbers.push_back(1);
    } else {
     // side A
     if (ai_ant_a->count == 1) {
        DEBUG_PRINT("Setting side A: ant_idx %d\n",ai_ant_a->ival[0]);
        antennaVector[0] = ai_ant_a->ival[0];
        channel_numbers.push_back(0);
     // side B
     } else {
        DEBUG_PRINT("Setting side B: ant_idx %d\n",ai_ant_b->ival[0]);
        antennaVector[0] = ai_ant_b->ival[0];
        channel_numbers.push_back(1);
        DEBUG_PRINT("Warning: For one side use DIO output is always on Side A!!!!!!!!!!!!!"); // TODO correct this


     }

    }

    // pointers to shared memory
    std::vector<std::vector<void *>> shm_rx_vec(nSides, std::vector<void *>( nSwings));
    std::vector<std::vector<void *>> shm_tx_vec(nSides, std::vector<void *>( nSwings));

    // local buffers for tx and rx
    std::vector<std::vector<std::complex<int16_t>>> tx_samples(nSides,         std::vector<std::complex<int16_t>>(MAX_PULSE_LENGTH,0));
    std::vector<std::vector<std::complex<int16_t>>> rx_data_buffer(nSides,     std::vector<std::complex<int16_t>>(0));
    std::vector<std::vector<std::complex<int16_t>>> rx_auto_clear_freq(nSides, std::vector<std::complex<int16_t>>(0));
     

    std::string usrpargs(as_host->sval[0]);
    usrpargs = "addr0=" + usrpargs + ",master_clock_rate=200.0e6";
//    usrpargs = "addr0=" + usrpargs + ",master_clock_rate=200.0e6,recv_frame_size=50000000";
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(usrpargs);
  //  usrp->set_rx_subdev_spec(uhd::usrp::subdev_spec_t("A:A B:A"));
  //  usrp->set_tx_subdev_spec(uhd::usrp::subdev_spec_t("A:A B:A"));
    boost::this_thread::sleep(boost::posix_time::seconds(SETUP_WAIT));
    uhd::stream_args_t stream_args("sc16", "sc16");
    
    if (usrp->get_rx_num_channels() < nSides || usrp->get_tx_num_channels() < nSides) {  
       DEBUG_PRINT("ERROR: Number of defined channels (%i) is smaller than avaialable channels:\n    usrp->get_rx_num_channels(): %lu \n    usrp->get_tx_num_channels(): %lu \n\n", nSides, usrp->get_rx_num_channels(),   usrp->get_tx_num_channels());
       return -1;
    }
    stream_args.channels = channel_numbers;
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);
    uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args);


    // TODO: retry uhd connection if fails..

    // Determine port from 3rd part of ip (192.168.x.2 => port = base_port + x ) 
    int start_idx = usrpargs.find("."); 
    start_idx = usrpargs.find(".", start_idx+1);
    int end_idx = usrpargs.find(".", start_idx+1);
    ip_part = atoi(usrpargs.substr(start_idx+1, end_idx-start_idx-1).c_str());



    // initialize rxfe gpio
    kodiak_init_rxfe(usrp, nSides);
    // initialize other gpio on usrp
    init_timing_signals(usrp, mimic_active, nSides);
    
    //if(CAPTURE_ERRORS) {
    //    signal(SIGINT, siginthandler);
    //}
    
    // open shared memory buffers and semaphores created by cuda_driver.py
    // for dual polarization we use antenna numbers 20 to 35 (side is always 0)
    for(iSwing = 0; iSwing < nSwings; iSwing++) {
        for(iSide = 0; iSide < nSides; iSide++) {
            int shm_side = 0;
            shm_rx_vec[iSide][iSwing] = open_sample_shm(antennaVector[iSide], RXDIR, shm_side, iSwing, rxshm_size);
            shm_tx_vec[iSide][iSwing] = open_sample_shm(antennaVector[iSide], TXDIR, shm_side, iSwing, txshm_size);
            DEBUG_PRINT("usrp_driver rx shm addr: %p iSide: %d iSwing: %d\n", shm_rx_vec[iSide][iSwing], iSide, iSwing);

            if (antennaVector[iSide] < 19 ) { // semaphores only for antennas of first polarization TODO check if this is enough
               sem_rx_vec[iSwing] = open_sample_semaphore(antennaVector[iSide], iSwing, RXDIR);
               sem_tx_vec[iSwing] = open_sample_semaphore(antennaVector[iSide], iSwing, TXDIR);
            }
        }
    }

    if(al_interferometer->count > 0) {
       DEBUG_PRINT("Disable tx_worker ...\n");
       tx_worker_active = 0;
    } else {
       tx_worker_active = 1;
    }

    if(al_intclk->count > 0) {
        usrp->set_clock_source("internal");
        usrp->set_time_source("internal");
    }
    else {
    // sync clock with external 10 MHz and PPS
        DEBUG_PRINT("Set clock: external\n");
        usrp->set_clock_source("external", 0);
        DEBUG_PRINT("Set time: external\n");
        usrp->set_time_source("external", 0);
        DEBUG_PRINT("Done setting time and clock\n");
     }

    while(true) {
        if(driversock) {
            close(driverconn);
            close(driversock);
        }
   
        boost::this_thread::sleep(boost::posix_time::seconds(SETUP_WAIT));

        // bind to socket for communication with usrp_server.py:
        driversock = socket(AF_INET, SOCK_STREAM, 0);
        if(driversock < 0){
            perror("opening stream socket\n");
            exit(1);
        }

        sockopt = 1;
        setsockopt(driversock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(int32_t));

        sockaddr.sin_family = AF_INET;
        // TODO: maybe limit addr to interface connected to usrp_server
        sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);

        fprintf(stderr, "listening on port: %d\n", usrp_driver_base_port + ip_part); 
        sockaddr.sin_port = htons(usrp_driver_base_port + ip_part);
        

        if( bind(driversock, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) < 0){
                perror("binding tx stream socket");
                exit(1);
        }
   
        // wait for connection...
        listen(driversock, 5);

        // and accept it
        fprintf(stderr, "waiting for socket connection\n");
        addr_size = sizeof(client_addr);
        driverconn = accept(driversock, (struct sockaddr *) &client_addr, &addr_size);
        fprintf(stderr, "accepted socket connection\n");



        while(true) {
            // wait for transport endpoint to connect?
            
            DEBUG_PRINT("USRP_DRIVER waiting for command\n");
            uint8_t command = sock_get_cmd(driverconn, &cmd_status);
            DEBUG_PRINT("USRP_DRIVER received command, status: %zu\n", cmd_status);
             
            // see if socket is closed..
            if(cmd_status == 11 || cmd_status == 0 || cmd_status < 0) {
                DEBUG_PRINT("USRP_DRIVER lost connection to usrp_server, waiting for fresh connection, %d tries remaining\n", connect_retrys);
                close(driversock);
                if(connect_retrys-- < 0) {
                    exit(1);
                }
                sleep(1);
                break;
            }

            connect_retrys = MAX_SOCKET_RETRYS;


            switch(command) {
                case USRP_SETUP: {
                    // receive infomation about a pulse sequence/integration period
                    // transmit/receive center frequenies and sampling rates
                    // number of tx/rx samples
                    // number of pulse sequences per integration period, and pulse start times
                    
                    swing      = sock_get_int16(  driverconn); 
                    
                    DEBUG_PRINT("entering USRP_SETUP command (swing %d)\n", swing);
                  
                    txfreq_new = sock_get_float64(driverconn);
                    rxfreq_new = sock_get_float64(driverconn);
                    txrate_new = sock_get_float64(driverconn);
                    rxrate_new = sock_get_float64(driverconn);

                    npulses = sock_get_uint32(driverconn);

                    nSamples_rx              = sock_get_uint64(driverconn);
                    nSamples_pause_after_rx  = sock_get_uint64(driverconn);
                    nSamples_auto_clear_freq = sock_get_uint64(driverconn);
                    nSamples_tx_pulse        = sock_get_uint64(driverconn);
                    nSamples_rx_total        = nSamples_rx + nSamples_pause_after_rx + nSamples_auto_clear_freq;

                    DEBUG_PRINT("USRP_SETUP number of requested rx samples: %d + %d pause + %d auto clear freq\n", (uint32_t) nSamples_rx, nSamples_pause_after_rx, nSamples_auto_clear_freq);
                    DEBUG_PRINT("USRP_SETUP number of requested tx samples per pulse: %d\n", (uint32_t) nSamples_tx_pulse);
                    DEBUG_PRINT("USRP_SETUP existing tx rate : %f (swing %d)\n", txrate, swing);
                    DEBUG_PRINT("USRP_SETUP requested tx rate: %f\n", txrate_new);

                    // resize 
                    pulse_sample_idx_offsets.resize(npulses);
                    pulse_time_offsets.resize(npulses);

                    for(uint32_t i = 0; i < npulses; i++) {
                //        DEBUG_PRINT("USRP_SETUP waiting for pulse offset %d of %d\n", i+2, npulses);
                        pulse_sample_idx_offsets[i] = sock_get_uint64(driverconn); 
                //        DEBUG_PRINT("USRP_SETUP received %zu pulse offset\n", pulse_sample_idx_offsets[i]);

                    }
                    DEBUG_PRINT("USRP_SETUP resize autoclear freq\n");

                    // RESIZE LOCAL BUFFERS
                    if(rx_data_buffer[0].size() < nSamples_rx_total) {
                       for(iSide = 0; iSide < nSides; iSide++) {
                           rx_data_buffer[iSide].resize(nSamples_rx_total);
                       }
                    }
                    DEBUG_PRINT("USRP_SETUP resize autoclear freq\n");

                    if(nSamples_auto_clear_freq != 0 and rx_auto_clear_freq[0].size() < nSamples_auto_clear_freq) {
                       for(iSide = 0; iSide < nSides; iSide++) {
                           rx_auto_clear_freq[iSide].resize(nSamples_auto_clear_freq);
                       }
                    }

                    // TODO use return argument of set_xx to save new rate/freq                    
   
                    // if necessary, retune USRP frequency and sampling rate
                    if(rxrate != rxrate_new) {
                       usrp->set_rx_rate(rxrate_new);
                       rxrate = usrp->get_rx_rate();
                    }

                    if(txrate != txrate_new) {
                       usrp->set_tx_rate(txrate_new);
                       txrate = usrp->get_tx_rate();
                    }

                    if(rxfreq != rxfreq_new) {
                       for(iSide = 0; iSide < nSides; iSide++) {
                          usrp->set_rx_freq(rxfreq_new, iSide);
                       }
                       rxfreq = usrp->get_rx_freq();
                    }

                    if(txfreq != txfreq_new) {
                       for(iSide = 0; iSide < nSides; iSide++) {
                          usrp->set_tx_freq(txfreq_new, iSide);
                       }
                       txfreq = usrp->get_tx_freq();
                    }

                    if(verbose) {
                        std::cout << boost::format("Actual RX Freq: %f MHz...") % (usrp->get_rx_freq()/1e6)  <<  std::endl;
                        std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate()/1e6) <<  std::endl;
                        std::cout << boost::format("Actual TX Freq: %f MHz...") % (usrp->get_tx_freq()/1e6)  <<  std::endl;
                        std::cout << boost::format("Actual TX Rate: %f Msps...") % (usrp->get_tx_rate()/1e6) <<  std::endl;
                    }

                    // TODO: set the number of samples in a pulse. this is calculated from the pulse duration and the sampling rate 
                    // when do we know this? after USRP_SETUP
                
                    // create local copy of transmit pulse data from shared memory
                    std::complex<int16_t> *shm_pulseaddr;
                    size_t spb = tx_stream->get_max_num_samps();
                    size_t pulse_bytes = sizeof(std::complex<int16_t>) * nSamples_tx_pulse;
                    size_t number_of_pulses = pulse_time_offsets.size();
                    size_t num_samples_per_pulse_with_padding = nSamples_tx_pulse + 2*spb;
                    DEBUG_PRINT("spb %d, pulse length %d samples, pulse with padding %d\n", spb, nSamples_tx_pulse, num_samples_per_pulse_with_padding);

                    // TODO unpack and pad tx sample
                    for (iSide = 0; iSide<nSides; iSide++) {
                        tx_samples[iSide].resize(number_of_pulses * (num_samples_per_pulse_with_padding));                   

                        for(uint32_t p_i = 0; p_i < number_of_pulses; p_i++) {
                            shm_pulseaddr = &((std::complex<int16_t> *) shm_tx_vec[iSide][swing])[p_i*nSamples_tx_pulse];
                            memcpy(&tx_samples[iSide][spb + p_i*(num_samples_per_pulse_with_padding)], shm_pulseaddr, pulse_bytes);
                        }
                    }


                    if(SAVE_RAW_SAMPLES_DEBUG) {
                        FILE *raw_dump_fp;
                        char raw_dump_name[80];
                       // DEBUG_PRINT("Exporting %i raw tx_samples (%i + 2* %i)\n", num_samples_per_pulse_with_padding, nSamples_tx_pulse, spb);
                        for (iSide =0; iSide < nSides; iSide++){
                            sprintf(raw_dump_name,"%s/raw_samples_tx_ant_%d.cint16", diag_dir, antennaVector[iSide]);
                            raw_dump_fp = fopen(raw_dump_name, "wb");
                            fwrite(&tx_samples[iSide][0], sizeof(std::complex<int16_t>),num_samples_per_pulse_with_padding*number_of_pulses, raw_dump_fp);
                            fclose(raw_dump_fp);
                        }
                    }


                    state_vec[swing] = ST_READY; 
                    DEBUG_PRINT("changing state_vec[swing] to ST_READY\n");
                    sock_send_uint8(driverconn, USRP_SETUP);
                    break;
                    }

                case RXFE_SET: {
                    DEBUG_PRINT("entering RXFE_SET command\n");
                    RXFESettings rf_settings;
                    rf_settings.amp1 = sock_get_uint8(driverconn);
                    rf_settings.amp2 = sock_get_uint8(driverconn);
                    uint8_t attTimes2 = sock_get_uint8(driverconn);
                    rf_settings.att_05_dB = ( attTimes2 & 0x01 ) != 0;
                    rf_settings.att_1_dB  = ( attTimes2 & 0x02 ) != 0;
                    rf_settings.att_2_dB  = ( attTimes2 & 0x04 ) != 0;
                    rf_settings.att_4_dB  = ( attTimes2 & 0x08 ) != 0;
                    rf_settings.att_8_dB  = ( attTimes2 & 0x10 ) != 0;
                    rf_settings.att_16_dB = ( attTimes2 & 0x20 ) != 0;
                   
                    kodiak_set_rxfe(usrp, rf_settings, nSides);
                    sock_send_uint8(driverconn, RXFE_SET);
                    break;
                    }

                case TRIGGER_PULSE: {

                    swing      = sock_get_int16(  driverconn); 
                    DEBUG_PRINT("entering TRIGGER_PULSE command (swing %d)\n", swing );

                    if (state_vec[swing] != ST_READY) {
                        sock_send_uint8(driverconn, TRIGGER_BUSY);
                        DEBUG_PRINT("TRIGGER_PULSE busy in state_vec[swing] %d, returning\n", state_vec[swing]);
                    }
                    else {

                        DEBUG_PRINT("TRIGGER_PULSE ready\n");
                        state_vec[swing] = ST_PULSE;

                        DEBUG_PRINT("TRIGGER_PULSE locking semaphore\n");
                        lock_semaphore(sem_rx_vec[swing]); 
                        lock_semaphore(sem_tx_vec[swing]); 

                        DEBUG_PRINT("TRIGGER_PULSE semaphore locked\n");

                        // create local copy of transmit pulse data from shared memory
                        size_t spb = tx_stream->get_max_num_samps();
                        size_t pulse_bytes = sizeof(std::complex<int16_t>) * nSamples_tx_pulse;
                        size_t number_of_pulses = pulse_time_offsets.size();
                        size_t num_samples_per_pulse_with_padding = nSamples_tx_pulse + 2*spb;
                        DEBUG_PRINT("spb %d, pulse length %d samples, pulse with padding %d\n", spb, nSamples_tx_pulse, num_samples_per_pulse_with_padding);


                        // read in time for start of pulse sequence over socket
                        uint32_t pulse_time_full = sock_get_uint32(driverconn);
                        double pulse_time_frac = sock_get_float64(driverconn);
                        start_time = uhd::time_spec_t(pulse_time_full, pulse_time_frac);
                        double tr_to_pulse_delay = sock_get_float64(driverconn);

                        
                        // calculate usrp clock time of the start of each pulse over the integration period
                        // so we can schedule the io (perhaps we will have to move io off of the usrp if it can't keep up)
                        for(uint32_t p_i = 0; p_i < number_of_pulses; p_i++) {
                            double offset_time = pulse_sample_idx_offsets[p_i] / txrate;
                            pulse_time_offsets[p_i] = offset_time_spec(start_time, offset_time);
                           // DEBUG_PRINT("TRIGGER_PULSE pulse time %d is %2.5f\n", p_i, pulse_time_offsets[p_i].get_real_secs());
                        }

                        DEBUG_PRINT("first TRIGGER_PULSE time is %2.5f and last is %2.5f\n", pulse_time_offsets[0].get_real_secs(), pulse_time_offsets.back().get_real_secs());

                        rx_start_time = offset_time_spec(start_time, tr_to_pulse_delay/1e6);
                        rx_start_time = offset_time_spec(rx_start_time, pulse_sample_idx_offsets[0]/txrate); 

                        // send_timing_for_sequence(usrp, start_time, pulse_times);
                        double pulseLength = nSamples_tx_pulse / txrate;
                        
                        // float debugt = usrp->get_time_now().get_real_secs();
                        // DEBUG_PRINT("USRP_DRIVER: spawning worker threads at usrp_time %2.4f\n", debugt);

                        DEBUG_PRINT("TRIGGER_PULSE creating rx and tx worker threads on swing %d (nSamples_rx= %d + %d pause + %d auto clear freq )\n", swing,(int) nSamples_rx, nSamples_pause_after_rx, nSamples_auto_clear_freq);
                        // works fine with tx_worker and dio_worker, fails if rx_worker is enabled
                        uhd_threads.create_thread(boost::bind(usrp_rx_worker, usrp, rx_stream, &rx_data_buffer, nSamples_rx_total, rx_start_time, &rx_worker_status));


			useconds_t usecs=1000;
                        if (tx_worker_active) { 
			  usleep(usecs);
			  uhd_threads.create_thread(boost::bind(usrp_tx_worker, tx_stream, &tx_samples, num_samples_per_pulse_with_padding, start_time, pulse_sample_idx_offsets)); 
                        }

			usleep(usecs);
                        uhd_threads.create_thread(boost::bind(send_timing_for_sequence, usrp, start_time,  pulse_time_offsets, pulseLength, mimic_active, mimic_delay, nSides)); 


                        sock_send_uint8(driverconn, TRIGGER_PULSE);

                        uhd_threads.join_all(); // wait for transmit threads to finish, drawn from shared memory..
                        DEBUG_PRINT("TRIGGER_PULSE rx_worker, tx_worker and dio threads on swing %d\n joined.", swing);


                    }


                    break;
                    }

                case READY_DATA: {
                    swing      = sock_get_int16(  driverconn); 
                    DEBUG_PRINT("READY_DATA command (swing %d), waiting for uhd threads to join back\n", swing);

                    
                    DEBUG_PRINT("READY_DATA unlocking swing a semaphore\n");
                    unlock_semaphore(sem_rx_vec[swing]);
                    unlock_semaphore(sem_tx_vec[swing]);
        
                    DEBUG_PRINT("READY_DATA usrp worker threads joined, semaphore unlocked, sending metadata\n");
                    // TODO: handle multiple channels of data.., use channel index to pick correct swath of memory to copy into shm
                  
                   // rx_worker_status =1; //DEBUG
                    
                    if(rx_worker_status){
                      fprintf(stderr, "Error in rx_worker. Setting state to %d.\n", rx_worker_status);
                      state_vec[swing] = rx_worker_status;
                      rx_worker_status = 0;
                      mute_output = 1;
                      rx_stream_error_count++;
                       
                      if (rx_stream_reset_count >= MAX_STREAM_RESETS) {
                          fprintf(stderr, "READY_DATA: shutting down usrp_driver to avoid streamer reset overflow (after %dth reset)\n", rx_stream_reset_count);
                          // send all data to server, clean up and exit after that
                          exit_driver = 1;
                      }

                      if((rx_worker_status != RX_WORKER_STREAM_TIME_ERROR) && (rx_stream_error_count > 4)) {
                          // recreate rx_stream unless the error was from sending the stream command too late
                          rx_stream_reset_count++;
                          fprintf(stderr, "READY_DATA: recreating rx_stream %dth time! (buffer overflow will occur for 126th time)\n", rx_stream_reset_count);
                          rx_stream.reset();
                          rx_stream = usrp->get_rx_stream(stream_args);
                      }
                      auto_clear_freq_available = 0;
                    }
                    else {
                      rx_stream_error_count = 0;
                      auto_clear_freq_available = 1;
                    }
    
                    DEBUG_PRINT("READY_DATA state: %d, ant: %d, num_samples: %zu\n", state_vec[swing], antennaVector[0], nSamples_rx);
                    sock_send_int32(driverconn, state_vec[swing]);  // send status
                    sock_send_int32(driverconn, antennaVector[0]);   // send antenna TODO do this for both antennas?
                    sock_send_int32(driverconn, nSamples_rx);     // nsamples;  send send number of samples
                   
                    // read FAULT status   
                    bool fault;
                    for (iSide =0; iSide<nSides; iSide++){  
                        fault = read_FAULT_status_from_control_board(usrp, iSide);
                    }
                    // TODO move this in loop as soon as usrp_server receives both sides
                    sock_send_bool(driverconn, fault);     // FAULT status from conrol board
                
  
                    if (mute_output) {
                       DEBUG_PRINT("READY_DATA: Filling SHM with zeros (because of rx_worker error) \n");

                       for (iSide = 0; iSide<nSides; iSide++) {
                          memset(shm_rx_vec[iSide][swing],  0, rxshm_size);
                          std::fill(rx_auto_clear_freq[iSide].begin(), rx_auto_clear_freq[iSide].end(), 0);
                       }
                       mute_output = 0;
                    }
                    else {
                        DEBUG_PRINT("READY_DATA starting copying rx data buffer to shared memory\n");
                        // regural rx data
                        for (iSide = 0; iSide<nSides; iSide++) {
                            // DEBUG_PRINT("usrp_drivercopy to rx shm addr: %p iSide: %d iSwing: %d\n", shm_rx_vec[iSide][swing], iSide, iSwing);
                            memcpy(shm_rx_vec[iSide][swing], &rx_data_buffer[iSide][0], sizeof(std::complex<int16_t>) * nSamples_rx);
                        }
                        // auto clear freq samples
                        for (iSide = 0; iSide<nSides; iSide++) {
                            for (int iSample = 0; iSample < nSamples_auto_clear_freq; iSample++) {
                                rx_auto_clear_freq[iSide][iSample] = rx_data_buffer[iSide][nSamples_rx+nSamples_pause_after_rx+ iSample];
                            }
                        }
                    }

                    if(SAVE_RAW_SAMPLES_DEBUG) {
                        FILE *raw_dump_fp;
                        char raw_dump_name[80];
                        for (iSide=0; iSide<nSides; iSide++) {
                           sprintf(raw_dump_name,"%s/raw_samples_rx_ant_%d.cint16", diag_dir, antennaVector[iSide]);
                           raw_dump_fp = fopen(raw_dump_name, "wb");
                           fwrite(&rx_data_buffer[iSide], sizeof(std::complex<int16_t>), nSamples_rx_total, raw_dump_fp);
                           fclose(raw_dump_fp);
                        }

                    }

                    DEBUG_PRINT("READY_DATA finished copying rx data buffer to shared memory\n");
                    state_vec[swing] = ST_READY; 
                    DEBUG_PRINT("changing state_vec[swing] to ST_READY\n");

                    DEBUG_PRINT("READY_DATA returning command success \n");
                    sock_send_uint8(driverconn, READY_DATA);
                    break;
                    }

                case UHD_GETTIME: {
                    DEBUG_PRINT("entering UHD_GETTIME command\n");
                    start_time = usrp->get_time_now();

                    uint32_t real_time = start_time.get_real_secs();
                    double frac_time = start_time.get_frac_secs();

                    sock_send_uint32(driverconn, real_time);
                    sock_send_float64(driverconn, frac_time);

                    DEBUG_PRINT("UHD_GETTIME current UHD time: %d %.2f command\n", real_time, frac_time);
                    sock_send_uint8(driverconn, UHD_GETTIME);
                    break;
                    }
                // command to reset time, sync time with external PPS pulse
                case UHD_SYNC: {
                    DEBUG_PRINT("entering UHD_SYNC command\n");
                    // if --intclk flag passed to usrp_driver, set clock source as internal and do not sync time
                    if(al_intclk->count > 0) {
                        usrp->set_time_now(uhd::time_spec_t(0.0));
                    }

                    else {

                 /*       const uhd::time_spec_t last_pps_time = usrp->get_time_last_pps();
                        while (last_pps_time == usrp->get_time_last_pps()) {
                            boost::this_thread::sleep(boost::posix_time::milliseconds(100));
                        }
                        usrp->set_time_next_pps(uhd::time_spec_t(0.0));
                        boost::this_thread::sleep(boost::posix_time::milliseconds(1100));
                 */
                        DEBUG_PRINT("Start setting unknown pps\n");
                        usrp->set_time_unknown_pps(uhd::time_spec_t(11.0));
                        DEBUG_PRINT("end setting unknown pps\n");
                     }

                    sock_send_uint8(driverconn, UHD_SYNC);
                    break;
                    }

                case AUTOCLRFREQ: {
                    // has to be called after GET_DATA and before USRP_SETUP
                    DEBUG_PRINT("entering getting auto clear freq command\n");
//                    uint32_t num_clrfreq_samples = sock_get_uint32(driverconn);

                    iSide = 0;// TODO both sides!
                    if (auto_clear_freq_available) {
                        DEBUG_PRINT("AUTOCLRFREQ samples sending %d samples for antenna %d...\n", rx_auto_clear_freq[iSide].size(),antennaVector[iSide]);
                        sock_send_int32(driverconn, (int32_t) antennaVector[iSide]); 
                        sock_send_uint32(driverconn, (uint32_t) rx_auto_clear_freq[iSide].size());

                        // send samples                   
                        send(driverconn, &rx_auto_clear_freq[iSide][0], sizeof(std::complex<short int>) * rx_auto_clear_freq[iSide].size() , 0);
                    }
                    else {
                        sock_send_int32(driverconn, (int32_t) -1); 
                        
                    }

                    sock_send_uint8(driverconn, AUTOCLRFREQ);

                    break;

                    }
                case CLRFREQ: {
                    DEBUG_PRINT("entering CLRFREQ command\n");
                    uint32_t num_clrfreq_samples = sock_get_uint32(driverconn);
                    uint32_t clrfreq_time_full   = sock_get_uint32(driverconn);
                    double clrfreq_time_frac     = sock_get_float64(driverconn);
                    double clrfreq_cfreq         = sock_get_float64(driverconn);
                    double clrfreq_rate          = sock_get_float64(driverconn);

                    std::vector<std::vector<std::complex<int16_t>>> clrfreq_data_buffer(nSides, std::vector<std::complex<int16_t>>(num_clrfreq_samples));

                    uint32_t real_time; 
                    double frac_time;

                    DEBUG_PRINT("CLRFREQ time: %d . %.2f \n", clrfreq_time_full, clrfreq_time_frac);
                    DEBUG_PRINT("CLRFREQ rate: %.2f, CLRFREQ_nsamples %d, freq: %.2f\n", clrfreq_rate, num_clrfreq_samples, clrfreq_cfreq);
                    uhd::time_spec_t clrfreq_start_time = uhd::time_spec_t(clrfreq_time_full, clrfreq_time_frac);
                    real_time = clrfreq_start_time.get_real_secs();
                    frac_time = clrfreq_start_time.get_frac_secs();
                    DEBUG_PRINT("CLRFREQ UHD clrfreq target time: %d %.2f \n", real_time, frac_time);


                    // TODO: only set rate if it is different!
                    if(rxrate != clrfreq_rate) {
                       usrp->set_rx_rate(clrfreq_rate);
                       rxrate = usrp->get_rx_rate();
                       clrfreq_rate = rxrate;
                    }
                    DEBUG_PRINT("CLRFREQ actual rate: %.2f\n", clrfreq_rate);
                    //clrfreq_cfreq = usrp->get_rx_freq(); 
                    //DEBUG_PRINT("CLRFREQ actual freq: %.2f\n", clrfreq_cfreq);
                    clrfreq_threads.create_thread(boost::bind(usrp_rx_worker, usrp, rx_stream, &clrfreq_data_buffer, num_clrfreq_samples, clrfreq_start_time, &clrfreq_rx_worker_status));

                    clrfreq_threads.join_all();

                    if(clrfreq_rx_worker_status){
                        fprintf(stderr, "Error in clrfreq_rx_worker, resetting rx_stream: %d.\n", clrfreq_rx_worker_status);
                        rx_stream_reset_count++;
                        fprintf(stderr, "CLRFREQ: recreating rx_stream %dth time! (buffer overflow will occur for 126th time)\n", rx_stream_reset_count);
                        rx_stream.reset();
                        rx_stream = usrp->get_rx_stream(stream_args);
                    }

                    if (rx_stream_reset_count >= MAX_STREAM_RESETS) {
                        fprintf(stderr, "CLRFREQ: shutting down usrp_driver to avoid streamer reset overflow (after %dth reset)\n", rx_stream_reset_count);
                        // finish clrfreq command, then clean up and exit to avoid buffer overflow
                        exit_driver = 1;
                    }



                    DEBUG_PRINT("CLRFREQ received samples, relaying %d samples back...\n", num_clrfreq_samples);
                    sock_send_int32(driverconn, (int32_t) antennaVector[0]); // TODO both sides?
                    sock_send_float64(driverconn, clrfreq_rate);

                    // send back samples                   
                    send(driverconn, &clrfreq_data_buffer[0][0], sizeof(std::complex<short int>) * num_clrfreq_samples, 0);

                    //for(uint32_t i = 0; i < num_clrfreq_samples; i++) {
                        //DEBUG_PRINT("sending %d - %d\n", i, clrfreq_data_buffer[0][i]);
                    //    sock_send_cshort(driverconn, clrfreq_data_buffer[0][i]);
                   // }

                    DEBUG_PRINT("CLRFREQ samples sent for antenna %d...\n", antennaVector[0]);
                    // restore usrp rates
                    usrp->set_rx_rate(rxrate);
                    usrp->set_rx_freq(rxfreq);

                    sock_send_uint8(driverconn, CLRFREQ);
                    start_time = usrp->get_time_now();
                    real_time = start_time.get_real_secs();
                    frac_time = start_time.get_frac_secs();
                    DEBUG_PRINT("CLRFREQ finished at UHD time: %d %.2f \n", real_time, frac_time);

                    break;

                    }

                case EXIT: {
                    DEBUG_PRINT("entering EXIT command\n");

                    exit_driver = 1;
                    break;
                    }

                default: {
                    printf("USRP_DRIVER unrecognized command: %d, %c, exiting..\n", command, command);
                    sleep(10);
                    exit(1);
                    break;
                }
            }
            if (not check_clock_lock(usrp)) {
                fprintf(stderr,  "Error: Lost clock for USRP: %s\n ", as_host->sval[0]);
                exit_driver = 1; 
            }

            // clean exit
            if (exit_driver) {
                DEBUG_PRINT("Shutting down driver\n");
                close(driverconn);

                for(iSide = 0; iSide < nSides; iSide++) {
                    for(iSwing = 0; iSwing < nSwings; iSwing++) {
                        // fill SHM with zeros
                        memset(shm_rx_vec[iSide][iSwing], 0, rxshm_size);
                        memset(shm_tx_vec[iSide][iSwing], 0, txshm_size);

                        munmap(shm_rx_vec[iSide][iSwing], rxshm_size);
                        munmap(shm_tx_vec[iSide][iSwing], txshm_size);
                        sem_close(&sem_rx_vec[iSwing]);
                        sem_close(&sem_tx_vec[iSwing]);
                    }
                }
            
            // TODO: close usrp streams?
//            sock_send_uint8(driverconn, EXIT);
            exit(1);
          }

        }
    }
    
    return 0;
}
示例#15
0
int main(int argc, char* argv[])
{
    struct arg_lit *help;
    struct arg_file *input, *output;
    struct arg_str *rotation;
    struct arg_end *end;

    /* command line parsing through argtable package */
    void* argtable[] = {
        help        = arg_lit0("h", "help", "display this help and exit"),
        input       = arg_file0("i", "input", "input", "name of the input file (default stdin"),
        output      = arg_file0("o", "output", "file", "name of the output file (default stdout)"),
        rotation    = arg_str1(NULL, NULL, "\"x y z w\"", "rotate w degrees around axis x y z"),
        end         = arg_end(20) };
    const char* progname = "xyztk-rotate";
    int rc = 0;
    int nerrors;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n", progname);
        rc=1;
        goto exit;
        }

    /* set default values */

    /* parse the command line flags, overriding default values */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
        {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout,argtable,"\n");
        printf("\n");
        arg_print_glossary(stdout,argtable,"  %-40s %s\n");
        printf("\n");
        rc=0;
        goto exit;
        }

    /* special case: no command line options induces brief help */
    if (argc==1) {
        printf("Try '%s --help' for more information.\n",progname);
        rc=0;
        goto exit;
    }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
        {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,progname);
        printf("Try '%s --help' for more information.\n",progname);
        rc=1;
        goto exit;
        }

    /* set global structures */

    /* initialize I/O pointers */
    FILE* in;
    if (input->count) {
      in = fopen(input->filename[0], "r");
    } else {
      in = stdin;
    }

    FILE* out;
    if (output->count) {
      out = fopen(output->filename[0], "w");
    } else {
      out = stdout;
    }

    /* initialize molecule structure */
    xyztk_molecule_t molecule;
    xyztk_molecule_load (&molecule, in);

    /* read rotation from string */
    xyztk_quat_t r;
    sscanf (rotation->sval[0], "%lf%lf%lf%lf", &r.x, &r.y, &r.z, &r.w);
    xyztk_molecule_rotate (&molecule, &r);

    /* print output */
    int i;
    fprintf(out, "%d\n", molecule.n_atoms);
    fprintf(out, "%s", molecule.name);
    for (i = 0; i < molecule.n_atoms; ++i)
      {
      fprintf(out, "%-8s %20.14lf %20.14lf %20.14lf \n",
	      molecule.label[i].s, molecule.coord[i].x, molecule.coord[i].y, molecule.coord[i].z);
      }

exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return rc;
}
示例#16
0
文件: client.c 项目: chiefdome/telex
int main(int argc, char *argv[])
{	
	struct arg_int *lport = arg_int0("p", "port", "<localport>",  "listening port (default is 8888)");
	struct arg_int *debug = arg_int0("d", "debug",  "<level>", "debug output level (default is 4)");	
#ifdef PUBKEY_DATA_
	struct arg_str *key   = arg_str0("k", "key",    "<keyfile>", "public key file (default is built-in)");
#else
	struct arg_str *key   = arg_str0("k", "key",    "<keyfile>", "public key file (default is pubkey)");
#endif
#ifdef ROOTPEM_DATA_
	struct arg_str *certdb= arg_str0(NULL, "certdb",    "<certfile>", "trusted CA database (default is built-in)");
#else
	struct arg_str *certdb= arg_str0(NULL, "certdb",    "<certfile>", "trusted CA database (default is root.pem)");
#endif
	struct arg_lit *help  = arg_lit0(NULL,"help",              "print this help and exit");
	struct arg_str *host  = arg_str1(NULL, NULL,    "<host>[:port]",  "non-blocked TLS server");
	struct arg_end *end   = arg_end(20);
	void *argtable[] = {lport, debug, key, certdb, help, host, end};
	const char* progname = "telex-client";
    int nerrors;
    int ret=0;
    assert(!arg_nullcheck(argtable));

	// defaults:
	lport->ival[0] = 8888;
	debug->ival[0] = 3;
#ifdef PUBKEY_DATA_
	key->sval[0] = NULL;
#else
	key->sval[0] = "pubkey";
#endif
#ifdef ROOTPEM_DATA_
	certdb->sval[0] = NULL;
#else
	certdb->sval[0] = "root.pem";
#endif

	nerrors = arg_parse(argc,argv,argtable);
    if (help->count > 0) {
		printf("Usage: %s", progname);
        arg_print_syntax(stdout,argtable,"\n");
        printf("\nEstablishes covert, encrypted tunnels, disguised as connections to <host>.\n\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        printf("\n");		
		ret = 0;
	} else if (nerrors > 0) {
		arg_print_errors(stdout,end,progname);
		printf("Try '%s --help' for more information.\n", progname);
		ret = 1;
	} else if (argc == 1) {
        printf("Try '%s --help' for more information.\n", progname);
        ret = 0;
	} else {		

      int port = 443;
      char hstr[255];
      assert(host->sval[0]);
      strncpy(hstr, host->sval[0], sizeof(hstr)-1);

      char *pstr=0;
      strtok(hstr, ":");
      pstr = strtok(NULL, ":");
      if (pstr) {
	port = strtol(pstr, NULL, 10);
	if (port < 1 || port > 65535) {
	  fprintf(stderr, "Invalid remote port: %d", port);
	  return 1;
	}
      }

		printf("WARNING: This software is an experimental prototype intended for\n");
        printf("         researchers. It does not provide strong security and is\n");
        printf("         UNSAFE FOR REAL-WORLD USE. For details of current limitations\n");
        printf("         of our proof-of-concept, please see telex-client/ISSUES.\n");

      ret = telex_client(lport->ival[0], port, debug->ival[0], hstr, key->sval[0], certdb->sval[0]);
    }
    arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0]));
    return ret;
}
示例#17
0
文件: myprog.c 项目: btbytes/examples
int main(int argc, char **argv)
    {
    struct arg_lit  *list    = arg_lit0("lL",NULL,                      "list files");
    struct arg_lit  *recurse = arg_lit0("R",NULL,                       "recurse through subdirectories");
    struct arg_int  *repeat  = arg_int0("k","scalar",NULL,              "define scalar value k (default is 3)");
    struct arg_str  *defines = arg_strn("D","define","MACRO",0,argc+2,  "macro definitions");
    struct arg_file *outfile = arg_file0("o",NULL,"<output>",           "output file (default is \"-\")");
    struct arg_lit  *verbose = arg_lit0("v","verbose,debug",            "verbose messages");
    struct arg_lit  *help    = arg_lit0(NULL,"help",                    "print this help and exit");
    struct arg_lit  *version = arg_lit0(NULL,"version",                 "print version information and exit");
    struct arg_file *infiles = arg_filen(NULL,NULL,NULL,1,argc+2,       "input file(s)");
    struct arg_end  *end     = arg_end(20);
    void* argtable[] = {list,recurse,repeat,defines,outfile,verbose,help,version,infiles,end};
    const char* progname = "myprog";
    int nerrors;
    int exitcode=0;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",progname);
        exitcode=1;
        goto exit;
        }

    /* set any command line default values prior to parsing */
    repeat->ival[0]=3;
    outfile->filename[0]="-";

    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
        {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout,argtable,"\n");
        printf("This program demonstrates the use of the argtable2 library\n");
        printf("for parsing command line arguments.\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        exitcode=0;
        goto exit;
        }

    /* special case: '--version' takes precedence error reporting */
    if (version->count > 0)
        {
        printf("'%s' example program for the \"argtable\" command line argument parser.\n",progname);
        printf("September 2003, Stewart Heitmann\n");
        exitcode=0;
        goto exit;
        }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
        {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,progname);
        printf("Try '%s --help' for more information.\n",progname);
        exitcode=1;
        goto exit;
        }

    /* special case: uname with no command line options induces brief help */
    if (argc==1)
        {
        printf("Try '%s --help' for more information.\n",progname);
        exitcode=0;
        goto exit;
        }

    /* normal case: take the command line options at face value */
    exitcode = mymain(list->count, recurse->count, repeat->ival[0],
                      defines->sval, defines->count,
                      outfile->filename[0], verbose->count,
                      infiles->filename, infiles->count);

    exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return exitcode;
    }
示例#18
0
int main(int argc, char **argv)
    {
    struct arg_dbl *a    = arg_dbl1(NULL,NULL,"a","a is <double>");
    struct arg_dbl *b    = arg_dbl0(NULL,NULL,"b","b is <double>");
    struct arg_dbl *c    = arg_dbl0(NULL,NULL,"c","c is <double>");
    struct arg_dbl *d    = arg_dbln("dD","delta","<double>",0,3,"d can occur 0..3 times");
    struct arg_dbl *e    = arg_dbl0(NULL,"eps,eqn","<double>","eps is optional");
    struct arg_lit *help = arg_lit0(NULL,"help","print this help and exit");
    struct arg_end *end  = arg_end(20);
    void* argtable[] = {a,b,c,d,e,help,end};
    int nerrors;
    int exitcode=0;
    int i;
    double sum=0;
    
    /*
    printf("a=%p\n",a);
    printf("b=%p\n",b);
    printf("c=%p\n",c);
    printf("d=%p\n",d);
    printf("e=%p\n",e);
    printf("help=%p\n",help);
    printf("end=%p\n",end);
    printf("argtable=%p\n",argtable);
    */
    
    /* print the command line */
    for (i=0; i<argc; i++)
        printf("%s ",argv[i]);
    printf("\n");
    
    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",argv[0]);
        exitcode=1;
        goto exit;
        }
    
    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
        {
        printf("Usage: %s ", argv[0]);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        exitcode=0;
        goto exit;
        }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
        {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,argv[0]);
        exitcode=1;
        goto exit;
        }

    /* parsing complete, verify all args sum to zero */
    for (i=0; i<a->count; i++)
        {
        printf("a[%d]=%f\n",i,a->dval[i]);
        sum += a->dval[i];
        }
    for (i=0; i<b->count; i++)
        {
        printf("b[%d]=%f\n",i,b->dval[i]);
        sum += b->dval[i];
        }
    for (i=0; i<c->count; i++)
        {
        printf("c[%d]=%f\n",i,c->dval[i]);
        sum += c->dval[i];
        }
    for (i=0; i<d->count; i++)
        {
        printf("d[%d]=%f\n",i,d->dval[i]);
        sum += d->dval[i];
        }
    for (i=0; i<e->count; i++)
        {
        printf("e[%d]=%f\n",i,e->dval[i]);
        sum += e->dval[i];
        }
    printf("sum=%f\n",sum);
    if (sum<-1.0e-6 || sum>1.0e-6)
        {
        printf("%s: error - sum=%f is non-zero\n",argv[0],sum);
        exitcode=1;
        goto exit;
        }
        
    exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));
    
    printf("%s: exitcode=%d\n\n",argv[0],exitcode);

    /* close stdin and stdout to stop memcheck whining about their memory not being freed */
    fclose(stdin);
    fclose(stdout);
   
    return exitcode;
    }
示例#19
0
int _tmain(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int 
main(int argc, const char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file

int Rslt;
bool bSkipFirst;			// true if first line contains header and should be skipped
int iMinLength;				// core elements must be of at least this length
int iMaxLength;				// and no longer than this length
char szInLociFile[_MAX_PATH];	// input element loci from this file
char szInSeqFile[_MAX_PATH];	// input bioseq file containing assembly
char szRsltsFile[_MAX_PATH];	// output stats to this file


// command line args
struct arg_lit  *help    = arg_lit0("hH","help",                "print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_int *ScreenLogLevel=arg_int0("S", "ScreenLogLevel",	"<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"diagnostics log file");

struct arg_file *InLociFile = arg_file1("i","inloci","<file>",	"element loci CSV file");
struct arg_file *InSeqFile = arg_file1("I","assembly","<file>",	"genome assembly bioseq file");
struct arg_file *RsltsFile = arg_file1("o","output","<file>",	"output file");
struct arg_lit  *SkipFirst    = arg_lit0("x","skipfirst",       "skip first line of CSV - header line");
struct arg_int  *MinLength = arg_int0("l","minlength","<int>",	"minimum element length (default 10)");
struct arg_int  *MaxLength = arg_int0("L","maxlength","<int>",	"maximum element length (default 1000000000)");
struct arg_end *end = arg_end(20);

void *argtable[] = {help,version,FileLogLevel,ScreenLogLevel,LogFile,
					InLociFile,InSeqFile,RsltsFile,SkipFirst,MinLength,MaxLength,
					end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

    /* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s csv2stats, Version %s\nOptions ---\n", gszProcName,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s @myparams.txt\n\n",gszProcName);
		exit(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s Version %s\n",gszProcName,cpszProgVer);
		exit(1);
        }

if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>'",FileLogLevel->ival[0]);
		exit(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d",iFileLogLevel,eDLNone,eDLDebug);
		exit(1);
		}
	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}

	bSkipFirst = SkipFirst->count ? true : false;

	iMinLength = MinLength->count ? MinLength->ival[0] : cDfltMinLengthRange;
	if(iMinLength < 1 || iMinLength > cMaxLengthRange)
		{
		printf("Error: Mininum element length '-l%d' is not in range 1..%d",iMinLength,cMaxLengthRange);
		exit(1);
		}

	iMaxLength = MaxLength->count ? MaxLength->ival[0] : cMaxLengthRange;
	if(iMaxLength < iMinLength || iMaxLength > cMaxLengthRange)
		{
		printf("Error: Maximum element length '-L%d' is not in range %d..%d",iMaxLength,iMinLength,cMaxLengthRange);
		exit(1);
		}

	strncpy(szInLociFile,InLociFile->filename[0],_MAX_PATH);
	szInLociFile[_MAX_PATH-1] = '\0';
	strncpy(szInSeqFile,InSeqFile->filename[0],_MAX_PATH);
	szInSeqFile[_MAX_PATH-1] = '\0';
	strncpy(szRsltsFile,RsltsFile->filename[0],_MAX_PATH);
	szRsltsFile[_MAX_PATH-1] = '\0';

		// now that command parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem.");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created",szLogFile);
		exit(1);
		}
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %s Processing parameters:",cpszProgVer);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input CSV element loci file: '%s'",szInLociFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input bioseq genome assembly file: '%s'",szInSeqFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output to file: '%s'",szRsltsFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"First line contains header: %s",bSkipFirst ? "yes" : "no");
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum element length: %d",iMinLength);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Maximum element length: %d",iMaxLength);

#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	// processing here...
	Rslt = Process(bSkipFirst,iMinLength,iMaxLength,szInLociFile,szInSeqFile,szRsltsFile);

	gStopWatch.Stop();
	Rslt = Rslt >=0 ? 0 : 1;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	exit(Rslt);
	}
else
	{
	printf("\n%s csv2stats, Version %s\n",gszProcName,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	exit(1);
	}
}
示例#20
0
文件: main.c 项目: omf2097/openomf
int main(int argc, char *argv[]) {
    SDL_AudioSpec want, have;
    SDL_AudioDeviceID dev;
    Streamer streamer;
    int retcode = 0;

    // Init SDL Audio
    if(SDL_Init(SDL_INIT_AUDIO) != 0) {
        fprintf(stderr, "Error: %s\n", SDL_GetError());
        return 1;
    }

    // commandline argument parser options
    struct arg_lit *help = arg_lit0("h", "help", "print this help and exit");
    struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit");
    struct arg_file *file = arg_file1("f", "file", "<file>", "SOUNDS.DAT file");
    struct arg_file *output = arg_file0("o", "output", "<file>", "Output sounds file");
    struct arg_int *sid = arg_int0("s", "sound", "<int>", "Sound ID");
    struct arg_int *sampleprint = arg_int0(NULL, "print", "<int>", "Print first n bytes from selected sound");
    struct arg_lit *play = arg_lit0("p", "play", "Play selected sound");
    struct arg_file *export = arg_file0("e", "export", "<file>", "Export selected sound to AU file");
    struct arg_file *import = arg_file0("i", "import", "<file>", "Import selected sound from AU file");
    struct arg_end *end = arg_end(20);
    void* argtable[] = {help,vers,file,output,sid,sampleprint,play,export,import,end};
    const char* progname = "soundtool";

    // Make sure everything got allocated
    if(arg_nullcheck(argtable) != 0) {
        printf("%s: insufficient memory\n", progname);
        goto exit_0;
    }

    // Parse arguments
    int nerrors = arg_parse(argc, argv, argtable);

    // Handle help
    if(help->count > 0) {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("\nArguments:\n");
        arg_print_glossary(stdout, argtable, "%-25s %s\n");
        goto exit_0;
    }

    // Handle version
    if(vers->count > 0) {
        printf("%s v0.1\n", progname);
        printf("Command line One Must Fall 2097 SOUNDS.DAT file editor.\n");
        printf("Source code is available at https://github.com/omf2097 under MIT license.\n");
        printf("(C) 2013 Tuomas Virtanen\n");
        goto exit_0;
    }

    // Handle errors
    if(nerrors > 0) {
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        goto exit_0;
    }

    // Open sounds.dat
    sd_sound_file sf;
    sd_sounds_create(&sf);
    retcode = sd_sounds_load(&sf, file->filename[0]);
    if(retcode) {
        printf("Error %d: %s\n", retcode, sd_get_error(retcode));
        goto exit_1;
    }

    if(sid->count > 0) {
        // Sound ID to handle
        int sound_id = sid->ival[0];
        const sd_sound *sound = sd_sounds_get(&sf, sound_id-1);
        if(sound == NULL) {
            printf("Invalid sound ID");
            goto exit_1;
        }

        if(sampleprint->count > 0) {
            int count = (sampleprint->ival[0] > sound->len) ? sound->len : sampleprint->ival[0];
            printf("Sample size = %d\n", sound->len);
            printf("Unknown = %d\n", sound->unknown);
            printf("Attempting to print %d first bytes.\n", count);
            for(int i = 0; i < count; i++) {
                unsigned int s = sound->data[i] & 0xFF;
                printf("%2x ", s);
            }
        } else if(play->count > 0) {
            printf("Attempting to play sample #%d.\n", sound_id);

            // Make sure there is data at requested ID position
            if(sound->len <= 0) {
                printf("Sample does not contain data.\n");
                goto exit_1;
            }

            // Streamer
            streamer.size = sound->len;
            streamer.pos = 0;
            streamer.data = sound->data;

            // Initialize required audio
            SDL_zero(want);
            want.freq = 8000;
            want.format = AUDIO_U8;
            want.channels = 1;
            want.samples = 4096;
            want.callback = stream;
            want.userdata = &streamer;

            // Open device, play file
            dev = SDL_OpenAudioDevice(NULL, 0, &want, &have, 0);
            if(dev == 0) {
                printf("Failed to open audio dev: %s\n", SDL_GetError());
                goto exit_0;
            } else {
                if(have.format != want.format) {
                    printf("Could not get correct playback format.\n");
                } else {
                    printf("Starting playback ...\n");
                    SDL_PauseAudioDevice(dev, 0);
                    while(streamer.pos < streamer.size) {
                        SDL_Delay(100);
                    }
                    printf("All done.\n");
                }
                SDL_CloseAudioDevice(dev);
            }
        } else if(import->count > 0) {
            if(sd_sound_from_au(&sf, sound_id, import->filename[0]) != SD_SUCCESS) {
                printf("Importing sample %d from file %s failed.\n", sound_id, import->filename[0]);
            } else {
                printf("Importing sample %d from file %s succeeded.\n", sound_id, import->filename[0]);
            }
        } else if(export->count > 0) {
            if(sd_sound_to_au(&sf, sound_id, export->filename[0]) != SD_SUCCESS) {
                printf("Exporting sample %d to file %s failed.\n", sound_id, export->filename[0]);
            } else {
                printf("Exporting sample %d to file %s succeeded.\n", sound_id, export->filename[0]);
            }
        } else {
示例#21
0
int main(int argc, char **argv)
    {
    /* SYNTAX 1: insert [-nvR] <file> [file]...  -o <file> */
    struct arg_rex  *cmd1     = arg_rex1(NULL,  NULL,  "insert", NULL, REG_ICASE, NULL);
    struct arg_lit  *noact1   = arg_lit0("n",   NULL,  "take no action");
    struct arg_lit  *verbose1 = arg_lit0("v", "verbose", "verbose messages");
    struct arg_lit  *recurse1 = arg_lit0("R",   NULL,  "recurse through subdirectories");
    struct arg_file *infiles1 = arg_filen(NULL, NULL,  NULL, 1,argc+2, "input file(s)");
    struct arg_file *outfile1 = arg_file0("o",  NULL,  "<output>", "output file (default is \"-\")");
    struct arg_end  *end1     = arg_end(20);
    void* argtable1[] = {cmd1,noact1,verbose1,recurse1,infiles1,outfile1,end1};
    int nerrors1;

    /* SYNTAX 2: remove [-nv] <file> */
    struct arg_rex  *cmd2     = arg_rex1(NULL, NULL, "remove", NULL, REG_ICASE, NULL);
    struct arg_lit  *noact2   = arg_lit0("n",  NULL, NULL);
    struct arg_lit  *verbose2 = arg_lit0("v",  "verbose", NULL);
    struct arg_file *infiles2 = arg_file1(NULL, NULL, NULL, NULL);
    struct arg_end  *end2     = arg_end(20);
    void* argtable2[] = {cmd2,noact2,verbose2,infiles2,end2};
    int nerrors2;

    /* SYNTAX 3: search [-v] <pattern> [-o <file>] [--help] [--version] */
    struct arg_rex  *cmd3     = arg_rex1(NULL, NULL, "search", NULL, REG_ICASE, NULL);
    struct arg_lit  *verbose3 = arg_lit0("v",  "verbose", NULL);
    struct arg_str  *pattern3 = arg_str1(NULL, NULL, "<pattern>", "search string");
    struct arg_file *outfile3 = arg_file0("o", NULL, "<output>", NULL);
    struct arg_end  *end3     = arg_end(20);
    void* argtable3[] = {cmd3,verbose3,pattern3,outfile3,end3};
    int nerrors3;

    /* SYNTAX 4: [-help] [-version] */
    struct arg_lit  *help4    = arg_lit0(NULL,"help",     "print this help and exit");
    struct arg_lit  *version4 = arg_lit0(NULL,"version",  "print version information and exit");
    struct arg_end  *end4     = arg_end(20);
    void* argtable4[] = {help4,version4,end4};
    int nerrors4;

    const char* progname = "multisyntax";
    int exitcode=0;

    /* verify all argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable1)!=0 ||
        arg_nullcheck(argtable2)!=0 ||
        arg_nullcheck(argtable3)!=0 ||
        arg_nullcheck(argtable4)!=0 )
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",progname);
        exitcode=1;
        goto exit;
        }

    /* set any command line default values prior to parsing */
    outfile1->filename[0]="-";
    outfile3->filename[0]="-";

    /* Above we defined a separate argtable for each possible command line syntax */
    /* and here we parse each one in turn to see if any of them are successful    */
    nerrors1 = arg_parse(argc,argv,argtable1);
    nerrors2 = arg_parse(argc,argv,argtable2);
    nerrors3 = arg_parse(argc,argv,argtable3);
    nerrors4 = arg_parse(argc,argv,argtable4);

    /* Execute the appropriate main<n> routine for the matching command line syntax */
    /* In this example program our alternate command line syntaxes are mutually     */
    /* exclusive, so we know in advance that only one of them can be successful.    */
    if (nerrors1==0)
        exitcode = mymain1(noact1->count, verbose1->count, recurse1->count,
                           outfile1->filename[0], infiles1->filename, infiles1->count);
    else if (nerrors2==0)
        exitcode = mymain2(noact2->count, verbose2->count, infiles2->filename[0]);
    else if (nerrors3==0)
        exitcode = mymain3(verbose3->count, pattern3->sval[0], outfile3->filename[0]);
    else if (nerrors4==0)
        exitcode = mymain4(help4->count, version4->count, progname,
                           argtable1, argtable2, argtable3, argtable4);
    else
        {
        /* We get here if the command line matched none of the possible syntaxes */
        if (cmd1->count > 0)
            {
            /* here the cmd1 argument was correct, so presume syntax 1 was intended target */ 
            arg_print_errors(stdout,end1,progname);
            printf("usage: %s ", progname);
            arg_print_syntax(stdout,argtable1,"\n");
            }
        else if (cmd2->count > 0)
            {
            /* here the cmd2 argument was correct, so presume syntax 2 was intended target */ 
            arg_print_errors(stdout,end2,progname);
            printf("usage: %s ", progname);
            arg_print_syntax(stdout,argtable2,"\n");
            }
        else if (cmd3->count > 0)
            {
            /* here the cmd3 argument was correct, so presume syntax 3 was intended target */ 
            arg_print_errors(stdout,end3,progname);
            printf("usage: %s ", progname);
            arg_print_syntax(stdout,argtable3,"\n");
            }
        else
            {
            /* no correct cmd literals were given, so we cant presume which syntax was intended */
            printf("%s: missing <insert|remove|search> command.\n",progname); 
            printf("usage 1: %s ", progname);  arg_print_syntax(stdout,argtable1,"\n");
            printf("usage 2: %s ", progname);  arg_print_syntax(stdout,argtable2,"\n");
            printf("usage 3: %s ", progname);  arg_print_syntax(stdout,argtable3,"\n");
            printf("usage 4: %s",  progname);  arg_print_syntax(stdout,argtable4,"\n");
            }
        }

exit:
    /* deallocate each non-null entry in each argtable */
    arg_freetable(argtable1,sizeof(argtable1)/sizeof(argtable1[0]));
    arg_freetable(argtable2,sizeof(argtable2)/sizeof(argtable2[0]));
    arg_freetable(argtable3,sizeof(argtable3)/sizeof(argtable3[0]));
    arg_freetable(argtable4,sizeof(argtable4)/sizeof(argtable4[0]));

    return exitcode;
    }
示例#22
0
int genkmarkers(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int
genkmarkers(int argc, char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file
int Rslt = 0;   			// function result code >= 0 represents success, < 0 on failure

int NumberOfProcessors;		// number of installed CPUs
int NumThreads;				// number of threads (0 defaults to number of CPUs)

int PMode;					// processing mode
int KMerLen;				// this length K-mers
int PrefixLen;				// inter-cultivar shared prefix length
int SuffixLen;				// cultivar specific suffix length
int MinWithPrefix;			// minimum number of cultivars required to have the shared prefix
int MinHamming;				// must be at least this Hamming away from any other K-mer in other species
char szCultivarName[cMaxDatasetSpeciesChrom+1];		// cultivar name
char szPartialCultivarsList[(cMaxDatasetSpeciesChrom + 10) * cMaxTargCultivarChroms];		// individual species parsed from this comma/tab/space separated list
int NumPartialCultivars;	// there are this many pseudo chromosomes for targeted cultivar for which K-mer markers are required
char *pszPartialCultivars[cMaxTargCultivarChroms+1];	// pseudo chromosome names which identify targeted cultivar
char szSfxPseudoGenome[_MAX_PATH];		// contains assembly + suffix array over all psuedo-chromosomes for all cultivars
char szMarkerFile[_MAX_PATH];			// output potential markers to this file
char szMarkerReadsFile[_MAX_PATH];		// output reads containing potential markers to this file


char szSQLiteDatabase[_MAX_PATH];	// results summaries to this SQLite file
char szExperimentName[cMaxDatasetSpeciesChrom+1];			// experiment name
char szExperimentDescr[1000];		// describes experiment

// command line args
struct arg_lit  *help    = arg_lit0("h","help",                 "Print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"Print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to screen and logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"Diagnostics log file");

struct arg_int *pmode = arg_int0("m","mode","<int>",			"Processing mode : 0 - default with K-mer extension, 1 - no K-mer extension, 2 - inter-cultivar shared prefix sequences ");
struct arg_int *kmerlen = arg_int0("k","kmer","<int>",			"Cultivar specific K-mers of this length (default 50, range 25..100)");

struct arg_int *prefixlen = arg_int0("p","prefixlen","<int>",	"Cultivar specific K-mers to contain inter-cultivar shared prefix sequences of this length (Mode 2 only");
struct arg_int *minwithprefix = arg_int0("s","minshared","<int>","Inter-cultivar shared prefix sequences must be present in this many cultivars (Mode 2 only, default all)");

struct arg_int *minhamming = arg_int0("K","minhamming","<int>", "Minimum Hamming separation distance in other non-target cultivars (default 2, range 1..5)");
struct arg_str *cultivar = arg_str1("c","cultivar","<str>",		"Cultivar name to associate with identified marker K-mers");
struct arg_str *chromnames = arg_str1("C","chromnames","<str>",	"Comma/space separated list of pseudo-chrom names specific to cultivar for which markers are required");
struct arg_file *infile = arg_file1("i","in","<file>",		    "Use this suffix indexed pseudo-chromosomes file");
struct arg_file *outfile = arg_file1("o","markers","<file>",		"Output accepted marker K-mer sequences to this multifasta file");
struct arg_file *outreadsfile = arg_file0("O","markerreads","<file>",	"Output reads containing accepted marker K-mers to this multifasta file");
struct arg_int *numthreads = arg_int0("T","threads","<int>",		"number of processing threads 0..128 (defaults to 0 which sets threads to number of CPU cores)");

struct arg_file *summrslts = arg_file0("q","sumrslts","<file>",		"Output results summary to this SQLite3 database file");
struct arg_str *experimentname = arg_str0("w","experimentname","<str>",		"experiment name SQLite3 database file");
struct arg_str *experimentdescr = arg_str0("W","experimentdescr","<str>",	"experiment description SQLite3 database file");
struct arg_end *end = arg_end(200);

void *argtable[] = {help,version,FileLogLevel,LogFile,
					summrslts,experimentname,experimentdescr,
	                pmode,kmerlen,prefixlen,minwithprefix,minhamming,cultivar,chromnames,infile,outfile,outreadsfile,
					numthreads,
					end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

/* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s %s %s, Version %s\nOptions ---\n", gszProcName,gpszSubProcess->pszName,gpszSubProcess->pszFullDescr,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s %s @myparams.txt\n",gszProcName,gpszSubProcess->pszName);
		printf("\nPlease report any issues regarding usage of %s at https://github.com/csiro-crop-informatics/biokanga/issues\n\n",gszProcName);
		return(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s %s Version %s\n",gszProcName,gpszSubProcess->pszName,cpszProgVer);
		return(1);
        }

if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>\n'",FileLogLevel->ival[0]);
		return(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d\n",iFileLogLevel,eDLNone,eDLDebug);
		return(1);
		}

	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}

	// now that log parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem\n");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created\n",szLogFile);
		return(1);
		}
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Subprocess %s Version %s starting",gpszSubProcess->pszName,cpszProgVer);

	gExperimentID = 0;
	gProcessID = 0;
	gProcessingID = 0;
	szSQLiteDatabase[0] = '\0';
	szExperimentName[0] = '\0';
	szExperimentDescr[0] = '\0';

	if(experimentname->count)
		{
		strncpy(szExperimentName,experimentname->sval[0],sizeof(szExperimentName));
		szExperimentName[sizeof(szExperimentName)-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(szExperimentName);
		CUtility::ReduceWhitespace(szExperimentName);
		}
	else
		szExperimentName[0] = '\0';

	gExperimentID = 0;
	gProcessID = 0;
	gProcessingID = 0;
	szSQLiteDatabase[0] = '\0';
	szExperimentDescr[0] = '\0';
	if(summrslts->count)
		{
		strncpy(szSQLiteDatabase,summrslts->filename[0],sizeof(szSQLiteDatabase)-1);
		szSQLiteDatabase[sizeof(szSQLiteDatabase)-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(szSQLiteDatabase);
		if(strlen(szSQLiteDatabase) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite database specified with '-q<filespec>' option");
			return(1);
			}

		if(strlen(szExperimentName) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite experiment name specified with '-w<str>' option");
			return(1);
			}
		if(experimentdescr->count)
			{
			strncpy(szExperimentDescr,experimentdescr->sval[0],sizeof(szExperimentDescr)-1);
			szExperimentDescr[sizeof(szExperimentDescr)-1] = '\0';
			CUtility::TrimQuotedWhitespcExtd(szExperimentDescr);
			}
		if(strlen(szExperimentDescr) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite experiment description specified with '-W<str>' option");
			return(1);
			}

		gExperimentID = gSQLiteSummaries.StartExperiment(szSQLiteDatabase,false,true,szExperimentName,szExperimentName,szExperimentDescr);
		if(gExperimentID < 1)
			return(1);
		gProcessID = gSQLiteSummaries.AddProcess((char *)gpszSubProcess->pszName,(char *)gpszSubProcess->pszName,(char *)gpszSubProcess->pszFullDescr);
		if(gProcessID < 1)
			return(1);
		gProcessingID = gSQLiteSummaries.StartProcessing(gExperimentID,gProcessID,(char *)cpszProgVer);
		if(gProcessingID < 1)
			return(1);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Initialised SQLite database '%s' for results summary collection",szSQLiteDatabase);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database experiment identifier for '%s' is %d",szExperimentName,gExperimentID);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database process identifier for '%s' is %d",(char *)gpszSubProcess->pszName,gProcessID);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database processing instance identifier is %d",gProcessingID);
		}
	else
		{
		szSQLiteDatabase[0] = '\0';
		szExperimentDescr[0] = '\0';
		}

// show user current resource limits
#ifndef _WIN32
	gDiagnostics.DiagOut(eDLInfo, gszProcName, "Resources: %s",CUtility::ReportResourceLimits());
#endif

#ifdef _WIN32
	SYSTEM_INFO SystemInfo;
	GetSystemInfo(&SystemInfo);
	NumberOfProcessors = SystemInfo.dwNumberOfProcessors;
#else
	NumberOfProcessors = sysconf(_SC_NPROCESSORS_CONF);
#endif
	int MaxAllowedThreads = min(cMaxWorkerThreads,NumberOfProcessors);	// limit to be at most cMaxWorkerThreads
	if((NumThreads = numthreads->count ? numthreads->ival[0] : MaxAllowedThreads)==0)
		NumThreads = MaxAllowedThreads;
	if(NumThreads < 0 || NumThreads > MaxAllowedThreads)
		{
		gDiagnostics.DiagOut(eDLWarn,gszProcName,"Warning: Number of threads '-T%d' specified was outside of range %d..%d",NumThreads,1,MaxAllowedThreads);
		gDiagnostics.DiagOut(eDLWarn,gszProcName,"Warning: Defaulting number of threads to %d",MaxAllowedThreads);
		NumThreads = MaxAllowedThreads;
		}


	PMode = (etPMode)(pmode->count ? pmode->ival[0] : ePMExtdKMers);
	if(PMode < ePMExtdKMers || PMode >= ePMplaceholder)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Processing mode '-m%d' specified outside of range %d..%d\n",PMode,ePMExtdKMers,(int)ePMplaceholder-1);
		exit(1);
		}

	KMerLen = kmerlen->count ? kmerlen->ival[0] : cDfltKMerLen;
	if(KMerLen < cMinKMerLen || KMerLen > cMaxKMerLen)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: K-mer core length '-k%d' must be in range %d..%d",KMerLen,cMinKMerLen,cMaxKMerLen);
		return(1);
		}

	if(PMode == 2)
		{
		PrefixLen = prefixlen->count ? prefixlen->ival[0] : KMerLen/2;
		if(PrefixLen < cMinKMerLen/2 || PrefixLen > KMerLen-(cMinKMerLen/2))
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Prefix length '-p%d' must be in range %d..%d",KMerLen,cMinKMerLen/2,KMerLen-(cMinKMerLen/2));
			return(1);
			}
		SuffixLen = KMerLen - PrefixLen;
		MinWithPrefix = minwithprefix->count ? minwithprefix->ival[0] : 0;
		if(MinWithPrefix != 0 && MinWithPrefix < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Minimum cultivars sharing prefix sequence '-s%d' must be either 0 (all) or at least 1",MinWithPrefix);
			return(1);
			}
		}

	MinHamming = minhamming->count ? minhamming->ival[0] : cDfltHamming;
	if(MinHamming < cMinHamming || MinHamming > cMaxHamming)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Minimum Hamming separation '-K%d' must be in range %d..%d",MinHamming,cMinHamming,cMaxHamming);
		return(1);
		}

	strncpy(szCultivarName,cultivar->sval[0],cMaxDatasetSpeciesChrom);
	szCultivarName[cMaxDatasetSpeciesChrom]= '\0';
	CUtility::TrimQuotedWhitespcExtd(szCultivarName);
	if(strlen(szCultivarName) < 1)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected cultivar name '-c<name>' is empty");
		return(1);
		}

	strncpy(szPartialCultivarsList,chromnames->sval[0],sizeof(szPartialCultivarsList));
	szPartialCultivarsList[sizeof(szPartialCultivarsList)-1] = '\0';
	CUtility::TrimQuotedWhitespcExtd(szPartialCultivarsList);
	CUtility::ReduceWhitespace(szPartialCultivarsList);
	char *pChr = szPartialCultivarsList;
	char *pStartChr;
	char Chr;
	int CurSpeciesLen;
	NumPartialCultivars=0;
	CurSpeciesLen = 0;
	pStartChr = pChr;
	while((Chr = *pChr++) != '\0')
		{
		if(Chr == ' ' || Chr == '\t' || Chr == ',')	// treat any of these as delimiters
			{
			pChr[-1] = '\0';
			if(CurSpeciesLen != 0)
				{
				pszPartialCultivars[NumPartialCultivars++] = pStartChr;
				CurSpeciesLen = 0;
				}
			pStartChr = pChr;
			continue;
			}
		CurSpeciesLen += 1;
		}
	if(CurSpeciesLen)
		pszPartialCultivars[NumPartialCultivars++] = pStartChr;

	if(!NumPartialCultivars)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected at least one ('-C<names>') targeted cultivar chromosme name");
		return(1);
		}

	strcpy(szSfxPseudoGenome,infile->filename[0]);
	CUtility::TrimQuotedWhitespcExtd(szSfxPseudoGenome);
	if(strlen(szSfxPseudoGenome) < 1)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected input pseudo-genome suffix array filename '-i<name>' is empty");
		return(1);
		}

	strcpy(szMarkerFile,outfile->filename[0]);
	CUtility::TrimQuotedWhitespcExtd(szMarkerFile);
	if(strlen(szMarkerFile) < 1)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected marker file to generate filename '-o<name>' is empty");
		return(1);
		}

	if(outreadsfile->count)
		{
		strcpy(szMarkerReadsFile,outreadsfile->filename[0]);
		CUtility::TrimQuotedWhitespcExtd(szMarkerReadsFile);
		if(strlen(szMarkerReadsFile) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Reads containing markers filename '-O<name>' is empty");
			return(1);
			}
		}
	else
		szMarkerReadsFile[0] = '\0';

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Processing parameters:");
	const char *pszDescr;
	switch(PMode) {
		case ePMExtdKMers:
			pszDescr = "Extended K-mer markers";
			break;
		case ePMNoExtdKMers:
			pszDescr = "Non-extended K-mer markers";
			break;
		case ePMPrefixKMers:
			pszDescr = "K-mers to share prefix sequence with other cultivars";
			break;
		}

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing mode is : '%s'",pszDescr);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Targeted cultivar name : '%s'",szCultivarName);

	for(int Idx = 0; Idx < NumPartialCultivars; Idx++)
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Targeted cultivar chromosome name (%d) : '%s'", Idx + 1,pszPartialCultivars[Idx]);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Core K-mer length : %d",KMerLen);
	if(PMode == ePMPrefixKMers)
		{
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Inter-cultivar shared prefix sequence length : %d",PrefixLen);
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Cultivar specific suffix sequence length : %d",SuffixLen);
		if(MinWithPrefix)
			gDiagnostics.DiagOutMsgOnly(eDLInfo,"Min number cultivars sharing prefix : %d",MinWithPrefix);
		else
			gDiagnostics.DiagOutMsgOnly(eDLInfo,"Min number cultivars sharing prefix : 'All'");
		}
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum Hamming separation : %d",MinHamming);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input indexed pseudo-genome file: '%s'",szSfxPseudoGenome);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Write marker K-mers to file: '%s'",szMarkerFile);
	if(szMarkerReadsFile[0] != '\0')
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Write marker containing reads to file: '%s'",szMarkerReadsFile);

	if(szExperimentName[0] != '\0')
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"This processing reference: %s",szExperimentName);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Number of processing threads: %d",NumThreads);

	if(gExperimentID > 0)
		{
		int ParamID;

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szLogFile),"log",szLogFile);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(PMode),"mode",&PMode);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(KMerLen),"kmer",&KMerLen);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(PrefixLen),"prefixlen",&PrefixLen);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(SuffixLen),"suffixlen",&SuffixLen);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(MinWithPrefix),"minwithprefix",&MinWithPrefix);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(MinHamming),"minhamming",&MinHamming);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(NumThreads),"threads",&NumThreads);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(NumberOfProcessors),"cpus",&NumberOfProcessors);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szCultivarName),"cultivar",szCultivarName);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(NumPartialCultivars),"NumPartialCultivars",&NumPartialCultivars);
		for(int Idx = 0; Idx < NumPartialCultivars; Idx++)
			ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(pszPartialCultivars[Idx]),"chromnames",pszPartialCultivars[Idx]);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szSfxPseudoGenome),"in",szSfxPseudoGenome);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szMarkerFile),"markers",szMarkerFile);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szMarkerReadsFile),"markerreads",szMarkerReadsFile);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szSQLiteDatabase),"sumrslts",szSQLiteDatabase);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szExperimentName),"experimentname",szExperimentName);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szExperimentDescr),"experimentdescr",szExperimentDescr);
		}


#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	gStopWatch.Start();
	Rslt = LocMarkers((etPMode)PMode,KMerLen,PrefixLen,SuffixLen,MinWithPrefix,MinHamming,szCultivarName,NumPartialCultivars,pszPartialCultivars,szSfxPseudoGenome,szMarkerFile,szMarkerReadsFile,NumThreads);
	Rslt = Rslt >=0 ? 0 : 1;
	if(gExperimentID > 0)
		{
		if(gProcessingID)
			gSQLiteSummaries.EndProcessing(gProcessingID,Rslt);
		gSQLiteSummaries.EndExperiment(gExperimentID);
		}
	gStopWatch.Stop();
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	return(Rslt);
	}
else
	{
    printf("\n%s %s %s, Version %s\n", gszProcName,gpszSubProcess->pszName,gpszSubProcess->pszFullDescr,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	return(1);
	}
return 0;
}
示例#23
0
int main(int argc, char* argv[])
{
	// Define arguments.
	struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
	struct arg_str* type_assembler = arg_str0("t", NULL, "<type>", "The type of assembler to output for.");
	struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file (or - to read from standard input).");
	struct arg_file* output_file = arg_file1("o", "output", "<file>", "The output file (or - to send to standard output).");
	struct arg_end *end = arg_end(20);
	void *argtable[] = { output_file, show_help, type_assembler, input_file, end };

	// Parse arguments.
	int nerrors = arg_parse(argc,argv,argtable);
	if (nerrors != 0 || show_help->count != 0)
	{
		if (show_help->count != 0)
			arg_print_errors(stdout, end, "compiler");
		fprintf(stderr, "syntax:\n    compiler");
		arg_print_syntax(stdout, argtable, "\n");
		fprintf(stderr, "options:\n");
		arg_print_glossary(stdout, argtable, "    %-25s %s\n");
		return 1;
	}

	// Parse C.
	pp_add_search_path(".");
	pp_add_search_path("include");
	pp_add_search_path(dirname<std::string>(input_file->filename[0]).c_str());
	yyout = stderr;
	yyin = pp_do(input_file->filename[0]);
	if (yyin == NULL)
	{
		pp_cleanup();
		return 1;
	}
	yyparse();
	if (yyin != stdin)
		fclose(yyin);
	pp_cleanup();
	if (program == NULL)
	{
		std::cerr << "An error occurred while compiling." << std::endl;
		return 1;
	}

	// Assembler type.
	const char* asmtype = "dcpu16toolchain";
	if (type_assembler->count > 0)
		asmtype = type_assembler->sval[0];

	// Spacing.
	std::cerr << std::endl;

	// Generate assembly using the AST.
	try
	{
		AsmGenerator generator(asmtype);
		AsmBlock* block = program->compile(generator);
		if (strcmp(output_file->filename[0], "-") == 0)
		{
			std::cout << generator.m_Preassembly << std::endl;
			std::cout << *block << std::endl;
			std::cout << generator.m_Postassembly << std::endl;
		}
		else
		{
			std::ofstream output(output_file->filename[0], std::ios::out | std::ios::trunc);
			output << generator.m_Preassembly << std::endl;
			output << *block << std::endl;
			output << generator.m_Postassembly << std::endl;
			output.close();
		}
		delete block;
	}
	catch (CompilerException* ex)
	{
		std::string msg = ex->getMessage();
		std::cerr << "An error occurred while compiling." << std::endl;
		std::cerr << msg << std::endl;
		return 1;
	}
	
	return 0;
}
示例#24
0
文件: uname.c 项目: btbytes/examples
int main(int argc, char **argv)
    {
    const char* progname = "uname";
    struct arg_lit *all   = arg_lit0("a", "all",              "print all information, in the following order:");
    struct arg_lit *kname = arg_lit0("s", "kernel-name",      "print the kernel name");
    struct arg_lit *nname = arg_lit0("n", "nodename",         "print the node name");
    struct arg_lit *krel  = arg_lit0("r", "kernel-release",   "print the kernel release");
    struct arg_lit *kver  = arg_lit0("v", "kernel-version",   "print the kernel version");
    struct arg_lit *mach  = arg_lit0("m", "machine",          "print the machine hardware name");
    struct arg_lit *proc  = arg_lit0("p", "processor",        "print the processor type");
    struct arg_lit *hard  = arg_lit0("i", "hardware-platform","print the hardware platform");
    struct arg_lit *opsys = arg_lit0("o", "operating-system", "print the operating system");
    struct arg_lit *help  = arg_lit0(NULL,"help",             "print this help and exit");
    struct arg_lit *vers  = arg_lit0(NULL,"version",          "print version information and exit");
    struct arg_end *end   = arg_end(20);
    void* argtable[] = {all,kname,nname,krel,kver,mach,proc,hard,opsys,help,vers,end};
    int nerrors;
    int exitcode=0;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",progname);
        exitcode=1;
        goto exit;
        }

    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
        {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout,argtable,"\n");
        printf("Print certain system information.  With no options, same as -s.\n\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        printf("\nReport bugs to <foo@bar>.\n");
        exitcode=0;
        goto exit;
        }

    /* special case: '--version' takes precedence error reporting */
    if (vers->count > 0)
        {
        printf("'%s' example program for the \"argtable\" command line argument parser.\n",progname);
        printf("September 2003, Stewart Heitmann\n");
        exitcode=0;
        goto exit;
        }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
        {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,progname);
        printf("Try '%s --help' for more information.\n",progname);
        exitcode=1;
        goto exit;
        }

    /* special case: uname with no command line options is equivalent to "uname -s" */
    if (argc==1)
        {
        exitcode = mymain(0,1,0,0,0,0,0,0);
        goto exit;
        }

    /* special case: "uname -a" is equivalent to "uname -snrvmpi" */
    if (all->count>0)
        {
        exitcode = mymain(1,1,1,1,1,1,1,1);
        goto exit;
        }

    /* normal case: take the command line options at face value */
    exitcode = mymain(kname->count, nname->count, krel->count, kver->count, mach->count, proc->count, hard->count, opsys->count);

    exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return exitcode;
    }
示例#25
0
int main(int argc, char* argv[])
{
    // Define our variables.
    int nerrors, i;
    int32_t saved = 0; // The number of words saved during compression and optimization.
    struct errinfo* errval;
    const char* prepend = "error: ";
    const char* warnprefix = "no-";
    int msglen;
    char* msg;
    int target;

    // Define arguments.
    struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
    struct arg_str* target_arg = arg_str0("l", "link-as", "target", "Link as the specified object, can be 'image', 'static' or 'kernel'.");
    struct arg_file* symbol_file = arg_file0("s", "symbols", "<file>", "Produce a combined symbol file (~triples memory usage!).");
    struct arg_str* symbol_ext = arg_str0(NULL, "symbol-extension", "ext", "When -s is used, specifies the extension for symbol files.  Defaults to \"dsym16\".");
    struct arg_file* input_files = arg_filen(NULL, NULL, "<file>", 1, 100, "The input object files.");
    struct arg_file* output_file = arg_file1("o", "output", "<file>", "The output file (or - to send to standard output).");
    struct arg_file* kernel_file = arg_file0("k", "kernel", "<file>", "Directly link in the specified kernel.");
    struct arg_file* jumplist_file = arg_file0("j", "jumplist", "<file>", "Link against the specified jumplist.");
    struct arg_str* warning_policies = arg_strn("W", NULL, "policy", 0, _WARN_COUNT * 2 + 10, "Modify warning policies.");
    struct arg_lit* keep_output_arg = arg_lit0(NULL, "keep-outputs", "Keep the .OUTPUT entries in the final static library (used for stdlib).");
    struct arg_lit* little_endian_mode = arg_lit0(NULL, "little-endian", "Use little endian serialization (for compatibility with older versions).");
    struct arg_lit* no_short_literals_arg = arg_lit0(NULL, "no-short-literals", "Do not compress literals to short literals.");
    struct arg_int* opt_level = arg_int0("O", NULL, "<level>", "The optimization level.");
    struct arg_lit* opt_mode = arg_lit0("S", NULL, "Favour runtime speed over size when optimizing.");
    struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
    struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
    struct arg_end* end = arg_end(20);
    void* argtable[] = { show_help, target_arg, keep_output_arg, little_endian_mode, opt_level, opt_mode, no_short_literals_arg,
                         symbol_ext, symbol_file, kernel_file, jumplist_file, warning_policies, output_file, input_files, verbose, quiet, end
                       };

    // Parse arguments.
    nerrors = arg_parse(argc, argv, argtable);

    version_print(bautofree(bfromcstr("Linker")));
    if (nerrors != 0 || show_help->count != 0)
    {
        if (show_help->count != 0)
            arg_print_errors(stdout, end, "linker");

        printd(LEVEL_DEFAULT, "syntax:\n    dtld");
        arg_print_syntax(stderr, argtable, "\n");
        printd(LEVEL_DEFAULT, "options:\n");
        arg_print_glossary(stderr, argtable, "    %-25s %s\n");
        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    // Set verbosity level.
    debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);

    // Set global path variable.
    osutil_setarg0(bautofree(bfromcstr(argv[0])));

    // Set endianness.
    isetmode(little_endian_mode->count == 0 ? IMODE_BIG : IMODE_LITTLE);

    // Set up warning policies.
    dsetwarnpolicy(warning_policies);

    // Set up error handling.
    if (dsethalt())
    {
        errval = derrinfo();

        // FIXME: Use bstrings here.
        msglen = strlen(derrstr[errval->errid]) + strlen(prepend) + 1;
        msg = malloc(msglen);
        memset(msg, '\0', msglen);
        strcat(msg, prepend);
        strcat(msg, derrstr[errval->errid]);
        printd(LEVEL_ERROR, msg, errval->errdata);

        // Handle the error.
        printd(LEVEL_ERROR, "linker: error occurred.\n");

        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    // Check to make sure target is correct.
    if (target_arg->count == 0)
        target = IMAGE_APPLICATION;
    else
    {
        if (strcmp(target_arg->sval[0], "image") == 0)
            target = IMAGE_APPLICATION;
        else if (strcmp(target_arg->sval[0], "static") == 0)
            target = IMAGE_STATIC_LIBRARY;
        else if (strcmp(target_arg->sval[0], "kernel") == 0)
            target = IMAGE_KERNEL;
        else
        {
            // Invalid option.
            dhalt(ERR_INVALID_TARGET_NAME, NULL);
        }
    }

    // Load all passed objects and use linker bin system to
    // produce result.
    bins_init();
    for (i = 0; i < input_files->count; i++)
        if (!bins_load(bautofree(bfromcstr(input_files->filename[i])), symbol_file->count > 0, (symbol_file->count > 0 && symbol_ext->count > 0) ? symbol_ext->sval[0] : "dsym16"))
            // Failed to load one of the input files.
            dhalt(ERR_BIN_LOAD_FAILED, input_files->filename[i]);
    bins_associate();
    bins_sectionize();
    bins_flatten(bautofree(bfromcstr("output")));
    if (target == IMAGE_KERNEL)
        bins_write_jump();
    saved = bins_optimize(
                opt_mode->count == 0 ? OPTIMIZE_SIZE : OPTIMIZE_SPEED,
                opt_level->count == 0 ? OPTIMIZE_NONE : opt_level->ival[0]);
    if (no_short_literals_arg->count == 0 && target != IMAGE_STATIC_LIBRARY)
        saved += bins_compress();
    else if (no_short_literals_arg->count == 0)
        dwarn(WARN_SKIPPING_SHORT_LITERALS_TYPE, NULL);
    else
        dwarn(WARN_SKIPPING_SHORT_LITERALS_REQUEST, NULL);
    bins_resolve(
        target == IMAGE_STATIC_LIBRARY,
        target == IMAGE_STATIC_LIBRARY);
    bins_save(
        bautofree(bfromcstr("output")),
        bautofree(bfromcstr(output_file->filename[0])),
        target,
        keep_output_arg->count > 0,
        symbol_file->count > 0 ? symbol_file->filename[0] : NULL,
        jumplist_file->count > 0 ? jumplist_file->filename[0] : NULL);
    bins_free();
    if (saved > 0)
        printd(LEVEL_DEFAULT, "linker: saved %i words during optimization.\n", saved);
    else if (saved < 0)
        printd(LEVEL_DEFAULT, "linker: increased by %i words during optimization.\n", -saved);

    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return 0;
}
示例#26
0
int main(int argc, char* argv[])
{
	// Define arguments.
	struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
	struct arg_str* type_assembler = arg_str0("t", NULL, "<type>", "The type of assembler to output for.");
	struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file (or - to read from standard input).");
	struct arg_file* output_file = arg_file1("o", "output", "<file>", "The output file (or - to send to standard output).");
	// 20 is maxcount for include directories, this has to be set to some constant number.
	struct arg_file* include_dirs = arg_filen("I", NULL, "<directory>", 0, 20, "Adds the directory <dir> to the directories to be searched for header files.");
	struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
	struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
	struct arg_end* end = arg_end(20);
	void* argtable[] = { output_file, show_help, type_assembler, include_dirs, input_file, verbose, quiet, end };

	// Parse arguments.
	int nerrors = arg_parse(argc, argv, argtable);

	version_print(bautofree(bfromcstr("Compiler")));
	if (nerrors != 0 || show_help->count != 0)
	{
		if (nerrors != 0)
			arg_print_errors(stderr, end, "compiler");

		fprintf(stderr, "syntax:\n    dtcc");
		arg_print_syntax(stderr, argtable, "\n");
		fprintf(stderr, "options:\n");
		arg_print_glossary(stderr, argtable, "	  %-25s %s\n");
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Set verbosity level.
	debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);

	// Set global path variable.
	osutil_setarg0(bautofree(bfromcstr(argv[0])));

	// Run the preprocessor.
	ppfind_add_path(bautofree(bfromcstr(".")));
	ppfind_add_path(bautofree(bfromcstr("include")));
	ppfind_add_autopath(bautofree(bfromcstr(input_file->filename[0])));
	for (int i = 0; i < include_dirs->count; ++i)
		ppfind_add_path(bautofree(bfromcstr(include_dirs->filename[i])));
	bstring pp_result_name = pp_do(bautofree(bfromcstr(input_file->filename[0])));

	if (pp_result_name == NULL)
	{
		fprintf(stderr, "compiler: invalid result returned from preprocessor.\n");
		pp_cleanup(bautofree(pp_result_name));
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Parse C.
	yyout = stderr;
	yyin = fopen((const char*)(pp_result_name->data), "r");

	if (yyin == NULL)
	{
		pp_cleanup(bautofree(pp_result_name));
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	yyparse();

	if (yyin != stdin)
		fclose(yyin);

	pp_cleanup(bautofree(pp_result_name));

	if (program == NULL)
	{
		std::cerr << "An error occurred while compiling." << std::endl;
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Assembler type.
	const char* asmtype = "toolchain";

	if (type_assembler->count > 0)
		asmtype = type_assembler->sval[0];

	// Initially save to a temporary file.
	std::string temp = std::string(tempnam(".", "cc."));

	// Generate assembly using the AST.
	try
	{
		AsmGenerator generator(asmtype);
		AsmBlock* block = program->compile(generator);

		std::ofstream output(temp.c_str(), std::ios::out | std::ios::trunc);
		if (output.bad() || output.fail())
		{
			printd(LEVEL_ERROR, "compiler: temporary file not writable.\n");
			arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
			return 1;
		}
		output << *block << std::endl;
		output.close();

		delete block;
	}
	catch (CompilerException* ex)
	{
		std::string msg = ex->getMessage();
		std::cerr << "An error occurred while compiling." << std::endl;
		std::cerr << msg << std::endl;
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Re-open the temporary file for reading.
	std::ifstream input(temp.c_str(), std::ios::in);
	if (input.bad() || input.fail())
	{
		printd(LEVEL_ERROR, "compiler: temporary file not readable.\n");
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Open the output file.
	std::ostream* output;
	if (strcmp(output_file->filename[0], "-") != 0)
	{
		// Write to file.
		output = new std::ofstream(output_file->filename[0], std::ios::out | std::ios::trunc);

		if (output->bad() || output->fail())
		{
			printd(LEVEL_ERROR, "compiler: output file not readable.\n");
			arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
			return 1;
		}
	}
	else
	{
		// Set output to cout.
		output = &std::cout;
	}

	// Copy data.
	std::copy(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>(), std::ostreambuf_iterator<char>(*output));

	// Close files and delete temporary.
	if (strcmp(output_file->filename[0], "-") != 0)
	{
		((std::ofstream*)output)->close();
		delete output;
	}
	input.close();
	unlink(temp.c_str());

	arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
	return 0;
}
示例#27
0
文件: main.c 项目: omf2097/openomf
int main(int argc, char* argv[]) {
    // commandline argument parser options
    struct arg_lit *help = arg_lit0("h", "help", "print this help and exit");
    struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit");
    struct arg_file *file = arg_file1("f", "file", "<file>", "Input altpals file");
    struct arg_int *pal = arg_int1("p", "palette", "<number>", "Select a palette");
    struct arg_file *export = arg_file0("e", "export", "<file>", "Export selected palette to GPL file");
    struct arg_file *import = arg_file0("i", "import", "<file>", "Import selected palette from GPL file");
    struct arg_file *output = arg_file0("o", "output", "<file>", "Output altpals file");
    struct arg_end *end = arg_end(20);
    void* argtable[] = {help,vers,file,pal,output,import,export,end};
    const char* progname = "altpaltool";

    // Make sure everything got allocated
    if(arg_nullcheck(argtable) != 0) {
        printf("%s: insufficient memory\n", progname);
        goto exit_0;
    }

    // Parse arguments
    int nerrors = arg_parse(argc, argv, argtable);

    // Handle help
    if(help->count > 0) {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("\nArguments:\n");
        arg_print_glossary(stdout, argtable, "%-25s %s\n");
        goto exit_0;
    }

    // Handle version
    if(vers->count > 0) {
        printf("%s v0.1\n", progname);
        printf("Command line One Must Fall 2097 Altpals file editor.\n");
        printf("Source code is available at https://github.com/omf2097 under MIT license.\n");
        printf("(C) 2014 Tuomas Virtanen\n");
        goto exit_0;
    }

    // Handle errors
    if(nerrors > 0) {
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        goto exit_0;
    }

    // Need import or export ...
    if(pal->count > 0 && import->count == 0 && export->count == 0) {
        printf("Define either --import or --export with --palette!\n");
        goto exit_0;
    }

    // Make sure output is set
    if(import->count > 0 && output->count <= 0) {
        printf("Define --output with --import.\n");
        goto exit_0;
    }

    // Load file
    sd_altpal_file alt;
    sd_altpal_create(&alt);
    int ret = sd_altpals_load(&alt, file->filename[0]);
    if(ret != SD_SUCCESS) {
        printf("Unable to load altpals file %s: %s.\n",
            file->filename[0],
            sd_get_error(ret));
        goto exit_1;
    }

    // Check ID
    int pal_id = pal->ival[0];
    if(pal_id < 0 || pal_id > SD_ALTPALS_PALETTES) {
        printf("Palette index %d does not exist!\n", pal_id);
        goto exit_1;
    }

    // Check what to do
    if(export->count > 0) {
        ret = sd_palette_to_gimp_palette(&alt.palettes[pal_id], export->filename[0]);
        if(ret == SD_SUCCESS) {
            printf("Palette %d exported to file %s succesfully.\n",
                pal_id,
                export->filename[0]);
        } else {
示例#28
0
int main(int argc, char* argv[])
{
    // Define our variables.
    FILE* load;
    uint16_t flash[0x10000];
    char leading[0x100];
    unsigned int i;
    bool uread = true;
    vm_t* vm;
    int nerrors;
    bstring ss, st;
    host_context_t* dtemu = malloc(sizeof(host_context_t));
    const char* warnprefix = "no-";

    // Define arguments.
    struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
    struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file, or - to read from standard input.");
    struct arg_file* execution_dump_file = arg_file0("e", "execution-dump", "<file>", "Produce a very large execution dump file.");
    struct arg_lit* debug_mode = arg_lit0("d", "debug", "Show each executed instruction.");
    struct arg_lit* terminate_mode = arg_lit0("t", "show-on-terminate", "Show state of machine when program is terminated.");
    struct arg_lit* headless_mode = arg_lit0("h", "headless", "Run machine witout displaying monitor and SPED output");
    struct arg_lit* legacy_mode = arg_lit0("l", "legacy", "Automatically initialize hardware to legacy values.");
    struct arg_str* warning_policies = arg_strn("W", NULL, "policy", 0, _WARN_COUNT * 2 + 10, "Modify warning policies.");
    struct arg_lit* little_endian_mode = arg_lit0(NULL, "little-endian", "Use little endian serialization (for compatibility with older versions).");
    struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
    struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
    struct arg_int* radiation = arg_intn("r", NULL, "<n>", 0, 1, "Radiation factor (higher is less radiation)");
    struct arg_lit* catch_fire = arg_lit0("c", "catch-fire", "The virtual machine should catch fire instead of halting.");
    struct arg_end* end = arg_end(20);
    void* argtable[] = { input_file, warning_policies, debug_mode, execution_dump_file, terminate_mode, headless_mode, legacy_mode, little_endian_mode, radiation, catch_fire, verbose, quiet, end };

    // Parse arguments.
    nerrors = arg_parse(argc, argv, argtable);

    if (nerrors != 0 || show_help->count != 0)
    {
        if (show_help->count != 0)
            arg_print_errors(stdout, end, "emulator");

        printd(LEVEL_DEFAULT, "syntax:\n    dtemu");
        arg_print_syntax(stderr, argtable, "\n");
        printd(LEVEL_DEFAULT, "options:\n");
        arg_print_glossary(stderr, argtable, "      %-25s %s\n");
        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    // Set verbosity level.
    debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);
    
    // Show version information.
    version_print(bautofree(bfromcstr("Emulator")));

    // Set global path variable.
    osutil_setarg0(bautofree(bfromcstr(argv[0])));

    // Set endianness.
    isetmode(little_endian_mode->count == 0 ? IMODE_BIG : IMODE_LITTLE);

    // Set up warning policies.
    dsetwarnpolicy(warning_policies);
    
    // Set up error handling.
    if (dsethalt())
    {
        // Handle the error.
        dautohandle();
        printd(LEVEL_ERROR, "emulator: error occurred.\n");

        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    // Zero out the flash space.
    for (i = 0; i < 0x10000; i++)
        flash[i] = 0x0;

    // Zero out the leading space.
    for (i = 0; i < 0x100; i++)
        leading[i] = 0x0;

    // Load from either file or stdin.
    if (strcmp(input_file->filename[0], "-") != 0)
    {
        // Open file.
        load = fopen(input_file->filename[0], "rb");

        if (load == NULL)
            dhalt(ERR_EMU_LOAD_FILE_FAILED, input_file->filename[0]);
    }
    else
    {
        // Windows needs stdin in binary mode.
#ifdef _WIN32
        _setmode(_fileno(stdin), _O_BINARY);
#endif

        // Set load to stdin.
        load = stdin;
    }
    
    // Read leading component.
    for (i = 0; i < strlen(ldata_objfmt); i++)
        leading[i] = fgetc(load);
    fseek(load, 0, SEEK_SET);

    // Read up to 0x10000 words.
    for (i = 0; i < 0x10000 && !feof(load); i++)
        iread(&flash[i], load);
    fclose(load);

    // Check to see if the first X bytes matches the header
    // for intermediate code and stop if it does.
    ss = bfromcstr("");
    st = bfromcstr(ldata_objfmt);
    for (i = 0; i < strlen(ldata_objfmt); i++)
        bconchar(ss, leading[i]);
    if (biseq(ss, st))
        dhalt(ERR_INTERMEDIATE_EXECUTION, NULL);

    // Set up the host context.
    glfwInit();
    dtemu->create_context = &dtemu_create_context;
    dtemu->activate_context = &dtemu_activate_context;
    dtemu->swap_buffers = &dtemu_swap_buffers;
    dtemu->destroy_context = &dtemu_destroy_context;
    dtemu->get_ud = &dtemu_get_ud;

    // And then use the VM.
    vm = vm_create();
    vm->debug = (debug_mode->count > 0);
    vm_flash(vm, flash);

    // Set radiation and catch fire settings.
    if (radiation->count == 1)
        vm->radiation_factor = radiation->ival[0];
    if (catch_fire->count == 1)
        vm->can_fire = true;

    // Init hardware.
    vm_hw_clock_init(vm);

    if (headless_mode->count < 1)
        vm->host = dtemu;

    vm_hw_sped3_init(vm);
    vm_hw_lem1802_init(vm);
    vm_hw_m35fd_init(vm);
    vm_hw_lua_init(vm);

    if (legacy_mode->count > 0)
    {
        for (i = 0; i < vm_hw_count(vm); i++) {

            hw_t* device = vm_hw_get_device(vm, i);
            if (device == NULL)
                continue;

            if (device->id == 0x7349F615 && device->manufacturer == 0x1C6C8B36)
            {
                vm_hw_lem1802_mem_set_screen((struct lem1802_hardware*)device->userdata, 0x8000);
                break;
            }
        }
    }

    vm_execute(vm, execution_dump_file->count > 0 ? execution_dump_file->filename[0] : NULL);

    if (terminate_mode->count > 0)
    {
        fprintf(stderr, "\n");
        fprintf(stderr, "A:   0x%04X     [A]:    0x%04X\n", vm->registers[REG_A], vm->ram[vm->registers[REG_A]]);
        fprintf(stderr, "B:   0x%04X     [B]:    0x%04X\n", vm->registers[REG_B], vm->ram[vm->registers[REG_B]]);
        fprintf(stderr, "C:   0x%04X     [C]:    0x%04X\n", vm->registers[REG_C], vm->ram[vm->registers[REG_C]]);
        fprintf(stderr, "X:   0x%04X     [X]:    0x%04X\n", vm->registers[REG_X], vm->ram[vm->registers[REG_X]]);
        fprintf(stderr, "Y:   0x%04X     [Y]:    0x%04X\n", vm->registers[REG_Y], vm->ram[vm->registers[REG_Y]]);
        fprintf(stderr, "Z:   0x%04X     [Z]:    0x%04X\n", vm->registers[REG_Z], vm->ram[vm->registers[REG_Z]]);
        fprintf(stderr, "I:   0x%04X     [I]:    0x%04X\n", vm->registers[REG_I], vm->ram[vm->registers[REG_I]]);
        fprintf(stderr, "J:   0x%04X     [J]:    0x%04X\n", vm->registers[REG_J], vm->ram[vm->registers[REG_J]]);
        fprintf(stderr, "PC:  0x%04X     SP:    0x%04X\n", vm->pc, vm->sp);
        fprintf(stderr, "EX:  0x%04X     IA:    0x%04X\n", vm->ex, vm->ia);
    }

    vm_hw_lua_free(vm);
    vm_free(vm);

    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    glfwTerminate();
    return 0;
}
示例#29
0
int main(int argc, char **argv)
{
	struct arg_int *serverport = arg_int0("pP","port","","serverport, default: 1337");
	struct arg_str *serialport = arg_str0("sS", "serial", "", "serial port, default /dev/ttyS0");

	struct arg_int *baud = arg_int0("bB", "baud","","baudrate, default: 9600");
	
	struct arg_str *client = arg_str0("cC","client","","only accept messages from this client");

    struct arg_lit  *help    = arg_lit0("hH","help","print this help and exit");
    struct arg_lit  *version = arg_lit0(NULL,"version","print version information and exit");

	struct arg_lit  *debug = arg_lit0(NULL,"debug","print debug messages");
    struct arg_lit  *silent = arg_lit0(NULL,"silent","print no messages");

    struct arg_end  *end     = arg_end(20);

    void* argtable[] = {serverport,serialport,baud,client,help,version,debug,silent,end};

    int nerrors;
    int exitcode=0;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0) {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",PROGNAME);
        exitcode=1;
        goto exit;
	}

    /* set any command line default values prior to parsing */
	/* nothing */

    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0) {
		printf("usage: %s", PROGNAME);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        exitcode=0;
        goto exit;
	}

    /* special case: '--version' takes precedence error reporting */
    if (version->count > 0) {
        printf("'%s' version ",PROGNAME);
		printf("%s",VERSION);
		printf("\nGIT-REVISION: ");
		printf("%s",GITREV);
        printf("\n%s receives udp-packets and controls\n",PROGNAME);
		printf("the EIWOMISA controller over RS-232\n");
        printf("%s",COPYRIGHT);
		printf("\n");
        exitcode=0;
        goto exit;
	}

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0) {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,PROGNAME);
        printf("Try '%s --help' for more information.\n",PROGNAME);
        exitcode=1;
        goto exit;
	}

    /* special case: with no command line options induce brief help and use defaults */
    if (argc==1) {
		printf("No command-line options present, using defaults.\n",PROGNAME);
        printf("Try '%s --help' for more information.\n",PROGNAME);
	}

    /* normal case: take the command line options at face value */

	/* check if server port is set */
	int i_serverport = -1;
	if(serverport->count>0)
		i_serverport = (int)serverport->ival[0];

	/* check if serial port is set */
	char* i_serialport = NULL;
	if(serialport->count>0)
		i_serialport = (char*)serialport->sval[0];

	/* check if baudrate is set */
	int i_baudrate = -1;
	if(baud->count>0)
		i_baudrate = (int)baud->ival[0];
	
	/* check if client ip is set */
	char* i_client = NULL;
	if(client->count>0) {
		i_client = (char *)client->sval[0];
	}
	
	/* --debug enables debug messages */
    if (debug->count > 0) {
		printf("debug messages enabled\n");
		msglevel = 3;
	}

	/* --silent disables all (!) messages */
    if (silent->count > 0) {
		msglevel = 0;
	}

	exitcode = mymain(i_serverport, i_serialport, i_baudrate, i_client);

exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return exitcode;
}
int main(int argc, char* argv[]) {

    double discountFactor;
    unsigned int maxNbEvaluations;
    char isTerminal = 0;
    char keepingTree = 0;
    int nbTimestep = -1;
    unsigned int branchingFactor = 0;

#ifdef USE_SDL
    char isDisplayed = 1;
    char isFullscreen = 1;
    char verbose = 0;
    char resolution[255] = "640x480";
#else
    char verbose = 1;
#endif

    uniform_instance* instance = NULL;

    state* crtState = NULL;
    state* nextState = NULL;
    double reward = 0.0;
    action* optimalAction = NULL;

    struct arg_dbl* g = arg_dbl1("g", "discountFactor", "<d>", "The discount factor for the problem");
    struct arg_int* n = arg_int1("n", "nbEvaluations", "<n>", "The number of evaluations");
    struct arg_int* s = arg_int0("s", "nbtimestep", "<n>", "The number of timestep");
    struct arg_int* b = arg_int0("b", "branchingFactor", "<n>", "The branching factor of the problem");
    struct arg_lit* k = arg_lit0("k", NULL, "Keep the subtree");
    struct arg_str* i = arg_str0(NULL, "state", "<s>", "The initial state to use");

#ifdef USE_SDL
    struct arg_lit* d = arg_lit0("d", NULL, "Display the viewer");
    struct arg_lit* f = arg_lit0("f", NULL, "Fullscreen");
    struct arg_lit* v = arg_lit0("v", NULL, "Verbose");
    struct arg_str* r = arg_str0(NULL, "resolution", "<s>", "The resolution of the display window");
    void* argtable[11];
    int nbArgs = 10;
#else
    void* argtable[7];
    int nbArgs = 6;
#endif

    struct arg_end* end = arg_end(nbArgs+1);
    int nerrors = 0;

    s->ival[0] = -1;
    b->ival[0] = 0;

    argtable[0] = g; argtable[1] = n; argtable[2] = s; argtable[3] = k; argtable[4] = b; argtable[5] = i;

#ifdef USE_SDL
    argtable[6] = d;
    argtable[7] = f;
    argtable[8] = v;
    argtable[9] = r;
#endif

    argtable[nbArgs] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, nbArgs+1);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, nbArgs+1);
        return EXIT_FAILURE;
    }

    discountFactor = g->dval[0];
    maxNbEvaluations = n->ival[0];

    branchingFactor = b->ival[0];

    initGenerativeModelParameters();
    if(branchingFactor)
        K = branchingFactor;
    initGenerativeModel();
    if(i->count)
        crtState = makeState(i->sval[0]);
    else
        crtState = initState();

#if USE_SDL
    isDisplayed = d->count;
    isFullscreen = f->count;
    verbose = v->count;
    if(r->count)
        strcpy(resolution, r->sval[0]);
#endif

    nbTimestep = s->ival[0];
    keepingTree = k->count;

    arg_freetable(argtable, nbArgs+1);

    instance = uniform_initInstance(crtState, discountFactor);

#ifdef USE_SDL
    if(isDisplayed) {
        if(initViewer(resolution, uniform_drawingProcedure, isFullscreen) == -1)
            return EXIT_FAILURE;
        viewer(crtState, NULL, 0.0, instance);
    }
#endif

    do {
        if(keepingTree)
            uniform_keepSubtree(instance);
        else
            uniform_resetInstance(instance, crtState);

        optimalAction = uniform_planning(instance, maxNbEvaluations);

        isTerminal = nextStateReward(crtState, optimalAction, &nextState, &reward);
        freeState(crtState);
        crtState = nextState;

        if(verbose) {
            printState(crtState);
            printAction(optimalAction);
            printf("reward: %f depth: %u\n", reward, uniform_getMaxDepth(instance));
        }

#ifdef USE_SDL
    } while(!isTerminal && (nbTimestep < 0 || --nbTimestep) && !viewer(crtState, optimalAction, reward, instance));
#else
    } while(!isTerminal && (nbTimestep < 0 || --nbTimestep));