#convert the maps to lists

from numpy import genfromtxt,pi
import sys

output='LQHya_map_2016.dat'

a=open('LQHya/map-espadons-2016.dat','r')
b=a.read()
a.close()
c=b.splitlines()
#print(c[3])

nlat=38
latdeg=180.0/nlat #the grid contains 38 latitudes

lon=[4,10,17,23,29,34,40,45,50,55,59,63,66,69,72,74,75,76,77,77,76,75,74,72,69,66,63,59,55,50,45,40,34,29,23,17,10,4] #number of longitudes on each latitude

Brad=[]
Bmer=[]
Bazi=[]
Temp=[]

rad=[]
mer=[]
azi=[] #add values to these until the latitude is full (see size from nlon)
temp=[]
    
i=0 #run this over latitudes; add +1 when Brad etc have been appended
ii=0 #use this to decide if the lists continue to next line or not
j=0

for j in range(0,int(len(c)/4)):
    er=c[j].split(',  ') #each line
    em=c[j+int(len(c)/4)].split(',  ')
    ea=c[j+2*int(len(c)/4)].split(',  ')
    et=c[j+3*int(len(c)/4)].split(',  ')
    #print(er)
    #print(em)
    #print(ea)
    #print(et)
    n=lon[i] #size of the latitude
    for f in range(0,len(er)): #each value in each line
        r=er[f].replace(',',' ')
        m=em[f].replace(',',' ')
        a=ea[f].replace(',',' ')
        t=et[f].replace(',',' ')
        rad.append(float(r)) #append until latitude is full
        mer.append(float(m))
        azi.append(float(a))
        temp.append(float(t))
        ii=ii+1
        if (ii==n):
            print(ii)
            Brad.append(rad)
            Bmer.append(mer)
            Bazi.append(azi)
            Temp.append(temp)
            rad=[]
            mer=[]
            azi=[]
            temp=[]
            ii=0
            i=i+1

#print(Brad[36])
#sys.exit()

out=open(output,'w')


#go through the grid

for q in range(0,nlat):
    nlon=lon[q]
    add=0.5*latdeg
    theta=(-90+add+q*latdeg)*pi/180
    print('theta='+str(theta*180/pi))
    print('nlon = ',nlon)
    for u in range(0,nlon):
        phi=((u+0.5)*360/nlon)*pi/180
        print(phi)
        out.write("%7.3f" % float(theta*180/pi)+' '+"%7.3f" % float(phi*180/pi)+' '+"%8.5f" % Brad[q][u]+' '+"%8.5f" % Bmer[q][u]+' '+"%8.5f" % Bazi[q][u]+' '+"%8.5f" % Temp[q][u]+'\n')
        
out.close()
