from __future__ import print_function
import math


cmdHeader = "OutPutTextBase>>"

def OutPutECASumText(eca,sp,ep,Header="RunXXXX"):
    xlist = []
    ylist = []
    elist = []

    for ii in range(sp,ep+1):
        ec = eca.Put(ii)

        tempx = ec.PutXList()
        tempy = ec.PutYList()
        tempe = ec.PutEList()
        
        for jj in range(len(tempy)):
            if ii == sp:
                xlist.append((tempx[jj]+tempx[jj+1])/2)
                ylist.append(tempy[jj])
                elist.append(tempe[jj])
            else:
                ylist[jj]+=tempy[jj]
                elist[jj] = math.sqrt(elist[jj]**2+tempe[jj]**2)

    footer = "_ecaSum.txt"
    filename = Header+footer
    
    f = open(filename,'w')
    for ii in range(len(xlist)):
        f.write("%f,%f,%f\n" %(xlist[ii],ylist[ii],elist[ii]))

    f.close

    print("%s OutPutfile is %s" %(cmdHeader, filename))
        
def OutPutEC(ec,filename):
    xlist = ec.PutX()
    ylist = ec.PutY()
    elist = ec.PutE()

    SaveString = ""
    for ii in range(len(ylist)):
        SaveString+= "%f,%f,%f\n" %((xlist[ii]+xlist[ii+1])/2,ylist[ii],elist[ii])
    
    if len(filename) ==0:
        filename = "outputEC.txt"
    fo = open(filename, "w")
    fo.write (SaveString)
    fo.close
    print("%s output file is %s" %(cmdHeader, filename))

def OutPutECAText(eca,filename):
    SaveString = ""
    for ii in range(eca.PutTableSize()):
        if ii % 100 == 0:
            print("%s %d / %d is finished" %(cmdHeader, ii, eca.PutTableSize()))

        ec = eca.Put(ii)
        xlist = ec.PutXList()
        ylist = ec.PutYList()
        elist = ec.PutEList()
        for jj in range(len(ylist)):
            SaveString += "%f\t%f\t%f\t%f\n" %(ii,(xlist[jj]+xlist[jj+1])/2,ylist[jj],elist[jj])

    f = open(filename, 'w')
    f.write(SaveString)
    f.close

    print("%s outputfile is %s" %(cmdHeader, filename))

def OutPutECMText(ecm):
    runno = ecm.PutHeader().PutString("RUNNUMBER")
    filenameHeader = "Run%s" %(runno)
    
    filename = ""
    for ii in range(ecm.PutTableSize()):
        eca = ecm.Put(ii)
        filename = "%s_ECA%d.txt" %(filenameHeader,ii)
        OutPutECAText(eca,filename)

    print("%s output is finished" %(cmdHeader))

