TEST_F(SimplePipelineTest, test_simple_pswf_exact)
{
    // Config file
    std::string configfile(config_path + "fastimg_exact_pswf_config.json");
    load_configdata(configfile);

    // Execute pipeline based on the loaded configurations
    stp::SourceFindImage sfimage = execute_pipeline();

    int total_islands = sfimage.islands.size();
    ASSERT_EQ(total_islands, 1);

    int label_idx = sfimage.islands[0].label_idx;
    int sign = sfimage.islands[0].sign;
    double extremum_val = sfimage.islands[0].extremum_val;
    int extremum_x_idx = sfimage.islands[0].extremum_x_idx;
    int extremum_y_idx = sfimage.islands[0].extremum_y_idx;

    EXPECT_EQ(label_idx, 1);
    EXPECT_EQ(sign, 1);
    EXPECT_NEAR(extremum_val, 0.49762858232302537, pipeline_tolerance);
    EXPECT_EQ(extremum_x_idx, 824);
    EXPECT_EQ(extremum_y_idx, 872);

    // Do not compare x_centre and y_centre (moments-fit) because there are differences
    // on the number of samples of the island. The difference seems to be caused by
    // numeric errors on sigma clip function (the function is not numerically stable).
}
TEST_F(SimplePipelineTest, test_simple_gaussiansinc_oversampling)
{
    // Config file
    std::string configfile(config_path + "fastimg_oversampling_gaussiansinc_config.json");
    load_configdata(configfile);

    // Execute pipeline based on the loaded configurations
    stp::SourceFindImage sfimage = execute_pipeline();

    int total_islands = sfimage.islands.size();
    ASSERT_EQ(total_islands, 1);

    int label_idx = sfimage.islands[0].label_idx;
    int sign = sfimage.islands[0].sign;
    double extremum_val = sfimage.islands[0].extremum_val;
    int extremum_x_idx = sfimage.islands[0].extremum_x_idx;
    int extremum_y_idx = sfimage.islands[0].extremum_y_idx;
    double xbar = sfimage.islands[0].moments_fit.x_centre;
    double ybar = sfimage.islands[0].moments_fit.y_centre;

    EXPECT_EQ(label_idx, 1);
    EXPECT_EQ(sign, 1);
    EXPECT_NEAR(extremum_val, 0.10973023095014588, pipeline_tolerance);
    EXPECT_EQ(extremum_x_idx, 824);
    EXPECT_EQ(extremum_y_idx, 872);
    EXPECT_NEAR(xbar, 823.363524400699, pipeline_tolerance);
    EXPECT_NEAR(ybar, 871.582414171632, pipeline_tolerance);
}
Ejemplo n.º 3
0
bool CFlashTool::GetVersionInfo(CFlashVersionInfo& versionInfo, std::string filename)
{
  std::string versionPath = LOCAL_MOUNT_DIR "/.version";
  printf("[CFlashTool] check filename: %s\n", filename.c_str());

  if (mountImage(filename)) {
    CConfigFile configfile('\t');
    bool success =configfile.loadConfig(versionPath);
    if (success) {
      const char * versionString = configfile.getString( "version", "????????????????").c_str();
      printf("[CFlashTool] read version string: %s\n", versionString);
      versionInfo.load(versionString);
      unmountImage();
      return true;
    } else {
      printf("[CFlashTool] error reading .version\n");
      unmountImage();
      return false;
    }
  } else {
    printf("[CFlashTool] mount error\n");
    unmountImage();
    return false;
  }
}
Ejemplo n.º 4
0
/** Write settings to config file. */
void UserConfig::saveConfig()
{
    const std::string filename = file_manager->getUserConfigFile(m_filename);

    try
    {
        std::ofstream configfile (filename.c_str(), std::ofstream::out);

        configfile << "<?xml version=\"1.0\"?>\n";
        configfile << "<stkconfig version=\"" << m_current_config_version
                   << "\" >\n\n";

        const int paramAmount = all_params.size();
        for(int i=0; i<paramAmount; i++)
        {
            //std::cout << "saving parameter " << i << " to file\n";
            all_params[i].write(configfile);
        }

        configfile << "</stkconfig>\n";
        configfile.close();
    }
    catch (std::runtime_error& e)
    {
        std::cerr << "[UserConfig::saveConfig] ERROR: Failed to write config to " << filename.c_str()
                  << "; cause : " << e.what() << "\n";
    }

}   // saveConfig
Ejemplo n.º 5
0
LoadBalancing::LoadBalancing() {
	fdr_=0;
	lastM=0;
	is_lpmodel_created_=false;
	quantiles_available_=false;
	lp_D=NULL;
	lp_G=NULL;
	lp_E=NULL;

	//Default configuration:
	reconstruction_method_=RECONSTRUCTION_METHOD_DEFAULT;
	bdr_update_coef_=BDR_UPDATE_COEF_DEFAULT;
	fdr_update_coef_=FDR_UPDATE_COEF_DEFAULT;
	scaling_coef_=SCALING_COEF_DEFAULT;

	num_quantiles_=NUM_QUANTILES_DEFAULT;
	solver_timeout_=SOLVER_TIMEOUT_DEFAULT;
	multicast_enabled_=MULTICAST_DEFAULT;

	use_fixed_uniform_cuts_=USE_FIXED_UNIFORM_CUTS_DEFAULT;

	//Try to read config file in "loadbalancing_config.txt":
	std::ifstream configfile(LB_CONFIG_FILE);
	if(configfile){
		std::cout << "LoadBalancing: Reading config from " <<  LB_CONFIG_FILE << std::endl;
		LoadBalancingConfig lbconfig;
		lbconfig.ParseConfigFile(LB_CONFIG_FILE);
		LoadNewConfig(lbconfig);
	}
}
Ejemplo n.º 6
0
//! Die Initialisierung des Servers mit Daten aus einer Datei
bool Init(const std::string &initfile) {
    // first we try to open the file
    std::ifstream configfile(initfile.c_str());

    // can't read config file
    if (!configfile.good()) {
        return false;
    }

    std::string temp;
    char buf[255];

    // read first token of a line while there are any tokens left...
    while (configfile >> temp && ! configfile.eof()) {

        if (temp[0] == '#') {
            // we found a comment... skip line
            configfile.ignore(255,'\n'); // ignore up to 255 chars until \n is found
            continue;
        }

        // store config options in map
        configfile.ignore(1); // ignore the blank char following the token
        configfile.getline(buf, 255, '\n');
        configOptions[temp] = buf;

        if (!configfile.good()) {
            return false;
        }
    }

    return true;
}
Ejemplo n.º 7
0
/** Write settings to config file. */
void UserConfig::saveConfig()
{
    const std::string filename = file_manager->getUserConfigFile(m_filename);
    std::stringstream ss;
    ss << "<?xml version=\"1.0\"?>\n";
    ss << "<stkconfig version=\"" << m_current_config_version
        << "\" >\n\n";
    for (unsigned i = 0; i < all_params.size(); i++)
    {
        all_params[i]->write(ss);
    }
    ss << "</stkconfig>\n";

    try
    {
        std::string s = ss.str();
        std::ofstream configfile(filename.c_str(), std::ofstream::out);
        configfile << ss.rdbuf();
        configfile.close();
    }
    catch (std::runtime_error& e)
    {
        Log::error("UserConfig::saveConfig", "Failed to write config to %s, "
            "because %s", filename.c_str(), e.what());
    }

}   // saveConfig
Ejemplo n.º 8
0
int main(int argc, char **argv)
{
  // Convert first argument of argv[0] (full pathspec to this executable) to path where executable is found
  char *dir = dirname(argv[0]);
  chdir(dir);

  // Read the ini file
  std::string iniFileName("lib/Rel.ini");
  std::ifstream configfile(iniFileName);
  std::string cmd((std::istreambuf_iterator<char>(configfile)), std::istreambuf_iterator<char>());

  // Empty or no ini file?
  if (cmd.length() == 0) {
    std::cerr << (std::string("Missing or Damaged .ini File: Unable to find ") + iniFileName).c_str() << std::endl;
    return 10;
  }

  // Include command-line args.
  std::string args("");
  for (int i = 1; i < argc; i++)
    args += std::string(" \"") + std::string(argv[i]) + std::string("\"");

  // Uncomment the following line to use GTK2
  // setenv("SWT_GTK3", "0", 1);
  return system((cmd + args).c_str());
}
Ejemplo n.º 9
0
/** Write settings to config file. */
void UserConfig::saveConfig()
{
    const std::string filename = file_manager->getUserConfigFile(m_filename);

    try
    {
        std::ofstream configfile (filename.c_str(), std::ofstream::out);

        configfile << "<?xml version=\"1.0\"?>\n";
        configfile << "<stkconfig version=\"" << m_current_config_version
                   << "\" >\n\n";

        const int paramAmount = all_params.size();
        for(int i=0; i<paramAmount; i++)
        {
            //Log::info("UserConfig", "Saving parameter %d to file", i);
            all_params[i].write(configfile);
        }

        configfile << "</stkconfig>\n";
        configfile.close();
    }
    catch (std::runtime_error& e)
    {
        Log::error("UserConfig::saveConfig", "Failed to write config to %s, because %s",
                   filename.c_str(), e.what());
    }

}   // saveConfig
TEST_F(SimplePipelineTest, test_simple_gaussiansinc_exact)
{
    // Config file
    std::string configfile(config_path + "fastimg_exact_gaussiansinc_config.json");
    load_configdata(configfile);

    // Execute pipeline based on the loaded configurations
    stp::SourceFindImage sfimage = execute_pipeline();

    int total_islands = sfimage.islands.size();
    ASSERT_EQ(total_islands, 1);

    int label_idx = sfimage.islands[0].label_idx;
    int sign = sfimage.islands[0].sign;
    double extremum_val = sfimage.islands[0].extremum_val;
    int extremum_x_idx = sfimage.islands[0].extremum_x_idx;
    int extremum_y_idx = sfimage.islands[0].extremum_y_idx;
    double xbar = sfimage.islands[0].moments_fit.x_centre;
    double ybar = sfimage.islands[0].moments_fit.y_centre;

    EXPECT_EQ(label_idx, 1);
    EXPECT_EQ(sign, 1);
    EXPECT_NEAR(extremum_val, 0.11045229607808271, pipeline_tolerance);
    EXPECT_EQ(extremum_x_idx, 824);
    EXPECT_EQ(extremum_y_idx, 872);
    EXPECT_NEAR(xbar, 823.435310857686, pipeline_tolerance);
    EXPECT_NEAR(ybar, 871.615973834618, pipeline_tolerance);
}
Ejemplo n.º 11
0
int main(int argc, const char* argv[])
{
    std::string text;
    std::string filename;
    std::string configuration;
    auto homepath = std::getenv("HOME");
    if(!homepath){
        std::cout << "HOME env var not found!";
        return 1;
    }
    configuration = std::getenv("HOME") ;
    configuration += "/.config/demo.cfg";
    po::options_description options("Options:");
    options.add_options()
            ("help,h", "print help message")
            ("output", po::value<std::string>(), "file to print to");
    std::ifstream configfile(configuration);
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, options), vm);
    po::store(po::parse_environment(options, "DEMO_"), vm);
    po::store(po::parse_config_file(configfile, options), vm);
    po::notify(vm);

    configfile.close();

    if (vm.count("help") != 0)
    {
        std::cout << options << std::endl;
        return 1;
    }

    std::string tmp;
    while(std::cin >> tmp)
    {
        text += tmp;
        if(!std::cin.eof())
        {
            text += " ";
        }
    }

    if(vm.count("output") != 0)
    {
        std::ofstream out(vm["output"].as<std::string>());
        std::cout<<text<<std::endl;
        out.close();
    } else {
        std::ofstream out("default.log");
        std::cout<<text<<std::endl;
        out.close();
    }

    return 0;
}
Ejemplo n.º 12
0
void CRBXInput::WriteTranslations()
{
    CConfigFile	configfile( '=' );
    configfile.loadConfig( TRCONFIG );

    std::list<_trpair>::iterator t;
    for( t = translations.begin(); t != translations.end(); t++ )
    {
        configfile.setInt32( GetKeyName( t->key ), t->rc );
    }
    std::cout << "Save config file with translations!" << std::endl;
    configfile.saveConfig( TRCONFIG );
}
Ejemplo n.º 13
0
// ----------------------------------------------------------------------------
void writeServerConfigToDisk()
{
    const std::string& config_xml = getServerConfigXML();
    try
    {
        std::ofstream configfile(g_server_config_path.c_str(),
            std::ofstream::out);
        configfile << config_xml;
        configfile.close();
    }
    catch (std::runtime_error& e)
    {
        Log::error("ServerConfig", "Failed to write server config to %s, "
            "because %s", g_server_config_path.c_str(), e.what());
    }
}   // writeServerConfigToDisk
void QConfigMenu::on_showConfigBtn()
{

    QFile configfile("config.txt");
    if(!configfile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::critical(this, tr("打开提示"), tr("配置文件不存在,请先生成配置文件!"), tr("确定"));
        return;
    }
    QTextStream in(&configfile);

    QString configOutput = in.readAll();

    m_runConfigEdit->setText(configOutput);
    m_runConfigEdit->setWindowModality(Qt::ApplicationModal);
    m_runConfigEdit->show();
    configfile.close();
}
Ejemplo n.º 15
0
bool LtcParams::Load(void) {
	m_tLtcParams.nSetList = 0;

	ReadConfigFile configfile(LtcParams::staticCallbackFunction, this);

	if (configfile.Read(LtcParamsConst::FILE_NAME)) {
		// There is a configuration file
		if (m_pLTcParamsStore != 0) {
			m_pLTcParamsStore->Update(&m_tLtcParams);
		}
	} else if (m_pLTcParamsStore != 0) {
		m_pLTcParamsStore->Copy(&m_tLtcParams);
	} else {
		return false;
	}

	return true;
}
Ejemplo n.º 16
0
InputCatcher::InputCatcher(ALLEGRO_DISPLAY *display)
{
    // Create an event queue, and error if it fails
    event_queue = al_create_event_queue();
    if (!event_queue)
    {
        fprintf(stderr, "Fatal Error: Could not create event queue!");
        throw -1;
    }

    // Connect the window, keyboard and mouse events to this event queue
    al_register_event_source(event_queue, al_get_display_event_source(display));
    al_register_event_source(event_queue, al_get_keyboard_event_source());
//    al_register_event_source(event_queue, al_get_mouse_event_source(display));

    std::ifstream configfile("config.json");
    config << configfile;
    configfile.close();
}
Ejemplo n.º 17
0
/*!
 * \fn bool Write()
 * \return true if everything is allright, false else.
 *
 * This function write configuration file, using a combinaison values already
 * available and default values.
 */
bool ConfigManager::Write()
{
    std::cout << "(function) ConfigManager::Write" << std::endl;            // debug

    // Write config file
    std::ofstream configfile(path, std::ios::out);
    if (!configfile)
    {
        return false;
    }
    else
    {
        //
        std::string fullscreen_temp;
        if (conf_rFullscreen == true)
            fullscreen_temp= "on";
        else
            fullscreen_temp= "off";

        // Edit
        configfile
        << "<?xml version=\"1.0\" encoding=\"ASCII\"?>"
                << "\n<!--  MapMe : configuration  -->"
        << "\n"
        << "\n<configuration>"
        << "\n    <game version=\"" << conf_rameVersion << "\" />"
        << "\n    <resolution resx=\"" << conf_rResx << "\" resy=\"" << conf_rResy << "\" fullscreen=\"" << fullscreen_temp << "\" />"
        << "\n    <language lng=\"" << conf_lLng << "\" />"
        << "\n    <volumes master=\"" << conf_vMaster << "\" music=\"" << conf_vMusic << "\" />"
        << "\n    <network name=\"" << conf_nUser << "\" port=\"" << conf_nPort << "\" />"
        << "\n</configuration>"
        << std::endl;

        // Close file
        configfile.close();

        // Update statut
        return true;
    }
}
Ejemplo n.º 18
0
//************************************************************************************************
// 	cMenu::SettingsMenu
//************************************************************************************************
void cMenu::SettingsMenu(int rc_fd)
{
    CConfigFile configfile('\t');
    configfile.loadConfig(VDRVIEWER_SETTINGS_FILE);
    std::string serverip = configfile.getString("server", "10.10.10.10");
    int    osdport 	 = configfile.getInt32("osdport", 20001);
    int    streamingport = configfile.getInt32("streamingport", 20002);
    

    cMenu Menu("VDR-Viewer Einstellungen");
    //Menu.Add(new cMenuStringItem("Server-Adresse", serverip));
    Menu.Add(new cMenuIntItem("OSD-Port", &osdport, 100, 99999));
    Menu.Add(new cMenuIntItem("Streaming-Port", &streamingport, 100, 99999));
    Menu.Add(new cMenuSeparatorItem());
    EMenuValue RetVal = Menu.Show(rc_fd);
    
    
    configfile.getString("server", serverip);
    configfile.setInt32("osdport", osdport);
    configfile.setInt32("streamingport", streamingport);
    configfile.saveConfig(VDRVIEWER_SETTINGS_FILE);
}
Ejemplo n.º 19
0
//Native RC
void CRBXInput::LoadNativeTranslations()
{
    unsigned int i;
    CConfigFile	configfile( '=' );
    configfile.loadConfig( TRCONFIG );

    //i loop over all defined keys and check wheither there is a defined key value
    for( i = UNKNOWN + 1; i < NOKEY; i++ )
    {
        _trpair tr;
        tr.key = (KEYS)i;
        tr.rc = configfile.getInt32( GetKeyName( (KEYS)i ) );


        if( strcmp( "unknown", CRCInput::getSpecialKeyName( tr.rc ) ) )
        {
            bool flag = true;

            std::list<_trpair>::iterator t;
            for( t = translations.begin(); t != translations.end(); t++ )
            {
                if( t->key == (KEYS)i )
                {
                    flag = false;

                    t->rc = tr.rc;
                    break;
                }
            }

            if( flag )
            {
                translations.push_back( tr );
            }
        }
    }
}
Ejemplo n.º 20
0
bool ArtNet4Params::Load(void) {
	DEBUG_ENTRY

	ArtNetParams::Load();

	m_tArtNet4Params.nSetList = 0;

	ReadConfigFile configfile(ArtNet4Params::staticCallbackFunction, this);

	if (configfile.Read(ArtNetParamsConst::FILE_NAME)) {
		// There is a configuration file
		if (m_pArtNet4ParamsStore != 0) {
			m_pArtNet4ParamsStore->Update(&m_tArtNet4Params);
		}
	} else if (m_pArtNet4ParamsStore != 0) {
		m_pArtNet4ParamsStore->Copy(&m_tArtNet4Params);
	} else {
		DEBUG_EXIT
		return false;
	}

	DEBUG_EXIT
	return true;
}
Ejemplo n.º 21
0
int main(int argc, char*argv[]) {
    // ████████ INITS 1 ████████
#ifndef COMMON_INITS1
    cfg.init("bedlab.cfg");
    ui2::init_ui();
    Vec2i windowsize;
    Vec2i screen_resolution = { int(VideoMode::getDesktopMode().width), int(VideoMode::getDesktopMode().height) };
    if (cfg.getvar<int>("auto_winsize")) {
        auto window_scale = cfg.getvar<Vec2>("window_scale");
        windowsize = Vec2i(scal(Vec2(screen_resolution), window_scale));
    }
    else {
        windowsize = cfg.getvar<Vec2i>("windowsize");
    }
    winsize = Vec2(windowsize);
    //UI.init_console(); // ALWAYS AFTER SO IT CAN GET WINDOW SIZE
    ui2::init_console(); // ALWAYS AFTER SO IT CAN GET WINDOW SIZE

    wincenter = 0.5f*Vec2(windowsize);
    Vec2i windowpos;
    VideoMode::getDesktopMode().height;
    if (cfg.getvar<int>("stick_left")) {
        windowpos = Vec2i(
            screen_resolution.x - windowsize.x - 10,
            screen_resolution.y - windowsize.y - 40
        );
    }
    else
        windowpos = (Vec2i(5, 25));

    sf::RenderWindow window(sf::VideoMode(windowsize.x, windowsize.y),
        "bedlab!", 7
        //,sf::ContextSettings(0, 0, 1)
    );
    window.setFramerateLimit(cfg.getvar<int>("fps_max"));
    frame_duration = 1.0f / cfg.getvar<int>("fps_max");

    window.setPosition(windowpos);

    vector<string> keys;
    auto choice = cfg.getstr("app");
    // show_keys(cfg.getstr("app"), keys);
#endif
// ████████ INITS2 ████████
#ifndef COMMON_INITS2

// we don't have a class/interface/struct with data, everything is local to this function, like a classic stack that all programs are anyway.
// Texture cursor_tx;
// if (!cursor_tx.loadFromFile(cfg.getstr("cursor")))
//     cout << "did not load cursor" << endl;
// Sprite cursor;
// cursor.setTexture(cursor_tx);
// cursor.setOrigin(3, 3);

    CircleShape cursor = mkcircle({ 0,0 }, Color::Transparent, 3, 1);
    Color background = cfg.getvar<Color>("background");
    window.setMouseCursorVisible(false);
    Vec2 mpos;
    bool leftclicked = false, rightclicked = false;

    // view and zoom
    View view, ui_view;
    ui_view = view = window.getDefaultView();
    float zoomlevel = 1;
    Vec2 mpos_abs;
    float frame_duration = 1.0f / cfg.getvar<int>("fps_max");
#endif // COMMON_INITS2
    // ████████ APP ACTUAL ████████

    float smaller_size = min(windowsize.y, windowsize.x);
    string descriptor;

    Transform transf;
    transf.translate(10, 10);
    transf.scale(Vec2(smaller_size, smaller_size));

    transf_glob = transf;

    auto addvt_col = [&](Vec2 v, Color col) {
        glob_vert_single.append(Vertex(transf.transformPoint(v), col));
    };

    auto va_to_va_col = [&](mesh2d&idxd_v, Color col) {
        for (unsigned int i = 0; i < idxd_v.size(); ++i)
        {
            // if (i<)
            addvt_col(idxd_v[i].first, col);
            addvt_col(idxd_v[i].second, col);

            //addpt(idxd_v[i].first, Orange, 5);
            //addpt(idxd_v[i].second, Cyan, 5);
        }

        for (auto&a : idxd_v.verts) {
            addpt_col(a, col, 2);
        }
    };
    auto stripify = [&](vector<Vec2> strip, Color col) {
        glob_vert_single = VertexArray(LineStrip);

        for (auto&a : strip) {
            glob_vert_single.append(Vertex(transf.transformPoint(a), col));
            addpt_col(a, col, 2);
        }

    };

    size_t edit_mode = 1;
    // ████████████████████████████████████████
    sf::Sound sound;

    auto make_segment = [](int size, int amplitude) {
        vector<Int16> sample;

        for (int i = 0; i < size; ++i)
        {
            sample.push_back(amplitude*sin(float(i)*PI*2.0f));
        }
        return sample;
    };

    /*
    <Jonny> duration will be sample count * sample rate
    <Jonny> so at 44khz you'll have 44k samples per second
    <Jonny> if you have 88k samples that will last 2 second
    */

    plot_bare pl;
    
    float sample_rate = 22050;

    auto make_tone = [&](float duration, float frequency, int amplitude_exp) {
        float sample_quantity = sample_rate * duration;
        vector<Int16> sample;
        int amplitude = 1 << amplitude_exp;
        float increment = frequency / sample_rate;
        float x = 0;
        for (int i = 0; i < sample_quantity; ++i){
            sample.push_back(amplitude*sin(float(x)*PI*2.0f));
            x += increment;
        }
        return sample;
    };
    // http://sol.gfxile.net/interpolation/

    auto make_tone_progressive_2 = [&](float duration, float frequency, int amplitude_exp) {
        float sample_quantity = sample_rate * duration;
        vector<Int16> sample;
        int amplitude = 1 << amplitude_exp;
        float increment = frequency / sample_rate;
        float x = 0;
        for (int i = 0; i < sample_quantity; ++i) {
            float soft = float(i) / sample_quantity;
            //soft = 1 - (1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft);
            soft = 1 - (1 - 2 * soft)*(1 - 2 * soft);
            soft *= amplitude;

            sample.push_back(soft*sin(float(x)*PI*2.0f));
            x += increment;
        }
        return sample;

    };
    auto make_tone_progressive_4 = [&](float duration, float frequency, int amplitude_exp) {
        float sample_quantity = sample_rate * duration;
        vector<Int16> sample;
        int amplitude = 1 << amplitude_exp;
        float increment = frequency / sample_rate;
        float x = 0;
        for (int i = 0; i < sample_quantity; ++i) {
            float soft = float(i) / sample_quantity;
            soft = 1 - (1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft);
            soft *= amplitude;

            sample.push_back(soft*sin(float(x)*PI*2.0f));
            x += increment;
        }
        return sample;

    };
    auto make_tone_progressive_6 = [&](float duration, float frequency, int amplitude_exp) {
        float sample_quantity = sample_rate * duration;
        vector<Int16> sample;
        int amplitude = 1 << amplitude_exp;
        float increment = frequency / sample_rate;
        float x = 0;
        for (int i = 0; i < sample_quantity; ++i) {
            float soft = float(i) / sample_quantity;
            soft = 1 - (1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft);
            soft *= amplitude;

            sample.push_back(soft*sin(float(x)*PI*2.0f));
            x += increment;
        }
        return sample;

    };


    auto sample_string2 = cfg.getstr("sound1");
    auto spl1 = splitdelim(sample_string2, ',');
    auto params2 = splitdelim(spl1[0]);
    //float freq = parse<float>(params[1]);
    //float duration = parse<float>(params[2]);
    //float amplitude_exp = parse<float>(params[3]);

    float freq,  duration, amplitude_exp, pause;
    int times, smoothstep_exp;
    dip_bars dbars(FONT, FONTSIZE, {400,20});
    //dbars.add("sampling", &sampling,5, 10000);
    dbars.add("sample_rate", &sample_rate, 1000, 45000);
    dbars.add("freq", &freq,50,5000);
    dbars.add("duration", &duration, 0.5, 5);
    dbars.add("amplitude_exp", &amplitude_exp, 1, 14);
    SoundBuffer buffer; // always lived!
    auto load_sample2 = [&](){
        auto delaystr = splitdelim(spl1[1]);
        vector<float> segment_sizes;
        float total = 0;
        for (auto&a : delaystr) {
            total += parse<float>(a);
            segment_sizes.push_back(parse<float>(a));
        }
        int i = 0;
        vector<Int16> sample;
        vector<vector<Int16>> samples;

        for (auto&a : segment_sizes) a /= total;
        //for (auto&a : segment_sizes) msg(a*total);
        for (auto&a : segment_sizes){
            auto scaled_back = duration * freq * a;

            int amplitude = i % 2 ? 0 : 1 << int(amplitude_exp);
            msg(scaled_back);
            samples.push_back(make_segment(scaled_back, amplitude));
            ++i;
        }
        for (auto&a : samples){
            concatenate(sample, a);
        }
        SoundBuffer buffer;
        // \param sampleRate   Sample rate (number of samples to play per second)

        buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size()/duration);
        {
            // plut josting just plotting
            vector<Vec2> plot_this;
            int i = 0;

            for (auto&a : sample) {
                //plot_this.push_back({ float(i), 200 * float(a) / (1 << 12) });
                plot_this.push_back({ float(i), float(a) });
                i++;
            }
            pl.clear();
            pl.from_data_normalized(plot_this);
        }

        return buffer;
    };
    auto load_sample = [&]() {
        auto delaystr = splitdelim(spl1[1]);
        vector<float> segment_sizes;
        float total = 0;
        for (auto&a : delaystr) {
            total += parse<float>(a);
            segment_sizes.push_back(parse<float>(a));
        }
        int i = 0;
        vector<Int16> sample;
        vector<vector<Int16>> samples;

        for (auto&a : segment_sizes) a /= total;
        //for (auto&a : segment_sizes) msg(a*total);
        if (smoothstep_exp == 2) {
            for (auto&a : segment_sizes) {
                samples.push_back(make_tone_progressive_2(duration*a, freq, i % 2 ? 0 : int(amplitude_exp)));
                ++i;
            }
       
        }
        else if (smoothstep_exp == 4){
            for (auto&a : segment_sizes) {
                samples.push_back(make_tone_progressive_4(duration*a, freq, i % 2 ? 0 : int(amplitude_exp)));
                ++i;
            }
        }


        for (auto&a : samples) {
            concatenate(sample, a);
        }
        SoundBuffer buffer;
        // \param sampleRate   Sample rate (number of samples to play per second)
        //sample = make_tone(2, 400, 8);
        //buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size() / duration);
        buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size() / duration);
        if (true) {
            // plut josting just plotting
            vector<Vec2> plot_this;
            int i = 0;

            for (auto&a : sample) {
                //plot_this.push_back({ float(i), 200 * float(a) / (1 << 12) });
                plot_this.push_back({ float(i), float(a) });
                i++;
            }
            pl.clear();
            pl.from_data_normalized(plot_this);
        }

        return buffer;
    };
    
    auto load_from_cfg = [
        &freq,
        &duration,
        &amplitude_exp,
        &pause,
        &times,
        &descriptor,
        &smoothstep_exp]() {
        auto temp_cfg = configfile();
        temp_cfg.init("bedlab.cfg");
        auto sample_string = temp_cfg.getstr("sound2");

        auto things = split2(sample_string, ",");
        auto params = split2(things[0], " ");
        auto segments = split2(things[1], " ");

        string segments_dashed = things[1];

        if (segments_dashed[0] == ' ') segments_dashed = segments_dashed.substr(1);
        if (things[1][0] == ' ') things[1] = things[1].substr(1);
        if (things[2][0] == ' ') things[2] = things[2].substr(1);
        if (things[3][0] == ' ') things[3] = things[3].substr(1);
        if (things[4][0] == ' ') things[4] = things[4].substr(1);
        
        for (auto&c : segments_dashed) {
            if (c == ' ') c = '-';
        }
        
        freq = parse<float>(params[0]);
        duration = parse<float>(params[1]);
        amplitude_exp = parse<float>(params[2]);
        pause = parse<float>(things[2]);
        times = parse<int>(things[3]);
        smoothstep_exp = parse<int>(things[4]);
        msgs(smoothstep_exp);
        descriptor =
            params[0]         // freq
            + "_" + params[1] // duration
            + "_" + params[2] // amplitude_exp
            + "_" + segments_dashed
            + "_" + things[2] // pause
            + "_" + things[3] // times
            + "_" + things[4] // smoothstep_exp
            ;
        msgs(descriptor);
        return segments;
    };
    auto segments = load_from_cfg();

    auto flexible_expanse = [&]() {
        vector<float> segment_sizes, segment_concat;
        for (auto&a : segments) {
            segment_sizes.push_back(parse<float>(a));
        }
        segment_sizes.push_back(pause);

        for (int i = 0; i < times; ++i) {
            concatenate(segment_concat, segment_sizes);
        }
        float total = 0;
        for (auto&a : segment_concat) total+=a;
        for (auto&a : segment_concat) a /= total;

        vector<vector<Int16>> samples;
        int i = 0;
        if (smoothstep_exp == 2) {
            for (auto&a : segment_concat) {
                samples.push_back(make_tone_progressive_2(duration*a, freq, i % 2 ? 0 : int(amplitude_exp)));
                ++i;
            }
        }
        else if (smoothstep_exp == 4) {
            for (auto&a : segment_concat) {
                samples.push_back(make_tone_progressive_4(duration*a, freq, i % 2 ? 0 : int(amplitude_exp)));
                ++i;
            }
        }
        else if (smoothstep_exp == 6) {
            for (auto&a : segment_concat) {
                samples.push_back(make_tone_progressive_6(duration*a, freq, i % 2 ? 0 : int(amplitude_exp)));
                ++i;
            }
        }
        vector<Int16> sample;

        for (auto&a : samples) { concatenate(sample, a); }
        SoundBuffer buffer;

        //buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size() / duration);
        buffer.loadFromSamples(&sample[0], sample.size(), 1, sample_rate);
        if (true) {
            // plut josting just plotting
            vector<Vec2> plot_this;
            int i = 0;

            for (auto&a : sample) {
                //plot_this.push_back({ float(i), 200 * float(a) / (1 << 12) });
                plot_this.push_back({ float(i), float(a) });
                i++;
            }
            pl.clear();
            pl.from_data_normalized(plot_this);
        }
        return buffer;
    };

    //buffer = load_sample(sample_string);
    auto make_sound = [&]() {
        //buffer = load_sample();
        segments = load_from_cfg();
        buffer = flexible_expanse();

        sound.setBuffer(buffer);
        string filename = "rngtn_" + descriptor+".wav";
        //buffer.saveToFile("file.wav");
        buffer.saveToFile(filename);
        sound.play();
    };

    make_sound();
    dbars.read_from_pointers();


    // ████████ callbacks ████████

#ifndef LOOP_LAMBDAS
    draw = [&]() {
        window.setView(view);
        //////////////// OBJECTS THAT CAN ZOOMED ////////////////
        window.draw(glob_vert_single);
        for (auto&a : glob_pts)window.draw(a);
        for (auto&a : glob_rects)window.draw(a);
        for (auto&a : glob_vert)window.draw(a);
        for (auto&a : glob_texts)window.draw(a);
        // UI draw, AFTER ui view and BEFORE other draw
        window.setView(ui_view);
        //////////////// OBJECTS THAT CANNOT ZOOMED, MEANING UI ////////////////
        pl.draw(window);
        dbars.draw(window);

        //br.drawwithtext(window);
        UI.draw(window);
        window.draw(cursor);
    };
    update = [&]() {
    };
    treatkeyevent = [&](Keyboard::Key k) {
        switch (k)
        {
        case Keyboard::E:
            break;
        case Keyboard::I:

            break;
        case Keyboard::Q:
            break;
        case Keyboard::BackSpace:
            glob_pts.clear();
            glob_texts.clear();
            glob_rects.clear();
            glob_vert.clear();
            break;

        case Keyboard::Space:
            make_sound();
            sound.play();
            sound.setLoop(false);
            break;

        case Keyboard::S:
            screenshot(window);
            break;
        case Keyboard::Num1:
        case Keyboard::Num2:
        case Keyboard::Num3:
        case Keyboard::Num4:
        case Keyboard::Num5:
            break;
        }
    };
    mousemoved = [&](Vec2 pos) {
        cursor.setPosition(pos);
        if (leftclicked);

        dbars.mouse_moved(pos);
    };
    mouseclick = [&](sf::Mouse::Button button) {
        if (button == Mouse::Button::Left) leftclicked = true;
        if (button == Mouse::Button::Right) rightclicked = true;
    
        if (button == Mouse::Button::Left) dbars.mouse_click(mpos);

    
    };
    mouserelease = [&](sf::Mouse::Button button) {
        if (button == Mouse::Button::Left) leftclicked = false;
        if (button == Mouse::Button::Right) rightclicked = false;

        if (button == Mouse::Button::Left) { 
            dbars.mouse_release(); 
            make_sound();

        }

    };
    loop = [&]() {
        while (window.isOpen())
        {
            sf::Event event;
            while (window.pollEvent(event))
            {
                switch (event.type)
                {
                case sf::Event::KeyPressed:
                    if (event.key.code == sf::Keyboard::Escape)
                        window.close();
                    treatkeyevent(event.key.code);
                    break;
                case sf::Event::Closed:
                    window.close();
                    break;
                case sf::Event::MouseButtonPressed:
                    mouseclick(event.mouseButton.button);
                    break;
                case sf::Event::MouseButtonReleased:
                    mouserelease(event.mouseButton.button);
                    break;
                case sf::Event::MouseMoved:
                    mpos = Vec2(event.mouseMove.x, event.mouseMove.y);
                    mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view);
                    mousemoved(mpos);
                    break;
                default:
                    treatotherevent(event);
                    break;
                }
            }

            window.clear(background);
            update();
            draw();
            window.display();
        }
    };
    treatotherevent = [&](Event&e) {
        if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta)
        {
            mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view);

            //view = window.getView();
            if (e.mouseWheel.delta < 0)
            {
                zoomlevel *= 2.f;
                view.setSize(view.getSize()*2.f);
                view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
                //view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
            }
            if (e.mouseWheel.delta > 0)
            {
                zoomlevel *= 0.5;
                view.setSize(view.getSize()*.5f);
                view.setCenter(.5f*(view.getCenter() + mpos_abs));
                //view.setCenter(.5f*(view.getCenter() + mpos_abs));
            }
            window.setView(view);
        }
    };
#endif // LOOP_LAMBDAS

    loop();
}
Ejemplo n.º 22
0
void SparkFunDmx::ReadConfigFiles(void) {
	DEBUG_ENTRY;

	m_bIsSpiCsSet = false;
	m_bIsResetSet = false;
	m_bIsBusyPinSet = false;

	ReadConfigFile configfile(SparkFunDmx::staticCallbackFunction, this);

	if (configfile.Read("sparkfun.txt")) {
#ifndef NDEBUG
		printf("\'sparkfun.txt\' (global settings):\n");

		if (m_bIsSpiCsSet) {
			printf("\tSPI CS : %d\n", m_nSpiCs);
		}

		if (m_bIsResetSet) {
			printf("\tReset pin: %d\n", m_nResetPin);
		}

		if (m_bIsBusyPinSet) {
			printf("\tBusy pin: %d\n", m_nBusyPin);
		}
#endif
	}

	if (!m_bIsResetSet) {
		m_nResetPin = GPIO_RESET_OUT;
		m_bIsResetSet = true;
#ifndef NDEBUG
		printf("\tReset pin: %d\n", m_nResetPin);
#endif
	}

	if (m_bIsBusyPinSet) {
		bcm2835_gpio_fsel(m_nBusyPin, BCM2835_GPIO_FSEL_INPT);
	}

	bcm2835_gpio_fsel(m_nResetPin, BCM2835_GPIO_FSEL_OUTP);
	bcm2835_gpio_set(m_nResetPin);

	bcm2835_gpio_clr(m_nResetPin);
	udelay(10000);
	bcm2835_gpio_set(m_nResetPin);
	udelay(10000);

	bcm2835_spi_begin();

	char fileName[] = "motor%.txt";

	for (int i = 0; i < SPARKFUN_DMX_MAX_MOTORS; i++) {

		fileName[5] = (char) i + '0';

		m_bIsPositionSet = false;

		if (configfile.Read(fileName)) {
#ifndef NDEBUG
			printf("Motor %d:\n", i);
#endif
			if (m_bIsPositionSet && m_bIsSpiCsSet) {
#ifndef NDEBUG
				printf("\t%s=%d\n", SPARKFUN_PARAMS_POSITION, m_nPosition);
				printf("\t%s=%d\n", SPARKFUN_PARAMS_SPI_CS, m_nSpiCs);
				printf("\t%s=%d\n", SPARKFUN_PARAMS_RESET_PIN, m_nResetPin);
				if(m_bIsBusyPinSet) {
					printf("\t%s=%d\n", SPARKFUN_PARAMS_BUSY_PIN, m_nBusyPin);
				}
				printf("\t-----------------------------\n");
				printf("\t%s=%d (DMX footprint=%d)\n", PARAMS_DMX_MODE, m_nDmxMode, L6470DmxModes::GetDmxFootPrintMode(m_nDmxMode));
				printf("\t%s=%d\n", PARAMS_DMX_START_ADDRESS, m_nDmxStartAddressMode);
				printf("\t=============================\n");
#endif
				if ((m_nDmxStartAddressMode <= DMX_MAX_CHANNELS) && (L6470DmxModes::GetDmxFootPrintMode(m_nDmxMode) != 0)) {

					if (m_bIsBusyPinSet) {
						m_pAutoDriver[i] = new AutoDriver(m_nPosition, m_nSpiCs, m_nResetPin, m_nBusyPin);
					} else {
						m_pAutoDriver[i] = new AutoDriver(m_nPosition, m_nSpiCs, m_nResetPin);
					}

					assert(m_pAutoDriver[i] != 0);

					if (m_pAutoDriver[i] != 0) {
						if (m_pAutoDriver[i]->IsConnected()) {
							m_pAutoDriver[i]->setMotorNumber(i);
							m_pAutoDriver[i]->Dump();

							m_pMotorParams[i] = new MotorParams(fileName);
							assert(m_pMotorParams[i] != 0);
							m_pMotorParams[i]->Dump();
							m_pMotorParams[i]->Set(m_pAutoDriver[i]);

							L6470Params l6470Params(fileName);
							l6470Params.Dump();
							l6470Params.Set(m_pAutoDriver[i]);

							m_pAutoDriver[i]->Dump();

							m_pModeParams[i] = new ModeParams(fileName);
							assert(m_pModeParams[i] != 0);
							m_pModeParams[i]->Dump();

							m_pL6470DmxModes[i] = new L6470DmxModes((TL6470DmxModes) m_nDmxMode, m_nDmxStartAddressMode, m_pAutoDriver[i], m_pMotorParams[i], m_pModeParams[i]);
							assert(m_pL6470DmxModes[i] != 0);

							if (m_pL6470DmxModes[i] != 0) {
								if (m_nDmxStartAddress == DMX_ADDRESS_INVALID) {
									m_nDmxStartAddress = m_pL6470DmxModes[i]->GetDmxStartAddress();
									m_nDmxFootprint = m_pL6470DmxModes[i]->GetDmxFootPrint();
								} else {
									const uint16_t nDmxChannelLastCurrent = m_nDmxStartAddress + m_nDmxFootprint;
									m_nDmxStartAddress = MIN(m_nDmxStartAddress, m_pL6470DmxModes[i]->GetDmxStartAddress());

									const uint16_t nDmxChannelLastNew = m_nDmxStartAddressMode + m_pL6470DmxModes[i]->GetDmxFootPrint();
									m_nDmxFootprint = MAX(nDmxChannelLastCurrent, nDmxChannelLastNew) - m_nDmxStartAddress;
								}
#ifndef NDEBUG
								printf("DMX Mode: %d, DMX Start Address: %d\n", m_pL6470DmxModes[i]->GetMode(), m_pL6470DmxModes[i]->GetDmxStartAddress());
								printf("DMX Start Address:%d, DMX Footprint:%d\n", (int) m_nDmxStartAddress, (int) m_nDmxFootprint);
#endif
							}
						} else {
							delete m_pAutoDriver[i];
							m_pAutoDriver[i] = 0;
							printf("Communication issues; check SPI configuration and cables\n");
						}
					} else {
						printf("Internal error!\n");
					}
				}
			} else {
				if(!m_bIsPositionSet) {
					printf("Missing %s=\n", SPARKFUN_PARAMS_POSITION);
				}
				if(!m_bIsSpiCsSet) {
					printf("Missing %s=\n", SPARKFUN_PARAMS_SPI_CS);
				}
			}
#ifndef NDEBUG
			printf("Motor %d: --------- end ---------\n", i);
#endif
		} else {
#ifndef NDEBUG
			printf("Configuration file : %s not found\n", fileName);
#endif
		}
	}

	for (int i = 0; i < SPARKFUN_DMX_MAX_MOTORS; i++) {
		if (m_pL6470DmxModes[i] != 0) {
			m_pL6470DmxModes[i]->InitSwitch();
		}
	}

	for (int i = 0; i < SPARKFUN_DMX_MAX_MOTORS; i++) {
		if (m_pAutoDriver[i] != 0) {
			while (m_pAutoDriver[i]->busyCheck())
				;
		}
	}

	for (int i = 0; i < SPARKFUN_DMX_MAX_MOTORS; i++) {
		if (m_pL6470DmxModes[i] != 0) {
			m_pL6470DmxModes[i]->InitPos();
		}
	}

#ifndef NDEBUG
	printf("Motors connected : %d\n", (int) AutoDriver::getNumBoards());
#endif
	DEBUG_EXIT;
}
Ejemplo n.º 23
0
void runGRJETSv11(TString mode       = "lite",            // local, lite, or cluster
               TString identifier = "run1",               // tag 
               TString dataset    = "Wprime1200.GRJETSv11",  // dataset name as in the fileList  
               TString username   = "******",           // username (e.g. swiatlow, fizisist)
               bool mcweights     = false,                 // use mc weights?
               bool doHists       = true,                 // do histograms or enable dataset mode 
               bool doSys         = false,                // do systematics 
               bool debug         = false,                // turn on debugging
               int  nWorkers      = 4                     //specify number of workers for proof(-1 for all available)
             ) 
{
    
    ///----------------------------------------------------------------
    /// Load libraries , set the config file, treenam, and cluster info
    ///----------------------------------------------------------------

    TString gridusername = "******";
    cout << "trying to load libraries" << endl;
    loadLibraries();

    cout << " Libraries loaded " << endl;

    // SetConfig
    TString configfile("../config/grjetsv11.config");

    // Change if defaulting to wrong TTree, otherwise leave
    TString treename("jets");
    
    // Best to leave alone  
    TString pathLite("");

    TString pathCluster("root://atlprf01.slac.stanford.edu:2094//atlas/output/");

    pathCluster.Append(username);
    pathCluster.Append("/");



    // Determine eventbuilder from dataset name
    TString eventbuilder(dataset);
    eventbuilder.Remove(0,eventbuilder.Last('.')+1);
    
    ///----------------------------------------------------------------
    /// Filename paths, URLs for PROOF running
    ///----------------------------------------------------------------
    TString url(mode);
    TString path("");
    if (mode.CompareTo("lite")==0) {
        url = "lite://";
        path = pathLite;
    }
    else if(mode.CompareTo("cluster")==0) {
      url = TString(username+"@atlprf01.slac.stanford.edu");
      path = pathCluster;
    }
    // Make an options file, edit as needed
    TFile* options = new TFile("options.root","RECREATE");

    ///----------------------------------------------------------------
    /// Overall Configuration
    ///----------------------------------------------------------------
    bool doPRW           = false;
    bool doBasic         = true;
    bool doTruthLinks    = false;
    bool doTrackJetLinks = true;
    bool doTruthJetLinks = true;
    bool doJetStructure  = true;
    bool doConstituents  = true;
    bool doTruthConstit  = true;
    bool doParentChild   = true;
    bool doTrack         = true;
    bool doLCCluster     = true;
    bool doEMCluster     = false;
    bool doTruth         = true;
    bool doVertex        = true;
    bool doPhotons       = false;
    
    /// JET TYPES
    bool doSomeJetTypes  = false;
    bool doMinJetTypes   = true;
    
    /// SELECTIONS
    float minJetPt       =  20.000;
    float maxJetEta      =   3.199;
    float minFatJetPt    = 100.000;
    float minJetJVF      =   0.750;
    float maxJetTrkDR    =   0.300;
    float maxJetTruthDR  =   0.300;
    TString badJetType   = "AntiKt4LCTopoAOD";
    TString badJetDef    = "isBadLooseMinus";
    
    /// Substructure
    int   nStdJetCut     = 4;
    float lowMassCRcut   = 100.000;
    float threeBodyCRcut =   0.700;
    
    ///----------------------------------------------------------------
    /// Jet types
    ///----------------------------------------------------------------
    
    TString aktCal = "AntiKt10LCTopo";
    TString aktTrk = "AntiKt10TrackZ";
    TString aktTru = "AntiKt10Truth";
    TString caCal  = "CamKt12LCTopo";
    TString caTrk  = "CamKt12TrackZ";
    TString caTru  = "CamKt12Truth";
    
    TString aktCalTrim = "AntiKt10LCTopoTrimmedPtFrac1SmallR20,AntiKt10LCTopoTrimmedPtFrac3SmallR20,AntiKt10LCTopoTrimmedPtFrac5SmallR20,AntiKt10LCTopoTrimmedPtFrac1SmallR30,AntiKt10LCTopoTrimmedPtFrac3SmallR30,AntiKt10LCTopoTrimmedPtFrac5SmallR30";
    TString aktCalPrun = "AntiKt10LCTopoPrunedKtRcutFactor10Zcut5,AntiKt10LCTopoPrunedKtRcutFactor20Zcut5,AntiKt10LCTopoPrunedKtRcutFactor30Zcut5,AntiKt10LCTopoPrunedKtRcutFactor10Zcut10,AntiKt10LCTopoPrunedKtRcutFactor20Zcut10,AntiKt10LCTopoPrunedKtRcutFactor30Zcut10";
    TString aktTrkTrim = "AntiKt10TrackZTrimmedPtFrac1SmallR20,AntiKt10TrackZTrimmedPtFrac3SmallR20,AntiKt10TrackZTrimmedPtFrac5SmallR20,AntiKt10TrackZTrimmedPtFrac1SmallR30,AntiKt10TrackZTrimmedPtFrac3SmallR30,AntiKt10TrackZTrimmedPtFrac5SmallR30";
    TString aktTrkPrun = "AntiKt10TrackZPrunedKtRcutFactor10Zcut5,AntiKt10TrackZPrunedKtRcutFactor20Zcut5,AntiKt10TrackZPrunedKtRcutFactor30Zcut5,AntiKt10TrackZPrunedKtRcutFactor10Zcut10,AntiKt10TrackZPrunedKtRcutFactor20Zcut10,AntiKt10TrackZPrunedKtRcutFactor30Zcut10";
    TString aktTruTrim = "AntiKt10TruthTrimmedPtFrac1SmallR20,AntiKt10TruthTrimmedPtFrac3SmallR20,AntiKt10TruthTrimmedPtFrac5SmallR20,AntiKt10TruthTrimmedPtFrac1SmallR30,AntiKt10TruthTrimmedPtFrac3SmallR30,AntiKt10TruthTrimmedPtFrac5SmallR30";
    TString aktTruPrun = "AntiKt10TruthPrunedKtRcutFactor10Zcut5,AntiKt10TruthPrunedKtRcutFactor20Zcut5,AntiKt10TruthPrunedKtRcutFactor30Zcut5,AntiKt10TruthPrunedKtRcutFactor10Zcut10,AntiKt10TruthPrunedKtRcutFactor20Zcut10,AntiKt10TruthPrunedKtRcutFactor30Zcut10";
    
    TString caCalTrim  = "CamKt12LCTopoTrimmedPtFrac1SmallR20,CamKt12LCTopoTrimmedPtFrac3SmallR20,CamKt12LCTopoTrimmedPtFrac5SmallR20,CamKt12LCTopoTrimmedPtFrac1SmallR30,CamKt12LCTopoTrimmedPtFrac3SmallR30,CamKt12LCTopoTrimmedPtFrac5SmallR30";
    TString caCalPrun  = "CamKt12LCTopoPrunedKtRcutFactor10Zcut5,CamKt12LCTopoPrunedKtRcutFactor20Zcut5,CamKt12LCTopoPrunedKtRcutFactor30Zcut5,CamKt12LCTopoPrunedKtRcutFactor10Zcut10,CamKt12LCTopoPrunedKtRcutFactor20Zcut10,CamKt12LCTopoPrunedKtRcutFactor30Zcut10";
    TString caCalFilt  = "CamKt12LCTopoSplitFilteredmassFraction20minSplitR0,CamKt12LCTopoSplitFilteredmassFraction33minSplitR0,CamKt12LCTopoSplitFilteredmassFraction67minSplitR0";
    TString caTrkTrim  = "CamKt12TrackZTrimmedPtFrac1SmallR20,CamKt12TrackZTrimmedPtFrac3SmallR20,CamKt12TrackZTrimmedPtFrac5SmallR20,CamKt12TrackZTrimmedPtFrac1SmallR30,CamKt12TrackZTrimmedPtFrac3SmallR30,CamKt12TrackZTrimmedPtFrac5SmallR30";
    TString caTrkPrun  = "CamKt12TrackZPrunedKtRcutFactor10Zcut5,CamKt12TrackZPrunedKtRcutFactor20Zcut5,CamKt12TrackZPrunedKtRcutFactor30Zcut5,CamKt12TrackZPrunedKtRcutFactor10Zcut10,CamKt12TrackZPrunedKtRcutFactor20Zcut10,CamKt12TrackZPrunedKtRcutFactor30Zcut10";
    TString caTrkFilt  = "CamKt12TrackZSplitFilteredmassFraction20minSplitR0,CamKt12TrackZSplitFilteredmassFraction33minSplitR0,CamKt12TrackZSplitFilteredmassFraction67minSplitR0";
    TString caTruTrim  = "CamKt12TruthTrimmedPtFrac1SmallR20,CamKt12TruthTrimmedPtFrac3SmallR20,CamKt12TruthTrimmedPtFrac5SmallR20,CamKt12TruthTrimmedPtFrac1SmallR30,CamKt12TruthTrimmedPtFrac3SmallR30,CamKt12TruthTrimmedPtFrac5SmallR30";
    TString caTruPrun  = "CamKt12TruthPrunedKtRcutFactor10Zcut5,CamKt12TruthPrunedKtRcutFactor20Zcut5,CamKt12TruthPrunedKtRcutFactor30Zcut5,CamKt12TruthPrunedKtRcutFactor10Zcut10,CamKt12TruthPrunedKtRcutFactor20Zcut10,CamKt12TruthPrunedKtRcutFactor30Zcut10";
    TString caTruFilt  = "CamKt12TruthSplitFilteredmassFraction20minSplitR0,CamKt12TruthSplitFilteredmassFraction33minSplitR0,CamKt12TruthSplitFilteredmassFraction67minSplitR0";
    
    
    //// Make derived lists
    TString aktData = aktCal + "," + aktTrk + "," + aktCalTrim + "," + aktCalPrun + "," + aktTrkTrim + "," + aktTrkPrun;
    TString aktMC   = aktTru + "," + aktTruTrim + "," + aktTruPrun;
    
    TString caData = caCal + "," + caTrk + "," + caCalTrim + "," + caCalPrun + "," + caCalFilt + "," + caTrkTrim + "," + caTrkPrun + "," + caTrkFilt;
    TString caMC   = caTru + "," + caTruTrim + "," + caTruPrun + "," + caTruFilt;
    
    
    //// DEFAULT FULL LIST
    TString jetTypes = aktData + "," + caData;
    if (!dataset.Contains("data")) jetTypes += "," + aktMC + "," + caMC;

    //// REDUCED SET OF JETS
    if (doSomeJetTypes) {
      jetTypes   = "AntiKt10LCTopo,CamKt12LCTopo,AntiKt10LCTopoTrimmedPtFrac3SmallR30,AntiKt10LCTopoTrimmedPtFrac5SmallR30,CamKt12LCTopoSplitFilteredmassFraction67minSplitR0,AntiKt10TrackZ,CamKt12TrackZ,AntiKt10TrackZTrimmedPtFrac3SmallR30,AntiKt10TrackZTrimmedPtFrac5SmallR30,CamKt12TrackZSplitFilteredmassFraction67minSplitR0";
        if (!dataset.Contains("data")) jetTypes += ",AntiKt10Truth,CamKt12Truth,AntiKt10TruthTrimmedPtFrac3SmallR30,AntiKt10TruthTrimmedPtFrac5SmallR30,CamKt12TruthSplitFilteredmassFraction67minSplitR0";
    }
    
    else if (!doSomeJetTypes && doMinJetTypes) {
      jetTypes   = "AntiKt10LCTopo,CamKt12LCTopo,AntiKt10LCTopoTrimmedPtFrac5SmallR30,CamKt12LCTopoSplitFilteredmassFraction67minSplitR0,AntiKt10TrackZ,CamKt12TrackZ,AntiKt10TrackZTrimmedPtFrac5SmallR30,CamKt12TrackZSplitFilteredmassFraction67minSplitR0";
        if (!dataset.Contains("data")) jetTypes += ",AntiKt10Truth,CamKt12Truth,AntiKt10TruthTrimmedPtFrac5SmallR30,CamKt12TruthSplitFilteredmassFraction67minSplitR0";
    }
        
    //jetTypes = aktCal + "," + aktTrk + "," + aktCalTrim + "," + aktTrkTrim;
    //jetTypes = caCal + "," + caTrk + "," + caCalTrim + "," + caTrkTrim;
    //jetTypes = aktCalPrun + "," + aktTrkPrun + "," + caCalPrun + "," + caTrkPrun;
    //jetTypes = caCalFilt + "," + caTrkFilt;
  
    
    // Be careful when loading up subjettypes and btagtypes: check that 
    // these exist in the D3PD before trying to register them!
    TString subjetTypes = "AntiKt10LCTopoTrimmedSubjetsPtFrac3SmallR30,AntiKt10TrackZTrimmedSubjetsPtFrac3SmallR30,AntiKt10TruthTrimmedSubjetsPtFrac3SmallR30";
    TString btagTypes = "AntiKt10LCTopoTrimmedSubjetsPtFrac3SmallR30";


    ///---------------------------------------------------------------
    /// New jet types! These will be constructed on the fly
    ///---------------------------------------------------------------

    TString baseCustomTrimming = "AntiKtLCTopo15";
    TString ptFracCustomTrimming = "0.05";
    TString smallRCustomTrimming = "0.3";


    ///----------------------------------------------------------------
    /// Nominal Configuration
    ///----------------------------------------------------------------
    Config* chain = new Config("chain",configfile);
    chain->AddVec("ANALYSIS");


    Config* setup = new Config("setup", configfile);
    setup->Set("ANALYSIS","GRJETSexample_setup");
    setup->Set("DEBUG",debug);
    chain->Add("ANALYSIS",setup);

    Config* example = new Config("example", configfile);
    example->Set("ANALYSIS","GRJETSexample");
    example->Set("DEBUG",debug);
    chain->Add("ANALYSIS",example);
    

    cout << endl << "+++ Using jet types: " << jetTypes << endl << endl;


    chain->Set("MCWEIGHTS"       , mcweights       );
    chain->Set("DEBUG"           , debug           );
    chain->Set("PILE"            , doPRW           );
    chain->Set("DOBASIC"         , doBasic         );
    chain->Set("DOTRUTHLINKS"    , doTruthLinks    );
    chain->Set("DOTRACKJETLINKS" , doTrackJetLinks );
    chain->Set("DOTRUTHJETLINKS" , doTruthJetLinks );
    chain->Set("DOJETSTRUCT"     , doJetStructure  );
    chain->Set("DOCONSTIT"       , doConstituents  );
    chain->Set("DOTRUTHCONSTIT"  , doTruthConstit  );
    chain->Set("DOPARENTCHILD"   , doParentChild   );
    chain->Set("DOTRACK"         , doTrack         );
    chain->Set("DOLCCLUSTER"     , doLCCluster     );
    chain->Set("DOEMCLUSTER"     , doEMCluster     );
    chain->Set("DOTRUTH"         , doTruth         );
    chain->Set("DOVTX"           , doVertex        );
    chain->Set("DOPHOTON"        , doPhotons       );
    
    /// Set Systematics
    chain->Set("DOTRACKSYST"     , false           );
    chain->Set("DOJETSYS"        , 0               );
    
    /// Set cuts and jet types and such
    chain->Set("BASECUSTOMTRIMMING",   baseCustomTrimming);
    chain->Set("PTFRACCUSTOMTRIMMING", ptFracCustomTrimming);
    chain->Set("SMALLRCUSTOMTRIMMING", smallRCustomTrimming);
    chain->Set("JETTYPES"       , jetTypes         );
    chain->Set("SUBJETTYPES"    , subjetTypes      );
    chain->Set("BTAGTYPES"      , btagTypes        );
    chain->Set("BADJETTYPE"     , badJetType       );
    chain->Set("BADJETDEF"      , badJetDef        );
    chain->Set("MINJETPT"       , minJetPt         );
    chain->Set("MAXJETETA"      , maxJetEta        );
    chain->Set("MINFATJETPT"    , minFatJetPt      );
    chain->Set("MAXFATJETETA"   , maxJetEta        );
    chain->Set("MINJETJVF"      , minJetJVF        );
    chain->Set("MAXJETTRKJETDR" , maxJetTrkDR      );
    chain->Set("MAXTRUTHJETDR"  , maxJetTruthDR    );
    
    chain->Set("NStdJetCut"     , 4                );
    chain->Set("LowMassCRcut"   , 100.             );
    chain->Set("ThreeBodyCRcut" , 0.7              );
    chain->Set("y12CRcut"       , 0.4              );
    
    ///----------------------------------------------------------------
    /// Trigger Information
    ///----------------------------------------------------------------
    TString trigTypes  = "EF_j360_a10tcem";
    TString trigParams = "jet_AntiKt10LCTopo_pt";
    TString trigCuts   = "450000.";               /// NEEDS TO BE IN MEV
    TString trigLumis  = "5725.04";               /// UPDATE ME!
    
    chain->Set("TRIGTYPES"      , trigTypes      );
    chain->Set("TRIGPARAM"      , trigParams     );
    chain->Set("TRIGCUT"        , trigCuts       );
    chain->Set("TRIGLUMI"       , trigLumis      );
    
    ///----------------------------------------------------------------
    /// Luminosity for trigger weighting
    ///----------------------------------------------------------------
    Float_t lumiVal = 5725.04;
    
    chain->Set("LUMI"           , lumiVal        );
    
    chain->Write();

    if (chain->Exists("GRL")) WriteGRLObject(chain->String("GRL"));  
  
		
	

    ///----------------------------------------------------------------
    /// ProofAna global Config object
    ///----------------------------------------------------------------
    Config* confProofAna = new Config("ProofAna");
    
    confProofAna->Set("DEBUG"          , false        );  // "false", 0, "0" etc. also works
    confProofAna->Set("SAVETIMERS"     , false        );  // ProofAna timer histos in output file 
    confProofAna->Set("IDENTIFIER"     , identifier   );
    confProofAna->Set("DATASET"        , dataset      );
    confProofAna->Set("OUTPUTPATH"     , path         );
    confProofAna->Set("EVENTBUILDER"   , eventbuilder );
    if (!doHists) 
      confProofAna->Set("MERGE"        , false        );     // enable dataset mode
    
    ///----------------------------------------------------------------
    /// Read information used in MC weighting, multi-dataset jobs
    ///----------------------------------------------------------------
    ReadDatasetInfo(dataset  , confProofAna  ); 
    WriteGroomedPRWO(options , "EF_j360_a10tcem_PeriodB" );
    confProofAna->Write();  
    options->Close();
    delete options;


    cout << "All setup, ready to go " << endl;    
    // Decide to run local or on the cluster
    if (mode.CompareTo("local") == 0) runLocal(dataset, treename);
    else if(mode.CompareTo("lite")==0||mode.CompareTo("cluster")==0) 
      runProof(url,dataset,-1,treename);
    else if(mode.CompareTo("grid")==0){
      TString gridname = "user."+gridusername+"."+identifier;
      cout << "submitting with gridname " << gridname << endl;
      runGrid(gridname);
    }   
    gSystem->Unlink("options.root");
}
Ejemplo n.º 24
0
/*
 * Config builds a set of files for building a UNIX
 * system given a description of the desired system.
 */
int
main(int argc, char *argv[])
{
	struct stat buf;
	int ch, len;
	unsigned int i;
	char *p;
	char linksrc[64], linkdest[MAXPATHLEN];
	static const char *emus[] = { "linux" };

	while ((ch = getopt(argc, argv, "d:gpr")) != -1)
		switch (ch) {
		case 'd':
			if (*destdir == '\0')
				strlcpy(destdir, optarg, sizeof(destdir));
			else
				errx(2, "directory already set");
			break;
		case 'g':
			debugging++;
			break;
		case 'p':
			profiling++;
			break;
		case 'r':
			no_config_clobber = FALSE;
			break;
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc != 1)
		usage();

	if (freopen(PREFIX = *argv, "r", stdin) == NULL)
		err(2, "%s", PREFIX);

	if (*destdir != '\0') {
		len = strlen(destdir);
		while (len > 1 && destdir[len - 1] == '/')
			destdir[--len] = '\0';
		get_srcdir();
	} else {
		strlcpy(destdir, CDIR, sizeof(destdir));
		strlcat(destdir, PREFIX, sizeof(destdir));
	}

	p = path(NULL);
	if (stat(p, &buf)) {
		if (mkdir(p, 0777))
			err(2, "%s", p);
	}
	else if ((buf.st_mode & S_IFMT) != S_IFDIR) {
		errx(2, "%s isn't a directory", p);
	}
	else if (!no_config_clobber) {
		char tmp[strlen(p) + 8];

		fprintf(stderr, "Removing old directory %s:  ", p);
		fflush(stderr);
		snprintf(tmp, sizeof(tmp), "rm -rf %s", p);
		if (system(tmp)) {
			fprintf(stderr, "Failed!\n");
			err(2, "%s", tmp);
		}
		fprintf(stderr, "Done.\n");
		if (mkdir(p, 0777))
			err(2, "%s", p);
	}

	dtab = NULL;
	if (yyparse())
		exit(3);
	if (platformname == NULL) {
		printf("Specify platform architecture, e.g. 'platform pc64'\n");
		exit(1);
	}
	if (machinename == NULL) {
		printf("Specify machine architecture, e.g. 'machine x86_64'\n");
		exit(1);
	}
	if (machinearchname == NULL) {
		printf("Specify cpu architecture, e.g. 'machine_arch x86_64'\n");
		exit(1);
	}
	newbus_ioconf();
	
	/*
	 * "machine" points into platform/<PLATFORM>/include
	 */
	if (*srcdir == '\0')
		snprintf(linkdest, sizeof(linkdest), "../../platform/%s/include",
		    platformname);
	else
		snprintf(linkdest, sizeof(linkdest), "%s/platform/%s/include",
		    srcdir, platformname);
	symlink(linkdest, path("machine"));

	/*
	 * "machine_base" points into platform/<PLATFORM>
	 */
	if (*srcdir == '\0')
		snprintf(linkdest, sizeof(linkdest), "../../platform/%s",
		    platformname);
	else
		snprintf(linkdest, sizeof(linkdest), "%s/platform/%s",
		    srcdir, platformname);
	symlink(linkdest, path("machine_base"));

	/*
	 * "cpu" points to cpu/<MACHINE_ARCH>/include
	 */
	if (*srcdir == '\0')
		snprintf(linkdest, sizeof(linkdest),
			 "../../cpu/%s/include", machinearchname);
	else
		snprintf(linkdest, sizeof(linkdest),
			 "%s/cpu/%s/include", srcdir, machinearchname);
	symlink(linkdest, path("cpu"));

	/*
	 * "cpu_base" points to cpu/<MACHINE_ARCH>
	 */
	if (*srcdir == '\0')
		snprintf(linkdest, sizeof(linkdest), "../../cpu/%s",
		    machinearchname);
	else
		snprintf(linkdest, sizeof(linkdest), "%s/cpu/%s",
		    srcdir, machinearchname);
	symlink(linkdest, path("cpu_base"));

	/*
	 * XXX check directory structure for architecture subdirectories and
	 * create the symlinks automatically XXX
	 */
	for (i = 0; i < sizeof(emus) / sizeof(emus[0]); ++i) {
		if (*srcdir == 0)  {
			snprintf(linkdest, sizeof(linkdest),
			    "../../emulation/%s/%s",
			    emus[i], machinearchname);
		} else {
			snprintf(linkdest, sizeof(linkdest),
			    "%s/emulation/%s/%s",
			    srcdir, emus[i], machinearchname);
		}
		snprintf(linksrc, sizeof(linksrc), "arch_%s", emus[i]);
		symlink(linkdest, path(linksrc));
	}

	options();			/* make options .h files */
	makefile();			/* build Makefile */
	headers();			/* make a lot of .h files */
	configfile();			/* put config file into kernel*/
	printf("Kernel build directory is %s\n", p);
	exit(EX_OK);
}
Ejemplo n.º 25
0
void runSusyBkg(TString mode = "cluster", TString identifier = "myTest", TString dataset = "su4.susy1118", TString username = "******", bool mcweights = true, bool sys = true) 
{
	//options for mode are local, lite, cluster, or grid

	LoadLibraries();
    
	//General user run options (now set in run command)
	//TString identifier("myTest"); //unique identifier for this job
	//TString dataset("test.example"); //dataset name
	//TString username("bcbutler"); //username for cluster, not important otherwise

	//SetConfig
	TString configfile("../config/periodsB-M.config");

	// Best to leave alone	
	TString pathLite("");
	
	TString pathCluster("root://atlprf01.slac.stanford.edu:2094//atlas/output/");
	pathCluster.Append(username);
	pathCluster.Append("/");

	//Determine eventbuilder from dataset name
	TString eventbuilder(dataset);
	eventbuilder.Remove(0,eventbuilder.Last('.')+1);

	//Filename paths, URLs for PROOF running
	TString url(mode);
	TString path("");
	if(mode.CompareTo("lite")==0) {
		url = "lite://"; //ROOT 5.32
		path = pathLite;
	}
	else if(mode.CompareTo("cluster")==0) {
		url = TString(username+"@atlprf01.slac.stanford.edu");
		path = pathCluster;
	}
	
	//Make an options file, edit as needed
	TFile* options = new TFile("options.root","RECREATE");
	
	//Analyses Configs, change as needed
	bool do0Lepton = true;
	bool do4Jet = false;
	bool do6Jet = false;
	bool doSR1 = true;
	bool doSR2 = true;
	bool doSR3 = true;
	bool do1Electron = true;
	bool do2Electron = true;
	bool do1Muon = true;
	bool do2Muon = true;
	bool doFakeNu = false; //convert Zmumubb to Znunubb
	bool doKillZnunuZbb = false;
	bool doDetail = true;
	bool doLocHad = false;
	bool doPRW = true;
	bool doHFT = true;
	bool doWriteTrees = eventbuilder.CompareTo("event") ? true : false;
	bool noBtagSFs = true;
	bool fancyBtagErr = false;
	bool truthEB = false;
	bool isData = false;
	
	if(dataset.Contains("Egamma_")) {
		do0Lepton = false;
		do1Muon = false;
		do2Muon = false;
		isData = true;
	}
	else if(dataset.Contains("Muons_")) {
		do0Lepton = false;
		do1Electron = false;
		do2Electron = false;
		isData = true;
	}
	else if(dataset.Contains("JetTauEtmiss_")) {
		do1Electron = false;
		do2Electron = false;
		do1Muon = false;
		do2Muon = false;
		isData = true;
	}

	if(truthEB) {
		if(isData) {
			cout << "You are asking to run the truth-based event builder on data?" << endl;
			exit(1);
		}

		//append for truth-only studies, turn of systematics
		eventbuilder.Append("_truth");	
		sys = false;
	}
	
	Config* chain = new Config("chain",configfile); //eventbuilder/mcweights flags in chain config
	chain->AddVec("ANALYSIS");
	chain->Set("MCWEIGHTS",mcweights);
	chain->Set("BTAG",2*(!isData));
	chain->Set("NOBTAGSF",noBtagSFs);	
	chain->Set("FANCYBTAGERR",fancyBtagErr);
	chain->Set("PILE",doPRW);
	chain->Set("HFT",doHFT);
	chain->Set("0LEPTON",do0Lepton);
	chain->Set("1ELECTRON",do1Electron);
	chain->Set("1MUON",do1Muon);
	chain->Set("2ELECTRON",do2Electron);
	chain->Set("2MUON",do2Muon);
	chain->Set("FAKENU",doFakeNu);
	chain->Set("KILLZNUNUZBB",doKillZnunuZbb);	
	chain->Set("LOCHAD",doLocHad);
	//chain->Set("DEBUG",true);

	Config* nom = new Config("nom");
	nom->Set("ANALYSIS","susybkg");
	nom->Set("BTAG",1*(!isData));
	nom->Set("0LEPTON",do0Lepton);
	nom->Set("4JET",do4Jet);
	nom->Set("6JET",do6Jet);
	nom->Set("SR1",doSR1);
	nom->Set("SR2",doSR2);
	nom->Set("SR3",doSR3);
	nom->Set("1ELECTRON",do1Electron);
	nom->Set("1MUON",do1Muon);	
	nom->Set("2ELECTRON",do2Electron);
	nom->Set("2MUON",do2Muon);	
	nom->Set("DETAIL",doDetail);
	nom->Set("WRITETREES",doWriteTrees);
	//nom->Set("DEBUG",true);
	chain->Add("ANALYSIS",nom);
	
	if(dataset.Contains("JetTauEtmiss_")||dataset.Contains("ttslLAr")) {
		Config* larreversed = new Config("larreversed",configfile);
		larreversed->Set("ANALYSIS","susybkg");
		larreversed->Set("MCWEIGHTS",mcweights);
		larreversed->Set("BTAG",0);
		larreversed->Set("PILE",doPRW);
		larreversed->Set("HFT",doHFT);
		larreversed->Set("0LEPTON",do0Lepton);
		larreversed->Set("4JET",do4Jet);
		larreversed->Set("6JET",do6Jet);
		larreversed->Set("SR1",doSR1);
		larreversed->Set("SR2",doSR2);
		larreversed->Set("SR3",doSR3);
		larreversed->Set("1ELECTRON",false);
		larreversed->Set("1MUON",false);
		larreversed->Set("2ELECTRON",false);
		larreversed->Set("2MUON",false);
		larreversed->Set("FAKENU",doFakeNu);
		larreversed->Set("KILLZNUNUZBB",doKillZnunuZbb);	
		larreversed->Set("DETAIL",doDetail);
		larreversed->Set("LOCHAD",doLocHad);
		larreversed->Set("LARVETOREVERSED",true);
		larreversed->Set("WRITETREES",doWriteTrees);
		//larreversed->Set("DEBUG",true);
		larreversed->Write();	
	}
	
	if(dataset.Contains("Egamma_")||dataset.Contains("Muons_")) {
	
		Config* mmnom = new Config("mmnom");
		mmnom->Set("ANALYSIS","susybkg");
		mmnom->Set("BTAG",0);
		mmnom->Set("0LEPTON",false);
		mmnom->Set("4JET",false);
		mmnom->Set("6JET",false);
		mmnom->Set("SR1",doSR1);
		mmnom->Set("SR2",doSR2);
		mmnom->Set("SR3",doSR3);
		mmnom->Set("1ELECTRON",do1Electron);
		mmnom->Set("1MUON",do1Muon);	
		mmnom->Set("2ELECTRON",false);
		mmnom->Set("2MUON",false);	
		mmnom->Set("DETAIL",doDetail);
		mmnom->Set("MM",1);		
		mmnom->Set("WRITETREES",doWriteTrees);
		//mmnom->Set("DEBUG",true);
		chain->Add("ANALYSIS",mmnom);
		
		Config* mmsys = new Config("mmsys");
		mmsys->Set("ANALYSIS","susybkg");
		mmsys->Set("BTAG",0);
		mmsys->Set("0LEPTON",false);
		mmsys->Set("4JET",false);
		mmsys->Set("6JET",false);
		mmsys->Set("SR1",doSR1);
		mmsys->Set("SR2",doSR2);
		mmsys->Set("SR3",doSR3);
		mmsys->Set("1ELECTRON",do1Electron);
		mmsys->Set("1MUON",do1Muon);	
		mmsys->Set("2ELECTRON",false);
		mmsys->Set("2MUON",false);	
		mmsys->Set("DETAIL",doDetail);
		mmsys->Set("MM",2);		
		mmsys->Set("WRITETREES",doWriteTrees);
		//mmsys->Set("DEBUG",true);
		chain->Add("ANALYSIS",mmsys);
		
		Config* mmstat = new Config("mmstat");
		mmstat->Set("ANALYSIS","susybkg");
		mmstat->Set("BTAG",0);
		mmstat->Set("0LEPTON",false);
		mmstat->Set("4JET",false);
		mmstat->Set("6JET",false);
		mmstat->Set("SR1",doSR1);
		mmstat->Set("SR2",doSR2);
		mmstat->Set("SR3",doSR3);
		mmstat->Set("1ELECTRON",do1Electron);
		mmstat->Set("1MUON",do1Muon);	
		mmstat->Set("2ELECTRON",false);
		mmstat->Set("2MUON",false);	
		mmstat->Set("DETAIL",doDetail);
		mmstat->Set("MM",3);		
		mmstat->Set("WRITETREES",doWriteTrees);
		//mmstat->Set("DEBUG",true);
		chain->Add("ANALYSIS",mmstat);
	}

	if((!isData)&&(!dataset.Contains("ttslLAr"))&&sys) {	

		Config* bup = new Config("bup");
		bup->Set("ANALYSIS","susybkg");
		bup->Set("BTAG",2);
		bup->Set("0LEPTON",do0Lepton);
		bup->Set("4JET",do4Jet);
		bup->Set("6JET",do6Jet);
		bup->Set("SR1",doSR1);
		bup->Set("SR2",doSR2);
		bup->Set("SR3",doSR3);
		bup->Set("1ELECTRON",do1Electron);
		bup->Set("1MUON",do1Muon);
		bup->Set("2ELECTRON",do2Electron);
		bup->Set("2MUON",do2Muon);
		bup->Set("WRITETREES",doWriteTrees);
		//bup->Set("DEBUG",true);
		chain->Add("ANALYSIS",bup);

		Config* bdown = new Config("bdown");
		bdown->Set("ANALYSIS","susybkg");
		bdown->Set("BTAG",3);
		bdown->Set("0LEPTON",do0Lepton);
		bdown->Set("4JET",do4Jet);
		bdown->Set("6JET",do6Jet);
		bdown->Set("SR1",doSR1);
		bdown->Set("SR2",doSR2);
		bdown->Set("SR3",doSR3);
		bdown->Set("1ELECTRON",do1Electron);
		bdown->Set("1MUON",do1Muon);
		bdown->Set("2ELECTRON",do2Electron);
		bdown->Set("2MUON",do2Muon);
		bdown->Set("WRITETREES",doWriteTrees);
		//bdown->Set("DEBUG",true);
		chain->Add("ANALYSIS",bdown);
		
		Config* cup = new Config("cup");
		cup->Set("ANALYSIS","susybkg");
		cup->Set("BTAG",4);
		cup->Set("0LEPTON",do0Lepton);
		cup->Set("4JET",do4Jet);
		cup->Set("6JET",do6Jet);
		cup->Set("SR1",doSR1);
		cup->Set("SR2",doSR2);
		cup->Set("SR3",doSR3);
		cup->Set("1ELECTRON",do1Electron);
		cup->Set("1MUON",do1Muon);
		cup->Set("2ELECTRON",do2Electron);
		cup->Set("2MUON",do2Muon);
		cup->Set("WRITETREES",doWriteTrees);
		//cup->Set("DEBUG",true);
		chain->Add("ANALYSIS",cup);

		Config* cdown = new Config("cdown");
		cdown->Set("ANALYSIS","susybkg");
		cdown->Set("BTAG",5);
		cdown->Set("0LEPTON",do0Lepton);
		cdown->Set("4JET",do4Jet);
		cdown->Set("6JET",do6Jet);
		cdown->Set("SR1",doSR1);
		cdown->Set("SR2",doSR2);
		cdown->Set("SR3",doSR3);
		cdown->Set("1ELECTRON",do1Electron);
		cdown->Set("1MUON",do1Muon);
		cdown->Set("2ELECTRON",do2Electron);
		cdown->Set("2MUON",do2Muon);
		cdown->Set("WRITETREES",doWriteTrees);
		//cdown->Set("DEBUG",true);
		chain->Add("ANALYSIS",cdown);
		
		Config* lup = new Config("lup");
		lup->Set("ANALYSIS","susybkg");
		lup->Set("BTAG",6);
		lup->Set("0LEPTON",do0Lepton);
		lup->Set("4JET",do4Jet);
		lup->Set("6JET",do6Jet);
		lup->Set("SR1",doSR1);
		lup->Set("SR2",doSR2);
		lup->Set("SR3",doSR3);
		lup->Set("1ELECTRON",do1Electron);
		lup->Set("1MUON",do1Muon);
		lup->Set("2ELECTRON",do2Electron);
		lup->Set("2MUON",do2Muon);
		lup->Set("WRITETREES",doWriteTrees);
		//lup->Set("DEBUG",true);
		chain->Add("ANALYSIS",lup);

		Config* ldown = new Config("ldown");
		ldown->Set("ANALYSIS","susybkg");
		ldown->Set("BTAG",7);
		ldown->Set("0LEPTON",do0Lepton);
		ldown->Set("4JET",do4Jet);
		ldown->Set("6JET",do6Jet);
		ldown->Set("SR1",doSR1);
		ldown->Set("SR2",doSR2);
		ldown->Set("SR3",doSR3);
		ldown->Set("1ELECTRON",do1Electron);
		ldown->Set("1MUON",do1Muon);
		ldown->Set("2ELECTRON",do2Electron);
		ldown->Set("2MUON",do2Muon);
		ldown->Set("WRITETREES",doWriteTrees);
		//ldown->Set("DEBUG",true);
		chain->Add("ANALYSIS",ldown);
		
		if(fancyBtagErr) {
			for(int i = 0; i<4; ++i) {
				for(int j = 0; j<1; ++j) {
					Config* bstat_up = new Config(TString::Format("bup_%i_%i",i+1,j+1));
					bstat_up->Set("ANALYSIS","susybkg");
					bstat_up->Set("BTAG",8);
					bstat_up->Set("BTAGFLAVOR",0);
					bstat_up->Set("BTAGDIR",0);	
					bstat_up->Set("BTAGPTBIN",i+1);
					bstat_up->Set("BTAGETABIN",j+1);
					bstat_up->Set("0LEPTON",do0Lepton);
					bstat_up->Set("4JET",do4Jet);
					bstat_up->Set("6JET",do6Jet);
					bstat_up->Set("SR1",doSR1);
					bstat_up->Set("SR2",doSR2);
					bstat_up->Set("SR3",doSR3);
					bstat_up->Set("1ELECTRON",do1Electron);
					bstat_up->Set("1MUON",do1Muon);
					bstat_up->Set("2ELECTRON",do2Electron);
					bstat_up->Set("2MUON",do2Muon);
					bstat_up->Set("WRITETREES",doWriteTrees);
					//bstat_up->Set("DEBUG",true);
					chain->Add("ANALYSIS",bstat_up);
					
					Config* bstat_down = new Config(TString::Format("bdown_%i_%i",i+1,j+1));
					bstat_down->Set("ANALYSIS","susybkg");
					bstat_down->Set("BTAG",8);
					bstat_down->Set("BTAGFLAVOR",0);
					bstat_down->Set("BTAGDIR",1);	
					bstat_down->Set("BTAGPTBIN",i+1);
					bstat_down->Set("BTAGETABIN",j+1);
					bstat_down->Set("0LEPTON",do0Lepton);
					bstat_down->Set("4JET",do4Jet);
					bstat_down->Set("6JET",do6Jet);
					bstat_down->Set("SR1",doSR1);
					bstat_down->Set("SR2",doSR2);
					bstat_down->Set("SR3",doSR3);
					bstat_down->Set("1ELECTRON",do1Electron);
					bstat_down->Set("1MUON",do1Muon);
					bstat_down->Set("2ELECTRON",do2Electron);
					bstat_down->Set("2MUON",do2Muon);
					bstat_down->Set("WRITETREES",doWriteTrees);
					//bstat_down->Set("DEBUG",true);
					chain->Add("ANALYSIS",bstat_down);
				}
			}
	
			for(int i = 0; i<1; ++i) {
				for(int j = 0; j<1; ++j) {
					Config* cstat_up = new Config(TString::Format("cup_%i_%i",i+1,j+1));
					cstat_up->Set("ANALYSIS","susybkg");
					cstat_up->Set("BTAG",8);
					cstat_up->Set("BTAGFLAVOR",1);
					cstat_up->Set("BTAGDIR",0);	
					cstat_up->Set("BTAGPTBIN",i+1);
					cstat_up->Set("BTAGETABIN",j+1);
					cstat_up->Set("0LEPTON",do0Lepton);
					cstat_up->Set("4JET",do4Jet);
					cstat_up->Set("6JET",do6Jet);
					cstat_up->Set("SR1",doSR1);
					cstat_up->Set("SR2",doSR2);
					cstat_up->Set("SR3",doSR3);
					cstat_up->Set("1ELECTRON",do1Electron);
					cstat_up->Set("1MUON",do1Muon);
					cstat_up->Set("2ELECTRON",do2Electron);
					cstat_up->Set("2MUON",do2Muon);
					cstat_up->Set("WRITETREES",doWriteTrees);
					//cstat_up->Set("DEBUG",true);
					chain->Add("ANALYSIS",cstat_up);
					
					Config* cstat_down = new Config(TString::Format("cdown_%i_%i",i+1,j+1));
					cstat_down->Set("ANALYSIS","susybkg");
					cstat_down->Set("BTAG",8);
					cstat_down->Set("BTAGFLAVOR",1);
					cstat_down->Set("BTAGDIR",1);	
					cstat_down->Set("BTAGPTBIN",i+1);
					cstat_down->Set("BTAGETABIN",j+1);
					cstat_down->Set("0LEPTON",do0Lepton);
					cstat_down->Set("4JET",do4Jet);
					cstat_down->Set("6JET",do6Jet);
					cstat_down->Set("SR1",doSR1);
					cstat_down->Set("SR2",doSR2);
					cstat_down->Set("SR3",doSR3);
					cstat_down->Set("1ELECTRON",do1Electron);
					cstat_down->Set("1MUON",do1Muon);
					cstat_down->Set("2ELECTRON",do2Electron);
					cstat_down->Set("2MUON",do2Muon);
					cstat_down->Set("WRITETREES",doWriteTrees);
					//cstat_down->Set("DEBUG",true);
					chain->Add("ANALYSIS",cstat_down);
				}
			}
			
			for(int i = 0; i<1; ++i) {
				for(int j = 0; j<1; ++j) {
					Config* lstat_up = new Config(TString::Format("lup_%i_%i",i+1,j+1));
					lstat_up->Set("ANALYSIS","susybkg");
					lstat_up->Set("BTAG",8);
					lstat_up->Set("BTAGFLAVOR",2);
					lstat_up->Set("BTAGDIR",0);	
					lstat_up->Set("BTAGPTBIN",i+1);
					lstat_up->Set("BTAGETABIN",j+1);
					lstat_up->Set("0LEPTON",do0Lepton);
					lstat_up->Set("4JET",do4Jet);
					lstat_up->Set("6JET",do6Jet);
					lstat_up->Set("SR1",doSR1);
					lstat_up->Set("SR2",doSR2);
					lstat_up->Set("SR3",doSR3);
					lstat_up->Set("1ELECTRON",do1Electron);
					lstat_up->Set("1MUON",do1Muon);
					lstat_up->Set("2ELECTRON",do2Electron);
					lstat_up->Set("2MUON",do2Muon);
					lstat_up->Set("WRITETREES",doWriteTrees);
					//lstat_up->Set("DEBUG",true);
					chain->Add("ANALYSIS",lstat_up);
					
					Config* lstat_down = new Config(TString::Format("ldown_%i_%i",i+1,j+1));
					lstat_down->Set("ANALYSIS","susybkg");
					lstat_down->Set("BTAG",8);
					lstat_down->Set("BTAGFLAVOR",2);
					lstat_down->Set("BTAGDIR",1);				
					lstat_down->Set("BTAGPTBIN",i+1);
					lstat_down->Set("BTAGETABIN",j+1);
					lstat_down->Set("0LEPTON",do0Lepton);
					lstat_down->Set("4JET",do4Jet);
					lstat_down->Set("6JET",do6Jet);
					lstat_down->Set("SR1",doSR1);
					lstat_down->Set("SR2",doSR2);
					lstat_down->Set("SR3",doSR3);
					lstat_down->Set("1ELECTRON",do1Electron);
					lstat_down->Set("1MUON",do1Muon);
					lstat_down->Set("2ELECTRON",do2Electron);
					lstat_down->Set("2MUON",do2Muon);
					lstat_down->Set("WRITETREES",doWriteTrees);
					//lstat_down->Set("DEBUG",true);
					chain->Add("ANALYSIS",lstat_down);
				}
			}
		}

		Config* jesup = new Config("jesup",configfile);
		jesup->Set("ANALYSIS","susybkg");
		jesup->Set("MCWEIGHTS",mcweights);
		jesup->Set("JETSYS",1);
		jesup->Set("BTAG",1);
		jesup->Set("NOBTAGSF",noBtagSFs);
		jesup->Set("PILE",doPRW);
		jesup->Set("HFT",doHFT);
		jesup->Set("0LEPTON",do0Lepton);
		jesup->Set("4JET",do4Jet);
		jesup->Set("6JET",do6Jet);
		jesup->Set("SR1",doSR1);
		jesup->Set("SR2",doSR2);
		jesup->Set("SR3",doSR3);
		jesup->Set("1ELECTRON",do1Electron);
		jesup->Set("1MUON",do1Muon);
		jesup->Set("2ELECTRON",do2Electron);
		jesup->Set("2MUON",do2Muon);
		jesup->Set("FAKENU",doFakeNu);
		jesup->Set("KILLZNUNUZBB",doKillZnunuZbb);	
		jesup->Set("WRITETREES",doWriteTrees);
		jesup->Write();
	
		Config* jesdown = new Config("jesdown",configfile);
		jesdown->Set("ANALYSIS","susybkg");
		jesdown->Set("MCWEIGHTS",mcweights);
		jesdown->Set("JETSYS",2);
		jesdown->Set("BTAG",1);
		jesdown->Set("NOBTAGSF",noBtagSFs);
		jesdown->Set("PILE",doPRW);
		jesdown->Set("HFT",doHFT);
		jesdown->Set("0LEPTON",do0Lepton);
		jesdown->Set("4JET",do4Jet);
		jesdown->Set("6JET",do6Jet);
		jesdown->Set("SR1",doSR1);
		jesdown->Set("SR2",doSR2);
		jesdown->Set("SR3",doSR3);
		jesdown->Set("1ELECTRON",do1Electron);
		jesdown->Set("1MUON",do1Muon);
		jesdown->Set("2ELECTRON",do2Electron);
		jesdown->Set("2MUON",do2Muon);
		jesdown->Set("FAKENU",doFakeNu);
		jesdown->Set("KILLZNUNUZBB",doKillZnunuZbb);	
		jesdown->Set("WRITETREES",doWriteTrees);
		jesdown->Write();
		
		Config* jer = new Config("jer",configfile);
		jer->Set("ANALYSIS","susybkg");
		jer->Set("MCWEIGHTS",mcweights);
		jer->Set("JETSYS",3);
		jer->Set("BTAG",1);
		jer->Set("NOBTAGSF",noBtagSFs);
		jer->Set("PILE",doPRW);
		jer->Set("HFT",doHFT);
		jer->Set("0LEPTON",do0Lepton);
		jer->Set("4JET",do4Jet);
		jer->Set("6JET",do6Jet);
		jer->Set("SR1",doSR1);
		jer->Set("SR2",doSR2);
		jer->Set("SR3",doSR3);
		jer->Set("1ELECTRON",do1Electron);
		jer->Set("1MUON",do1Muon);
		jer->Set("2ELECTRON",do2Electron);
		jer->Set("2MUON",do2Muon);
		jer->Set("FAKENU",doFakeNu);
		jer->Set("KILLZNUNUZBB",doKillZnunuZbb);	
		jer->Set("WRITETREES",doWriteTrees);
		jer->Write();

		Config* scalestup = new Config("scalestup",configfile);
		scalestup->Set("ANALYSIS","susybkg");
		scalestup->Set("MCWEIGHTS",mcweights);
		scalestup->Set("METSYS",1);
		scalestup->Set("BTAG",1);
		scalestup->Set("NOBTAGSF",noBtagSFs);
		scalestup->Set("PILE",doPRW);
		scalestup->Set("HFT",doHFT);
		scalestup->Set("0LEPTON",do0Lepton);
		scalestup->Set("4JET",do4Jet);
		scalestup->Set("6JET",do6Jet);
		scalestup->Set("SR1",doSR1);
		scalestup->Set("SR2",doSR2);
		scalestup->Set("SR3",doSR3);
		scalestup->Set("1ELECTRON",do1Electron);
		scalestup->Set("1MUON",do1Muon);
		scalestup->Set("2ELECTRON",do2Electron);
		scalestup->Set("2MUON",do2Muon);
		scalestup->Set("FAKENU",doFakeNu);
		scalestup->Set("KILLZNUNUZBB",doKillZnunuZbb);	
		scalestup->Set("WRITETREES",doWriteTrees);
		scalestup->Write();
	
		Config* scalestdown = new Config("scalestdown",configfile);
		scalestdown->Set("ANALYSIS","susybkg");
		scalestdown->Set("MCWEIGHTS",mcweights);
		scalestdown->Set("METSYS",2);
		scalestdown->Set("BTAG",1);
		scalestdown->Set("NOBTAGSF",noBtagSFs);
		scalestdown->Set("PILE",doPRW);
		scalestdown->Set("HFT",doHFT);
		scalestdown->Set("0LEPTON",do0Lepton);
		scalestdown->Set("4JET",do4Jet);
		scalestdown->Set("6JET",do6Jet);
		scalestdown->Set("SR1",doSR1);
		scalestdown->Set("SR2",doSR2);
		scalestdown->Set("SR3",doSR3);
		scalestdown->Set("1ELECTRON",do1Electron);
		scalestdown->Set("1MUON",do1Muon);
		scalestdown->Set("2ELECTRON",do2Electron);
		scalestdown->Set("2MUON",do2Muon);
		scalestdown->Set("FAKENU",doFakeNu);
		scalestdown->Set("KILLZNUNUZBB",doKillZnunuZbb);	
		scalestdown->Set("WRITETREES",doWriteTrees);
		scalestdown->Write();
		
		Config* resostup = new Config("resostup",configfile);
		resostup->Set("ANALYSIS","susybkg");
		resostup->Set("MCWEIGHTS",mcweights);
		resostup->Set("METSYS",3);
		resostup->Set("BTAG",1);
		resostup->Set("NOBTAGSF",noBtagSFs);
		resostup->Set("PILE",doPRW);
		resostup->Set("HFT",doHFT);
		resostup->Set("0LEPTON",do0Lepton);
		resostup->Set("4JET",do4Jet);
		resostup->Set("6JET",do6Jet);
		resostup->Set("SR1",doSR1);
		resostup->Set("SR2",doSR2);
		resostup->Set("SR3",doSR3);
		resostup->Set("1ELECTRON",do1Electron);
		resostup->Set("1MUON",do1Muon);
		resostup->Set("2ELECTRON",do2Electron);
		resostup->Set("2MUON",do2Muon);
		resostup->Set("FAKENU",doFakeNu);
		resostup->Set("KILLZNUNUZBB",doKillZnunuZbb);	
		resostup->Set("WRITETREES",doWriteTrees);
		resostup->Write();
	
		Config* resostdown = new Config("resostdown",configfile);
		resostdown->Set("ANALYSIS","susybkg");
		resostdown->Set("MCWEIGHTS",mcweights);
		resostdown->Set("METSYS",4);
		resostdown->Set("BTAG",1);
		resostdown->Set("NOBTAGSF",noBtagSFs);
		resostdown->Set("PILE",doPRW);
		resostdown->Set("HFT",doHFT);
		resostdown->Set("0LEPTON",do0Lepton);
		resostdown->Set("4JET",do4Jet);
		resostdown->Set("6JET",do6Jet);
		resostdown->Set("SR1",doSR1);
		resostdown->Set("SR2",doSR2);
		resostdown->Set("SR3",doSR3);
		resostdown->Set("1ELECTRON",do1Electron);
		resostdown->Set("1MUON",do1Muon);
		resostdown->Set("2ELECTRON",do2Electron);
		resostdown->Set("2MUON",do2Muon);
		resostdown->Set("FAKENU",doFakeNu);
		resostdown->Set("KILLZNUNUZBB",doKillZnunuZbb);	
		resostdown->Set("WRITETREES",doWriteTrees);
		resostdown->Write();
	}
	
	//Write chain (nominal analysis + b-tagging systematics/matrix method, identical eventbuilder result, just reweighted)
	chain->Write();	

	//ProofAna global Config object
	Config* confProofAna = new Config("ProofAna");
	//confProofAna->Set("DEBUG",true); 	// "false", 0, "0" etc. also works
	//confProofAna->Set("MERGE",false);	// enable dataset mode
	//confProofAna->Set("NFILES",1000000); 	// how many input files to merge per worker in dataset mode, very large number = 49 output files
	confProofAna->Set("SAVETIMERS",false); 	// ProofAna timer histograms in output file
	//confProofAna->Set("COUNTER",1);
	confProofAna->Set("IDENTIFIER",identifier);
	confProofAna->Set("DATASET",dataset);
	confProofAna->Set("OUTPUTPATH",path);
	confProofAna->Set("EVENTBUILDER",eventbuilder);

	ReadDatasetInfo(dataset,confProofAna); //Reads information used in MC weighting, multi-dataset jobs
	TString treename;
	if(!confProofAna->Get("TREENAME",treename)) {
		cout << "TREENAME not set in dataset config file, exiting" << endl;
		return;
	} 
	confProofAna->Write();	

	bool isAF2 = false;
	confProofAna->Get("AF2",isAF2);	
	WriteSUSYObjDefObject(options, isData, isAF2);
	
	WriteGRLObject(chain->String("GRL"));	
	WriteMuonTrigReweighterObjects(options);
	WriteMuonTriggerSFToolObject(options);
	//WriteMultijetJESUncertaintyObject(options);
	//WriteBTagCalibObject(options,"SV0","5_85");
	//WriteBTagCalibObject(options,"JetFitterCOMBNN","1_80");
	//WriteBTagCalibObject(options,"JetFitterCOMBNN","0_35");
	//WriteBTagCalibObject(options,"JetFitterCOMBNN","-1_25");
	WriteBTagCalibObject(options,"MV1","0_905363");
	WriteBTagCalibObject(options,"MV1","0_601713");
	WriteBTagCalibObject(options,"MV1","0_404219");
	//WriteJERObject(options);
	Write0LeptonPileupReweightingObject(options);
	Write1ElectronPileupReweightingObject(options);
	Write1MuonPileupReweightingObject(options);
	WriteFakeMetEstimator(options);
	WriteSmearingReweightHist(options);
	WriteElectronMMObject(options);
	
	options->Close();
	delete options;
	
	if(mode.CompareTo("local")==0) runLocal(dataset,treename);
  	else if(mode.CompareTo("grid")==0) {
    		TString prefix = "user."+username+"."+identifier;
		runGrid(prefix);
	}
	else runProof(url,dataset,-1,treename);
	
	gSystem->Unlink("options.root");
}
Ejemplo n.º 26
0
bool OSCParams::Load(void) {
	m_bSetList = 0;

	ReadConfigFile configfile(OSCParams::staticCallbackFunction, this);
	return configfile.Read(PARAMS_FILE_NAME);
}
Ejemplo n.º 27
0
int main( int argc, char ** argv )
{
	// Register custom message handler if desired
	bool handler_registered = FALSE;
	MyMessageOutput * mymsghandler = NULL;
	for(int i = 1; i < argc; i++)
	{
		QString arg(argv[i]);
		QString opt("-msg_handler");
		if(arg.startsWith(opt))
		{
			// Extract handler type
			QString handler = arg.section("=",1,1);
			if(handler.isEmpty())
			{
				qWarning("Option '-msg_handler' is not complete. Use default handler.");
				handler_registered = TRUE;
				break;
			}
			if(handler == "console")
			{
				handler_registered = TRUE;
				break;
			}
			if(!handler.endsWith(".txt"))
			{
				qWarning("File '%s' does not end with '.txt'. Use default handler.",handler.ascii());
				handler_registered = TRUE;
				break;
			}
			QFileInfo hfinfo(handler);
			if(hfinfo.exists())
			{
				if(!hfinfo.isWritable())
				{
					qWarning("Cannot write to '%s'. Use default handler",handler.ascii());
					handler_registered = TRUE;
					break;
				}
			}
			else
			{
				QString path = hfinfo.dirPath();
				QFileInfo hfdinfo(path);
				if(!hfdinfo.isWritable())
				{
					qWarning("Cannot create file in dir '%s'. Use default handler",path.ascii());
					handler_registered = TRUE;
					break;
				}

			}
			mymsghandler = new MyMessageOutput(handler);
			handler_registered = TRUE;
			break;
		}
	}
	if(!handler_registered)
	{
		mymsghandler = new MyMessageOutput(QString("debuglog.txt"));
		handler_registered = TRUE;
	}

#ifdef Q_WS_X11
	if(XInitThreads() == 0)
		qFatal("XInitThreads didn't succeed");
#endif

	// Create a QApplication object and add default close
    QApplication a( argc, argv );
    a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) );

	// Start the configuration selection dialog if more than one config file is available
	ConfigSelector cs;
	if(cs.getNumConfigs() > 1)
	{
		cs.resize(300,150);
		cs.show();
		a.exec();
	}

	// Load configuration
	Configuration * config = new Configuration();
	QString configfile(cs.getConfig());
	if(!config->load(configfile))
	{
		qFatal("Unable to load %s", configfile.ascii());
	}

	ConfigNode * cn = config->getConfig();
	if(!cn)
	{
		qFatal("Unable to get ConfigNode");
	}

	ApplicationNode * an = cn->getApplicationNode();
	if(!an)
	{
		qFatal("Unable to get ApplicationNode");
	}

	PluginsNode * pn = cn->getPluginsNode();
	if(!pn)
	{
		qFatal("Unable to get PluginsNode");
	}

	OBJECTVALUENODE_DECLARE_AND_GET(QPoint,position,an);
	OBJECTVALUENODE_DECLARE_AND_GET(QSize,size,an);
	SIMPLEVALUENODE_DECLARE_AND_GET(bool,maximized,an);
	SIMPLEVALUENODE_DECLARE_AND_GET(Q_INT8,tbindex,an);

    // Create the toplevel window
	Q3HBox * w = new Q3HBox();
	w->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);

	// Add a widget that contains the toolbox and measurements
	Q3VBox * pVBox = new Q3VBox( w );
	pVBox->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Preferred );
	pVBox->setSpacing( 5 );
	pVBox->setMargin( 2 );

	// Create the toolbox
	QToolBox * tb = new QToolBox( pVBox );

	// Create all plugins
    Plugin * VisualizePlugin = new Plugin("visualize");
    Plugin * AnalysePlugin = new Plugin("analyse_os");
    Plugin * WaveInPlugin = new Plugin("wavein");
    Plugin * FileWriterPlugin = new Plugin("filewriter");
    // Load plugin objects
	PI_Unknown *ukvi = VisualizePlugin->getObject();
	PI_Unknown *ukan = AnalysePlugin->getObject();
	PI_Unknown *ukwi = WaveInPlugin->getObject();
	PI_Unknown *ukfw = FileWriterPlugin->getObject();

	// Configure the system
	if( ukvi && ukan && ukwi && ukfw )
	{
		PI_GuiContainer* gcwiobj = NULL;
		PI_GuiContainer* gcviobj = NULL;
		PI_GuiContainer* gcfwobj = NULL;
		PI_Configuration* xcanobj = NULL;
		PI_Configuration* xcviobj = NULL;
		PI_Configuration* xcwiobj = NULL;
		PI_Configuration* xcfwobj = NULL;
		PI_DataBufferProvider* dbpwiobj = NULL;
		PI_DataBufferProvider* dbpanobj = NULL;
		PI_DataBufferConsumer* dbcanobj = NULL;
		PI_DataBufferConsumer* dbcviobj = NULL;
		PI_DataBufferConsumer* dbcfwobj = NULL;
		PI_TimeProvider* tpwiobj = NULL;
		PI_TimeConsumer* tcviobj = NULL;
		PI_TimeConsumer* tcfwobj = NULL;

		ukwi->queryInterface( PIID_GUI_CONTAINER, (void**)&gcwiobj );
		ukvi->queryInterface( PIID_GUI_CONTAINER , (void**)&gcviobj );
		ukfw->queryInterface( PIID_GUI_CONTAINER, (void**)&gcfwobj );
		ukan->queryInterface( PIID_CONFIGURATION, (void**)&xcanobj );
		ukvi->queryInterface( PIID_CONFIGURATION, (void**)&xcviobj );
		ukwi->queryInterface( PIID_CONFIGURATION, (void**)&xcwiobj );
		ukfw->queryInterface( PIID_CONFIGURATION, (void**)&xcfwobj );
		ukwi->queryInterface( PIID_DATA_BUFFER_PROVIDER, (void**)&dbpwiobj );
		ukan->queryInterface( PIID_DATA_BUFFER_PROVIDER, (void**)&dbpanobj );
		ukan->queryInterface( PIID_DATA_BUFFER_CONSUMER, (void**)&dbcanobj );
		ukvi->queryInterface( PIID_DATA_BUFFER_CONSUMER, (void**)&dbcviobj );
		ukfw->queryInterface( PIID_DATA_BUFFER_CONSUMER, (void**)&dbcfwobj );
		ukwi->queryInterface( PIID_TIME_PROVIDER, (void**)&tpwiobj );
		ukvi->queryInterface( PIID_TIME_CONSUMER, (void**)&tcviobj );
		ukfw->queryInterface( PIID_TIME_CONSUMER, (void**)&tcfwobj );

		if( gcwiobj && gcviobj && gcfwobj &&
			xcwiobj && xcanobj && xcviobj && xcfwobj &&
			dbpwiobj && dbpanobj && dbcanobj && dbcviobj && dbcfwobj &&
			tpwiobj && tcviobj && tcfwobj)
		{
			// Wave in object
			gcwiobj->setParentWindow( tb, "WaveDeviceConfiguration" );
			// Visualize object
    		gcviobj->setParentWindow( tb, "Diagram1" );
    		gcviobj->setParentWindow( tb, "Diagram2" );
    		gcviobj->setParentWindow( tb, "Diagram3" );
			gcviobj->setParentWindow( tb, "Diagram4" );
			gcviobj->setParentWindow( tb, "Diagram5" );
			gcviobj->setParentWindow( tb, "Configuration" );
			gcviobj->setParentWindow( tb, "BaseFrequency" );
			gcviobj->setParentWindow( pVBox, "TopDisplay" );
			gcviobj->setParentWindow( w, "Graph" );
			// File writer object
			gcfwobj->setParentWindow( tb, "SpectralDataSaveGui" );

			// Wave in object
			PLUGINNODE_DECLARE_AND_GET(wavein,pn);
			xcwiobj->configure(NODE_VARIABLE_NAME(wavein));
			// Analyse object
			PLUGINNODE_DECLARE_AND_GET(analyse,pn);
			xcanobj->configure(NODE_VARIABLE_NAME(analyse));
			// Visualize object
			PLUGINNODE_DECLARE_AND_GET(visualize,pn);
			xcviobj->configure(NODE_VARIABLE_NAME(visualize));
			// File writer object
			PLUGINNODE_DECLARE_AND_GET(filewriter,pn);
			xcfwobj->configure(NODE_VARIABLE_NAME(filewriter));

			// Connect the 'pause' source to different sinks
			gcviobj->connectSlot( "pause", gcwiobj->getObject("WaveDeviceConfiguration"), "setPause" );
			gcviobj->connectSlot( "pause", gcfwobj->getObject("SpectralDataSaveGui"), "setPause" );

			// Add visualize object configurations to the toolbox
			tb->addItem( gcviobj->getWidget("Diagram1"), "Diagramm 1" );
			tb->addItem( gcviobj->getWidget("Diagram2"), "Diagramm 2" );
			tb->addItem( gcviobj->getWidget("Diagram3"), "Diagramm 3" );
			tb->addItem( gcviobj->getWidget("Diagram4"), "Diagramm 4" );
			tb->addItem( gcviobj->getWidget("Diagram5"), "Diagramm 5" );
			tb->addItem( gcviobj->getWidget("Configuration"), "Konfiguration" );
			tb->addItem( gcviobj->getWidget("BaseFrequency"), "Bezugston, Stimmung" );
			// Add file writer object configuration to the toolbox
			tb->addItem( gcfwobj->getWidget("SpectralDataSaveGui"), "Datenspeicherung" );
			// Add wave in object configuration to the toolbox
			tb->addItem( gcwiobj->getWidget("WaveDeviceConfiguration"), "Soundkarte" );

			dbpwiobj->addRef();
			dbcanobj->connectToProvider( dbpwiobj );
			dbpanobj->addRef();
			dbcviobj->connectToProvider( dbpanobj );

			dbpwiobj->addRef();
			dbcfwobj->connectToProvider( dbpwiobj ); //filewrite
			dbpanobj->addRef();
			dbcfwobj->connectToProvider( dbpanobj ); //filewrite

			tpwiobj->addRef();
			tcviobj->connectToProvider( tpwiobj );
			tpwiobj->addRef();
			tcfwobj->connectToProvider( tpwiobj ); //filewrite

			xcwiobj->startRunning();
			xcanobj->startRunning();
			xcviobj->startRunning();
			xcfwobj->startRunning(); //filewrite

		}

		if( gcwiobj ) gcwiobj->release();
		if( gcviobj ) gcviobj->release();
		if( gcfwobj ) gcfwobj->release();
		if( xcanobj ) xcanobj->release();
		if( xcviobj ) xcviobj->release();
		if( xcwiobj ) xcwiobj->release();
		if( xcfwobj ) xcfwobj->release();
		if( dbpwiobj ) dbpwiobj->release();
		if( dbpanobj ) dbpanobj->release();
		if( dbcanobj ) dbcanobj->release();
		if( dbcviobj ) dbcviobj->release();
		if( dbcfwobj ) dbcfwobj->release();
		if( tpwiobj ) tpwiobj->release();
		if( tcviobj ) tcviobj->release();
		if( tcfwobj ) tcfwobj->release();
	}

	// Set active item in the ToolBox
	tb->setCurrentIndex(VALUENODE_GET_VALUE(tbindex));

	w->resize(VALUENODE_GET_VALUE(size));
	w->move(VALUENODE_GET_VALUE(position));
	if(VALUENODE_GET_VALUE(maximized))
		w->showMaximized();
	w->setCaption("Prisma-Realtime v1.3b");
    w->show();

    Q3Accel *esc = new Q3Accel( w );
    esc->connectItem( esc->insertItem( Qt::Key_Escape ), &a, SLOT( quit() ) );

    a.exec();

	w->hide();

	if(!w->isMaximized())
	{
		VALUENODE_SET_VALUE(size,w->size());
		VALUENODE_SET_VALUE(position,w->pos());
	}
	VALUENODE_SET_VALUE(maximized,w->isMaximized());

	VALUENODE_SET_VALUE(tbindex,tb->currentIndex());

	if( ukvi && ukan && ukwi && ukfw )
	{
		PI_Configuration * xmlconfig = NULL;

		ukvi->queryInterface(PIID_CONFIGURATION, (void**)&xmlconfig);
		if(xmlconfig != NULL)
		{
			xmlconfig->stopRunning();
			xmlconfig->release();
			xmlconfig = NULL;
		}
		ukan->queryInterface(PIID_CONFIGURATION, (void**)&xmlconfig);
		if(xmlconfig != NULL)
		{
			xmlconfig->stopRunning();
			xmlconfig->release();
			xmlconfig = NULL;
		}
		ukwi->queryInterface(PIID_CONFIGURATION, (void**)&xmlconfig);
		if(xmlconfig != NULL)
		{
			xmlconfig->stopRunning();
			xmlconfig->release();
			xmlconfig = NULL;
		}
		ukfw->queryInterface(PIID_CONFIGURATION, (void**)&xmlconfig);
		if(xmlconfig != NULL)
		{
			xmlconfig->stopRunning();
			xmlconfig->release();
			xmlconfig = NULL;
		}
	}

	if(ukvi) ukvi->release();
	if(ukan) ukan->release();
	if(ukwi) ukwi->release();
	if(ukfw) ukfw->release();

	delete w;

	config->save(configfile);
	// Delete before unloading plugins!!!
	delete config;

	// Release plugins
	delete VisualizePlugin;
	delete FileWriterPlugin;
	delete AnalysePlugin;
	delete WaveInPlugin;


	if(mymsghandler)
		delete mymsghandler;

    return 0;

}
Ejemplo n.º 28
0
bool CFlashUpdate::checkVersion4Update()
{
	if(g_settings.softupdate_mode==1) //internet-update
	{
		if(!getInfo())
		{
			hide();
			ShowHint("messagebox.error", g_Locale->getText("flashupdate.getinfofileerror") );
			return false;
		}

		showLocalStatus(100);
		showGlobalStatus(20);
		showStatusMessage(g_Locale->getText("flashupdate.versioncheck").c_str());


		string sFileName = gTmpPath+VersionFile;

		CConfigFile configfile('\t');
		if(!configfile.loadConfig(sFileName))
		{
			ShowHint ( "messagebox.error", g_Locale->getText("flashupdate.getinfofileerror") );
			return false;
		}
		else
		{
			newVersion = configfile.getString( "version", "" );
			if(newVersion=="")
			{
				ShowHint ( "messagebox.error", g_Locale->getText("flashupdate.getinfofileerror") );
				return false;
			}
		}
		printf("internet version: %s\n", newVersion.c_str());

		if(newVersion==installedVersion)
		{
			ShowHint ( "messagebox.error", g_Locale->getText("flashupdate.nonewversion") );
			return false;
		}
	}
	else
	{
		//manuelles update -- filecheck + abfrage
		FILE* fd = fopen((string(gTmpPath+ ImageFile)).c_str(), "r");
		if(fd)
		{
			fclose(fd);
		}
		else
		{
			hide();
			printf("flash-file not found: %s\n", (string(gTmpPath+ ImageFile)).c_str() );
			ShowHint ( "messagebox.error", g_Locale->getText("flashupdate.cantopenfile") );
			return false;
		}
		hide();
		
		//bestimmung der CramfsDaten
		char cramfsName[30];
		cramfs_name( (char*) (string(gTmpPath+ImageFile)).c_str(), (char*) &cramfsName);

		CFlashVersionInfo versionInfo(cramfsName);

		char msg[400];
		sprintf( (char*) &msg, g_Locale->getText("flashupdate.msgbox_manual").c_str(), versionInfo.getDate().c_str(), 
				versionInfo.getTime().c_str(), versionInfo.getBaseImageVersion().c_str(), versionInfo.getType().c_str() );
		if ( ShowMsg ( "messagebox.info", msg, CMessageBox::mbrYes, CMessageBox::mbYes | CMessageBox::mbNo, "softupdate.raw" ) != CMessageBox::mbrYes )
		{
			return false;
		}

		return true;
	}
	
	showLocalStatus(100);
	showGlobalStatus(20);
	hide();

	//bestimmung der CramfsDaten
	CFlashVersionInfo versionInfo(newVersion);
	
	char msg[250];
	sprintf( (char*) &msg, g_Locale->getText("flashupdate.msgbox").c_str(), versionInfo.getDate().c_str(), 
				versionInfo.getTime().c_str(), versionInfo.getBaseImageVersion().c_str(), versionInfo.getType().c_str() );
    if ( ShowMsg ( "messagebox.info", msg, CMessageBox::mbrYes, CMessageBox::mbYes | CMessageBox::mbNo, "softupdate.raw" ) != CMessageBox::mbrYes )
    {
		return false;
    }

	return true;
}
Ejemplo n.º 29
0
int
main(int argc, char **argv)
{
	struct bsdtar		*bsdtar;
	int			 opt;
	char			 possible_help_request;
	char			 buff[16];
	char			 cachedir[PATH_MAX + 1];
	struct passwd		*pws;
	char			*conffile;
	const char		*missingkey;
	time_t			 now;
	size_t 			 i;

	WARNP_INIT;

	/* Use a pointer for consistency. */
	bsdtar = bsdtar_init();

#if defined(_WIN32) && !defined(__CYGWIN__)
	/* Make sure open() function will be used with a binary mode. */
	/* on cygwin, we need something similar, but instead link against */
	/* a special startup object, binmode.o */
	_set_fmode(_O_BINARY);
#endif

	/* Need bsdtar->progname before calling bsdtar_warnc. */
	if (*argv == NULL)
		bsdtar->progname = "tarsnap";
	else {
#if defined(_WIN32) && !defined(__CYGWIN__)
		bsdtar->progname = strrchr(*argv, '\\');
#else
		bsdtar->progname = strrchr(*argv, '/');
#endif
		if (bsdtar->progname != NULL)
			bsdtar->progname++;
		else
			bsdtar->progname = *argv;
	}

	/* We don't have a machine # yet. */
	bsdtar->machinenum = (uint64_t)(-1);

	/* Allocate space for archive names; at most argc of them. */
	if ((bsdtar->tapenames = malloc(argc * sizeof(const char *))) == NULL)
		bsdtar_errc(bsdtar, 1, ENOMEM, "Cannot allocate memory");
	bsdtar->ntapes = 0;

	/* Allocate space for config file names; at most argc of them. */
	if ((bsdtar->configfiles = malloc(argc * sizeof(const char *))) == NULL)
		bsdtar_errc(bsdtar, 1, ENOMEM, "Cannot allocate memory");
	bsdtar->nconfigfiles = 0;

	time(&now);
	bsdtar->creationtime = now;

	if (setlocale(LC_ALL, "") == NULL)
		bsdtar_warnc(bsdtar, 0, "Failed to set default locale");
#if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
	bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
#endif
	possible_help_request = 0;

	/* Initialize key cache.  We don't have any keys yet. */
	if (crypto_keys_init())
		exit(1);

	/*
	 * Make stdout line-buffered (if possible) so that operations such as
	 * "tarsnap --list-archives | more" will run more smoothly.  The only
	 * downside to this is a slight performance cost; but we don't write
	 * enough data to stdout for that to matter.
	 */
	setvbuf(stdout, NULL, _IONBF, 0);

	/*
	 * Unless specified otherwise, we consider ourselves to be
	 * constructing a snapshot of the disk as it is right now.
	 */
	/*
	 * POSIX doesn't provide any mechanism for distinguishing between
	 * an error and the time (time_t)(-1).  Since we only use this to
	 * avoid race conditions in the chunkification cache (i.e., so
	 * that we can determine if a file has been modified since it was
	 * last backed up), and hopefully nobody will have any files with
	 * negative last-modified dates, an error return of (-1) can be
	 * handled the same was as a legitimate return of (-1): Nothing
	 * gets cached.
	 */
	bsdtar->snaptime = time(NULL);

	/* Store original argument vector. */
	bsdtar->argc_orig = argc;
	bsdtar->argv_orig = argv;

	/* Look up the current user and his home directory. */
	if ((pws = getpwuid(geteuid())) != NULL)
		if ((bsdtar->homedir = strdup(pws->pw_dir)) == NULL)
			bsdtar_errc(bsdtar, 1, ENOMEM, "Cannot allocate memory");

	/* Look up uid of current user for future reference */
	bsdtar->user_uid = geteuid();

	/* Default: preserve mod time on extract */
	bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;

	/* Default: Perform basic security checks. */
	bsdtar->extract_flags |= SECURITY;

	/* Defaults for root user: */
	if (bsdtar_is_privileged(bsdtar)) {
		/* --same-owner */
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
		/* -p */
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
	}

	bsdtar->argv = argv;
	bsdtar->argc = argc;

	/* We gather some options in a 'delayed options queue'. */
	bsdtar->delopt = NULL;
	bsdtar->delopt_tail = &bsdtar->delopt;

	/*
	 * Comments following each option indicate where that option
	 * originated:  SUSv2, POSIX, GNU tar, star, etc.  If there's
	 * no such comment, then I don't know of anyone else who
	 * implements that option.
	 */
	while ((opt = bsdtar_getopt(bsdtar)) != -1) {
		switch (opt) {
		case OPTION_AGGRESSIVE_NETWORKING: /* tarsnap */
			optq_push(bsdtar, "aggressive-networking", NULL);
			break;
		case 'B': /* GNU tar */
			/* libarchive doesn't need this; just ignore it. */
			break;
		case 'C': /* GNU tar */
			if (strlen(bsdtar->optarg) == 0)
				bsdtar_errc(bsdtar, 1, 0,
				    "Meaningless option: -C ''");

			set_chdir(bsdtar, bsdtar->optarg);
			break;
		case 'c': /* SUSv2 */
			set_mode(bsdtar, opt, "-c");
			break;
		case OPTION_CACHEDIR: /* multitar */
			optq_push(bsdtar, "cachedir", bsdtar->optarg);
			break;
		case OPTION_CHECK_LINKS: /* GNU tar */
			bsdtar->option_warn_links = 1;
			break;
		case OPTION_CHECKPOINT_BYTES: /* tarsnap */
			optq_push(bsdtar, "checkpoint-bytes", bsdtar->optarg);
			break;
		case OPTION_CHROOT: /* NetBSD */
			bsdtar->option_chroot = 1;
			break;
		case OPTION_CONFIGFILE:
			bsdtar->configfiles[bsdtar->nconfigfiles++] =
			    bsdtar->optarg;
			break;
		case OPTION_CREATIONTIME: /* tarsnap */
			errno = 0;
			bsdtar->creationtime = strtol(bsdtar->optarg,
			    NULL, 0);
			if ((errno) || (bsdtar->creationtime == 0))
				bsdtar_errc(bsdtar, 1, 0,
				    "Invalid --creationtime argument: %s",
				    bsdtar->optarg);
			break;
		case OPTION_CSV_FILE: /* tarsnap */
			if (bsdtar->option_csv_filename != NULL)
				bsdtar_errc(bsdtar, 1, errno,
				    "Two --csv-file options given.\n");
			if ((bsdtar->option_csv_filename = strdup(
			    bsdtar->optarg)) == NULL)
				bsdtar_errc(bsdtar, 1, errno, "Out of memory");
			break;
		case 'd': /* multitar */
			set_mode(bsdtar, opt, "-d");
			break;
		case OPTION_DISK_PAUSE: /* tarsnap */
			optq_push(bsdtar, "disk-pause", bsdtar->optarg);
			break;
		case OPTION_DRYRUN: /* tarsnap */
			bsdtar->option_dryrun = 1;
			break;
		case OPTION_EXCLUDE: /* GNU tar */
			optq_push(bsdtar, "exclude", bsdtar->optarg);
			break;
		case 'f': /* multitar */
			bsdtar->tapenames[bsdtar->ntapes++] = bsdtar->optarg;
			break;
		case OPTION_FSCK: /* multitar */
			set_mode(bsdtar, opt, "--fsck");
			break;
		case OPTION_FSCK_PRUNE: /* multitar */
			set_mode(bsdtar, opt, "--fsck-prune");
			break;
		case 'H': /* BSD convention */
			bsdtar->symlink_mode = 'H';
			break;
		case 'h': /* Linux Standards Base, gtar; synonym for -L */
			bsdtar->symlink_mode = 'L';
			/* Hack: -h by itself is the "help" command. */
			possible_help_request = 1;
			break;
		case OPTION_HELP: /* GNU tar, others */
			long_help(bsdtar);
			exit(0);
			break;
		case OPTION_HUMANIZE_NUMBERS: /* tarsnap */
			optq_push(bsdtar, "humanize-numbers", NULL);
			break;
		case 'I': /* GNU tar */
			/*
			 * TODO: Allow 'names' to come from an archive,
			 * not just a text file.  Design a good UI for
			 * allowing names and mode/owner to be read
			 * from an archive, with contents coming from
			 * disk.  This can be used to "refresh" an
			 * archive or to design archives with special
			 * permissions without having to create those
			 * permissions on disk.
			 */
			bsdtar->names_from_file = bsdtar->optarg;
			break;
		case OPTION_INCLUDE:
			optq_push(bsdtar, "include", bsdtar->optarg);
			break;
		case OPTION_INSANE_FILESYSTEMS:
			optq_push(bsdtar, "insane-filesystems", NULL);
			break;
		case 'k': /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE;
			break;
		case OPTION_KEEP_GOING: /* tarsnap */
			bsdtar->option_keep_going = 1;
			break;
		case OPTION_KEEP_NEWER_FILES: /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
			break;
		case OPTION_KEYFILE: /* tarsnap */
			optq_push(bsdtar, "keyfile", bsdtar->optarg);
			break;
		case 'L': /* BSD convention */
			bsdtar->symlink_mode = 'L';
			break;
	        case 'l': /* SUSv2 and GNU tar beginning with 1.16 */
			/* GNU tar 1.13  used -l for --one-file-system */
			bsdtar->option_warn_links = 1;
			break;
		case OPTION_LIST_ARCHIVES: /* multitar */
			set_mode(bsdtar, opt, "--list-archives");
			break;
		case OPTION_LOWMEM: /* tarsnap */
			optq_push(bsdtar, "lowmem", NULL);
			break;
		case 'm': /* SUSv2 */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_TIME;
			break;
		case OPTION_MAXBW: /* tarsnap */
			optq_push(bsdtar, "maxbw", bsdtar->optarg);
			break;
		case OPTION_MAXBW_RATE: /* tarsnap */
			optq_push(bsdtar, "maxbw-rate", bsdtar->optarg);
			break;
		case OPTION_MAXBW_RATE_DOWN: /* tarsnap */
			optq_push(bsdtar, "maxbw-rate-down", bsdtar->optarg);
			break;
		case OPTION_MAXBW_RATE_UP: /* tarsnap */
			optq_push(bsdtar, "maxbw-rate-up", bsdtar->optarg);
			break;
		case 'n': /* GNU tar */
			bsdtar->option_no_subdirs = 1;
			break;
	        /*
		 * Selecting files by time:
		 *    --newer-?time='date' Only files newer than 'date'
		 *    --newer-?time-than='file' Only files newer than time
		 *         on specified file (useful for incremental backups)
		 * TODO: Add corresponding "older" options to reverse these.
		 */
		case OPTION_NEWER_CTIME: /* GNU tar */
			bsdtar->newer_ctime_sec = get_date(now, bsdtar->optarg);
			break;
		case OPTION_NEWER_CTIME_THAN:
			{
				struct stat st;
				if (stat(bsdtar->optarg, &st) != 0)
					bsdtar_errc(bsdtar, 1, 0,
					    "Can't open file %s", bsdtar->optarg);
				bsdtar->newer_ctime_sec = st.st_ctime;
				bsdtar->newer_ctime_nsec =
				    ARCHIVE_STAT_CTIME_NANOS(&st);
			}
			break;
		case OPTION_NEWER_MTIME: /* GNU tar */
			bsdtar->newer_mtime_sec = get_date(now, bsdtar->optarg);
			break;
		case OPTION_NEWER_MTIME_THAN:
			{
				struct stat st;
				if (stat(bsdtar->optarg, &st) != 0)
					bsdtar_errc(bsdtar, 1, 0,
					    "Can't open file %s", bsdtar->optarg);
				bsdtar->newer_mtime_sec = st.st_mtime;
				bsdtar->newer_mtime_nsec =
				    ARCHIVE_STAT_MTIME_NANOS(&st);
			}
			break;
		case OPTION_NODUMP: /* star */
			optq_push(bsdtar, "nodump", NULL);
			break;
		case OPTION_NOISY_WARNINGS: /* tarsnap */
			tarsnap_opt_noisy_warnings = 1;
			break;
		case OPTION_NORMALMEM:
			optq_push(bsdtar, "normalmem", NULL);
			break;
		case OPTION_NO_AGGRESSIVE_NETWORKING:
			optq_push(bsdtar, "no-aggressive-networking", NULL);
			break;
		case OPTION_NO_CONFIG_EXCLUDE:
			optq_push(bsdtar, "no-config-exclude", NULL);
			break;
		case OPTION_NO_CONFIG_INCLUDE:
			optq_push(bsdtar, "no-config-include", NULL);
			break;
		case OPTION_NO_DEFAULT_CONFIG:
			bsdtar->option_no_default_config = 1;
			break;
		case OPTION_NO_DISK_PAUSE:
			optq_push(bsdtar, "no-disk-pause", NULL);
			break;
		case OPTION_NO_HUMANIZE_NUMBERS:
			optq_push(bsdtar, "no-humanize-numbers", NULL);
			break;
		case OPTION_NO_INSANE_FILESYSTEMS:
			optq_push(bsdtar, "no-insane-filesystems", NULL);
			break;
		case OPTION_NO_MAXBW:
			optq_push(bsdtar, "no-maxbw", NULL);
			break;
		case OPTION_NO_MAXBW_RATE_DOWN:
			optq_push(bsdtar, "no-maxbw-rate-down", NULL);
			break;
		case OPTION_NO_MAXBW_RATE_UP:
			optq_push(bsdtar, "no-maxbw-rate-up", NULL);
			break;
		case OPTION_NO_NODUMP:
			optq_push(bsdtar, "no-nodump", NULL);
			break;
		case OPTION_NO_PRINT_STATS:
			optq_push(bsdtar, "no-print-stats", NULL);
			break;
		case OPTION_NO_QUIET:
			optq_push(bsdtar, "no-quiet", NULL);
			break;
		case OPTION_NO_RETRY_FOREVER:
			optq_push(bsdtar, "no-retry-forever", NULL);
			break;
		case OPTION_NO_SAME_OWNER: /* GNU tar */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_NO_SAME_PERMISSIONS: /* GNU tar */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_PERM;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_ACL;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_XATTR;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_FFLAGS;
			break;
		case OPTION_NO_SNAPTIME:
			optq_push(bsdtar, "no-snaptime", NULL);
			break;
		case OPTION_NO_STORE_ATIME:
			optq_push(bsdtar, "no-store-atime", NULL);
			break;
		case OPTION_NO_TOTALS:
			optq_push(bsdtar, "no-totals", NULL);
			break;
		case OPTION_NUKE: /* tarsnap */
			set_mode(bsdtar, opt, "--nuke");
			break;
		case OPTION_NULL: /* GNU tar */
			bsdtar->option_null++;
			break;
		case OPTION_NUMERIC_OWNER: /* GNU tar */
			bsdtar->option_numeric_owner++;
			break;
		case 'O': /* GNU tar */
			bsdtar->option_stdout = 1;
			break;
		case 'o':
			bsdtar->option_no_owner = 1;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_ONE_FILE_SYSTEM: /* GNU tar */
			bsdtar->option_dont_traverse_mounts = 1;
			break;
		case 'P': /* GNU tar */
			bsdtar->extract_flags &= ~SECURITY;
			bsdtar->option_absolute_paths = 1;
			break;
		case 'p': /* GNU tar, star */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
			break;
		case OPTION_PRINT_STATS: /* multitar */
			bsdtar->option_print_stats = 1;
			break;
		case 'q': /* FreeBSD GNU tar --fast-read, NetBSD -q */
			bsdtar->option_fast_read = 1;
			break;
		case OPTION_QUIET:
			optq_push(bsdtar, "quiet", NULL);
			break;
		case 'r': /* multitar */
			set_mode(bsdtar, opt, "-r");
			break;
		case OPTION_RECOVER:
			set_mode(bsdtar, opt, "--recover");
			break;
		case OPTION_RETRY_FOREVER:
			optq_push(bsdtar, "retry-forever", NULL);
			break;
		case OPTION_SNAPTIME: /* multitar */
			optq_push(bsdtar, "snaptime", bsdtar->optarg);
			break;
		case OPTION_STORE_ATIME: /* multitar */
			optq_push(bsdtar, "store-atime", NULL);
			break;
		case 'S': /* NetBSD pax-as-tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_SPARSE;
			break;
		case 's': /* NetBSD pax-as-tar */
#if HAVE_REGEX_H
			add_substitution(bsdtar, bsdtar->optarg);
#else
			bsdtar_warnc(bsdtar, 0,
			    "-s is not supported by this version of tarsnap");
			usage(bsdtar);
#endif
			break;
		case OPTION_SAME_OWNER: /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_STRIP_COMPONENTS: /* GNU tar 1.15 */
			errno = 0;
			bsdtar->strip_components = strtol(bsdtar->optarg,
			    NULL, 0);
			if (errno)
				bsdtar_errc(bsdtar, 1, 0,
				    "Invalid --strip-components argument: %s",
				    bsdtar->optarg);
			break;
		case 'T': /* GNU tar */
			bsdtar->names_from_file = bsdtar->optarg;
			break;
		case 't': /* SUSv2 */
			set_mode(bsdtar, opt, "-t");
			bsdtar->verbose++;
			break;
		case OPTION_TOTALS: /* GNU tar */
			optq_push(bsdtar, "totals", NULL);
			break;
		case 'U': /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
			bsdtar->option_unlink_first = 1;
			break;
		case 'v': /* SUSv2 */
			bsdtar->verbose++;
			break;
		case OPTION_VERSION: /* GNU convention */
			version();
			break;
		case OPTION_VERYLOWMEM: /* tarsnap */
			optq_push(bsdtar, "verylowmem", NULL);
			break;
#if 0
		/*
		 * The -W longopt feature is handled inside of
		 * bsdtar_getopt(), so -W is not available here.
		 */
		case 'W': /* Obscure GNU convention. */
			break;
#endif
		case 'w': /* SUSv2 */
			bsdtar->option_interactive = 1;
			break;
		case 'X': /* GNU tar */
			if (exclude_from_file(bsdtar, bsdtar->optarg))
				bsdtar_errc(bsdtar, 1, 0,
				    "failed to process exclusions from file %s",
				    bsdtar->optarg);
			break;
		case 'x': /* SUSv2 */
			set_mode(bsdtar, opt, "-x");
			break;
		default:
			usage(bsdtar);
		}
	}

	/*
	 * Sanity-check options.
	 */

	/*
	 * If --print-stats was specified but no mode was set, then
	 * --print-stats *is* the mode.
	 */
	if ((bsdtar->mode == '\0') && (bsdtar->option_print_stats == 1))
		set_mode(bsdtar, OPTION_PRINT_STATS, "--print-stats");

	/* If no "real" mode was specified, treat -h as --help. */
	if ((bsdtar->mode == '\0') && possible_help_request) {
		long_help(bsdtar);
		exit(0);
	}

	/*
	 * If we're doing a dry run and the user hasn't specified an archive
	 * name via -f, use a fake name.  This will result in the statistics
	 * printed by --print-stats being a few bytes off, since the archive
	 * name is included in the metadata block... but we're going to be a
	 * few bytes off anyway since the command line, including "--dry-run"
	 * is included in the metadata.
	 */
	if (bsdtar->option_dryrun && (bsdtar->ntapes == 0))
		bsdtar->tapenames[bsdtar->ntapes++] = "(dry-run)";

	/* At this point we must have a mode set. */
	if (bsdtar->mode == '\0')
		bsdtar_errc(bsdtar, 1, 0,
		    "Must specify one of -c, -d, -r, -t, -x,"
		    " --list-archives, --print-stats,"
		    " --fsck, --fsck-prune, or --nuke");

	/* Process "delayed" command-line options which we queued earlier. */
	while (bsdtar->delopt != NULL) {
		dooption(bsdtar, bsdtar->delopt->opt_name,
		    bsdtar->delopt->opt_arg, 0);
		optq_pop(bsdtar);
	}

	/* Process config files passed on the command line. */
	for (i = 0; i < bsdtar->nconfigfiles; i++)
		configfile(bsdtar, bsdtar->configfiles[i]);

	/* If we do not have --no-default-config, process default configs. */
	if (bsdtar->option_no_default_config == 0) {
		/* Process options from ~/.tarsnaprc. */
		if (bsdtar->homedir != NULL) {
			if (asprintf(&conffile, "%s/.tarsnaprc",
			    bsdtar->homedir) == -1)
				bsdtar_errc(bsdtar, 1, errno, "No memory");

			configfile(bsdtar, conffile);

			/* Free string allocated by asprintf. */
			free(conffile);
		}

		/* Process options from system-wide tarsnap.conf. */
		configfile(bsdtar, ETC_TARSNAP_CONF);
	}

	/* Continue with more sanity-checking. */
	if ((bsdtar->ntapes == 0) &&
	    (bsdtar->mode != OPTION_PRINT_STATS &&
	     bsdtar->mode != OPTION_LIST_ARCHIVES &&
	     bsdtar->mode != OPTION_RECOVER &&
	     bsdtar->mode != OPTION_FSCK &&
	     bsdtar->mode != OPTION_FSCK_PRUNE &&
	     bsdtar->mode != OPTION_NUKE))
		bsdtar_errc(bsdtar, 1, 0,
		    "Archive name must be specified");
	if ((bsdtar->ntapes > 1) &&
	    (bsdtar->mode != OPTION_PRINT_STATS &&
	     bsdtar->mode != 'd'))
		bsdtar_errc(bsdtar, 1, 0,
		    "Option -f may only be specified once in mode %s",
		    bsdtar->modestr);
	if ((bsdtar->mode == 'c') &&
	    (strlen(bsdtar->tapenames[0]) > 1023))
		bsdtar_errc(bsdtar, 1, 0,
		    "Cannot create an archive with a name > 1023 characters");
	if ((bsdtar->mode == 'c') &&
	    (strlen(bsdtar->tapenames[0]) == 0))
		bsdtar_errc(bsdtar, 1, 0,
		    "Cannot create an archive with an empty name");
	if ((bsdtar->cachedir == NULL) &&
	    (((bsdtar->mode == 'c') && (!bsdtar->option_dryrun)) ||
	     bsdtar->mode == 'd' ||
	     bsdtar->mode == OPTION_RECOVER ||
	     bsdtar->mode == OPTION_FSCK ||
	     bsdtar->mode == OPTION_FSCK_PRUNE ||
	     bsdtar->mode == OPTION_PRINT_STATS))
		bsdtar_errc(bsdtar, 1, 0,
		    "Cache directory must be specified for %s",
		    bsdtar->modestr);
	if (tarsnap_opt_aggressive_networking != 0) {
		if ((bsdtar->bwlimit_rate_up != 0) ||
		    (bsdtar->bwlimit_rate_down != 0)) {
			bsdtar_warnc(bsdtar, 0,
			    "--aggressive-networking is incompatible with"
			    " --maxbw-rate options;\n"
			    "         disabling --aggressive-networking");
			tarsnap_opt_aggressive_networking = 0;
		}
	}

	/*
	 * The -f option doesn't make sense for --list-archives, --fsck,
	 * --fsck-prune, or --nuke.
	 */
	if ((bsdtar->ntapes > 0) &&
	    (bsdtar->mode != OPTION_PRINT_STATS))
		only_mode(bsdtar, "-f", "cxtdr");

	/*
	 * These options don't make sense for the "delete" and "convert to
	 * tar" modes.
	 */
	if (bsdtar->pending_chdir)
		only_mode(bsdtar, "-C", "cxt");
	if (bsdtar->names_from_file)
		only_mode(bsdtar, "-T", "cxt");
	if (bsdtar->newer_ctime_sec || bsdtar->newer_ctime_nsec)
		only_mode(bsdtar, "--newer", "cxt");
	if (bsdtar->newer_mtime_sec || bsdtar->newer_mtime_nsec)
		only_mode(bsdtar, "--newer-mtime", "cxt");
	if (bsdtar->option_absolute_paths)
		only_mode(bsdtar, "-P", "cxt");
	if (bsdtar->option_null)
		only_mode(bsdtar, "--null", "cxt");

	/* Check options only permitted in certain modes. */
	if (bsdtar->option_dont_traverse_mounts)
		only_mode(bsdtar, "--one-file-system", "c");
	if (bsdtar->option_fast_read)
		only_mode(bsdtar, "--fast-read", "xt");
	if (bsdtar->option_no_subdirs)
		only_mode(bsdtar, "-n", "c");
	if (bsdtar->option_no_owner)
		only_mode(bsdtar, "-o", "x");
	if (bsdtar->option_stdout)
		only_mode(bsdtar, "-O", "xt");
	if (bsdtar->option_unlink_first)
		only_mode(bsdtar, "-U", "x");
	if (bsdtar->option_warn_links)
		only_mode(bsdtar, "--check-links", "c");
	if (bsdtar->option_dryrun)
		only_mode(bsdtar, "--dry-run", "c");

	/* Check other parameters only permitted in certain modes. */
	if (bsdtar->symlink_mode != '\0') {
		strcpy(buff, "-?");
		buff[1] = bsdtar->symlink_mode;
		only_mode(bsdtar, buff, "c");
	}
	if (bsdtar->strip_components != 0)
		only_mode(bsdtar, "--strip-components", "xt");

	/*
	 * If the keyfile in the config file is invalid but we're doing a
	 * dryrun, continue anyway (and don't use a cachedir).
	 */
	if (bsdtar->config_file_keyfile_failed && bsdtar->option_dryrun &&
	    bsdtar->cachedir != NULL) {
		bsdtar_warnc(bsdtar, 0,
		    "Ignoring cachedir due to missing or invalid "
		    "keyfile in config file.");
		free(bsdtar->cachedir);
		bsdtar->cachedir = NULL;
	}

	/*
	 * Canonicalize the path to the cache directories.  This is
	 * necessary since the tar code can change directories.
	 */
	if (bsdtar->cachedir != NULL) {
		build_dir(bsdtar, bsdtar->cachedir, "--cachedir");
		if (realpath(bsdtar->cachedir, cachedir) == NULL)
			bsdtar_errc(bsdtar, 1, errno, "realpath(%s)",
			    bsdtar->cachedir);
		free(bsdtar->cachedir);
		if ((bsdtar->cachedir = strdup(cachedir)) == NULL)
			bsdtar_errc(bsdtar, 1, errno, "Out of memory");
	}

	/* If we're running --fsck, figure out which key to use. */
	if (bsdtar->mode == OPTION_FSCK) {
		if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_PUT) == NULL)
			bsdtar->mode = OPTION_FSCK_WRITE;
		else if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_DELETE) == NULL)
			bsdtar->mode = OPTION_FSCK_DELETE;
		else
			bsdtar_errc(bsdtar, 1, 0,
			    "The write or delete authorization key is"
			    " required for --fsck but is not available");
	}

	/* If we're running --recover, figure out which key to use. */
	if (bsdtar->mode == OPTION_RECOVER) {
		if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_PUT) == NULL)
			bsdtar->mode = OPTION_RECOVER_WRITE;
		else if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_DELETE) == NULL)
			bsdtar->mode = OPTION_RECOVER_DELETE;
		else
			bsdtar_errc(bsdtar, 1, 0,
			    "The write or delete authorization key is"
			    " required for --recover but is not available");
	}

	/* Make sure we have whatever keys we're going to need. */
	if (bsdtar->have_keys == 0) {
		if (!bsdtar->option_dryrun) {
			bsdtar_errc(bsdtar, 1, 0,
			    "Keys must be provided via --keyfile option");
		} else {
			if (bsdtar->cachedir != NULL) {
				bsdtar_errc(bsdtar, 1, 0,
				    "Option mismatch for --dry-run: cachedir"
				    " specified but no keyfile");
			}
			if (crypto_keys_generate(CRYPTO_KEYMASK_USER))
				bsdtar_errc(bsdtar, 1, 0,
				    "Error generating keys");
			if (bsdtar->option_print_stats)
				bsdtar_warnc(bsdtar, 0,
				    "Performing dry-run archival without keys\n"
				    "         (sizes may be slightly "
				    "inaccurate)");
		}
	}

	missingkey = NULL;
	switch (bsdtar->mode) {
	case 'c':
		if (argv_has_archive_directive(bsdtar))
			missingkey = crypto_keys_missing(CRYPTO_KEYMASK_WRITE | CRYPTO_KEYMASK_READ);
		else
			missingkey = crypto_keys_missing(CRYPTO_KEYMASK_WRITE);
		break;
	case OPTION_RECOVER_WRITE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_WRITE);
		break;
	case 'd':
	case OPTION_FSCK_PRUNE:
	case OPTION_FSCK_DELETE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_READ |
		    CRYPTO_KEYMASK_AUTH_DELETE);
		break;
	case OPTION_FSCK_WRITE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_READ |
		    CRYPTO_KEYMASK_AUTH_PUT);
		break;
	case OPTION_NUKE:
	case OPTION_RECOVER_DELETE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_AUTH_DELETE);
		break;
	case OPTION_PRINT_STATS:
		/* We don't need keys for printing global stats. */
		if (bsdtar->ntapes == 0)
			break;

		/* FALLTHROUGH */
	case OPTION_LIST_ARCHIVES:
	case 'r':
	case 't':
	case 'x':
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_READ);
		break;
	}
	if (missingkey != NULL)
		bsdtar_errc(bsdtar, 1, 0,
		    "The %s key is required for %s but is not available",
		    missingkey, bsdtar->modestr);

	/* Tell the network layer how much bandwidth to use. */
	if (bsdtar->bwlimit_rate_up == 0)
		bsdtar->bwlimit_rate_up = 1000000000.;
	if (bsdtar->bwlimit_rate_down == 0)
		bsdtar->bwlimit_rate_down = 1000000000.;
	network_bwlimit(bsdtar->bwlimit_rate_down, bsdtar->bwlimit_rate_up);

	/* Perform the requested operation. */
	switch(bsdtar->mode) {
	case 'c':
		tarsnap_mode_c(bsdtar);
		break;
	case 'd':
		tarsnap_mode_d(bsdtar);
		break;
	case OPTION_FSCK_DELETE:
		tarsnap_mode_fsck(bsdtar, 0, 1);
		break;
	case OPTION_FSCK_PRUNE:
		tarsnap_mode_fsck(bsdtar, 1, 1);
		break;
	case OPTION_FSCK_WRITE:
		tarsnap_mode_fsck(bsdtar, 0, 0);
		break;
	case OPTION_PRINT_STATS:
		tarsnap_mode_print_stats(bsdtar);
		break;
	case OPTION_RECOVER_DELETE:
		tarsnap_mode_recover(bsdtar, 1);
		break;
	case OPTION_RECOVER_WRITE:
		tarsnap_mode_recover(bsdtar, 0);
		break;
	case OPTION_LIST_ARCHIVES:
		tarsnap_mode_list_archives(bsdtar);
		break;
	case OPTION_NUKE:
		tarsnap_mode_nuke(bsdtar);
		break;
	case 'r':
		tarsnap_mode_r(bsdtar);
		break;
	case 't':
		tarsnap_mode_t(bsdtar);
		break;
	case 'x':
		tarsnap_mode_x(bsdtar);
		break;
	}

#ifdef DEBUG_SELECTSTATS
	double N, mu, va, max;

	network_getselectstats(&N, &mu, &va, &max);
	fprintf(stderr, "Time-between-select-calls statistics:\n");
	fprintf(stderr, "N = %6g   mu = %12g ms  "
	    "va = %12g ms^2  max = %12g ms\n",
	    N, mu * 1000, va * 1000000, max * 1000);
#endif

#ifdef PROFILE
	/*
	 * If we're compiling with profiling turned on, chdir to a directory
	 * into which we're likely to be able to write to before exiting.
	 */
	if (bsdtar->cachedir != NULL)
		chdir(cachedir);
#endif

	if (bsdtar->return_value != 0)
		bsdtar_warnc(bsdtar, 0,
		    "Error exit delayed from previous errors.");
	return (bsdtar->return_value);
}
Ejemplo n.º 30
0
int main(int argc, char *argv[])
{
  try
  {
    edmplugin::PluginManager::configure(edmplugin::standard::config());
  }
  catch (cms::Exception& e)
  {
    edm::LogInfo("DDCompareCPV") << "Attempting to configure the plugin manager. Exception message: " << e.what();
    return 1;
  }
  
    // Process the command line arguments
    std::string descString("DDCompareCPV");
    descString += " [options] configurationFileName1 configurationFileName2 Compares two DDCompactViews\n";
    descString += "Allowed options";
    boost::program_options::options_description desc(descString);   
    desc.add_options()
      ("help,h", "Print this help message")
      ("file1,f", boost::program_options::value<std::string>(), "XML configuration file name. "
       "Default is DetectorDescription/RegressionTest/test/configuration.xml")
      ("file2,g", boost::program_options::value<std::string>(), "XML configuration file name. "
       "Default is DetectorDescription/RegressionTest/test/configuration.xml")
      ("dist-tolerance,t", boost::program_options::value<std::string>(), "Value tolerance for distances (in mm). "
       "Default value 0.0004 (anything larger is an error)")
      ("rot-tolerance,r", boost::program_options::value<std::string>(), "Value tolerance for rotation matrix elements. "
       "Default value is 0.0004 (anything larger is an error)")
      ("spec-tolerance,s", boost::program_options::value<std::string>(), "Value tolerance for rotation matrix elements. "
       "Default value is 0.0004 (anything larger is an error) NOT USED YET")
      ("user-ns,u", "Use the namespaces in each file and do NOT use the filename as namespace. "
       "Default is to use the filename of each file in the configuration.xml file as a filename")
      ("comp-rot,c", "Use the rotation name when comparing rotations. "
       "Default is to use the matrix only and not the name when comparing DDRotations")
      ("continue-on-error,e", "Continue after an error in values. "
       "Default is to stop at the first error. NOT IMPLEMENTED")
      ("attempt-resync,a", "Continue after an error in graph position, attempt to resync. "
       "Default is to stop at the first mis-match of the graph. NOT IMPLEMENTED");
    
    boost::program_options::positional_options_description p;
    p.add("file1", 1);
    p.add("file2", 2);
    
    boost::program_options::variables_map vm;
    try {
      store(boost::program_options::command_line_parser(argc,argv).options(desc).positional(p).run(),vm);
      notify(vm);
    } catch(boost::program_options::error const& iException) {
      std::cerr << "Exception from command line processing: "
                << iException.what() << "\n";
      std::cerr << desc << std::endl;
      return 1;
    }
    if(vm.count("help")) {
      std::cout << desc << std::endl;
      return 0;
    }

    bool fullPath = false;
    std::string configfile("DetectorDescription/RegressionTest/test/configuration.xml");
    std::string configfile2("DetectorDescription/RegressionTest/test/configuration.xml");
    DDCompOptions ddco;
    //    double dtol(0.0004), rottol(0.0004);
    // bool usrns(false), comprot(false);
    bool usrns(false);
    try {
      if (vm.count("file1")) {
	configfile = vm["file1"].as<std::string>();
	if (vm.count("file2")) {
	  configfile2 = vm["file2"].as<std::string>();
	}
      }
      if (vm.count("dist-tolerance"))
	ddco.distTol_ = vm["dist-tolerance"].as<double>();
      if (vm.count("rot-tolerance"))
	ddco.rotTol_ = vm["rot-tolerance"].as<double>();
      if (vm.count("spec-tolerance"))
	ddco.rotTol_ = vm["spec-tolerance"].as<double>();
      if (vm.count("user-ns")) 
	usrns = true;
      if (vm.count("comp-rot")) 
	ddco.compRotName_ = true;
      if (vm.count("continue-on-error")) 
	ddco.contOnError_ = true;
      if (vm.count("attempt-resync"))
	ddco.attResync_ = true;
    }
    catch(boost::exception& e)
    {
      edm::LogInfo("DDCompareCPV") << "Attempting to parse the options. Exception message: " << boost::diagnostic_information(e);
      return 1;
    }

    std::ios_base::fmtflags originalFlags = std::cout.flags();
    
    std::cout << "Settings are: " << std::endl;
    std::cout << "Configuration file 1: " << configfile << std::endl;
    std::cout << "Configuration file 2: " << configfile2 << std::endl;
    std::cout << "Length/distance tolerance: " << ddco.distTol_ << std::endl;
    std::cout << "Rotation matrix element tolerance: " << ddco.rotTol_ << std::endl;
    std::cout << "SpecPar tolerance: " << ddco.specTol_ << std::endl;
    std::cout << "User controlled namespace (both file sets)? " << std::boolalpha << usrns << std::endl;
    std::cout << "Compare Rotation names? " << ddco.compRotName_ << std::endl;
    std::cout << "Continue on error (data mismatch)? " << ddco.contOnError_ << std::endl;
    std::cout << "Attempt resyncronization of disparate graphs? " << ddco.attResync_ << std::endl;

    DDCompactView cpv1;
    DDLParser myP(cpv1);
    myP.getDDLSAX2FileHandler()->setUserNS(usrns);

    /* The configuration file tells the parser what to parse.
       The sequence of files to be parsed does not matter but for one exception:
       XML containing SpecPar-tags must be parsed AFTER all corresponding
       PosPart-tags were parsed. (Simply put all SpecPars-tags into seperate
       files and mention them at end of configuration.xml. Functional SW 
       will not suffer from this restriction).
    */  

    // Use the File-In-Path configuration document provider.
    FIPConfiguration fp(cpv1);
    try
    {
      fp.readConfig(configfile, fullPath);
    }
    catch (cms::Exception& e)
    {
      edm::LogInfo("DDCompareCPV") << "Attempting to read config. Exception message: " << e.what();
      return 1;
    }
    
    std::cout << "FILE 1: " << configfile << std::endl;
    if ( fp.getFileList().size() == 0 ) {
      std::cout << "FILE 1: configuration file has no DDD xml files in it!" << std::endl;
      exit(1);
    }
    int parserResult = myP.parse(fp);
    if (parserResult != 0) {
      std::cout << "FILE 1: problem encountered during parsing. exiting ... " << std::endl;
      exit(1);
    }
    cpv1.lockdown();

    DDCompactView cpv2;
    DDLParser myP2(cpv2);
    myP2.getDDLSAX2FileHandler()->setUserNS(usrns);

    /* The configuration file tells the parser what to parse.
       The sequence of files to be parsed does not matter but for one exception:
       XML containing SpecPar-tags must be parsed AFTER all corresponding
       PosPart-tags were parsed. (Simply put all SpecPars-tags into seperate
       files and mention them at end of configuration.xml. Functional SW 
       will not suffer from this restriction).
    */  

    // Use the File-In-Path configuration document provider.
    FIPConfiguration fp2(cpv2);
    fp2.readConfig(configfile2, fullPath);
    std::cout << "FILE 2: " << configfile2 << std::endl;
    if ( fp2.getFileList().size() == 0 ) {
      std::cout << "FILE 2: configuration file has no DDD xml files in it!" << std::endl;
      exit(1);
    }
    int parserResult2 = myP2.parse(fp2);
    if (parserResult2 != 0) {
      std::cout << "FILE 2: problem encountered during parsing. exiting ... " << std::endl;
      exit(1);
    }
    cpv2.lockdown();

    std::cout << "Parsing completed. Start comparing." << std::endl;

//      DDErrorDetection ed(cpv1);

//      bool noErrors = ed.noErrorsInTheReport(cpv1);
//      if (noErrors && fullPath) {
//        std::cout << "DDCompareCPV did not find any errors and is finished." << std::endl;
//      }
//     else {
//       ed.report(cpv1, std::cout);
//       if (!noErrors) {
//         return 1;
//       }
//     }

    DDCompareCPV ddccpv(ddco);
    bool graphmatch = ddccpv(cpv1, cpv2);

    if (graphmatch) {
      std::cout << "DDCompactView graphs match" << std::endl;
    } else {
      std::cout << "DDCompactView graphs do NOT match" << std::endl;
    }

    // Now set everything back to defaults
    std::cout.flags( originalFlags );

    return 0;
}