/// \file
/// \ingroup tutorial_tree
/// \notebook -nodraw
/// Example of Root macro to copy a subset of a Tree to a new Tree, selecting entries.
///
/// Only selected entries are copied to the new Tree.
/// The input file has been generated by the program in `$ROOTSYS/test/Event`
/// with `Event 1000 1 99 1`
///
/// \macro_code
///
/// \author Rene Brun

R__LOAD_LIBRARY($ROOTSYS/test/libEvent.so)

void copytree3()
{
   // Get old file, old tree and set top branch address
   TString dir = "$ROOTSYS/test/Event.root";
   gSystem->ExpandPathName(dir);
   const auto filename = gSystem->AccessPathName(dir) ? "./Event.root" : "$ROOTSYS/test/Event.root";

   TFile oldfile(filename);
   TTree *oldtree;
   oldfile.GetObject("T", oldtree);

   const auto nentries = oldtree->GetEntries();

   Event *event = nullptr;
   oldtree->SetBranchAddress("event", &event);

   // Create a new file + a clone of old tree in new file
   TFile newfile("small.root", "recreate");
   auto newtree = oldtree->CloneTree(0);

   for (auto i : ROOT::TSeqI(nentries)) {
      oldtree->GetEntry(i);
      if (event->GetNtrack() > 605)
         newtree->Fill();
      event->Clear();
   }

   newtree->Print();
   newtree->Write();
}