import numpy as np
import glob
import matplotlib
matplotlib.use('Agg')
import pylab as P

fo=open('Luminosity_UV.out','w')
for i in xrange(3980,4000):
 if glob.glob('halo%05i.out'%i) ==  []:continue
 f=open('halo%05i.out'%i,'r')
 L=[]
 WL=[]
 for line in f:
    L.append(float(line.split()[1]))
    WL.append(float(line.split()[0]))
 f.close()
 L=np.array(L);WL=np.array(WL) 
 f=3.0e10/(WL/1.0e8)
 Lf=(WL/1.0e8)**2/3.0e10*L*1.0e8*3.846e33
 MAB = -5.0/2.0*np.log10(Lf/(4.0*3.14*(10.0*3.086e18)**2)/3631.0e-23)
 fo2=open('halo%05i.out'%i,'w')
 for j in xrange(len(WL)):
     #fo2.write(str(WL[j])+" "+str(L[j])+" "+str(f[j])+" "+str(Lf[j])+" "+str(MAB[j])+"\n")
     fo2.write("%7.5e %7.5e %7.5e %7.5e %7.5e \n"%(WL[j],L[j],f[j],Lf[j],MAB[j]))
 fo2.close()
 sumL=0.0
 M1500=0.0
 jj=0
 for j,Li in enumerate(L):
    if WL[j] < 1450: continue
    if WL[j] > 1550: break
    jj=jj+1
    sumL = sumL+Li
    M1500 = M1500+MAB[j]
    #if np.logical_and(j>0,j<len(L)-1):
    #   sumL=sumL+0.5*(WL[j+1]-WL[j-1])*Li
    #elif j==0:
    #   sumL=sumL+(WL[j+1]-WL[j])*Li
    #elif j==len(L)-1:
    #   sumL=sumL+(WL[j]-WL[j-1])*Li
 #print sumL,4.74-2.5*np.log10(sumL)
 sumL = sumL/jj*100
 M1500,=(MAB[WL==1495.0]+MAB[WL==1505.0])/2
 fo.write(str(i)+" "+str(sumL)+" "+str(5.48-2.5*np.log10(sumL))+" "+str(M1500)+"\n")
fo.close()
  
f=open('Luminosity_UV.out','r')
L=[]
L1=[]
for line in f:
    L.append(float(line.split()[2]))
    L1.append(float(line.split()[3]))  

f.close()
L=np.array(L)
L1=np.array(L1)
xmin = -20
xmax = -1
bin = 19
n, bins, patches = P.hist(L, bin,range=(xmin,xmax), normed=0, histtype='step',log=1) 
n1, bins, patches = P.hist(L1, bin,range=(xmin,xmax), normed=0, histtype='step',log=1)
#P.setp(patches, 'facecolor', 'g', 'alpha', 0.75)
P.savefig('LF_UV.png')
f=open('LF_UV.txt','w')
conv=1.0/(xmax-xmin)*bin/(6*6*6.125)
for M,ni,ni1 in zip(bins,n,n1):
    f.write(str(M)+" "+str(ni*conv)+" "+str(ni1*conv)+"\n") 

f.close()
   
