#Reorganizes the arrays in TGraph in a way x is ascending, as ROOT is stupidly behaving when plotting when it is not the case
#Renata Kopecna

from ROOT import TTree, TChain, TFile, TVector3, TObject, TGraphErrors, TGraph
import numpy as np
import os

def redoGraph(Run, graphFile, name):

    graph = graphFile.Get("MLP "+name+"Run"+str(Run))
    size = graph.GetN()
    buffer_X = graph.GetX()
    X = np.fromiter(buffer_X,dtype=np.float, count = size)
    buffer_Y = graph.GetY()
    Y = np.fromiter(buffer_Y,dtype=np.float, count = size)
    arr = np.column_stack((X,Y))
    arr = np.unique(arr,axis=0)
    print(arr)

    X = arr[:,0].flatten('C')
    Y = arr[:,1].flatten('C')
    newGraph = TGraph(X.size,X,Y)
    newGraph.SetTitle(name)
    newGraph.SetName(name)
    return newGraph

def rewriteMVAscan(Run):
    path = "/home/lhcb/kopecna/B2KstarMuMu_clean/Data/Tuples/FinalSelection/KplusPi0Resolved_BDTscan_Run"+str(Run)+"_fine.root"

    graphFile = TFile.Open(path,"READ")

    list_of_names = ["sigYield","bkgYield","bkgYield_fromAllEvts","refYield","significance","significance_fromAllEvts"]
    
    newFile = TFile.Open(path.replace(".root","_new.root"),"RECREATE")
    newFile.cd()
    for name in list_of_names:
        redoGraph(Run,graphFile,name).Write()
    newFile.Close()
    graphFile.Close()

    cmd = "mv " + path + " " + path.replace(".root","_old.root")
    os.system(cmd)
    cmd = "mv " + path.replace(".root","_new.root") + " " + path
    os.system(cmd)
    

rewriteMVAscan(1)
rewriteMVAscan(2)
