Copy trees with selections from different files using a function

Hi,
I want to copy trees with selections from different files, in addition I want create a new branch, my code compiles by crashes!

//FullMCSampleName is map<string,vector<string>>    
 for (auto &it : FullMCSampleName) {

        auto &value = it.second;
        gROOT->cd();
        TTree *tree = nullptr;
        CopyTree(value, tree, true);

        auto file = new TFile("TESTt.root", "recreate");
        tree->Write(); //[color=#FF0000] Here it crashes[/color]
        file->Close();
        delete file;
    }

void CopyTree(vector<string> &Files, TTree *&tree, bool MC) {

    int bjetCut = gDConfig["BjetCut"];

    for (auto &f_name : Files) {
        auto file = TFile::Open(f_name.c_str());
        if (file) {
            cout << f_name << " is opened \n";
        } else {
            cout << "could not find file " << f_name << endl;
            exit(0);
        }
	TTree *inputtree = nullptr;
        file->GetObject("variables", inputtree);

        float bjet_n;
        if (!bjetCut) {
            inputtree->SetBranchAddress("bjet_n", &bjet_n);
        }

	float LumiWeight = 1;
        if (tree == nullptr) {
            tree = inputtree->CloneTree(0);
            tree->Branch("LumiWeight", &LumiWeight, "LumiWeight/F");
        }

	if (MC) {
            TH1* h = nullptr;
            file->GetObject("Counter", h);
            LumiWeight = h->GetBinContent(h->GetNbinsX() + 1); //this is from the overflow bin
            delete h;
        }
	//loop over all events in one root file
        for (int iEvent = 0;; ++iEvent) {
            Long64_t ientry = inputtree->LoadTree(iEvent);
            if (ientry < 0) {
                break;
            }
            inputtree->GetEntry(ientry);

            if (!bjetCut) {
                if (bjet_n != bjetCut)
                    continue;
            }
            tree->Fill();
        }
	file->Close();
        delete file;
        break;

    }

}

it looks like the tree is allocated, but somehow I can not use it.
Cheers

Hi,

I would advise to run with gdb (gdb root.exe) and use ACLiC…

Cheers, Bertrand.

Instead of:[code] gROOT->cd();
TTree *tree = nullptr;
CopyTree(value, tree, true);

    auto file = new TFile("TESTt.root", "recreate");
    tree->Write(); //[color=#FF0000] Here it crashes[/color]
    file->Close();
    delete file;[/code]

Use[code]

auto file = new TFile(“TESTt.root”, “recreate”);
CopyTree(value, file, true);

    file->Write();
    file->Close();
    delete file;

void CopyTree(vector &Files, TFile *outputfile, bool MC) {
TTree *tree = nullptr;

if (tree == nullptr) {
tree = inputtree->CloneTree(0);
tree->SetDirectory(outputfile);
tree->Branch(“LumiWeight”, &LumiWeight, “LumiWeight/F”);
}

[/code]

Unless you have good reason not to, a TTree ought to be associated to a TFile while being filled.