#ifndef MARS_MWriteRootFile
#define MARS_MWriteRootFile

#ifndef MARS_MWriteFile
#include "MWriteFile.h"
#endif
#ifndef ROOT_TObjArray
#include <TObjArray.h>
#endif

class TFile;
class TTree;
class TBranch;

class MRootFileBranch : public TNamed
{
private:
    TTree         *fTree;
    TBranch       *fBranch;

    MParContainer *fContainer;
    TString        fContName;

    void Init(const char *name, const char *title)
    {
        SetName(name?name:"");
        SetTitle(title?title:"");
    }

public:
    MRootFileBranch(const char *cname, const char *tname=NULL, const char *ttitle=NULL)
        : fTree(NULL), fBranch(NULL), fContainer(NULL)
    {
        Init(tname, ttitle);
        fContName = cname;
    }

    MRootFileBranch(MParContainer *cont, const char *tname=NULL, const char *ttitle=NULL)
        : fTree(NULL), fBranch(NULL), fContName("")
    {
        Init(tname, ttitle);
        fContainer = cont;
    }

    TTree         *GetTree() const      { return fTree; }
    MParContainer *GetContainer() const { return fContainer; }
    void          *GetAddress()         { return &fContainer; }
    TBranch       *GetBranch() const    { return fBranch; }
    const char    *GetContName() const  { return fContName; }

    void SetContainer(MParContainer *cont) { fContainer = cont; }
    void SetTree(TTree *tree)              { fTree = tree; }

    ClassDef(MRootFileBranch, 0) // Storage container for MWriteRootFile to store TBranch informations
};

class MWriteRootFile : public MWriteFile
{
private:
    TFile *fOut;

    TObjArray fBranches;
    TObjArray fTrees;

    void        CheckAndWrite() const;
    Bool_t      IsFileOpen() const;
    Bool_t      GetContainer(MParList *pList);
    const char *GetFileName() const;

public:
    MWriteRootFile(const char *fname,
                   const Option_t *opt="RECREATE",
                   const char *ftitle="Untitled",
                   const Int_t comp=9,
                   const char *name=NULL,
                   const char *title=NULL);
    ~MWriteRootFile();


    void AddContainer(const char *cname,
                      const char *tname=NULL, const char *ttitle=NULL);
    void AddContainer(MParContainer *cont,
                      const char *tname=NULL, const char *ttitle=NULL);


    void Print(Option_t *t=NULL) const;

    ClassDef(MWriteRootFile, 0)	// Class to write one container to a root file
};

#endif
