import numpy as np
import math

#massmax = 1.2e9
massmin = 1.0e6
bins =31  # 300
binwidth = 0.1 #math.log10(massmax/massmin)/bins
massmax = 10**(math.log10(massmin)+bins*binwidth)
#eV_erg = 6.24e11

f=open('PopIII_haloes.txt','r')

fo = open('PopIII_histogram.txt','w')

halolist = []
PopIIInumber = []

line = f.readline()
while line != '':
   halomass = float(line.split()[0])
   halolist.append(halomass)
   PopIIInumber.append(int(line.split()[1]))
   line = f.readline()

halocount = np.zeros(bins+1)
totalPopIII = np.zeros(bins+1)
totalhalo = np.zeros(bins+1)

for halomass,PopIII in zip(halolist,PopIIInumber):
   index = int((math.log10(halomass/massmin)+0.5*binwidth)/binwidth)
   if PopIII > 0:
     halocount[index] = halocount[index] + 1
     totalPopIII[index] = totalPopIII[index] + PopIII
   totalhalo[index] = totalhalo[index] + 1

cumulation = 0.0
bin = math.log10(massmin) + 0.5*binwidth
for count,PopIII,halo in zip(halocount,totalPopIII,totalhalo):
    cumulation = cumulation + PopIII
    fo.write(str(10**bin)+" "+str(count)+" "+str(PopIII)+" "+str(cumulation)+" "+str((PopIII/count if count > 0 else 0))+" "+str(halo)+"\n")
    bin =  bin + binwidth

f.close()
fo.close()


