;+
;
; PROJECT:  CHIANTI
;
;       CHIANTI is an atomic database package for the calculation of
;       continuum and emission line spectra from astrophysical plasmas. It is a 
;       collaborative project involving the Naval Research Laboratory
;       (Washington DC, USA), the Arcetri Observatory (Firenze, Italy), and the
;       Cambridge University (United Kingdom).
;
;
;
; NAME:
;	LATEX_WVL_DEM
;
; PURPOSE:
;
;	create a latex file of predicted spectral line intensities and
;       wavelengths corresponding to a selected abundance and differential
;       emission measure (DEM)
;
; CATEGORY:
;
;	science.
;
; CALLING SEQUENCE:
;
;       LATEX_WVL_DEM, Wmin, Wmax, Pressure
;
;
; INPUTS:
;
;	Wmin:   lower limit of the wavelength/energy range of interest (Angstroms)
;               if kev keyword set, then wmin is in kev	
;	Wmax:   upper limit of the wavelength/energy range of interest (Angstroms)
;               if kev keyword set, then wmax is in kev	
;       Pressure:  electron density (cm-3) * temperature (K), assumed constant	
;
; OPTIONAL INPUTS:
;
;	Elemental abundance file:  selected with widget
;       Ionization equilibrium file:  selected with widget
;       Differential emission measure file:  selected with widget
;	
; KEYWORD PARAMETERS:
;
;	MINI:	Minimum intensity for line to be included in output
;
;	SNGL_ION:  specified a single ion to be used instead of the complete
;                  set of ions specified in !xuvtop/masterlist/masterlist.ions
;
;       PHOTONS:  units will be in photons rather than ergs
;
;       KEV:  wavelengths will be given in kev rather than Angstroms
;
;
;       MASTERLIST:  string of a specific masterlist file or set to '' to select a 
;                particular masterlist file.  Otherwise, masterlist.ions is used
;
;
;       OUTFILE:  the name of the file to be written.

; OUTPUTS:
;
;	a latex file:  linelist.tex in the user's working  directory 
;
;
;
; COMMON BLOCKS:
;
;	common elvlc,l1a,term,conf,ss,ll,jj,ecm,eryd,ecmth,erydth,eref
;       common wgfa, wvl,gf,a_value
;       common upsilon,t_type,deu,c_ups,splups
;       common elements,abund,abund_ref,ioneq,ioneq_t,ioneq_ref,ionpot,ip_ref
;
;
; SIDE EFFECTS:
;
;	Some of the ions have 100+ energy levels and the inversion of the
;       necessary matrices can be time consuming
;
;
; EXAMPLE:
;
;             > latex_wvl_dem,100.,200.,1.e+15,mini=10.,sngl_ion='c_2'
;
; MODIFICATION HISTORY:
; 	Written by:	Ken Dere
;	March 1996:     Version 2.0
;       September 1996:   modified to work with VMS
;       September 1998:  Ken Dere added kev keyword
;       December 1998:  Modified for use with CHIANTI database version 3.0  
;       April 2000:  uses latex longtable style
;       14-Jul-2000:   Peter Young, now calls pop_solver
;       30-Oct-2000: Giulio Del Zanna, added the keyword outfile and changed
;                    default. Now it creates an 'linelist_dem.tex' file in the
;                    working directory. Added minor things.
;
; VERSION     : Version 8, 30-Oct-2000
; 
;
;-
pro latex_wvl_dem,wmin,wmax,pressure,minI=minI,sngl_ion=sngl_ion,photons=photons,kev=kev, $
         masterlist=masterlist,elapsed=elapsed, outfile=outfile
;
;  wmin=short wavelength limit in Angstroms
;  wmax=long wavelength limit in Angstroms
;  pressure = electron pressure (Ne*T) in cm^(-3) K
;
;  set mini= minimum intensity for which lines will be output, i.e. mini=0.1
;  set sngl_ion to select only on ion, i.e. sngl_ion='fe_15' to do Fe_XV
;
; to create a latex table of wavelength, transitions  and intensity information  etc
;   filename='linelist_int.tex'
;
;  derived from latex_wvl_int.pro
;
;
common elvlc,l1a,term,conf,ss,ll,jj,ecm,eryd,ecmth,erydth,eref
common wgfa, wvl,gf,a_value
common upsilon,t_type,deu,c_ups,splups
common elements,abund,abund_ref,ioneq,ioneq_t,ioneq_ref
;
if n_params(0) lt 3 then begin
  print,'  IDL>  latex_wvl_dem,wmin,wmax,pressure, $'
  print,'    [outfile= , mini= , sngl_ion=, /photons, /kev ,/elapsed, masterlist=]'
  return
endif
;
;
if keyword_set(elapsed) then time0=systime(1)  ; check on how long the procedure takes
;
ang2kev=12.39854d
;
if keyword_set(minI) then begin
   min_int=minI
endif else min_int=0.
;
if keyword_set(photons) then begin
   wmin=ang2kev/wmax
   wmax=ang2kev/wmin
endif
;
;
setup_elements
;
n_ioneq_t=n_elements(ioneq_t)
dlnt=alog(10.^(ioneq_t(1)-ioneq_t(0)))
;
;
;  select differential emission measure (.dem) file
;
dir=add_subdir(!xuvtop,'dem')
dem_name=pickfile(path=dir,filter='*.dem',title='Select DEM File')
;   print,' latex_title= ',latex_title
;
read_dem,dem_name,dem_t,dem,dem_ref
;
i1=strpos(dem_name,'/dem/')
i2=strpos(dem_name,'.dem')
latex_title=strmid(dem_name,i1+5,i2-i1-5)
latex_title=ch_repstr(latex_title,'_','\_')
;
;
gdt=where((ioneq_t ge min(dem_t)) and (ioneq_t le max(dem_t)))
;
dem_int1=10.^(spline(dem_t,dem,ioneq_t(gdt)))
dem_int=fltarr(n_ioneq_t)
ngt=n_elements(gdt)
for igt=0,ngt-1 do begin
   dem_int(gdt(igt))=dem_int1(igt)
endfor
;
b=where((ioneq_t lt min(dem_t)) and (ioneq_t gt max(dem_t)))
if max(b) ge 0 then dem_int(b)=0.
;  for it=0,n_ioneq_t-1 do begin
;     print,it,ioneq_t(it),dem_int(it)
;  endfor

;
linesperpage=41
;
spd=['S','P','D','F','G','H','I','K']
jvalue=['0','1/2','1','3/2','2','5/2','3','7/2','4','9/2','5','11/2','13/2','15/2','17/2','19/2']
;
maxwvl=30000
;
mast_z=intarr(maxwvl)
mast_ion=intarr(maxwvl)
mast_lvl=intarr(maxwvl)
mast_wvl=fltarr(maxwvl)
mast_A=fltarr(maxwvl)
mast_snote=strarr(maxwvl)
;
mast_term1=strarr(maxwvl)
mast_desig1=strarr(maxwvl)
mast_term2=strarr(maxwvl)
mast_desig2=strarr(maxwvl)
;
mast_abund=fltarr(maxwvl)
mast_ioneq=fltarr(maxwvl)
mast_tmax=fltarr(maxwvl)
mast_pop=fltarr(maxwvl)
mast_popazidem=fltarr(maxwvl)
;
mast_index=0
;
;
;
;  open the file that has the names of the ions
;
if ch_datatype(masterlist,2) gt 0 then begin
   mname=masterlist
endif else begin
   mname=!xuvtop+'/masterlist/masterlist.ions'
endelse
;
if keyword_set(sngl_ion) then begin
   list=sngl_ion
endif else begin
   read_masterlist,mname,list
endelse
;
nlist=n_elements(list)
;
elstage=''
;
;   main input and calculation loop  **************
;
for ilist=0,nlist-1 do begin
;
;
   gname=list(ilist)
   convertname,gname,iz,ion
   ion2spectroscopic,gname,snote
;
print,' current ion = ',gname  
;
abundtest=abund(iz-1)
if (abundtest gt 0.) then begin  ;********************************************
;
   elstage=elstage+snote+', '  
;
;
setup_ion,gname,wmin,wmax,wvltst,lvl1,lvl2,wvl1,gf1,a_value1
;
;
if (wvltst gt 0) then begin  ;***********************************************
;
;
;
;
locname=strlowcase(gname)
pos=strpos(locname,'_')
l=strlen(pos)
first=strmid(locname,0,pos)
last=strmid(locname,pos+1,l-pos-1)
;
if strpos(last,'d') ge 0 then dielectronic=1 else dielectronic=0
;
;
;
  ntrans=n_elements(lvl1)
  nlvls=max([lvl1,lvl2])
;
;
;  calculate level populations
;
        this_ioneq=ioneq(*,iz-1,ion-1+dielectronic)
;
        itmax=where(this_ioneq eq max(this_ioneq))
        ltmax=ioneq_t(itmax)
        tmax=10.^(ioneq_t(itmax))
        tmax=tmax(0)  ; necessary to make tmax a scalar
;
       gioneq_t=where((this_ioneq gt 0.) and (dem_int gt 0.),ngt)
;

;
        popazidem=dblarr(nlvls)
;
if ngt gt 0 then begin
for ig=0,ngt-1 do begin
   it=gioneq_t(ig)
   tt=10.^ioneq_t(it)
   edensity=pressure/tt
   pop_solver,tt,edensity,pop
   pop = reform(pop)
   dt=tt*dlnt
   popazidem(0)=popazidem(*)+pop(*)*this_ioneq(it)*dem_int(it)*dt/edensity
endfor
;


   for itrans=0,ntrans-1 do begin
      l1=lvl1(itrans)-1
      l2=lvl2(itrans)-1
      ww=wvl1(itrans)
;     print,ww,l1,l2
;
;     can the level be excited?
      upssiz=size(splups)
      upssiz2=upssiz(2)-1
      if(l2 le upssiz2) then begin
         maxups=max(splups(*,l2,0))
         if(maxups gt 0.) then upstst=1 else upstst=0
      endif else upstst=0
;
;
;
     if (abs(ww) gt wmin) and (abs(ww) le wmax) and (upstst gt 0) then begin
        if(abs(ww) gt 0.) then begin   ;  select only observed wvl's
           mast_z(mast_index)=iz
           mast_ion(mast_index)=ion
           mast_snote(mast_index)=snote
           mast_lvl(mast_index)=lvl2(itrans)
           mast_wvl(mast_index)=wvl1(itrans)
           mast_A(mast_index)=a_value1(itrans)
           mast_abund(mast_index)=abund(iz-1)
;
           mast_tmax(mast_index)=ltmax
           mast_ioneq(mast_index)=this_ioneq(itmax)
           mast_popazidem(mast_index)=popazidem(l2)
;
;      print,iz,ion,wvl1(itrans),popazidem(l2)
       
;
;  get lower level designation
           term0=strtrim(term(l1),2)
;
           term1=''
           blank=strpos(term0,' ')
           while blank gt 0 do begin
              term1=term1+' '+strmid(term0,0,blank)
              term0=strmid(term0,blank,100)
              term0=strtrim(term0,2)
              blank=strpos(term0,' ')
           endwhile
           ch_remchar,term1,'^'
           mast_term1(mast_index)=strlowcase(term1)
;
           jinteger=fix(2.*jj(l1))
           jstring=jvalue(jinteger)
;
           spins=strtrim(string(ss(l1),'(i2)'),2)
           mast_desig1(mast_index)= $
              '$^'+spins+'$'+spd(ll(l1))+'$_{'+jstring+'}$'
;
;
;  get upper level designation
           term0=strtrim(term(l2),2)
;
           term2=''
           blank=strpos(term0,' ')
;           print,term0
           while blank gt 0 do begin
              term2=term2+' '+strmid(term0,0,blank)
              term0=strmid(term0,blank,100)
              term0=strtrim(term0,2)
              blank=strpos(term0,' ')
           endwhile
           ch_remchar,term2,'^'
           mast_term2(mast_index)=strlowcase(term2)

;
           jinteger=fix(2.*jj(l2))
           jstring=jvalue(jinteger)
;
           spins=strtrim(string(ss(l2),'(i2)'),2)
           mast_desig2(mast_index)= $
              '$^'+spins+'$'+spd(ll(l2))+'$_{'+jstring+'}$'
;
           mast_index=mast_index+1
           if mast_index gt  maxwvl then begin
              print,' need to increase size of maxwvl'
              print,' current value of maxwvl = ',maxwvl
              stop
           endif
        endif
     endif
   endfor ;  over itrans  (spectral lines)
;
endif  else begin
   print,' ionization equilibrium eq 0 in DEM temperature interval' ;  ngt gt 0
endelse
;
endif else begin
   print,' no lines in specified wavelength interval'    ; wvltest
endelse
;
endif else print,' elemental abundance = 0'   ;  abundtest  ****************
;
;
;
;
endfor   ;  loop over ions list
;
;   end of main input and calculation loop   ***************
;
;
print,' number of lines =',mast_index
if mast_index gt maxwvl-1 then begin
    print,' must increase size of maxwvl to ',mast_index
    return
endif else if mast_index le 0 then begin
    print,' No lines in this wavelength region'
    return
endif
;
;
mast_z=mast_z(0:mast_index-1)
mast_ion=mast_ion(0:mast_index-1)
mast_snote=mast_snote(0:mast_index-1)
mast_lvl=mast_lvl(0:mast_index-1)
mast_wvl=mast_wvl(0:mast_index-1)
mast_A=mast_A(0:mast_index-1)
mast_term1=mast_term1(0:mast_index-1)
mast_desig1=mast_desig1(0:mast_index-1)
mast_term2=mast_term2(0:mast_index-1)
mast_desig2=mast_desig2(0:mast_index-1)
;
mast_abund=mast_abund(0:mast_index-1)
mast_tmax=mast_tmax(0:mast_index-1)
mast_ioneq=mast_ioneq(0:mast_index-1)
mast_popazidem=mast_popazidem(0:mast_index-1)
;
;

srt_index=sort(abs(mast_wvl))
mast_z(0)=mast_z(srt_index)
mast_ion(0)=mast_ion(srt_index)
mast_snote(0)=mast_snote(srt_index)
mast_lvl(0)=mast_lvl(srt_index)
mast_wvl(0)=mast_wvl(srt_index)
mast_A=mast_A(srt_index)
mast_term1=mast_term1(srt_index)
mast_desig1=mast_desig1(srt_index)
mast_term2=mast_term2(srt_index)
mast_desig2=mast_desig2(srt_index)
;
mast_abund=mast_abund(srt_index)
mast_tmax=mast_tmax(srt_index)
mast_ioneq=mast_ioneq(srt_index)
mast_popazidem=mast_popazidem(srt_index)
;
nlines=mast_index
;
intensity=fltarr(nlines)
;
;
;
for iline=0,nlines-1 do begin
   if keyword_set(photons) then begin
       hc=1.d/(4.d*3.14159d)
   endif else begin
       hc=6.626d-27*2.998d+10*1.d+8/(4.d*3.14159d*abs(mast_wvl(iline)))
   endelse
;
   intensity(iline)=hc*mast_abund(iline)*mast_A(iline)*mast_popazidem(iline)
endfor
;
if keyword_set(kev) then mast_wvl=ang2kev/mast_wvl
;
;for i=0,nlines-1 do begin
;print,mast_z(i),mast_ion(i),mast_lvl(i),mast_wvl(i),mast_A(i),mast_tmax(i),  $
;   format='$(3i3,f12.3,2e10.3)'
;endfor
;
lines=0
;

IF n_elements(outfile) EQ 0 THEN outfile = 'linelist_dem.tex'
;outname='~/linelist_dem.tex'
openw,luo,outfile,/get_lun
;
printf,luo,'\documentstyle[longtable,12pt]{article}'
;
;   \setlength{\textheight}{250mm} %UK
printf,luo,'\setlength{\textheight}{220mm}' ;%US
printf,luo,'\setlength{\headheight}{0.0mm}'
printf,luo,'\setlength{\headsep}{0.0mm}' 
printf,luo,'\setlength{\topmargin}{-5mm}' 
printf,luo,'\setlength{\textwidth}{165mm}'
printf,luo,'\setlength{\oddsidemargin}{-0.5cm}'   ;-1.0cm
;   printf,luo,'\setlength{\evensidemargin}{3mm}'  
;
printf,luo,'\begin{document}'
;   printf,luo,'\textwidth=17cm'
;   printf,luo,'\textheight=22cm'
;   printf,luo,'\topmargin=-1cm'
;   printf,luo,'\oddsidemargin=-1cm'
;
printf,luo,'\begin{center}'
printf,luo,'\large\bf{Predicted XUV Line Intensities}\\'
printf,luo,'from the CHIANTI database  \\'
printf,luo,'\vspace{0.5cm}'
printf,luo,'\large\bf{'+strupcase(latex_title)+'}\\'
printf,luo,' Pressure (n$_{\rm e}$T)='+string(pressure,'(e10.2)')+'\\'
printf,luo,'\large\bf{'+strtrim(string(wmin,'(f6.1)'),2)+' to '+strtrim(string(wmax,'(f6.1)'),2)+'\AA}\\'
if keyword_set(sngl_ion) then begin
   n_ion=n_elements(sngl_ion)
   for j=0,n_ion-1 do begin
      ion2spectroscopic,sngl_ion(j),snote
      printf,luo,'\large\bf{Ion:  '+snote+'}\\'
   endfor
endif
;
;
printf,luo,'\large\bf{Number of lines:  '+strtrim(string(mast_index,'(i7)'),2)+'}\\'
;
if keyword_set(photons) then begin
   printf,luo,'\large\bf{Units are in photons}\\'
endif
;
printf,luo,'\today\\'
printf,luo,'\end{center}'
;
printf,luo,'\newpage'
;
;
printf,luo,'{\bf Ions included:}\\'
printf,luo,elstage
;
printf,luo,'\\'
;
;
printf,luo,'\vspace{0.5cm}'
;
printf,luo,'{\bf Abundances:}\\'
;
;
; get rid of %'s and _'s which kill you in latex
;
asize=size(abund_ref)
  for iref=0,asize(1)-1 do begin
      reflen=strlen(abund_ref(iref))
      ipc=strpos(abund_ref(iref),'%')
      thisref=strmid(abund_ref(iref),ipc+1,reflen-ipc-1)
      thisref=ch_repstr(thisref,'&','\&')
      thisref=ch_repstr(thisref,'_','\_')
      printf,luo,thisref+' \\'
   endfor
;
;
printf,luo,'\\ \vspace{0.5cm}'
;
printf,luo,'{\bf Differential Emission Measure:}\\'
;
asize=size(dem_ref)
  for iref=0,asize(1)-1 do begin
      reflen=strlen(dem_ref(iref))
      ipc=strpos(dem_ref(iref),'%')
      thisref=strmid(dem_ref(iref),ipc+1,reflen-ipc-1)
      thisref=ch_repstr(thisref,'&','\&')
      thisref=ch_repstr(thisref,'_','\_')
      printf,luo,thisref+' \\'
  endfor
;
printf,luo,'\vspace{0.5cm}'
;
;printf,luo,'\begin{center}'
;printf,luo,'\begin{tabular}[p]{|lrlclccr|} \hline'
;printf,luo,'\multicolumn{8}{|c|}{\bf{Table 1. XUV Line List}} \\ \hline \hline'
;
;            printf,luo,'\begin{longtable}[c]{@{}|lllrll|@{}}'
printf,luo,'\begin{longtable}[c]{@{}|lrlclccr|@{}}'
printf,luo,'\caption{\em \normalsize Line List } \label{tab:obs} \\'
printf,luo,'\hline'
if keyword_set(kev) then begin
   printf,luo,' Ion & Kev & Conf($\ell$) & Desig($\ell$) & Conf(u) & Desig(u) & T$_{\rm max}$ & Int\\ \hline'
endif else begin
   printf,luo,' Ion & $\lambda$ (\AA) & Conf($\ell$) & Desig($\ell$) & Conf(u) & Desig(u) & T$_{\rm max}$ & Int\\ \hline'
endelse
;
printf,luo,'\hline \endfirsthead'
printf,luo,'\caption[]{\normalsize (continued)}\\ '
printf,luo,'\hline '
if keyword_set(kev) then begin
   printf,luo,' Ion & Kev & Conf($\ell$) & Desig($\ell$) & Conf(u) & Desig(u) & T$_{\rm max}$ & Int\\ \hline'
endif else begin
   printf,luo,' Ion & $\lambda$ (\AA) & Conf($\ell$) & Desig($\ell$) & Conf(u) & Desig(u) & T$_{\rm max}$ & Int\\ \hline'
endelse
printf,luo,'\hline \endhead'
;
;
for i=0,nlines-1 do begin

elstage=mast_snote(i)
;
if mast_wvl(i) gt 0. then begin
   if keyword_set(kev) then begin
      wvls=strtrim(string(abs(mast_wvl(i)),'(f12.3)'),2)
   endif else begin
      wvls=strtrim(string(abs(mast_wvl(i)),'(f12.4)'),2)
   endelse
endif else wvls='*'+strtrim(string(abs(mast_wvl(i)),'(f12.4)'),2)
;
term1=strtrim(mast_term1(i),2)
desig1=strtrim(mast_desig1(i),2)
term2=strtrim(mast_term2(i),2)
desig2=strtrim(mast_desig2(i),2)
;
;   az=string(mast_abund(i),'(e9.2)')
item1=string(mast_tmax(i),'(f4.1)')
;   item2=string(mast_ioneq(i),'(e9.2)')
;   item2=string(mast_pop(i),'(e9.2)')
;
if keyword_set(photons) then begin
   item2=string(intensity(i),'(e10.2)')
endif else begin
   item2=string(intensity(i),'(f10.1)')
;     item2=string(intensity(i),'(e10.2)')
endelse
;
if intensity(i) ge min_int then begin
  printf,luo,elstage+' & '+wvls+' & ' + term1+' & '+desig1+' & ' + term2+' & '+desig2 +' & '+item1+' & ' +item2+ ' \\'
endif
;
endfor
;
printf,luo,'\hline'
;

printf,luo,'\end{longtable}'
printf,luo,'\end{document}'

free_lun,luo
;
if keyword_set(elapsed) then begin
    time1=systime(1)
    dt=time1-time0
    print,' elapsed seconds in synthetic = ',dt
endif
;

print,' The file '+outfile+ ' has been created !'
;
end
;


