pro temperature_barplot,name,T,Nx,Nz,vol,rho,abund,Mgas,absolut=absolut,NT=NT,Tbin=Tbin
  
  Msun= 1.988922500d+33
  Mspecies=0.d0
  if(not(keyword_Set(NT))) then NT = 20
  Mass_cum=dblarr(NT)
; 5 K temperature bins
  if(not(keyword_Set(Tbin))) then Tbin = 5.
  Tmin=findgen(NT)*Tbin
  Tmax=(findgen(NT)+1)*Tbin
  Tmax(NT-1)=1.e5
  filename = 'Cumulativemass_T'+name+'.out'
  openw,1,filename
  for ix=0,Nx-1 do begin
    for iz=0,Nz-1 do begin
      T1=T(ix,iz)
       mass = vol(ix,iz)*rho(ix,iz)*abund(ix,iz)
       for j=0, NT-1 do begin
          if (T1 ge Tmin(j) and T1 lt Tmax(j)) then Mass_cum(j) = Mass_cum(j) + mass
       endfor
      Mspecies = Mspecies + vol(ix,iz)*rho(ix,iz)*abund(ix,iz)       
    endfor
  endfor
  for j=0, NT-1 do begin
      printf,1,Tmax(j),Mass_cum(j)/Msun, format='(F9.1,E11.3)' 
  endfor 
  close,1
;  !y.range = [(1.e-3*Mgas/Msun),(Mgas/Msun)]
  !y.range = [0,100]
  !y.style=-1 
  Tmax_name=string(Tmax, format='(i7)')
  for i=0, NT-1 do begin & $
      if ((i mod 2) eq 0) then Tmax_name(i)=' ' & $
  endfor
  Tmax_name(NT-1)='>'+strtrim(string(Tmax(NT-2)+Tbin,format='(i7)'),1)
  cut=findgen(NT)*0.;+(1.e-3*Mgas/Msun)
  colbars=indgen(NT)*0.+50.
  xtit = 'T!D'+name+' !N [K]'
  ytit = 'M!D'+name+' !N[T-'+string(Tbin, format='(i3)')+' K,T]!N/M!D'+name+' !N [%]'
  if (keyword_set(absolut)) then begin
     legen = 'M!D'+name+'!N(total) ='+string(Mspecies/Msun, format='(E12.4)')+'M!DSun!N'
     endif else begin   
     legen = 'X!Emass!D'+name+'!N(total) ='+string(Mspecies/Mgas, format='(E12.4)')
  endelse   
  bar = 100.*(Mass_cum/Mspecies)
  bar_plot, bar, BarNames=Tmax_name, baselines=cut, $
               YTITLE=ytit, $
               XTITLE=xtit, colors=colbars
  xyouts, 6., 80., legen
end  

;----------------------------------------------------------
FUNCTION READ_TABLE, filename, $
                     columns=columns, nrows=nrows, $
                     nmax=nmax, double=double, $
                     text=text, head=head
;----------------------------------------------------------
;+
; NAME:
;       READ_TABLE
;
; PURPOSE:
;       Read an ASCII table into a data array.
;
; AUTHOR:
;       Simon Vaughan (U.Leicester)
;
; CALLING SEQUENCE:
;       data = READ_TABLE('file.dat')
;
; INPUTS:
;       file - (string) file name 
;
; OPTIONAL INPUTS:  
;       columns - (integer vector) which columns of table to retain 
;       nrows   - (integer) number of lines to read 
;       nmax    - (integer) minimum size of file, default is 100,000
;       double  - (logical) whether to use double or single prec.
;       text    - (logical) whether to load text from file       
;       head    - (integer) number of lines to skip in header
;
; OUTPUTS:
;       2-dimensional data array (floating point values)
;
; DETAILS:
;       Data are assumed to be floating point numbers, by
;       default single precision, seperated by spaces in a
;       rectangular grid (ncols*nrow)
;
; Example calls:
;
; IDL> data = read_table('table.txt')
; IDL> data = read_table('table.txt', columns=[2,3])
; IDL> data = read_table('table.txt', n=100, HEAD=1, /TEXT)
;
; HISTORY:
;       Based losely on DDREAD.PRO by Frank Knight (MIT)
;       11/01/2007 -  v1.0 - first working version
;       27/04/2007 -  v1.1 - added TEXT option
;       22/11/2007 -  v1.2 - added HEAD option
;       22/09/2008 -  v1.3 - HEAD now takes integer input
;       16/06/2010 -  v1.4 - fixed handling of text input
;                             using STRSPLIT function.
;       20/07/2012 -  v1.5 - If error encountered then RETURN
;                             a value -1, for consistency with
;                             other routines.
;       28/07/2012 - v1.6  - Replace obsolete FINDFILE with
;                             FILE_SEARCH. Upon error return
;                             !NULL. (New to IDL 8). Use 
;                             QUERY_ASCII to check the file is
;                             indeed ASCII, and to define the
;                             number of rows in the file.
;                              
; NOTES:
;       This is similar to the IDL READ_ASCII function. But
;       it allow you to force the data type. This is useful
;       if the input file comprises columns of different types,
;       e.g. 1 column of strings, 3 columns of floats. In this
;       case use READ_TABLE(..., /TEXT) which will force all
;       columns to be read as strings, and then convert the
;       numerical columns from string to float as needed.
;-
; ----------------------------------------------------------

; options for compilation (recommended by RSI)

  COMPILE_OPT idl2, HIDDEN

; watch out for errors

  ON_ERROR, 0

; ----------------------------------------------------------
; Check the arguments

; is the file name defined?

  IF (N_ELEMENTS(filename) eq 0) THEN BEGIN
      filename = ''
      READ, '-- Enter file name (ENTER to list current directory): ', filename
  ENDIF

  IF (filename eq '') THEN BEGIN
      list = FILE_SEARCH(/TEST_READ, /TEST_REGULAR)
      PRINT, list
      READ,'-- Enter file name: ', filename
  ENDIF

; are we reading in single (=4) or double precision (=5)?
 
  type=4
  IF (KEYWORD_SET(double)) THEN type=5

; are we reading numbers or text?
 
  IF (KEYWORD_SET(text)) THEN type=7
 
; ----------------------------------------------------------
; Checks of the file existance and shape

; check the file exists

  file = (FILE_SEARCH(filename, /TEST_READ, /TEST_REGULAR))
  IF (file[0] eq '') THEN BEGIN
      PRINT,'** File not found.'
      RETURN, !NULL
  ENDIF
  IF (N_ELEMENTS(file) ne 1) THEN BEGIN
      PRINT,'** File not found.'
      RETURN, !NULL
  ENDIF

; check the file is ASCII and count the total number of lines

  check = QUERY_ASCII(file, file_info)
  IF (check eq 0) THEN BEGIN
      PRINT, '** File is not ASCII.'
      RETURN, !NULL
  ENDIF
  file_row = file_info.lines
  IF KEYWORD_SET(head) THEN file_row = file_row - head
  IF NOT KEYWORD_SET(nrows) THEN nrows = file_row
  nrows = (nrows < file_row)
  
; find the number of columns in the file by reading first line
; into a string (tmp)

  ncols = 0
  tmp = ''
  OPENR, lun, file, /GET_LUN
  if KEYWORD_SET(head) THEN BEGIN
      FOR i=0, head-1 DO READF, lun, tmp ; skip header
  ENDIF
  READF, lun, tmp
  FREE_LUN, lun

; remove whitespace

  tmp = ' ' + STRCOMPRESS(STRTRIM(tmp, 2))

; count the spaces (there is one per column)

  FOR i=0, STRLEN(tmp)-1 DO BEGIN
      ncols = ncols + (STRPOS(tmp, ' ', i) eq i)
  END

; ----------------------------------------------------------
; load the data into an array

; define the data array ready to receive data

  data = MAKE_ARRAY(size=[2, ncols, nrows, type, ncols*nrows])

; define a single line (row) array for reading each line
; except for text which is loaded a whole line at a time 

  IF NOT KEYWORD_SET(text) THEN BEGIN
      record = MAKE_ARRAY(size=[1, ncols, type, ncols])
  ENDIF ELSE BEGIN
      record = ''
  ENDELSE

; Open the file ready to read

  OPENR, lun, file, /GET_LUN

; skip header line if HEAD keyword is set

  if KEYWORD_SET(head) THEN BEGIN
      FOR i=0, head-1 DO READF, lun, tmp 
  ENDIF

; Read each line one at a time, until either end-of-file
; or we reach nrows.

  n = 0L
  WHILE (eof(lun) ne 1) DO BEGIN
      ON_IOERROR, IOERR
      error = 1
      READF, lun, record
      error = 0
      IF KEYWORD_SET(text) THEN BEGIN
          data[*, n] = STRSPLIT(record, ' ', /EXTRACT)
      ENDIF ELSE BEGIN
          data[*,n] = record
      ENDELSE
      n = n + 1
      IF (n eq nrows) THEN BREAK

      IOERR:
      IF (error eq 1) THEN BEGIN
          PRINT, '** Error reading line', n, ' in READ_TABLE'
          FREE_LUN, lun
          RETURN, !NULL
      ENDIF

  ENDWHILE

; Close the file

  FREE_LUN, lun

; ----------------------------------------------------------
; Return the data array to the user

; if no column selection, RETURN entire array 

  if (N_ELEMENTS(columns) eq 0) THEN RETURN, data

; otherwise remove unwanted columns before RETURNing

  indx = WHERE((columns ge ncols-1), count)
  IF (count eq 0) THEN BEGIN
      data = data[columns, *]
  ENDIF ELSE BEGIN
      PRINT, '** Requested columns outside allowed range'
      PRINT, '** Returning all columns from READ_TABLE'
  ENDELSE

  RETURN, data

END
;--------------------------------------------------------------------
PRO READCHARGE,SPname2,SPcharge,SPmass
print,'Reading Species.out'
readcol,'Species.out',format='(A,I,A,F,F)',dummy,num,SPname2,SPmass,SPcharge
NSP = n_elements(SPname2)
SPname2=['e-',SPname2]
SPmass=[0.0,SPmass]
SPcharge=[-1.,SPcharge]
;print,'NSP =',NSP+1
;print,'Species Charge'
;for i=0,Nsp do begin
;   print,i,'  ',SPname2(i),'  ',SPcharge(i)
;endfor
END
; ------------------------------------------------------
; compute the species abundance relative to each element
pro species_abund_elem,Nx,Nz,xx,zz,Nsp,nmol,SPname,nelem,Elname,Elabund,Elmass,emol,main_carrier,main_carrier_rel_abund,abund_gas,abund_ice

print,'Determine the abundance per element'  
openr,2,"Elements.in"
readf,2,nelem
Elname  = strarr(nelem)
Elabund = fltarr(nelem)
Elmass  = fltarr(nelem)
close,2
Elabund=10.^(Elabund-12.) 
readcol,'Elements.in',format='(A,F,F)',elname,elabund,elmass,skip=1,numline=nelem
line=''
data = READ_TABLE('Species.out',head=1,/text)
sp_name  = data(2,*)
spcharge = fix(data(3,*))
chempot  = float(data(4,*))
spcomp   = float(data(6:nelem+5,*))
tmp_abund = fltarr(Nx,Nz)
emol = fltarr(Nx,Nz,nelem,nsp+1)
emol(*,*,0,0) = 1.
main_carrier=intarr(Nx,Nz,nelem)
main_carrier_rel_abund=fltarr(Nx,Nz,nelem)
abund_ice = fltarr(Nx,Nz,nelem)
abund_gas = fltarr(Nx,Nz,nelem)  
; -----
openw,3,'species_relative_elemental_abundances.txt'
for ix=0,Nx-1 do begin
   for iz=0,Nz-1 do begin
      printf,3,ix,iz
      for iel=0,nelem-1 do begin
         abundl    = [0.]
         spl       = [0]
         for isp=1,nsp do begin
            tmp_abund = nmol(ix,iz,isp)*spcomp(iel,isp-1)
            if(tmp_abund gt 0.) then begin
               abundl = [abundl,tmp_abund]
               spl       = [spl,isp]
               emol(ix,iz,iel,isp) = tmp_abund
               ice=strpos(Spname(isp),'#')
               if(ice gt 0) then begin
                  abund_ice(ix,iz,iel) = abund_ice(ix,iz,iel) $
                                         + emol(ix,iz,iel,isp)
               endif else begin
                  abund_gas(ix,iz,iel) = abund_gas(ix,iz,iel) $
                                         + emol(ix,iz,iel,isp)
               endelse   
            endif
         endfor   
         ntot1  = n_elements(abundl)
         abundl = abundl(1:ntot1-1)
         spl    = spl(1:ntot1-1)
         j=reverse(sort(abundl))
         spl = spl(j)
         abundl=abundl(j)
         tot_abund = total(abundl)
         emol(ix,iz,iel,spl) =  emol(ix,iz,iel,spl)/tot_abund
         abund_ice(ix,iz,iel) = abund_ice(ix,iz,iel)/tot_abund
         abund_gas(ix,iz,iel) = abund_gas(ix,iz,iel)/tot_abund
         main_carrier(ix,iz,iel)=spl(0)
         main_carrier_rel_abund(ix,iz,iel) = abundl(0)/tot_abund
         if (N_ELEMENTS(spl) eq 1) then begin
            printf,3,Elname(iel),': ',spname(spl(0)),abundl(0)/tot_abund,' ; '
         endif else begin
            printf,3,Elname(iel),': ',spname(spl(0)),abundl(0)/tot_abund,' ; ',spname(spl(1)),abundl(1)/tot_abund
         endelse
      endfor
   endfor
endfor
close,3
;stop;
end
; ---------------------------------------------
pro plot_element_carriers,Nx,Nz,xx,zz,iel,Nsp,Spname,main_carrier,Elname,nametit

black   = 0
white   = 255
orange  = 210
red     = 250
yellow  = 195
green   = 160
cyan    = 100
blue    = 70
magenta = 40
in = main_carrier(*,*,iel)  
in2 = reform(main_carrier(*,*,iel),Nx*Nz)
in2 = in2(sort(in2))
w = where(in2 ne shift(in2,1),nuniq)
in3 = intarr(Nsp)
levs = indgen(nuniq)+1
in3(in2(w))= levs
yy = in3(in)
nlev = nuniq-1
; ----------
name = Spname(in2(w))
if(nuniq GT 1) then begin
   col_list  = (240./(nuniq-1))*findgen(nuniq)
endif else begin
   col_list = [black]
endelse  
tit = 'Major carriers of the '+strtrim(ElName(iel))+' element'
!p.multi=[0,2,1]
!x.margin=[11,1]
!y.margin=[8,2]
pos=[0.15,0.3,0.92,0.90]
csize=1.0
;stop
zz2 = zz/xx
contour, yy, xx, zz2,/fill,levels=levs,/xlog, $
             xtitle='!7r [au]',ytitle='!7z [au]', $
         position=pos,c_colors=col_list,title=tit
nm = min([nuniq,7])
al_legend,name(0:nm-1),box=0,pos=[0.1,0.2],/norm,charsize=csize,$
          textcolors=col_list(0:nm-1),charthick=1.5
if(nuniq gt 7) then begin
   al_legend,name(7:nuniq-1),box=0,pos=[0.6,0.2],/norm,charsize=csize,$
          textcolors=col_list(7:nuniq-1),charthick=1.5
endif

end

;--------------------------------------------------------------------------------------- 
pro charge_statistics,Nx,Nz,xx,zz,Nsp,nmol,SPname,nHtot,NH_ver,ndust,dust_charge,Zcharge
;--------------------------------------------------------------------------------------- 
 READCHARGE,SPname2,SPcharge,SPmass 
 ; charges  	  	 
 Zcharge = fltarr(Nx,Nz)  	  	 
 for i=0,Nsp do begin
    Zcharge = Zcharge + abs(SPcharge(i))*nmol(*,*,i) ; trick from Geoffroy Lesur  	  	 
 endfor  	  	 
 Zcharge = Zcharge*0.5 ; part two of the trick  	  	 
 Zplusmax=fltarr(Nx,Nz)  	  	 
 Zminusmax=fltarr(Nx,Nz)  	  	 
 indexZplus=intarr(Nx,Nz)  	  	 
 indexZminus=intarr(Nx,Nz)  	  	 
 for ix=0,Nx-1 do begin  	  	 
    for iz=0,Nz-1 do begin  	  	 
       Zplusmax(ix,iz) = 0.  	  	 
       Zminusmax(ix,iz) = 0.  	  	 
       for i=0,Nsp do begin  	  	 
          if (SPcharge(i) gt 0.) then begin  	  	 
             if (SPcharge(i)*nmol(ix,iz,i) gt Zplusmax(ix,iz)) then begin  	  	 
                Zplusmax(ix,iz) = SPcharge(i)*nmol(ix,iz,i)  	  	 
                indexZplus(ix,iz) = i
                ;print,ix,iz,Spname(i),SPcharge(i),nmol(ix,iz,i),Zplusmax(ix,iz)
             endif  	  	 
          endif else if(SPcharge(i) lt 0.) then begin  	  	 
              if (SPcharge(i)*nmol(ix,iz,i) lt Zminusmax(ix,iz)) then begin  	  	 
                Zminusmax(ix,iz) = SPcharge(i)*nmol(ix,iz,i)   	  	 
                indexZminus(ix,iz) = i
                ;print,ix,iz,Spname(i),SPcharge(i),nmol(ix,iz,i)/nHtot(ix,iz),nmol(ix,iz,i)/ndust(ix,iz),dust_charge(ix,iz),ndust(ix,iz)/nHtot(ix,iz)
             endif  	  	 
           endif  	  	 
       endfor  	  	 
    endfor  	  	 
 endfor   	  	 
 uniq_indexZminus=[-1]  	  	 
 uniq_indexZplus=[-1]  	  	 
 for ix=0,Nx-1 do begin  	  	 
    for iz=0,Nz-1 do begin  	  	 
       ifound=-1  	  	 
       for i=0,n_elements(uniq_indexZminus)-1 do begin  	  	 
          if (uniq_indexZminus(i) eq indexZminus(ix,iz)) then ifound=i  	  	 
       endfor  	  	 
       if(ifound eq -1) then uniq_indexZminus=[uniq_indexZminus,indexZminus(ix,iz)]     	  	 
       ifound=-1  	  	 
       for i=0,n_elements(uniq_indexZplus)-1 do begin  	  	 
          if (uniq_indexZplus(i) eq indexZplus(ix,iz)) then ifound=i  	  	 
       endfor  	  	 
       if(ifound eq -1) then uniq_indexZplus=[uniq_indexZplus,indexZplus(ix,iz)]     	  	 
   	  	 
    endfor  	  	 
 endfor     	  	 
 nuniq=n_elements(uniq_indexZminus)  	  	 
 uniq_indexZminus=uniq_indexZminus(1:nuniq-1)  	  	 
 nuniq=n_elements(uniq_indexZplus)  	  	 
 uniq_indexZplus=uniq_indexZplus(1:nuniq-1)  	  	 
 print,'Main positive charge carriers'  	  	 
 print,SPname(uniq_indexZplus)  	  	 
 print  	  	 
 print,'Main negative charge carriers'  	  	 
 print,SPname(uniq_indexZminus)  	  	 
 print  	  	 
 ; ----- write a file providing at each location the main
 ;       positive and negative charge carrier, the ionization fraction
 ;       and the half disk surface density profile.  	  	 
 openw,1,'charge_carriers.txt'  	  	 
 printf,1,'Main positive & negative charge carriers (R,z)'  	  	 
 for i=0,Nx-1 do begin  	  	 
    printf,1,' R(AU) z(AU)   Species +/-  log10(Z/nH)   Surf dens(cm^-2)'  	  	 
    for j=0,Nz-1 do begin  	  	 
       ip = indexZplus(i,j)  	  	 
       im = indexZminus(i,j)  	  	 
       Zc = Zcharge(i,j)  	  	 
       printf,1,format='(F6.1,X,F6.1,3X,A,F5.2,2X,A,F5.2,4X,F6.2,4X,E12.4,3X,E12.4)',xx(i),zz(i,j),SPname(ip),nmol(i,j,ip)/Zc,SPname(im),nmol(i,j,im)/Zc,alog10(Zc/nHtot(i,j)),NH_ver(i,j)  	  	 
    endfor  	  	 
    printf,1,' '  	  	 
 endfor  	  	 
 close,1  	  	 
 print  	  	 
 ;--------  	  	 
 mH = 1.4*1.672d-24 ; g  	  	 
 AU=1.5d13  	  	 
 Msun=2d33  	  	 
 print,'Computed disk gas mass in MSun'  	  	 
 ;print,int_tabulated(xx(*,0),xx(*,0)*NH_ver(*,0),/double)*mH*AU*AU/2d33*2.*2.0d0*!dpi  	  	 
 ; -------  	  	 
 y1 = max(alog10(Zcharge/nHtot(*,*)))*10.  	  	 
 y2 = y1-12.  	  	 
 CONTFILL2, xx,zz,Zcharge/nHtot(*,*),'Zcharge',1,1,1, $  	  	 
            YMAX=y1,YMIN=y2,ZMAX=zmax  	  	
end


;--------------------------------------------------------
PRO DUST_MEANCHARGE,Nx,Nz,ndust,nmol,SPname,Zmean,computed
;--------------------------------------------------------
  Zindex = WHERE(STRPOS(SPname,'Z') GE 0, Ncharged)
  computed = (Ncharged GT 0)
  if (NOT computed) then return
  Zcharge = INTARR(Ncharged)
  Zmean   = DBLARR(Nx,Nz)
  for i=0,Ncharged-1 do begin
    isp = Zindex(i)
    sp = strtrim(SPname(isp),2)
    ZZ = 0
    for j=0,strlen(sp) do begin
      char = STRMID(sp,j,1)
      if (char EQ '+') then ZZ = ZZ+1
      if (char EQ '-') then ZZ = ZZ-1
    endfor
    Zmean(*,*) = Zmean(*,*) + ZZ*nmol(*,*,isp)
  endfor
  Zmean = Zmean/ndust
end


;--------------------------------------------------------
FUNCTION SPindex, Nsp, SPname, sp
;--------------------------------------------------------
  i=0
  for j=0,Nsp do if (sp EQ SPname(j)) then i=j
  return, i
end; SPindex

;--------------------------------------------------------------------
PRO READDATA, folder,fname,Nx,Nz,Nsp,SPname,xx,zz,mainheat,maincool,$
              rho_gr,NH_rad,NH_ver,AV_rad,AV_ver,$
              chi,TgRE,Tgas,Tdust,rho,press,cT,nHtot,nmol,ndust,$
              NHEAT,NCOOL,heatname,coolname,$
              tauchem,taucool,taudiff,heat,cool,$
              NLAM,lam,Jlam,urad,chiRT,solved,Rstar,Rin,Rout,Mstar,$
              kapR,tauR,amean,dust_to_gas_c,dustgas,version,zrelevant,$
              fPAH,H_X,$
              tau_1keV,tau_10keV,zeta_HX,rH2form,rH2diss,alpha_vis,CRI_rz
;--------------------------------------------------------------------
  print,"============================================="
  print,"   reading "+folder+"/"+fname+" ..."
  print,"============================================="
  dum=" "
  header=" "
  firstdata=" "
  openr, 1, folder+"/"+fname
  for i=1,99 do begin
    readf,1,header
    len=STRLEN(header)
    if (len GT 300) then break
  endfor
  readf,1,firstdata
  close,1  
  version=0
  if (i EQ 21) then version=1
  if ((i EQ 24) AND (strpos(header,'tauR') EQ -1)) then version=2
  if ((i EQ 24) AND (strpos(header,'tauR') GT 0) $
      AND (strpos(header,'z[au]') EQ 25)) then version=3
  if ((i EQ 24) AND (strpos(header,'tauR') GT 0) $
      AND (strpos(header,'z[au]') EQ 27)) then version=4
  if (strpos(header,'dust/gas') GT 0) then version=5
  if (strpos(header,'zeta_H_X') GT 0) then version=6
  if (strpos(header,'rH2form') GT 0) then version=7
  if (strpos(header,'CRI_rz') GT 0) then version=8
  if (strpos(header,'iz           x[AU]') GT 0) then version=10
  if (version EQ 0) then begin
    print,"*** unknown ProDiMo output version"
    print,header
    print,i
    print,len
    stop
  endif  
  print,"reading ProDiMo.out, VERSION="+STRTRIM(STRING(version),2) 
  openr, 1, folder+"/"+fname
  Nx=0
  Nz=0
  Nsp=0
  NHEAT=0
  NCOOL=0
  NLAM=0
  fPAH=1.0
  readf, 1, format='(18x,D30)', Mstar
  readf, 1, format='(18x,D30)', Lstar
  readf, 1, format='(18x,D30)', Teff
  readf, 1, format='(18x,D30)', Rstar
  readf, 1, format='(18x,D30)', logg
  readf, 1, format='(18x,D30)', Mdisk
  readf, 1, format='(18x,D30)', Rin
  readf, 1, format='(18x,D30)', Rout
  readf, 1, format='(18x,D30)', epsilon
  readf, 1, format='(18x,D30)', dust_to_gas_c
  readf, 1, format='(18x,D30)', rho_gr
  readf, 1, format='(18x,D30)', amin
  readf, 1, format='(18x,D30)', amax
  readf, 1, format='(18x,D30)', apow
  if (version EQ 1) then begin
    readf, 1, format='(18x,D30)', CRI
    readf, 1, format='(18x,D30)', CHI_ISM
    readf, 1, format='(18x,D30)', alpha_vis
  endif else begin  
    readf, 1, format='(18x,D30)', fPAH
    readf, 1, format='(18x,D30)', CRI
    readf, 1, format='(18x,D30)', CHI_ISM
    readf, 1, format='(18x,D30)', alpha_vis
    readf, 1, format='(18x,D30)', v_turb
    readf, 1, dum
  endelse
  readf, 1, dum
  readf, 1, format='(23x,I5,I5,I5,I5,I5,I5)', Nx,Nz,Nsp,NHEAT,NCOOL,NLAM
  readf, 1, dum
  print,format='("dimension ",i3," x",i3)',Nx,Nz
  xx = dblarr(Nx,Nz) 
  zz = dblarr(Nx,Nz) 
  mainheat = intarr(Nx,Nz)
  maincool = intarr(Nx,Nz)
  NH_rad = dblarr(Nx,Nz) 
  NH_ver = dblarr(Nx,Nz) 
  AV_rad = dblarr(Nx,Nz) 
  AV_ver = dblarr(Nx,Nz) 
  chi   = dblarr(Nx,Nz) 
  ndust = dblarr(Nx,Nz) 
  Tgas  = dblarr(Nx,Nz)
  Tdust = dblarr(Nx,Nz)
  cT    = dblarr(Nx,Nz)
  rho   = dblarr(Nx,Nz)
  press = dblarr(Nx,Nz)
  nHtot = dblarr(Nx,Nz)
  kapR  = dblarr(Nx,Nz)
  tauR  = dblarr(Nx,Nz)
  tauchem = dblarr(Nx,Nz)
  taucool = dblarr(Nx,Nz)
  taudiff = dblarr(Nx,Nz)
  nmol  = dblarr(Nx,Nz,Nsp+1)
  heat  = dblarr(Nx,Nz,NHEAT+1)
  cool  = dblarr(Nx,Nz,NCOOL+1)
  Jlam  = dblarr(Nx,Nz,NLAM+1)
  chiRT = dblarr(Nx,Nz) 
  solved= lonarr(Nx,Nz) 
  Nlines=1L*Nx*Nz
  amean   = dblarr(Nx,Nz) 
  dustgas = dblarr(Nx,Nz) 
  SPname=strarr(Nsp+1)
  nn=dblarr(Nsp+1)
  JJ=dblarr(NLAM)
  hrate=dblarr(NHEAT)
  crate=dblarr(NCOOL)
  H_X      = dblarr(Nx,Nz) 
  zeta_HX  = dblarr(Nx,Nz) 
  tau_1keV = dblarr(Nx,Nz) 
  tau_5keV = dblarr(Nx,Nz) 
  tau_10keV= dblarr(Nx,Nz) 
  rH2form  = dblarr(Nx,Nz) 
  rH2diss  = dblarr(Nx,Nz,3) 
  CRI_rz=DBLARR(Nx,Nz)  
  ix=0
  iz=0
  iheat=0
  icool=0
  solve=0
  str1v1='(8x,22x,52x,13x,22x,39x,1x,7x,13x,26x,12x,'
  str1v2='(8x,22x,52x,13x,22x,39x,1x,7x,13x,39x,12x,'
  str1v4='(8x,24x,52x,13x,22x,39x,1x,7x,13x,39x,12x,'
  str1v9='(8x,26x,52x,13x,22x,39x,1x,7x,13x,39x,12x,' $
        +strtrim(string(13*(NHEAT+NCOOL)),2)+'x,13x,999(A13))' 
  str1v10='(8x,32x,52x,13x,22x,39x,1x,7x,13x,39x,12x,'
  str1v10=str1v10+strtrim(string(13*(NHEAT+NCOOL+1)),2)+'x,999(A13))' 
  str2  ='(2(i4),2(F11.4),4(E13.5),E13.5,2(F11.4),3(E13.5),'
  str2v1=str2  +'1x,i7,E13.5,2(E13.5),2(1x,i5),'
  str2v2=str2  +'1x,i7,E13.5,3(E13.5),2(1x,i5),'
  str2v4='(2(i4),2(F12.6),4(E13.5),E13.5,2(F11.4),3(E13.5),'
  str2v4=str2v4+'1x,i7,E13.5,3(E13.5),2(1x,i5),'
  str2v10='(2(i4),2(E16.9),4(E13.5),E13.5,2(F11.4),3(E13.5),'
  str2v10=str2v10+'1x,i7,E13.5,3(E13.5),2(1x,i5),'
  for i=1,NHEAT+NCOOL do begin
    str1v1=str1v1+'13x,'
    str1v2=str1v2+'13x,'
    str1v4=str1v4+'13x,'
    str2v1=str2v1+'E13.5,'
    str2v2=str2v2+'E13.5,'
    str2v4=str2v4+'E13.5,'
    str2v10=str2v10+'E13.5,'
  endfor
  str1v1=str1v1+'13x,999(A13))'
  str1v2=str1v2+'13x,999(A13))'
  str1v4=str1v4+'13x,999(A13))'
  str2v1=str2v1+'999(E13.5))'
  str2v2=str2v2+'999(E13.5))'
  str2v4=str2v4+'999(E13.5))'
  str2v10=str2v10+'999(E13.5))'
  ; -----------------------------
  array = READ_TABLE('ProDiMo.out',head=24,nrows=Nx*(Nz*1L),/double)
  size_array = size(array)
  if ((version EQ 8) AND (size_array(1) ge 300)) then begin
    version = 9
    print,'Version 8 with large number of cooling species'
  endif
  ; -----------------------------
  ;if (version EQ 1) then readf,1, format=str1v1, SPname
  ;if (version EQ 2) then readf,1, format=str1v2, SPname
  ;if (version EQ 3) then readf,1, format=str1v4, SPname
  ;if (version EQ 4) then readf,1, format=str1v4, SPname
  ;if (version EQ 5) then readf,1, format=str1v4, SPname
  ;if (version EQ 6) then readf,1, format=str1v4, SPname
  ;if (version EQ 7) then readf,1, format=str1v4, SPname
  ;if (version EQ 8) then readf,1, format=str1v4, SPname
  ;if (version EQ 9) then readf,1, format=str1v9, SPname
  ;if (version EQ 10)then readf,1, format=str1v10,SPname
  ; ----------------------------
  dums = " "
  dumf = 0.0
  readcol,'Species.out',format='(A,I,A)',dums,num,SPname
  Nsp = n_elements(SPname)
  SPname = ["e-",SPname]
  for i=0,Nsp do begin
    SPname(i)=STRTRIM(SPname(i),2)
  endfor
  chitot=1.D+200
  chitot2=1.D+200
  tdiff=1.d0
  kap_R=1.d0
  tau_R=1.d0
  nd=0.d0
  a_mean=0.d0
  dust_gas=1.d0*dust_to_gas_c
  HXX=0.0
  tau01=0.d0
  tau05=0.d0
  tau10=0.d0
  zetaHX=0.d0  
  rateH2form=0.d0    
  rateH2diss1=0.d0  
  rateH2diss2=0.d0  
  rateH2diss3=0.d0
  nHIbf=0.d0
  nHIIbf=0.d0  
  CRIrz=0.0
  iH=SPindex(Nsp,SPname,"H")
  iH2=SPindex(Nsp,SPname,"H2")
  i=0L
  while (i LT Nlines) do begin
    i=i+1L
    if (version EQ 1) then readf,1, format=str2v1, $
      ix,iz,x,z,NHrad,NHver,AVrad,AVver,nd,Tg,Td,cT1,rho1,pp,solve,$
      chitot,tchem,tcool,iheat,icool,hrate,crate,nH,nn,JJ,chitot2
    if (version EQ 2) then readf,1, format=str2v2, $
      ix,iz,x,z,NHrad,NHver,AVrad,AVver,nd,Tg,Td,cT1,rho1,pp,solve,$
      chitot,tchem,tcool,tdiff,iheat,icool,hrate,crate,nH,nn,JJ,chitot2
    if (version EQ 3) then readf,1, format=str2v2, $
      ix,iz,x,z,NHrad,NHver,AVrad,AVver,nd,Tg,Td,cT1,rho1,pp,solve,$
      chitot,tchem,tcool,tdiff,iheat,icool,hrate,crate,nH,nn,JJ,chitot2,$
      kap_R,tau_R
    if (version EQ 4) then readf,1, format=str2v4, $
      ix,iz,x,z,NHrad,NHver,AVrad,AVver,nd,Tg,Td,cT1,rho1,pp,solve,$
      chitot,tchem,tcool,tdiff,iheat,icool,hrate,crate,nH,nn,JJ,chitot2,$
      kap_R,tau_R
    if (version EQ 5) then readf,1, format=str2v4, $
      ix,iz,x,z,NHrad,NHver,AVrad,AVver,nd,Tg,Td,cT1,rho1,pp,solve,$
      chitot,tchem,tcool,tdiff,iheat,icool,hrate,crate,nH,nn,JJ,chitot2,$
      kap_R,tau_R,a_mean,dust_gas
    if (version EQ 6) then readf,1, format=str2v4, $
      ix,iz,x,z,NHrad,NHver,AVrad,AVver,nd,Tg,Td,cT1,rho1,pp,solve,$
      chitot,tchem,tcool,tdiff,iheat,icool,hrate,crate,nH,nn,JJ,chitot2,$
      kap_R,tau_R,a_mean,dust_gas,HXX,tau01,tau05,tau10,zetaHX
    if (version EQ 7) then readf,1, format=str2v4, $
      ix,iz,x,z,NHrad,NHver,AVrad,AVver,nd,Tg,Td,cT1,rho1,pp,solve,$
      chitot,tchem,tcool,tdiff,iheat,icool,hrate,crate,nH,nn,JJ,chitot2,$
      kap_R,tau_R,a_mean,dust_gas,HXX,tau01,tau05,tau10,zetaHX,$
      rateH2form,rateH2diss1,rateH2diss2,rateH2diss3
    if (version EQ 8) then readf,1, format=str2v4, $
      ix,iz,x,z,NHrad,NHver,AVrad,AVver,nd,Tg,Td,cT1,rho1,pp,solve,$
      chitot,tchem,tcool,tdiff,iheat,icool,hrate,crate,nH,nn,JJ,chitot2,$
      kap_R,tau_R,a_mean,dust_gas,HXX,tau01,tau05,tau10,zetaHX,$
      rateH2form,rateH2diss1,rateH2diss2,rateH2diss3,nHIbf,nHIIbf,CRIrz
      
    if (version GE 9) then begin
       ii     = i - 1
       ix     = fix(array(0,ii))
       iz     = fix(array(1,ii))
       x      = array(2,ii)
       z      = array(3,ii)
       NHrad  = array(4,ii)
       NHver  = array(5,ii)
       AVrad  = array(6,ii)
       AVver  = array(7,ii)
       nd     = array(8,ii)
       Tg     = array(9,ii)
       Td     = array(10,ii)
       cT1    = array(11,ii)
       rho1   = array(12,ii)
       pp     = array(13,ii)
       solve  = array(14,ii)
       chitot = array(15,ii)
       tchem  = array(16,ii)
       tcool  = array(17,ii)
       tdiff  = array(18,ii)
       iheat  = array(19,ii)
       icool  = array(20,ii)
       hrate  = array(21:20+NHEAT,ii)
       N2     = NHEAT+NCOOL
       crate  = array(21+NHEAT:20+N2,ii)
       nH     = array(21+N2,ii)
       N3     = N2 + NSP
       nn     = array(22+N2:22+N3,ii)
       N4     = N3 + NLAM
       JJ     = array(23+N3:22+N4,ii)
       chitot2= array(23+N4,ii)
       kap_R  = array(24+N4,ii)
       tau_R  = array(25+N4,ii)
       a_mean = array(26+N4,ii)
       dust_gas   = array(27+N4,ii)
       HXX        = array(28+N4,ii)
       tau01      = array(29+N4,ii)
       tau05      = array(30+N4,ii)
       tau10      = array(31+N4,ii)
       zetaHX     = array(32+N4,ii)
       rateH2form = array(33+N4,ii)
       rateH2diss1= array(34+N4,ii)
       rateH2diss2= array(35+N4,ii)
       rateH2diss3= array(36+N4,ii)
       nHIbf      = array(37+N4,ii)
       nHIIbf     = array(38+N4,ii)
       CRIrz      = array(39+N4,ii)
    endif    

    if (kap_R GT 0.01) then kap_R=1.e-99 ; correct entries like "1.234-199"
       
    ix = ix-1
    iz = iz-1
    xx   (ix,iz)    = x
    zz   (ix,iz)    = z
    NH_rad(ix,iz)   = NHrad
    NH_ver(ix,iz)   = NHver
    AV_rad(ix,iz)   = AVrad
    AV_ver(ix,iz)   = AVver
    chi  (ix,iz)    = chitot
    chiRT(ix,iz)    = chitot2
    solved(ix,iz)   = solve
    ndust(ix,iz)    = nd 
    Tgas (ix,iz)    = Tg
    Tdust(ix,iz)    = Td
    cT   (ix,iz)    = cT1
    rho  (ix,iz)    = rho1
    press(ix,iz)    = pp
    nHtot(ix,iz)    = nH
    kapR (ix,iz)    = kap_R
    tauR (ix,iz)    = tau_R
    amean(ix,iz)    = a_mean
    dustgas(ix,iz)  = dust_gas
    tauchem(ix,iz)  = tchem
    taucool(ix,iz)  = tcool
    taudiff(ix,iz)  = tdiff
    nmol(ix,iz,*)   = nn(*)
    mainheat(ix,iz) = iheat
    maincool(ix,iz) = icool
    H_X(ix,iz)      = HXX
    zeta_HX(ix,iz)  = zetaHX
    tau_1keV(ix,iz) = tau01
    tau_5keV(ix,iz) = tau05
    tau_10keV(ix,iz)= tau10
    rH2form(ix,iz)  = rateH2form*nn(iH)
    rH2diss(ix,iz,0)= rateH2diss1*nn(iH2)
    rH2diss(ix,iz,1)= rateH2diss2*nn(iH2)
    rH2diss(ix,iz,2)= rateH2diss3*nn(iH2)
    CRI_rz(ix,iz)=CRIrz
    for j=1,NHEAT do heat(ix,iz,j) = hrate(j-1)
    for j=1,NCOOL do cool(ix,iz,j) = crate(j-1)
    for j=1,NLAM  do Jlam(ix,iz,j) = JJ(j-1)
    dummy =''
    if (version GE 9) then readf,1,dummy
  endwhile
  NHEAT=0
  NCOOL=0
  nr=0
  name=' '
  readf, 1, dum
  readf, 1, NHEAT
  heatname=strarr(NHEAT+1)
  for i=1,NHEAT do begin
    readf, 1, format='(i3,1x,a45)', nr,name
    heatname(i)=name 
  endfor  
  readf, 1, dum
  readf, 1, NCOOL
  coolname=strarr(NCOOL+1)
  for i=1,NCOOL do begin
    readf, 1, format='(i3,1x,a45)', nr,name
    coolname(i)=name 
  endfor  
  readf, 1, dum
  readf, 1, dum
  lam=dblarr(NLAM+1)
  for i=1,NLAM do begin
    readf, 1, nr, lambda1
    lam(i)=lambda1
  endfor  
  close,1
  zrelevant=0.1*MAX(zz)
  for iz=0,Nz-1 do begin
    if (nHtot(Nx-1,iz) GT 1.E+3) then zrelevant=zz(Nx-1,iz)
  endfor
  ;print,xx(   0,0   ),zz(   0,0   ),NH_ver(   0,0   )
  ;print,xx(   0,Nz-1),zz(   0,Nz-1),NH_ver(   0,Nz-1)
  ;print,xx(Nx-1,0   ),zz(Nx-1,0   ),NH_ver(Nx-1,0   )
  ;print,xx(Nx-1,Nz-1),zz(Nx-1,Nz-1),NH_ver(Nx-1,Nz-1)

  ;--- calc Jtot ---
  cl      = 2.99792458D+10  ; speed of light
  hplanck = 6.62607554D-27  ; Planck's constant
  bk      = 1.38065812D-16  ; Boltzmann's constant
  pi      = ACOS(-1.d0)
  cPl1    = 2.d0*hplanck*cl^2
  cPl2    = hplanck*cl/bk    
  sig_SB  = cPl1/cPl2^4*pi^5/15.d0
  lamb=dblarr(NLAM+1)
  nub=dblarr(NLAM+1)
  dnu=dblarr(NLAM+1)
  urad=dblarr(Nx,Nz)
  lamb(0)=0.0912
  for i0=1,NLAM do begin
    if (lam(i0) GT lamb(0)) then break
  endfor
  lamb(i0-1)=0.0912
  for i=i0,NLAM   do lamb(i)=lam(i)^2/lamb(i-1)
  for i=i0-1,NLAM do  nub(i)=cl/(lamb(i)*1.E-4)
  for i=i0,NLAM   do  dnu(i)=nub(i-1)-nub(i)
  for ix=0,Nx-1 do for iz=0,Nz-1 do begin
    Jtot=0.d0
    for i=i0,NLAM do begin
      Jtot = Jtot + Jlam(ix,iz,i)*dnu(i)
    endfor
    urad(ix,iz)=4.d0*pi/cl*Jtot
    ;print,ix,iz,Jtot,sig_SB/pi*Tdust(ix,iz)^4
  endfor 
  for ix=0,Nx-1 do begin
    for iz=0,Nz-1 do begin
      pp = 0.0
      for i=0,Nsp do begin
        pp = pp+nmol(ix,iz,i)
      endfor  
      press(ix,iz) = pp*bk*Tgas(ix,iz)
      cT(ix,iz) = SQRT(press(ix,iz)/rho(ix,iz))
    endfor
  endfor  
  iix=0
  iiz=0
  dval=0.d0
  TgRE = dblarr(Nx,Nz)
  openr,1,'TgRE.out',ERROR = err
  if (err EQ 0) then begin
    for ix=0,Nx-1 do begin
      for iz=0,Nz-1 do begin
        readf,1,iix,iiz,dval
        TgRE(iix-1,iiz-1)=dval
      endfor
    endfor  
  endif
  close,1
end

;-----------------------------------------------------------------------
PRO SCALEHEIGHTS, Nx,Nz,xx,zz,AV,rho,press,cT,Mstar,Tgas,Tdust,MCMAXpath
;-----------------------------------------------------------------------
  AU   = 1.495978700D+13
  grav = 6.672598500D-08 
  Msun = 1.988922500E+33   
  amu  = 1.660531000d-24
  bk   = 1.38065812D-16  
  plot1='rho = max ... max/10'
  plot2='A!LV!N = max...0.001'
  Hrho1 = fltarr(Nx)
  Hrho2 = fltarr(Nx)
  Hrho3 = fltarr(Nx)
  Hrho4 = fltarr(Nx)
  rtmp  = fltarr(Nz)
  for ix=0,Nx-1 do begin
    ;----------------------------------------------------
    ; search for indices where z/r~search1 and AV=search2
    ;----------------------------------------------------
    rtmp(*) = rho(ix,*) 
    iz0 = WHERE(rtmp EQ MAX(rtmp),count)
    search1 = MAX(rtmp)/10.0
    search2 = 0.001   ; AV_rad
    qbest1 = 99.0
    qbest2 = 99.0     
    for iz=0,Nz-1 do begin
      qual1 = ABS(zz(ix,iz)/xx(ix,0)-search1)
      qual1 = ABS(rtmp(iz)-search1)
      qual2 = ABS(AV(ix,iz)-search2)
      if (qual1 LT qbest1) then begin
        qbest1 = qual1
        iz1 = iz
        zr1 = zz(ix,iz)/xx(ix,iz)
      endif    
      if (qual2 LT qbest2) then begin
        qbest2 = qual2
        iz2 = iz
        zr2 = zz(ix,iz)/xx(ix,iz)
      endif
    endfor
    ;print,format='(4i4)',ix,iz0,iz1,iz2
    iz1 = MAX([iz1,5])
    iz2 = MAX([iz2,iz1])
    ;---------------------------------------
    ; from rho(z) as present in the model 
    ; rho(z)/rho(z0) = exp(-(z^2-z0^2)/2H^2)
    ;---------------------------------------
    if (count NE 1) then begin
      Hrho1(ix)=!values.f_nan
      Hrho2(ix)=!values.f_nan
    endif else begin  
      Hrho1(ix) = SQRT(-(zz(ix,iz1)^2-zz(ix,iz0)^2)/2.0/ALOG(rho(ix,iz1)/rho(ix,iz0))) 
      Hrho2(ix) = SQRT(-(zz(ix,iz2)^2-zz(ix,iz0)^2)/2.0/ALOG(rho(ix,iz2)/rho(ix,iz0))) 
    endelse  
    ;-----------------------------------------------
    ; solve differential equation up to zr1 and zr2
    ;    1/rho dp/dz = -zGM/r^3  and  p=rho*cT^2
    ; ==>  dln(p)/dz = -zGM/cT^2/r^3 
    ;-----------------------------------------------
    x = xx(ix,*)                                ; quantities at ix on
    z = zz(ix,*)                                ; grid resolution
    r = SQRT(x^2+z^2)
    c = cT(ix,*)
    f = -grav*Mstar*Msun/2.d0/c^2/(r*AU)^3      ; r.h.s. of dlnp/d(z^2)
    Nhigh = 200
    zh = dblarr(Nhigh)                          ; high-res z
    lp = dblarr(Nhigh)                          ; high-res ln(p)
    for i=0,Nhigh-1 do zh(i)=max(z)*i/(Nhigh-1) ; high-res z-values 
    fh = INTERPOL(f,z,zh)                       ; high-res r.h.s.
    c2 = INTERPOL(c^2,z,zh)                     ; high-res cT^2
    p0   = press(ix,0)
    rho0 = rho(ix,0)
    lp = ALOG(p0)
    ;print,zh(0),lp(0),1.0
    for i=1,Nhigh-1 do begin
      dz2  = (zh(i)*AU)^2 - (zh(i-1)*AU)^2      ; d(z^2) 
      lp   = lp + 0.5*(fh(i)+fh(i-1))*dz2       ; ln(p) at zh(i)
      rh   = EXP(lp)/c2(i)                      ; rho at zh(i)
      Hrho = SQRT(-zh(i)^2/2.0/ALOG(rh/rho0))   ; H with respect to midplane
      pp   = EXP(lp)
      Hp   = SQRT(-zh(i)^2/2.0/ALOG(pp/p0))     ; H with respect to midplane
      zr   = zh(i)/x(0)
      if (zr LE zr1) then Hrho3(ix)=Hrho
      if (zr LE zr2) then Hrho4(ix)=Hrho
      if (zr GT zr2) then break
      ;print,i,zr,rh,Hrho
    endfor  
    ;print,ix,xx(ix,iz1),Hrho1(ix),Hrho3(ix),Hrho2(ix),Hrho4(ix)
    ;if (x(0) GT 300.0) then stop
  endfor

  x1 = xx(*,0)
  xmin = min(x1)*0.8
  xmax = max(x1)*1.2
  Hrho = [Hrho1/x1,Hrho2/x1,Hrho3/x1,Hrho4/x1]
  Hrho = Hrho(WHERE(FINITE(Hrho) AND (Hrho GT 0.0)))
  ymin = min(Hrho)/1.5
  ymax = max(Hrho)*1.5
  pos = [0.13,0.1,0.95,0.95]

  plot,x1,Hrho1/x1,/nodata,/xlog,/ylog,thick=4,position=pos,$
     xrange=[xmin,xmax],yrange=[ymin,ymax],xstyle=1,ystyle=1,$
     xtitle="!7r [au]",ytitle="!7H!L!9r!7!N/r"

  black = 0  
  blue  = 70
  red   = 250
  green = 160
  oplot,x1,Hrho4/x1,linestyle=1,thick=4,color=black
  oplot,x1,Hrho2/x1,thick=4,color=blue,PSYM=1,SYMSIZE=0.8
  oplot,x1,Hrho3/x1,linestyle=0,thick=4,color=black
  oplot,x1,Hrho1/x1,thick=4,color=blue,PSYM=7,SYMSIZE=0.8

  Hrho5 = sqrt((x1*AU)^3*cT(*,0)^2/(grav*Mstar*Msun))/AU
  oplot,x1,Hrho5/x1,thick=3,color=red,linestyle=2
  ;rref = 10.0
  ;H0   = 1.35353307016332  
  ;beta = 1.04578411851063
  ;Hrho5  = H0*(x1/rref)^beta
  ;oplot,x1,Hrho5/x1,linestyle=2,thick=4,color=red

  xp1 = EXP(ALOG(xmin)+ALOG(xmax)*0.47)
  xp2 = EXP(ALOG(xmin)+ALOG(xmax)*0.50)
  yp1 = EXP(ALOG(ymin)+ALOG(ymax/ymin)*0.18)
  oplot,[xp1,xp2],[yp1,yp1],linestyle=1,thick=4,color=black
  yp2 = EXP(ALOG(ymin)+ALOG(ymax/ymin)*0.15)
  oplot,[xp1,xp2],[yp2,yp2],thick=4,color=blue,PSYM=1,SYMSIZE=0.8
  yp3 = EXP(ALOG(ymin)+ALOG(ymax/ymin)*0.12)
  oplot,[xp1,xp2],[yp3,yp3],linestyle=0,thick=4,color=black
  yp4 = EXP(ALOG(ymin)+ALOG(ymax/ymin)*0.09)
  oplot,[xp1,xp2],[yp4,yp4],thick=4,color=blue,PSYM=7,SYMSIZE=0.8
  yp5 = EXP(ALOG(ymin)+ALOG(ymax/ymin)*0.06)
  oplot,[xp1,xp2],[yp5,yp5],linestyle=2,thick=3,color=red
  xp3=xp2*1.2
  f=0.98
  xyouts,xp3,yp1*f,charsize=1.1,color=black,"expected from Tgas, "+plot2
  xyouts,xp3,yp2*f,charsize=1.1,color=blue ,"as present in model, "+plot2
  xyouts,xp3,yp3*f,charsize=1.1,color=black,"expected from Tgas, "+plot1
  xyouts,xp3,yp4*f,charsize=1.1,color=blue ,"as present in model, "+plot1
  xyouts,xp3,yp5*f,charsize=1.1,color=red ,"from cT at midplane"

  hfile=MCMAXpath+"/scaleheight.dat"
  openr,1,hfile,ERROR = err
  close,1  
  if (err EQ 0) then begin
    readcol,hfile,x6,Hp6,Hrho6,/silent
    oplot,x6,Hrho6/x6,thick=3,color=green,linestyle=0
    yp6 = EXP(ALOG(ymin)+ALOG(ymax/ymin)*0.03)
    oplot,[xp1,xp2],[yp6,yp6],linestyle=2,thick=3,color=green
    xyouts,xp3,yp6*f,charsize=1.1,color=green ,"from MCMax"
  endif 
end

;----------------------------------
PRO COLUMN_DENS,Nx,Nz,zz,nmol,cdmol
;----------------------------------
cdmol = 0.0*nmol
for ix=0,Nx-1 do begin
  cdmol(ix,Nz-1)=0.0
  for iz=Nz-2,0,-1 do begin
    dz = zz(ix,iz+1)-zz(ix,iz)
    nn = 0.5*(nmol(ix,iz+1)+nmol(ix,iz)) 
    cdmol(ix,iz) = cdmol(ix,iz+1) + nn*dz
  endfor
endfor
end; COLUMN_DENS  

;-------------------------------------------
PRO TDUST_GRAD,Nx,Nz,xx,zz,Tdust,AVrad,AVver
;-------------------------------------------
  xmin = min(xx)
  xmax = max(xx)
  ymin = min(Tdust)/1.2
  ymax = max(Tdust)*1.2
  pos = [0.15,0.15,0.9,0.9]
  plot,xx(*,0),Tdust(*,0),/nodata,/xlog,/ylog,thick=4,position=pos,$
     xrange=[xmin,xmax],yrange=[ymin,ymax],xstyle=1,ystyle=1,$
     xtitle="!7r [au]",ytitle="!7T!Ldust!N [K]",$  
     title="fitting Tdust ~ r!U-q!N"
  zcut = interpol(zz(Nx-1,*),AVrad(Nx-1,*),10.0)
  icut = WHERE(ABS(zz(Nx-1,*)-zcut) EQ MIN(ABS(zz(Nx-1,*)-zcut)))
  icut = MAX([icut,Nz*0.1])
  icut = MIN([icut,Nz*0.8])
  zcut = [0,icut,Nz*0.9]
  xtmp = fltarr(Nx)
  xtmp(*) = xx(*,0)
  for i=0,2 do begin
    if (i EQ 2) then begin 
      iz = zcut[i]
      Td = Tdust(*,iz)
      oplot, xtmp(*),Td(*)
      bem = string(format='("z/r=",F4.2)',zz(0,iz)/xx(0,iz))
      ind = where(xtmp GT max(xx)/15.0)
      xfit = ALOG(xtmp(ind))
      yfit = ALOG(Td(ind))
      res  = LINFIT(xfit,yfit,SIGMA=sig)
      Tfit = EXP(res[0]+res[1]*xfit)
      oplot, EXP(xfit),Tfit,linestyle=2,thick=5
      xp = exp(alog(xmin)+0.05*alog(xmax/xmin))
      yp = exp(alog(ymin)+(0.03*(i+2))*alog(ymax/xmin))
      xyouts,xp,yp,string(format='(A8,":  q=",F6.3," +/- ",F6.4)',$
                          bem,-res[1],sig[1])
    endif else if (i EQ 0) then begin 
      iz = zcut[i]
      Td = Tdust(*,iz)
      oplot, xtmp(*),Td(*)
      bem = string(format='("z/r=",F4.2)',zz(0,iz)/xx(0,iz))
      ind = where(xtmp GT min(xx)*3 AND xtmp LT 2.0,icount)
      if (icount GT 1) then begin
        xfit = ALOG(xtmp(ind))
        yfit = ALOG(Tdust(ind,0))
        res  = LINFIT(xfit,yfit,SIGMA=sig)
        Tfit = EXP(res[0]+res[1]*xfit)
        oplot, EXP(xfit),Tfit,linestyle=2,thick=5
        xp = exp(alog(xmin)+0.05*alog(xmax/xmin))
        yp = exp(alog(ymin)+(0.03*(i+2))*alog(ymax/xmin))
        xyouts,xp,yp,string(format='(A8,":  q=",F6.3," +/- ",F6.4)',$
                            bem,-res[1],sig[1])
      endif
    endif else begin
      Td = Tdust(*,1)
      for ix=0,Nx-1 do begin
        Td[ix] = interpol(Tdust(ix,*),AVver(ix,*),1.0)
        if (MAX(AVver(ix,*)) LT 1.0) then Td[ix]=0.0
      endfor
      oplot, xtmp(*),Td(*)
      xp = exp(alog(xmin)+0.05*alog(xmax/xmin))
      yp = exp(alog(ymin)+(0.03*(i+2))*alog(ymax/xmin))
      xyouts,xp,yp,"Av,ver = 1"
    endelse
  endfor
  ;ind = where(xtmp GT min(xx)*3 AND xtmp LT 2.0)
  ;xfit = ALOG(xtmp(ind))
  ;yfit = ALOG(Tdust(ind,0))
  ;res  = LINFIT(xfit,yfit,SIGMA=sig)
  ;Tfit = EXP(res[0]+res[1]*xfit)
  ;oplot, EXP(xfit),Tfit,linestyle=2,thick=5
  ;xp = exp(alog(xmin)+0.05*alog(xmax/xmin))
  ;yp = exp(alog(ymin)+(0.03*(-1+2))*alog(ymax/xmin))
  ;xyouts,xp,yp,string(format='("inner z=0: q=",F6.3," +/- ",F5.3)',$
  ;                             -res[1],sig[1])
end

;----------------------------------------------------
PRO PLOT_OPACITY,folder,MCFOSTpath,MCMAXpath,Rin,Rout
;----------------------------------------------------
  line='bla'
  NDUST=0
  NLAM=0
  black = 0
  red   = 250
  blue  = 70
  openr,1,folder+"/dust_opac.out"
  readf,1,NDUST,NLAM
  for i=1,NDUST+2 do readf,1,line
  lambda1  = dblarr(NLAM) 
  kap_ext = dblarr(NLAM) 
  kap_abs = dblarr(NLAM) 
  kap_sca = dblarr(NLAM) 
  for i=0,NLAM-1 do begin
    readf,1,lamval,kext,kabs,ksca
    lambda1(i)=lamval           ; [mic]
    kap_ext(i)=kext             ; [cm^2/g(dust)]
    kap_abs(i)=kabs             ; [cm^2/g(dust)]
    kap_sca(i)=ksca             ; [cm^2/g(dust)]
  endfor
  close,1
  for iplot=1,2 do begin
    ymin=min([kap_ext,kap_abs,kap_sca])
    ymax=max([kap_ext,kap_abs,kap_sca])*1.5
    havePAH = (0 EQ 1)
    if (iplot EQ 2) then begin
      openr,1,"PAH_cross.out",ERROR = err
      close,1  
      havePAH = (err EQ 0)
      if (err NE 0) then break
      openr,1,"PAH_cross.out"
      readf,1,line
      readf,1,NC,NH,NLAM2,dust_to_gas,fPAH
;      fPAH=0.01
;      dust_to_gas=0.01
      readf,1,line
      readf,1,line
      readf,1,line
      readf,1,line
      readf,1,line
      lamPAH = dblarr(NLAM2) 
      sigPAH_neutral = dblarr(NLAM2) 
      sigPAH_charged = dblarr(NLAM2) 
      for i=0,NLAM2-1 do begin
        readf,1,lamval,kabs1,kabs2
        lamPAH(i) = lamval
        sigPAH_neutral(i) = kabs1
        sigPAH_charged(i) = kabs2
      endfor  
      close,1
      amu         = 1.660531E-24             ; atomar mass unit
      massH       = 1.0079*amu               ; mass of H
      massC       = 12.011*amu               ; mass of C
      massPAH     = massH*NH + massC*NC      ; mass of one PAH
      eps_PAH     = fPAH*3.E-7*(50.0/NC)
      nHtot       = 1.E+10
      rho_gas     = nHtot*1.4*amu
      rho_dust    = rho_gas*dust_to_gas
      rho_PAH     = nHtot*eps_PAH*massPAH
      kapPAH_neutral = sigPAH_neutral*nHtot*eps_PAH / rho_dust ; cm^2/g(dust)   
      kapPAH_charged = sigPAH_charged*nHtot*eps_PAH / rho_dust ; cm^2/g(dust)   
      ind = WHERE(lamPAH LT 30.0)
      ymax=max([ymax,1.2*kapPAH_neutral])
      ymin=min([ymin,0.8*kapPAH_neutral(ind)])
    endif  
    pos=[0.18,0.15,0.95,0.95]
    plot,lambda1,kap_ext,/xlog,/ylog,yrange=[ymin,ymax],$
       linestyle=0,thick=2,position=pos,$
       xtitle="!9l !7[!9m!7m]",$
       ytitle="!9k !7[cm!U2!N/g(dust)]"
    oplot,lambda1,kap_abs,thick=2,color=red
    oplot,lambda1,kap_sca,thick=2,color=blue
    oplot,lambda1,30000.0/lambda1,linestyle=1,thick=1
    qual04=9.d+99
    qual20=9.d+99
    i04=0
    i20=0
    for i=0,NLAM-1 do begin
      if(ABS(lambda1(i)-0.4) LT qual04) then begin
        qual04=ABS(lambda1(i)-0.4)
        i04=i
      endif  
      if(ABS(lambda1(i)-2.0) LT qual20) then begin
        qual20=ABS(lambda1(i)-2.0)
        i20=i
      endif  
    endfor
    xyouts, 0.4,kap_sca(i04)*0.7,"!9k!7!Lsca!N",ALIGNMENT=0.5,color=blue
    xyouts, 2.0,kap_abs(i20)*0.7,"!9k!7!Labs!N",ALIGNMENT=0.5,color=red
    xyouts, 200.0,200.0,"!9l!7!U-1!N",ALIGNMENT=0.5
    yout = exp(alog(ymin)+alog(ymax/ymin)*0.2)
    plotsym,3,1.4,/FILL,color=red
    oplot,[300.0,300],[10.0,10.0],psym=8
    oplot,[850.0,850],[3.5,3.5],psym=8
    oplot,[0.19,0.41],[yout,yout]
    xyouts,0.47,yout*0.92,"ProDiMo"
    ;----- PAH opacities -----
    if (havePAH) then begin
      green1 = 140
      green2 = 170
      oplot,lamPAH,kapPAH_neutral,thick=1,linestyle=0,color=green1
      oplot,lamPAH,kapPAH_charged,thick=1,linestyle=0,color=green2
      oplot,[60.0,100.0],[1.0,1.0],thick=1,linestyle=0,color=green1
      oplot,[60.0,100.0],[0.5,0.5],thick=1,linestyle=0,color=green2
      xyouts,110.0,1.0/1.2,color=green1,"neutral PAH"
      xyouts,110.0,0.5/1.2,color=green2,"charged PAH"
      comment=STRING(format='("(g/d=",F6.1,"  fPAH=",F6.3,")")',$
              1.0/dust_to_gas,fPAH)
      xyouts,110.0,0.25/1.2,charsize=0.9,color=green1,comment
    endif
    ;----- MCFOST -----
    openr,1,MCFOSTpath+"/data_dust/lambda.fits.gz",ERROR = err1
    openr,2,MCFOSTpath+"/data_ProDiMo/forProDiMo.fits.gz",ERROR = err2
    openr,3,MCFOSTpath+"/data_disk/dust_mass_density.fits.gz",ERROR = err3
    close,1
    close,2
    close,3
    err2 = err2 + err3
    if (err1 EQ 0) then begin
       ;--- "just the opacities on first grid point" (Christophe) --- 
       lam = MRDFITS(MCFOSTpath+"/data_dust/lambda.fits.gz",0,/silent)
       alb = MRDFITS(MCFOSTpath+"/data_dust/albedo.fits.gz",0,/silent)
       kext= MRDFITS(MCFOSTpath+"/data_dust/kappa.fits.gz",0,/silent)
       ksca= kext*alb
       kabs= kext*(1.0-alb)
    endif
    if (err2 EQ 0) then begin
       ;--- proper mass-averaged opacities across whole disk ---
       grid = MRDFITS(MCFOSTpath+"/data_ProDiMo/forProDiMo.fits.gz",0,header,/silent)
       lam  = MRDFITS(MCFOSTpath+"/data_ProDiMo/forProDiMo.fits.gz",2,/silent)
       opac = MRDFITS(MCFOSTpath+"/data_ProDiMo/forProDiMo.fits.gz",10,/silent)
       rhod = MRDFITS(MCFOSTpath+"/data_disk/dust_mass_density.fits.gz",0,/silent)
       sz_grid = SIZE(grid)
       sz_lam  = SIZE(lam)
       sz_opac = SIZE(opac)
       NNx   = sz_grid[1]
       NNz   = sz_grid[2]
       NNlam = sz_lam[1]
       ;print,NNx,NNz,NNlam
       AU    = 1.495978700D+13
       Msun  = 1.988922500E+33
       rgrid = DBLARR(NNx+1)
       zgrid = DBLARR(NNz+1)
       dVol  = DBLARR(NNx,NNz)
       rgrid[0] = Rin*AU
       rgrid[NNx] = Rout*AU
       for ix=1,NNx-1 do begin
          rgrid[ix] = sqrt(grid[ix-1,1,0]*grid[ix,1,0])*AU
       endfor
       for ix=1,NNx do begin
          zgrid[0] = 0.0
          zgrid[1:NNz] = grid(ix-1,0:NNz-1,1)*AU
          for iz=1,NNz do begin
             r1 = rgrid[ix-1]
             r2 = rgrid[ix]
             z1 = zgrid[iz-1]
             z2 = zgrid[iz]
             if (iz GT   1) then z1=0.5*(zgrid[iz-1]+zgrid[iz])
             if (iz LT NNz) then z2=0.5*(zgrid[iz+1]+zgrid[iz])
             dVol[ix-1,iz-1] = 2.d0*!PI*(r2^2-r1^2)*(z2-z1)
          endfor
       endfor
       ;help,grid
       ;help,lam
       ;help,dVol
       ;help,opac
       ;help,rhod
       dext_mono = opac(*,*,0,*)/AU
       dabs_mono = opac(*,*,1,*)/AU
       kext = lam
       kabs = lam
       for il=0,NNlam-1 do begin
          kkext = 0.d0
          kkabs = 0.d0
          dmass = 0.d0
          for ix=0,NNx-1 do begin
             for iz=0,NNz-1 do begin
                kkext = kkext + dext_mono[ix,iz,0,il]*dVol[ix,iz] 
                kkabs = kkabs + dabs_mono[ix,iz,0,il]*dVol[ix,iz] 
                dmass = dmass + rhod[ix,iz]*dVol[ix,iz]
             endfor
          endfor
          kext[il] = kkext/dmass
          kabs[il] = kkabs/dmass
          ;print,dmass/Msun
       endfor
       ksca = kext-kabs
    endif
    if ((err1 EQ 0) OR (err2 EQ 0)) then begin
      AA = FINDGEN(17) * (!PI*2/16.)  
      USERSYM, COS(AA), SIN(AA)
      plotsym,0,0.8,color=blue
      oplot,lam,ksca,PSYM=8,SYMSIZE=0.5
      plotsym,0,0.8,color=red
      oplot,lam,kabs,PSYM=8,SYMSIZE=0.5
      plotsym,0,0.8,color=black
      oplot,lam,kext,PSYM=8,SYMSIZE=0.5
      yout = exp(alog(ymin)+alog(ymax/ymin)*0.15)
      oplot,[0.2,0.25,0.32,0.4],[yout,yout,yout,yout],PSYM=8,SYMSIZE=0.8
      xyouts,0.47,yout*0.92,"MCFOST"
    endif  
    ;----- MCMax -----
    MCMAXfile=MCMAXpath+"/particle_average.opacity"
    openr,1,MCMAXfile,ERROR = err
    close,1  
    if (err EQ 0) then begin
      readcol,MCMAXfile,lam,kext,kabs,ksca,/silent
      AA = FINDGEN(17) * (!PI*2/16.)  
      USERSYM, COS(AA), SIN(AA)
      plotsym,0,0.8,/fill,color=blue
      oplot,lam,ksca,PSYM=8,SYMSIZE=0.5
      plotsym,0,0.8,/fill,color=red
      oplot,lam,kabs,PSYM=8,SYMSIZE=0.5
      plotsym,0,0.8,/fill,color=black
      oplot,lam,kext,PSYM=8,SYMSIZE=0.5
      yout = exp(alog(ymin)+alog(ymax/ymin)*0.1)
      oplot,[0.2,0.25,0.32,0.4],[yout,yout,yout,yout],PSYM=8,SYMSIZE=0.8
      xyouts,0.47,yout*0.92,"MCMax"
    endif  
  endfor  

  ind = WHERE(lambda1 GT 850.0 AND lambda1 LT 1300.0, nn)
  if (nn gt 1) then begin
      xx  = ALOG(lambda1(ind))
      yy  = ALOG(kap_abs(ind))
      coeff = LINFIT(xx,yy,SIGMA=sigma)
      print,"the opacity mm-slope (0.85-1.3)mm is",-coeff[1]," +/- ",sigma[1]
  endif
  ind = WHERE(lambda1 GT 5000.0 AND lambda1 LT 10000.0, nn)
  if (nn gt 1) then begin
      xx  = ALOG(lambda1(ind))
      yy  = ALOG(kap_abs(ind))
      coeff = LINFIT(xx,yy,SIGMA=sigma)
      print,"the opacity cm-slope     (5-10)mm is",-coeff[1]," +/- ",sigma[1]
  endif
end

;---------------------------------------------------------------------------
PRO PLOT_SED,folder,NLAM,lam,Rstar,dist,col,FluxJy,$
             MCFOSTpath,MCMAXpath,ebv=ebv,r_v=r_v
;---------------------------------------------------------------------------
  cl     = 2.997924580D+10       ; speed of light
  pc     = 3.085680250D+18       ; 1 parsec
  Rsun   = 6.959900000D+10       ; solar radius
  nm     = 1.D-7                 ; 1 nanometer
  mic    = 1.D-4                 ; 1 micron
  Ang    = 1.D-8                 ; 1 Angstroem
  Wm2    = 1.D+3                 ; 1 W/m^2 in [erg/cm^2/s]
  Jansky = 1.D-23                ; 1 Jy in [erg/cm^2/s/Hz]
  line="blasel"
  openr,1,folder+"/SED.out"
  readf,1,format='(24x,F20)',dist
  dist  = dist*pc
  close,1
  ; NSPEC = 0 ; with ProDiMo release 2083 and the addition of the new, higher-resolution DriftPhoenix model
              ; spectra, prodimo.pro does not work. NSPEC is written correctly but the number is too high for
              ; IDL to read (??!!). Commenting out the pre-allocation to zero seems to fix it.
  openr,1,folder+"/StarSpectrum.out"
  readf,1,line
  readf,1,line
  if (STRLEN(line) GT 60) then reads,line,format='(14x,F20,20x,F26.16)',logg,Rstar
  Astar = !PI*(Rstar*Rsun)^2
  readf,1,line
  readf,1,NSPEC
  readf,1,line
  lambstar = dblarr(NSPEC) 
  Flamstar = dblarr(NSPEC) 
  Lstar = 0.0
  nuval = 1.d0
  Ival  = 1.d0
  Fold  = 0.d0
  for i=0,NSPEC-1 do begin
    readf,1,lamval,nuval,Ival
    if (Ival GT 1.0) then Ival=1.e-99   ; "1.23-123"
    lambstar(i) = lamval
    Fval = Astar*Ival/dist^2
    Flamstar(i) = nuval * Fval
    if (i GT 0) then Lstar = Lstar + 0.5*(Fval+Fold)*(nuold-nuval)
    nuold=nuval
    Fold=Fval
  endfor
  close,1
  NLAM1=0
  NLAM2=0
  openr,1,folder+"/SED.out"
  readf,1,line
  readf,1,line
  readf,1,NLAM1
  readf,1,line
  lamb1 = dblarr(NLAM1) 
  Flam1 = dblarr(NLAM1) 
  for i=0,NLAM1-1 do begin
    readf,1,lamval,nuval,F1val,F2val,F3val
    lamb1(i)=lamval
    Flam1(i)=nuval*F1val
  endfor
MCinterpol:
  readf,1,line
  readf,1,format='(24x,F20)',incl
  readf,1,NLAM2
  readf,1,line
  lamb2 = dblarr(NLAM2) 
  Flam2 = dblarr(NLAM2) 
  Lbolo = 0.0
  LNIR  = 0.0
  LMIR  = 0.0
  LFIR  = 0.0
  NIRmin = 10000.0
  NIRmax = 0.0
  MIRmin = 10000.0
  MIRmax = 0.0
  FIRmin = 10000.0
  FIRmax = 0.0
  FluxJy = fltarr(NLAM2)
  for i=0,NLAM2-1 do begin
    readf,1,lamval,nuval,F1val,F2val,F3val
    FluxJy(i)=F3val
    lamb2(i)=lamval
    Flam2(i)=nuval*F1val
    Fstar = INTERPOL(Flamstar,lambstar,lamval)/nuval
    F2val = F1val - Fstar       ; subtract naked star
    if (i GT 0) then begin
      Lbolo = Lbolo + 0.5*(F1old+F1val)*(nuold-nuval)
      if ((lamold GT 2.0) AND (lamval LE 7.0)) then begin
        LNIR = LNIR + 0.5*(F2old+F2val)*(nuold-nuval)
        NIRmin = min([NIRmin,lamold])
        NIRmax = max([NIRmax,lamval])
      endif  
      if ((lamval GT 7.0) AND (lamval LE 30.0)) then begin
        LMIR = LMIR + 0.5*(F2old+F2val)*(nuold-nuval)
        MIRmin = min([MIRmin,lamold])
        MIRmax = max([MIRmax,lamval])
      endif  
      if ((lamval GT 30.0) AND (lamval LE 1000.0)) then begin
        LFIR = LFIR + 0.5*(F2old+F2val)*(nuold-nuval)
        FIRmin = min([FIRmin,lamold])
        FIRmax = max([FIRmax,lamval])
      endif  
    endif  
    lamold=lamval
    nuold=nuval
    F1old=F1val
    F2old=F2val
  endfor
  ;if (~EOF(1)) then goto,MCinterpol
  close,1
  Fmin=min(alog10(Flam1(WHERE(lamb2 GT 1.0))))-0.7
  Fmax=max(alog10(Flam1))+0.3
  ;Fmin=-12.7
  ;Fmax=-7.0
  xmin=[min(lamb2)*0.8]
  xmax=[max(lamb2)*1.1]
  xmin=max([xmin,0.07])
  ;xmax=1500.0
  pos=[0.13,0.11,0.95,0.95]
  plot, lamb2,alog10(Flam1),/nodata,/xlog,$
       xrange=[xmin,xmax],yrange=[Fmin,Fmax],$
       linestyle=2,thick=2,position=pos,$  ;psym=-8,$ 
       xtitle="!9l !7[!9m!7m]",$
       ytitle="log !9n !N!7F!9!Ln!N !7[erg/cm!U2!N/s]"
      ;ytitle="log !9n !N!7F!9!Ln!N !7[W/m!U2!N]"
  ; --- overplot stellar spectrum ---
  ind1 = WHERE(lambstar LT 0.45)
  ind2 = WHERE(lambstar GE 0.45)
  Fstar1 = Flamstar(ind1)
  Fstar2 = Flamstar(ind2)
  Fstar1 = exp(SMOOTH(alog(Fstar1),3,/EDGE_TRUNCATE))
  Fstar2 = exp(SMOOTH(alog(Fstar2),2,/EDGE_TRUNCATE))
  Flamstar = [Fstar1,Fstar2]
  ind = WHERE(lambstar GT 0.091)
  oplot, lambstar(ind),alog10(Flamstar(ind)),COLOR=col,thick=1
  bbem=strarr(99)
  bcol=intarr(99)
  blin=intarr(99)
  bthi=intarr(99)
  Nbem=3
  bbem(0)="dist = "+STRTRIM(STRING(format="(F8.1)",dist/pc),2)+"!L !Npc"$
      +",  incl = "+STRTRIM(STRING(format="(I3)",incl+0.5),2)+"!Uo!N"
  bbem(1)="star + UV"
  bbem(2)="ProDiMo"
  bcol(0)=0   &  blin(0)=0  & bthi(0)=0
  bcol(1)=col &  blin(1)=0  & bthi(1)=1
  bcol(2)=0   &  blin(3)=0  & bthi(3)=2

  Lbolo = Lbolo*(4.0*!PI*dist^2) ; bolometric luminosity
  Lstar = Lstar*(4.0*!PI*dist^2) ; naked stellar luminosity
  LNIR  = LNIR *(4.0*!PI*dist^2) ; mid IR luminosity
  LMIR  = LMIR *(4.0*!PI*dist^2) ; mid IR luminosity
  LFIR  = LFIR *(4.0*!PI*dist^2) ; far IR luminosity
  Lsun  = 3.8260D+33             ; solar luminosity

  ind = WHERE(lamb2 GT 850 AND lamb2 LT 1300,nn)
  if (nn gt 1) then begin
    print,'-------------------------------------------------------------------------'
    xx  = ALOG(lamb2(ind))
    yy  = ALOG(FluxJy(ind))
    coeff = LINFIT(xx,yy,SIGMA=sigma)
    print,"the SED mm-slope   (850mic-1.3mm) is",-coeff[1]," +/- ",sigma[1]
  endif  
  ind = WHERE(lamb2 GT 5000 AND lamb2 LT 10000,nn)
  if (nn gt 1) then begin
    xx  = ALOG(lamb2(ind))
    yy  = ALOG(FluxJy(ind))
    coeff = LINFIT(xx,yy,SIGMA=sigma)
    print,"the SED mm-slope         (5-10)mm is",-coeff[1]," +/- ",sigma[1]
    print,'-------------------------------------------------------------------------'
  endif  
  Fmin1 = FluxJy(where(ABS(lamb2- 6.8) EQ MIN(ABS(lamb2- 6.8))))
  Fmin2 = FluxJy(where(ABS(lamb2-13.1) EQ MIN(ABS(lamb2-13.1))))
  Fmax1 = FluxJy(where(ABS(lamb2- 9.6) EQ MIN(ABS(lamb2- 9.6)))) 
  print,"           10mic emission amplitude = ",Fmax1/sqrt(Fmin1*Fmin2)

  ; ------- compare to MCMax SED ----------
  tmp='0'+STRTRIM(STRING(format='(F4.1)',incl),2)
  len=STRLEN(tmp)
  tmp=STRMID(tmp,len-4)
  sedfile=MCMAXpath+"/spectrum"+tmp+".dat"
  openr,1,sedfile,ERROR = err
  close,1  
  lamMCMax = 0
  if (err EQ 0) then begin
    print,"reading "+sedfile
    readcol,sedfile,lamSpec,Fval,/silent
    Nval = N_ELEMENTS(Fval)
    lamSpec = lamSpec(0:Nval-1)
    Fval    = Fval(0:Nval-1)
    ;openr,1,'extinct.dat',ERROR=err
    ;if(err EQ 0) then begin
    ;  readf,1,line
    ;  readf,1,ebv
    ;  readf,1,line
    ;  readf,1,R_V 
    ;  close,1
    ;  fm_unred,lamSpec*mic/Ang,Fval,ebv,r_v=R_V
    ;endif  
    nuval = cl/(lamSpec*mic)
    FnuSpec = nuval*(Fval*Jansky)
    AA = FINDGEN(17) * (!PI*2/16.)  
    USERSYM, COS(AA), SIN(AA)
    plotsym,0,0.8,color=black
    green   = 160
    oplot,lamSpec,alog10(FnuSpec),color=green,PSYM=8,SYMSIZE=1.0 
    lamMCMax = lamSpec
    FnuMCMax = FnuSpec
    bbem(Nbem)="MCMax (FS)"
    bcol(Nbem)=green  & blin(Nbem)=0  & bthi(Nbem)=2
    Nbem=Nbem+1
  endif  
  flist = FINDFILE(MCMAXpath+"/MCSpec??.?.dat")
  Nlist = N_ELEMENTS(flist)
  if ((Nlist GE 1) AND (flist(0) NE '')) then begin
    incl2 = fltarr(Nlist)
    for j=0,Nlist-1 do begin
      i1 = STRPOS(flist(j),".dat")
      istr = STRMID(flist(j),i1-4,4)
      READS,istr,dum
      incl2(j)=dum 
    endfor  
    bestq1 = 9.e+99
    bestq2 = 9.e+99
    besti1 = -1
    besti2 = -1
    for i=0,Nlist-1 do begin
      qual = abs(incl2(i)-incl)
      if (qual LT bestq1) then begin
        bestq2 = bestq1 
        bestq1 = qual
        besti2 = besti1
        besti1 = i
      endif else begin 
        if (qual LT bestq2) then begin  
        bestq2 = qual
        besti2 = i
        endif 
      endelse
    endfor
    if (besti1 GE 0 AND besti2 GE 0) then begin
      print,"reading "+flist(besti1)
      readcol,flist(besti1),lamSpec,Fval2,/silent
      nuval = cl/(lamSpec*mic)
      FlamA = nuval*(Fval2*Jansky)
      print,"reading "+flist(besti2)
      readcol,flist(besti2),lamSpec2,Fval2,/silent
      nuval = cl/(lamSpec*mic)
      FlamB = nuval*(Fval2*Jansky)
      fac     = (incl-incl2(besti1))/(incl2(besti2)-incl2(besti1))
      FnuSpec = FlamA*(1.d0-fac)+FlamB*fac
      plotsym,0,0.8,color=black,/fill
      green = 90
      oplot,lamSpec,alog10(FnuSpec),color=green,PSYM=8,SYMSIZE=0.6 
      bbem(Nbem)="MCMax (MC)"
      bcol(Nbem)=green  & blin(Nbem)=0  & bthi(Nbem)=2
      Nbem=Nbem+1
    endif  
  endif

  ; ------- compare to MCFOST SED ----------
  sedfile=MCFOSTpath+"/data_th/sed_rt.fits.gz"
  openr,1,sedfile,ERROR = err2
  close,1
  err = err2
  lamMCFOST = 0
  if (err2 NE 0) then begin
    sedfile=MCFOSTpath+"/data_th/sed2.fits.gz"
    openr,1,sedfile,ERROR = err
    close,1  
  endif  
  if (err EQ 0) then begin
    lamm = MRDFITS(sedfile,1,header,/silent)
    sed2 = MRDFITS(sedfile,0,header,/silent)
    if (err2 EQ 0) then begin
      Flam = sed2*1.D+3
      bbem(Nbem)="MCFOST (FS)"
    endif else begin
      Nincl1 = n_elements(sed2(0,*,0,0))
      incl1 = fltarr(Nincl1)
      cosi = fltarr(Nincl1+1)
      for i=0,Nincl1 do begin
        cosi(i) = 1.0-1.0*i/Nincl1
      endfor
      bestq1 = 9.e+99
      bestq2 = 9.e+99
      besti1 = -1
      besti2 = -1
      for i=0,Nincl1-1 do begin
        incl1(i) = acos(0.5*(cosi(i)+cosi(i+1)))*180.0/!pi
        qual = abs(incl1(i)-incl)
        if (qual LT bestq1) then begin
          bestq2 = bestq1 
          bestq1 = qual
          besti2 = besti1
          besti1 = i
        endif else begin 
          if (qual LT bestq2) then begin  
          bestq2 = qual
          besti2 = i
          endif 
        endelse
      endfor
      FlamA = sed2(*,besti1,0,0)*1.D+3             ; second index incl    
      FlamB = sed2(*,besti2,0,0)*1.D+3             ; second index incl    
      fac   = (incl-incl1(besti1))/(incl1(besti2)-incl1(besti1))
      Flam  = FlamA*(1.d0-fac)+FlamB*fac      
      bbem(Nbem)="MCFOST (MC)"
    endelse
    blue = 70
    print,"plotting MCFOST's SED from ",sedfile 
    oplot,lamm,alog10(Flam),color=blue,PSYM=5,SYMSIZE=0.8
    lamMCFOST = lamm
    FnuMCFOST = Flam
    bcol(Nbem)=blue  & blin(Nbem)=0  & bthi(Nbem)=2
    Nbem=Nbem+1
  endif  
  
  ; ------- compare to observations ----------
  openr,1,'extinct.dat',ERROR=err
  if(err EQ 0) then begin
    readf,1,line
    readf,1,ebv
    readf,1,line
    readf,1,R_V 
    close,1
    A_V=R_V*ebv
    print,'ISM de-reddening with A_V=',A_V
    print,'E(B-V)=',ebv
    print,'R_V=',R_V
  endif

  ; ------- overplot IR spectra -------
  Jansky = 1.D-23               ; 1 Jy in [erg/cm^2/s/Hz]
  cl     = 2.99792458D+10       ; speed of light
  openr,1,"ISO-SWS-spectrum.dat",ERROR=err ; Jy
  if (err EQ 0) then begin
    close,1
    readcol,"ISO-SWS-spectrum.dat",lamISO,Fval,/silent
    nuval = cl/(lamISO*mic)
    FnuISO = nuval*(Fval*Jansky)
    oplot,lamISO,alog10(FnuISO),color=195,thick=3
    bbem(Nbem)="ISO-SWS"
    bcol(Nbem)=195  & blin(Nbem)=0  & bthi(Nbem)=3
    Nbem=Nbem+1
  end   
  openr,1,"ISO-LWS-spectrum.dat",ERROR=err ; in W/cm^2/micron
  if (err EQ 0) then begin
    close,1
    readcol,"ISO-LWS-spectrum.dat",lamSpec,Fval,/silent
    FnuSpec=lamSpec*Fval*1e7
    oplot,lamSpec,alog10(FnuSpec),color=230,thick=3
    bbem(Nbem)="ISO-LWS"
    bcol(Nbem)=230  & blin(Nbem)=0  & bthi(Nbem)=3
    Nbem=Nbem+1
  end
  IRspecFile = "JWSTspec.dat"
  IRspecName = "JWST/MIRI"
  openr,1,IRspecFile,ERROR = err
  close,1 
  if (err NE 0) then begin
    IRspecFile = "SpitzerIRSspec.dat"
    IRspecName = "Spitzer/IRS"
    openr,1,IRspecFile,ERROR = err
    close,1 
  endif
  if (err EQ 0) then begin
    readcol,IRspecFile,lamSpitzer,Fval,/silent
    nuval = cl/(lamSpitzer*mic)
    FnuSpitzer = nuval*(Fval*Jansky)
    ;good = WHERE((lamSpitzer GT 0.0) AND (FnuSpitzer EQ FnuSpitzer), Npoints)
    ;good(0) = 0
    ;good(Npoints-1) = 0
    ;lmax = lamSpitzer(0)
    ;for i=1,Npoints-2 do begin
    ;  if (FnuSpitzer(i) LT 0.7*FnuSpitzer(i-1)) then good(i)=0
    ;  if (FnuSpitzer(i) LT 0.7*FnuSpitzer(i+1)) then good(i)=0
    ;  if (lamSpitzer(i) LT lmax) then good(i)=0
    ;  lmax = max([lmax,lamSpitzer(i)])
    ;endfor
    ;goodind = WHERE(good GT 0)
    ;oplot,lamSpitzer(goodind),alog10(FnuSpitzer(goodind)),color=205,thick=4
    oplot,lamSpitzer,alog10(FnuSpitzer),color=205,thick=4
    bbem(Nbem)=IRspecName
    bcol(Nbem)=205  & blin(Nbem)=0  & bthi(Nbem)=3
    Nbem=Nbem+1
    for i=10,17 do begin
      filename="SpitzerIRSspec"+STRING(format='(I2.2)',i)+".dat"
      openr,1,filename,ERROR = err
      if (err EQ 0) then begin
        close,1 
        readcol,filename,lamSpec,Fval,/silent
        nuval = cl/(lamSpec*mic)
        FnuSpec = nuval*(Fval*Jansky)
        oplot,lamSpec,alog10(FnuSpec),color=213,thick=1
        ;print,filename,max(Fval)
      endif
    endfor  
  endif  
  openr,1,"nearIR_Spectrum.dat",ERROR = err
  if (err EQ 0) then begin
    close,1 
    readcol,"nearIR_Spectrum.dat",lamIRspec,Fval,/silent  ; [mic],[W/m^2/mic] 
    if (KEYWORD_SET(ebv)) then begin                      ; de-reddening
      fm_unred,lamIRspec/mic*Ang,Fval,ebv,r_v=r_v
    endif  
    Fval = Fval*Wm2                                       ; Flam[erg/cm^2/s/mic]
    FnuIRspec = lamIRspec*Fval
    oplot,lamIRspec,alog10(FnuIRspec),color=120,thick=3
    bbem(Nbem)="SpeX/IRTF"
    bcol(Nbem)=120  & blin(Nbem)=0  & bthi(Nbem)=3
    Nbem=Nbem+1
  endif  
  openr,1,"OpticalSpectrum.dat",ERROR = err
  if (err EQ 0) then begin
    close,1 
    readcol,"OpticalSpectrum.dat",lamOPspec,Fval,/silent  ; [A],[erg/cm^2/s/Hz] 
    if (KEYWORD_SET(ebv)) then begin                      ; de-reddening
      fm_unred,lamOPspec,Fval,ebv,r_v=r_v
    endif  
    nuval = cl/(lamOPspec*Ang)                            
    lamOPspec = lamOPspec*Ang/mic
    FnuOPspec = nuval*Fval
    oplot,lamOPspec*Ang/mic,alog10(FnuOPspec),color=150,thick=3
    bbem(Nbem)="WHT/UES"
    bcol(Nbem)=150  & blin(Nbem)=0  & bthi(Nbem)=3
    Nbem=Nbem+1
  endif  
  openr,1,"UV.dat",ERROR = err
  if (err EQ 0) then begin
    close,1 
    readcol,"UV.dat",lamUV,Fval,/silent         ; lam[A], F[erg/cm^2/s/A]
    if (KEYWORD_SET(ebv)) then begin            ; de-reddening
      fm_unred,lamUV,Fval,ebv,r_v=r_v
    endif  
    FnuUV = lamUV*Fval
    lamUV = lamUV*Ang/mic
    oplot,lamUV,alog10(FnuUV),color=95,thick=3
    bbem(Nbem)="<UV>data"
    ;bbem(Nbem)="FUSE, STIS"
    bcol(Nbem)=95  & blin(Nbem)=0  & bthi(Nbem)=3
    Nbem=Nbem+1
  endif  
  openr,1,"PACSspec_50-75.dat",ERROR = err
  if (err EQ 0) then begin
    close,1 
    readcol,"PACSspec_50-75.dat",lamSpec,Fval,/silent   ; [mic],[Jy]
    nuval = cl/(lamSpec*mic)
    FnuSpec = nuval*(Fval*Jansky)
    oplot,lamSpec,alog10(FnuSpec),color=120,thick=1
    readcol,"PACSspec_70-110.dat",lamSpec,Fval,/silent   ; [mic],[Jy]
    nuval = cl/(lamSpec*mic)
    FnuSpec = nuval*(Fval*Jansky)
    oplot,lamSpec,alog10(FnuSpec),color=120,thick=1
    readcol,"PACSspec_100-150.dat",lamSpec,Fval,/silent   ; [mic],[Jy]
    nuval = cl/(lamSpec*mic)
    FnuSpec = nuval*(Fval*Jansky)
    oplot,lamSpec,alog10(FnuSpec),color=120,thick=1
    readcol,"PACSspec_140-210.dat",lamSpec,Fval,/silent   ; [mic],[Jy]
    nuval = cl/(lamSpec*mic)
    FnuSpec = nuval*(Fval*Jansky)
    oplot,lamSpec,alog10(FnuSpec),color=120,thick=1
    bbem(Nbem)="PACSspec"
    bcol(Nbem)=120  & blin(Nbem)=0  & bthi(Nbem)=3
    Nbem=Nbem+1
  endif  
  openr,1,"SPIREspec.dat",ERROR = err
  if (err EQ 0) then begin
    close,1 
    readcol,"SPIREspec.dat",nuval,Fval,/silent     ; [GHz],[Jy]
    nuval = nuval*1.E+9
    lamSPIRE = cl/nuval/mic
    FnuSPIRE = nuval*(Fval*Jansky)
    oplot,lamSPIRE,alog10(FnuSPIRE),color=195,thick=4
    bbem(Nbem)="SPIREspec"
    bcol(Nbem)=195  & blin(Nbem)=0  & bthi(Nbem)=3
    Nbem=Nbem+1
  endif  

  ;------- photometry --------
  Nobs = 0
  openr,1,"SEDobs.dat",ERROR = err
  if (err EQ 0) then begin
    readf,1,Nobs
    readf,1,line
    lamval = 0.0
    Fnuval = 0.0
    sigma  = 0.0
    bem = " "
    filter = " "
    rest = " "
    chi = 0.0
    ichi = 0
    print," lambda[mic]     filter  nu*Fnu(obs) nu*Fnu(mod)     sigma  deviation"
    AA = FINDGEN(17) * (!PI*2/16.)  
    USERSYM, COS(AA), SIN(AA)
    plotsym,0,0.8,/fill,color=black
    lamPHOT = fltarr(Nobs+1)
    FnuPHOT = fltarr(Nobs+1)
    bemPHOT = strarr(Nobs+1)
    filPHOT = strarr(Nobs+1)
    refPHOT = strarr(Nobs+1)
    for i=1,Nobs do begin
      readf,1,line 
      reads,line,lamval,Fnuval,sigma,rest
      rest   = STRTRIM(rest,2)
      bem    = STRMID(rest,0,2)
      rest   = STRTRIM(STRMID(rest,3),2)
      ispace = STRPOS(rest," ")
      filter = STRMID(rest,0,ispace)
      ref    = STRTRIM(STRMID(rest,ispace),2)
      ;if (lamval LT 1.2*max(lamb2) and lamval GT min(lamb2)) then begin
      lamPHOT(i) = lamval
      FnuPHOT(i) = Fnuval
      bemPHOT(i) = bem
      filPHOT(i) = filter
      refPHOT(i) = ref
      nuval = cl/(lamval*mic)
      sigma = nuval*MAX([sigma,0.05*Fnuval])*Jansky    ; sigma [erg/cm^2/s]
      Fval  = nuval*Fnuval*Jansky                      ; obs.flux ["]
      F1val = alog10(MAX([1.e-99,Fval-sigma]))
      F2val = alog10(Fval+sigma)
      ;------------
      ; deredening
      ;------------ 
      if (KEYWORD_SET(ebv)) then begin
        wave=lamval*1e4
        rf=[Fval,Fval-sigma,Fval+sigma]
        fm_unred,[wave,wave,wave],rf,ebv,r_v=r_v
        Fval             = rf(0)
        Fval_minus_sigma = rf(1)
        Fval_plus_sigma  = rf(2)
        sigma = Fval_plus_sigma-Fval
        F1val = alog10(MAX([1.e-99,Fval_minus_sigma]))       
        F2val = alog10(Fval_plus_sigma)
      endif   
      F1val = MAX([F1val,Fmin])
      ; -----
      ltest = alog(lamval*(0.93+0.14*FINDGEN(201)/200.0))   ; +/- 7%
      Ftest = INTERPOL(alog(Flam2),alog(lamb2),ltest,/SPLINE) 
      Ftest = exp(Ftest)                                    ; model flux
      Fmodel= 0.0
      Fqual = 9.e+99
      ;--- take best value in small lam-interval ---
      for j=0,200 do begin
        qual = ABS(Ftest[j]-Fval)
        if (qual LT Fqual) then begin
          Fmodel = Ftest[j]
          Fqual  = qual
        endif
      endfor
      if (bem EQ "ok") then begin
        black   = 0
        orange  = 210
        red     = 250
        yellow  = 195
        green   = 160
        cyan    = 100
        blue    = 70
        magenta = 40
        col=blue
        if (STRPOS(filter,"AKARI") GE 0) then col=magenta   ; AKARI
        if (STRPOS(filter,"WISE") GE 0) then col=blue+15    ; WISE
        if (STRPOS(ref,"GASPS") GE 0) then col=red          ; Herschel/GASPS-cont 
        if (STRPOS(ref,"SPIRE") GE 0) then col=orange-10    ; SPIRE
        if (STRPOS(ref,"ALMA") GE 0) then col=green         ; ALMA
        ;if (i GE 44) then col=0 
        if (sigma/Fval GT 0.01) then begin
          plots,lamval,alog10(Fval),color=col,PSYM=8,SYMSIZE=1.2,THICK=2.0,$
                noclip=0
          errplot,lamval,F1val,F2val,color=col,SYMSIZE=1.2,THICK=2.0,$
                noclip=0
        endif else begin
          plots,lamval,alog10(Fval),color=col,PSYM=8,SYMSIZE=1.2,THICK=2.0,$
                noclip=0
        endelse
        dev  = alog(Fmodel/Fval)/alog(1.0+sigma/Fval)
        chi  = chi + dev^2
        ichi = ichi + 1
        print,format='(2x,F10.2,1x,A10,E12.3,E12.3,E12.3,F9.3)',$
              lamval,filter,Fval,Fmodel,sigma,dev
      endif  
      if (bem EQ "ul") then begin
        sval = alog10(3.0*sigma)  
        color = 70
        ARROW,lamval,sval,lamval,sval-0.5,/data,color=color
        plots,lamval,sval,color=color,PSYM=8,SYMSIZE=1.2,THICK=2.0,$
                noclip=0
        chi = chi + (Fmodel/sigma)^2
        ichi = ichi + 1
        print,format='(2x,F10.2,1x,A10,E12.3,E12.3,E12.3,F9.3)',$
              lamval,filter,0.0,Fmodel,sigma,Fmodel/sigma
      endif  
      if (bem EQ "ll") then begin
        sval = alog10(sigma)  
        color = 70
        ARROW,lamval,sval,lamval,sval+0.5,/data,color=color
        plots,lamval,sval,color=color,PSYM=8,SYMSIZE=1.2,THICK=2.0,$
                noclip=0
        chi = chi + (sigma/Fmodel)^2
        ichi = ichi + 1
        print,format='(2x,F10.2,1x,A10,E12.3,E12.3,E12.3,F9.3)',$
              lamval,filter,0.0,Fmodel,sigma,sigma/Fmodel
      endif  
      if (bem EQ "UL") then begin
        sval = alog10(3.0*sigma)  
        color = 100
        ARROW,lamval,sval,lamval,sval-0.5,/data,color=color
        plots,lamval,sval,color=color,PSYM=8,SYMSIZE=1.2,THICK=2.0,$
                noclip=0
      endif  
      if (bem EQ "LL") then begin
        sval = alog10(sigma)  
        color = 100
        ARROW,lamval,sval,lamval,sval+0.5,/data,color=color
        plots,lamval,sval,color=color,PSYM=8,SYMSIZE=1.2,THICK=2.0,$
                noclip=0
      endif  
      if (bem EQ "??") then begin
        if (sigma/Fval GT 0.01) then begin
          plots,lamval,alog10(Fval),color=100,PSYM=8,SYMSIZE=0.8,THICK=1.0,$
                noclip=0
          errplot,lamval,F1val,F2val,color=100,SYMSIZE=8.0,THICK=4.0,$
                noclip=0
        endif else begin
          plots,lamval,alog10(Fval),color=100,PSYM=8,SYMSIZE=0.8,THICK=1.0,$
                noclip=0
        endelse  
      endif
      ;endif  
    endfor
    close,1  
    chi = sqrt(chi/ichi)
    print,"==> mean deviation model-observations chi=",chi
  endif  

  ; ------- legend -------
  x0=0.22
  y0=0.1+Nbem*0.03
  xyouts,x0,y0+0.03-0.01,/normal,bbem(0)
  for i=1,Nbem-1 do begin
    plots,[x0,x0+0.05],[y0,y0]-0.03*(i-1),/normal,$
          color=bcol(i),linestyle=blin(i),thick=bthi(i)
    xyouts,x0+0.06,y0-0.03*(i-1)-0.01,bbem(i),/normal
  endfor  

  ; ------- overplot continua from line computations -------
  if (1 EQ 0) then begin
  Jansky  = 1.E-23              ; 1 Jy in [erg/cm^2/s/Hz]
  txt     = "blasel"
  molname = txt
  Nline   = 0
  Nvelo   = 0
  openr,1,folder+"/line_flux.out",ERROR = err
  if (err EQ 0) then begin
    readf,1,format='(25x,F20)',dist
    readf,1,format='(25x,F20)',incl
    readf,1,format='(25x,I21)',Nline
    readf,1,format='(25x,I21)',Nvelo
    firstLine = 1
    for i=0L,Nline-1 do begin
      readf,1,txt
      lamval=1.d0
      nuval=1.d0
      if (firstLine EQ 1) then begin
        readf,1,txt
        frmt=''
        if (strlen(txt) EQ 70) then frmt='(10x,a6,23x,F9.3,9x,F11.3)'
        if (strlen(txt) EQ 75) then frmt='(10x,a11,23x,F9.3,9x,F11.3)'
        if (strlen(txt) EQ 79) then frmt='(10x,a11,23x,F11.5,9x,F13.5)'
        if (strlen(txt) EQ 93) then frmt='(10x,a11,26x,E17.10,9x,E17.10)'
        ; this is for the new format having the ident lengh consistently with SPLen (ie. SPlen+4)
        ; which is currently 16
        if (strlen(txt) EQ 99) then frmt='(10x,a17,26x,E17.10,9x,E17.10)'
        if (frmt EQ '') then begin
          print,"*** unknown format in line_flux.out"
          stop
        endif  
        reads,txt,format=frmt,molname,lamval,nuval
        firstLine=0       
      endif else begin
        readf,1,txt
        reads,txt,format=frmt,molname,lamval,nuval
      endelse
      readf,1,format='(24x,E30)',Fline  
      readf,1,format='(24x,F30)',Fcont
      ;print,i,lamval,cl/(nuval*1.E+9)/mic,Fline,Fcont
      ;if (lamval LT 10) then stop
      readf,1,txt
      readf,1,vv,FF
      for j=0,Nvelo-2 do begin
        readf,1,vv,FF
      endfor
      Fval = alog10((nuval*1.E+9)*(Fcont*Jansky))
      plots,lamval,Fval,color=140,PSYM=5,SYMSIZE=1.0
    endfor
    close,1
  endif
  endif

  ;oplot, lamb1,alog10(Flam1),linestyle=2,thick=2
  oplot, lamb2,alog10(Flam2),linestyle=0,thick=2

  ;--- magnification mid-IR ---
  openr,1,IRspecFile,ERROR = err
  close,1 
  if (err EQ 0) then begin
    Nbem=2
    bbem(0)="dist = "+STRTRIM(STRING(format="(F8.1)",dist/pc),2)+"!L !Npc"$
        +",  incl = "+STRTRIM(STRING(format="(I3)",incl+0.5),2)+"!Uo!N"
    bbem(1)="ProDiMo"
    bcol(0)=0   &  blin(0)=0  & bthi(0)=0
    bcol(1)=0   &  blin(1)=0  & bthi(1)=2
    xmin  = 3.0
    xmax  = 25.0
    ind   = WHERE(lamSpitzer GT xmin AND lamSpitzer LT xmax)
    nuval = cl/(lamSpitzer(ind)*mic)
    ymin  = min(FnuSpitzer(ind)/nuval/Jansky)
    ymax  = max(FnuSpitzer(ind)/nuval/Jansky)
    ind   = WHERE(lamb2 GT xmin AND lamb2 LT xmax)
    nuval = cl/(lamb2(ind)*mic)
    ymin  = min([ymin,Flam2(ind)/nuval/Jansky]) * 0.5
    ymax  = max([ymax,Flam2(ind)/nuval/Jansky]) * 1.3
    pos=[0.13,0.13,0.95,0.95]
    plot, [xmin,xmax],[ymin,ymax],/nodata,$
       xrange=[xmin,xmax],yrange=[ymin,ymax],$
       linestyle=2,thick=3,position=pos,xthick=4,ythick=4,$  
       xcharsize=1.3,ycharsize=1.3,$ 
       xtitle="!9l !7[!9m!7m]",$
       ytitle="F!9!Ln!N !7[Jy]"
    nuval = cl/(lamSpitzer*mic)
    oplot,lamSpitzer,FnuSpitzer/nuval/Jansky,color=205,thick=9
    bbem(Nbem)=IRspecName
    bcol(Nbem)=205  & blin(Nbem)=0  & bthi(Nbem)=3
    Nbem=Nbem+1
    openr,1,"nearIR_Spectrum.dat",ERROR = err
    close,1 
    if (err EQ 0) then begin
      nuval = cl/(lamIRspec*mic)
      oplot,lamIRspec,FnuIRspec/nuval/Jansky,color=120,thick=3
      bbem(Nbem)="SpeX/IRTF"
      bcol(Nbem)=120  & blin(Nbem)=0  & bthi(Nbem)=3
      Nbem=Nbem+1
    endif  
    openr,1,"ISO-SWS-spectrum.dat",ERROR = err
    close,1
    if (err EQ 0) then begin
      nuval = cl/(lamISO*mic)
      oplot,lamISO,FnuISO/nuval/Jansky,color=120,thick=3
      bbem(Nbem)="ISO SWS"
      bcol(Nbem)=120  & blin(Nbem)=0  & bthi(Nbem)=3
      Nbem=Nbem+1
    endif  
    for i=1,Nobs do begin
      black   = 0
      orange  = 210
      red     = 250
      yellow  = 195
      green   = 160
      cyan    = 100
      blue    = 70
      magenta = 40
      col=blue
      filter=filPHOT(i)
      ref=refPHOT(i)
      bem=bemPHOT(i)
      if (STRPOS(filter,"AKARI") GE 0) then col=magenta    ; AKARI
      if (STRPOS(filter,"WISE") GE 0) then col=blue+15     ; WISE
      if (STRPOS(ref,"GASPS") GE 0) then col=red           ; Herschel/GASPS 
      if (STRPOS(ref,"SPIRE") GE 0) then col=orange-10     ; SPIRE
      if (STRPOS(ref,"ALMA") GE 0) then col=green          ; ALMA
      if (bem EQ 'ok') then begin
        plots, lamPHOT(i),FnuPHOT(i),color=col,PSYM=8,SYMSIZE=1.2,THICK=2.0,noclip=0
      endif  
      if (bem EQ '??') then begin
        plots, lamPHOT(i),FnuPHOT(i),color=100,PSYM=8,SYMSIZE=0.8,THICK=1.0,noclip=0
      endif  
    endfor
    if (lamMCMax[0] NE 0) then begin
      green = 90
      nuval = cl/(lamMCMax*mic)
      oplot,lamMCMax,FnuMCMax/nuval/Jansky,color=green,thick=2
      bbem(Nbem)="MCMax (FS)"
      bcol(Nbem)=green  & blin(Nbem)=0  & bthi(Nbem)=2
      Nbem=Nbem+1
    endif  
    if (lamMCFOST[0] NE 0) then begin
      blue = 70
      nuval = cl/(lamMCFOST*mic)
      oplot,lamMCFOST,FnuMCFOST/nuval/Jansky,color=blue,thick=2
      bbem(Nbem)="MCFOST"
      bcol(Nbem)=blue  & blin(Nbem)=0  & bthi(Nbem)=2
      Nbem=Nbem+1
    endif  
    nuval = cl/(lamb2*mic)
    oplot, lamb2,Flam2/nuval/Jansky,linestyle=0,thick=5
    plots, lamb2,Flam2/nuval/Jansky,PSYM=8,SYMSIZE=0.8,thick=1,noclip=0

    ; ------- legend -------
    x0=0.18
    y0=0.85
    xyouts,x0,y0+0.03-0.01,/normal,bbem(0)
    for i=1,Nbem-1 do begin
      plots,[x0,x0+0.05],[y0,y0]-0.03*(i-1),/normal,$
          color=bcol(i),linestyle=blin(i),thick=bthi(i)
      xyouts,x0+0.06,y0-0.03*(i-1)-0.01,bbem(i),/normal
    endfor  
  endif  

  print,'----------------------------------------------------------'
  print,'  naked stellar L[Lsun] = '+STRING(format='(F12.5)',Lstar/Lsun)
  print,'     bolometric L[Lsun] = '+STRING(format='(F12.5)',Lbolo/Lsun)
  print,'        near IR L[Lsun] = '+STRING(format='(F12.5)',LNIR/Lsun)+$
        ' (lam='+STRTRIM(STRING(format='(F5.2)',NIRmin),2)+$
             '-'+STRTRIM(STRING(format='(F5.2)',NIRmax),2)+'mic)'
  print,'         mid IR L[Lsun] = '+STRING(format='(F12.5)',LMIR/Lsun)+$
        ' (lam='+STRTRIM(STRING(format='(F5.2)',MIRmin),2)+$
             '-'+STRTRIM(STRING(format='(F4.1)',MIRmax),2)+'mic)'
  print,'         far IR L[Lsun] = '+STRING(format='(F12.5)',LFIR/Lsun)+$
        ' (lam='+STRTRIM(STRING(format='(F4.1)',FIRmin),2)+$
             '-'+STRTRIM(STRING(format='(F5.0)',FIRmax),2)+'mic)'
END

;------------------------------------------------------
PRO PLOT_SED_ANALYSIS,folder,Nx,Nz,xx,zz,nHtot,AV,NHver
;------------------------------------------------------
  black   = 0
  white   = 255
  orange  = 210
  red     = 250
  yellow  = 195
  green   = 160
  cyan    = 100
  blue    = 70
  magenta = 40
  openr,1,folder+"/SEDana.out",ERROR = err
  if (err NE 0) then begin
    close,1
    return
  endif   
  readf,1,NSED,NXX
  if (NXX NE Nx) then return
  lam = dblarr(NSED)
  r15 = dblarr(NSED)
  r85 = dblarr(NSED)
  z15 = dblarr(NSED,NXX)
  z85 = dblarr(NSED,NXX)
  for l=0,NSED-1 do begin
    readf,1,lread,r15read,r85read
    lam(l) = lread
    r15(l) = r15read
    r85(l) = r85read
    for ix=0,NXX-1 do begin
      readf,1,z15read,z85read
      z15(l,ix) = z15read
      z85(l,ix) = z85read
    endfor  
  endfor
  close,1
  ; --- gaps ---
  gap=0
  for ix=1,Nx-2 do begin
    if (NHver(ix) LT NHver(ix-1)/100) then gap=1
    if (NHver(ix) GT NHver(ix-1)*100) then gap=0
    ;print,xx(ix),NHver(ix),gap
    if (gap EQ 1) then begin
      z15(*,ix) = 0.0 
      z85(*,ix) = 0.0 
    endif   
  endfor
  xmin = min(lam)
  xmax = max(lam)
  ymin = min(r15)/2.0
  ymax = max(r85)*2.0
  pos=[0.13,0.13,0.96,0.93]
  plot,lam,r15,/xlog,/ylog,/nodata,$
       xrange=[xmin,xmax],yrange=[ymin,ymax],position=pos,$
       xtitle="!9l !7[!9m!7m]",$
       ytitle="r!L !N[au]"
  oplot,lam,r15,color=red,thick=4
  oplot,lam,r85,color=blue,thick=4
  i=NSED*0.8
  xyouts,lam(i),r15(i),color=red,'  15%'
  xyouts,lam(i),r85(i),color=blue,'  85%'
  ; --- log(n)-contour and height of cell with max. contribution ---
  xmin = MIN(xx)
  xmax = MAX(xx)
  xtmp = xx(*,0)
  ymax = 0.0 
  for l=0,NSED-1 do begin
    if (lam[l] GT 1.0) then begin 
      ztmp  = z15(l,*)
      ind   = WHERE(xtmp GT r15(l) AND xtmp LT r85(l),nd) 
      if (nd gt 0) then zxtmp = ztmp(ind)/xtmp(ind)
      ymax  = MAX([ymax,zxtmp])
    endif  
  endfor  
  ymax = 0.8*1.3*ymax + 0.2*MAX(zz/xx)
  ymin = -ymax
  zmax = alog10(MAX(nHtot))
  zmin = min([zmax-2.0,3.5])
  ilev = 80
  lev=dblarr(ilev+1)
  col=intarr(ilev+1)      
  colmin=2                    
  colmax=253
  for i=0,ilev do begin
    lev(i)=zmin+(zmax-zmin)*i/ilev
    col(i)=fix(colmin+(colmax-colmin)*(lev(i)-zmin)/(zmax-zmin))
  endfor
  nplot = alog10(nHtot)
  ind=WHERE(nplot LT zmin+0.2,count)
  if (count GT 0) then nplot(ind) = zmin+0.2
  pos=[0.10,0.08,0.98,0.98]
  loadct,0,/silent
  contour,nplot,xx,zz/xx,/xlog,thick=3,$
        xrange=[xmin,xmax],yrange=[ymin,ymax],xminor=9,yminor=4,xticklen=0.03,$
        charsize=1.1,xcharsize=1.1,ycharsize=1.1,position=pos,$
        levels=lev,c_colors=col,/fill, $
        xtitle="r [au]",ytitle="z/r"
  contour,nplot,xx,-zz/xx,/noerase,/xlog,thick=3,$
        xrange=[xmin,xmax],yrange=[ymin,ymax],xminor=9,yminor=4,xticklen=0.03,$
        charsize=1.1,xcharsize=1.1,ycharsize=1.1,position=pos,$
        levels=lev,c_colors=col,/fill, $
        xtitle="r [au]",ytitle="z/r"
  contour,AV,xx,zz/xx,/overplot,level=[1,10],$
      C_ANNOTATION=[' ',' '],C_COLORS=[black,black],$
      C_LINESTYLE=2,C_CHARSIZE=1.2,C_THICK=2
  contour,AV,xx,-zz/xx,/overplot,level=[1,10],$
      C_ANNOTATION=['AV=1','AV=10'],C_COLORS=[black,black],$
      C_LINESTYLE=2,C_CHARSIZE=1.2,C_THICK=2
  loadct,39,/silent
  lamb = [1.0,3.0,6.0,10.0,30.0,60.0,100.0,200.0,1000.0]
  colo = [magenta-10,blue,0.5*(blue+cyan),cyan,green,white,yellow,orange,red]
  AU = 1.495978700D+13  
  xplot = xx(*,1)
  z15lam = dblarr(NXX)
  z85lam = dblarr(NXX)
  for ilam=0,N_ELEMENTS(lamb)-1 do begin
    lambda1 = lamb[ilam]
    x15lam=interpol(r15,lam,lambda1)
    x85lam=interpol(r85,lam,lambda1)
    for ix=0,NXX-1 do begin
      z15lam(ix)=interpol(z15(*,ix),lam,lambda1)
      z85lam(ix)=interpol(z85(*,ix),lam,lambda1)
    endfor  
    index=where(xplot GE x15lam AND xplot LE x85lam, count)
    if (count GT 0) then begin
      xx1=[x15lam,xplot(index),x85lam]
    endif else begin    
      xx1=[x15lam,x85lam]
    endelse
    zz1=interpol(z15lam/xplot,xplot,xx1)
    zz2=interpol(z85lam/xplot,xplot,xx1)
    xxx=[xx1,xx1]
    yyy=[zz1,zz2]
    Nxxx=N_ELEMENTS(xx1)
    for ix=0,Nxxx-1 do begin
      iix = 2*Nxxx-1-ix  
      xxx(iix) = xx1(ix)
      yyy(iix) = zz2(ix)
    endfor 
    ;polyfill,xxx,yyy,color=white,noclip=0
    ;oplot,xplot,zplot/xplot,thick=7,color=black,linestyle=2
    ;oplot,xplot,z15/AU/xplot,thick=1,color=black,linestyle=2
    ;oplot,xplot,z85/AU/xplot,thick=1,color=black,linestyle=2
    oplot,[xxx,xxx(0)],[yyy,yyy(0)],thick=5,color=colo[ilam]
    label = strtrim(string(format='(I5)',lambda1),2)+"!9m!7m"
    xyouts,x85lam,zz1(N_ELEMENTS(zz1)-1)+0.01,color=colo[ilam],$
           alignment=0.5,label,charsize=0.9
  endfor
  loadct,0,/silent
  label = "log n!L<H> !N[cm!U-3!N]"
  SKALA, ilev+1, lev, col, label, [0.13,0.19,0.55,0.25], 1.3
  loadct,39,/silent
END

;-----------------------------------------------
pro PLOT_VISIB_MIDI,MCMAXpath
;-----------------------------------------------
  line = "bla"
  openr,1,"baseline.in",ERROR = err
  close,1  
  if (err NE 0) then return
  readcol,"baseline.in",baselines,basePAs,SKIPLINE=3
  Nbase = N_ELEMENTS(baselines)  
  openr,1,"VISIB.out",ERROR = err
  close,1  
  if (err NE 0) then return
  readcol,"VISIB.out",baseline,basePA,lmic,V2obs,sigma,V2mod
  openr,1,"visibilities.out"
  readf,1,line
  readf,1,incl
  readf,1,NSED
  lamSED = dblarr(NSED)
  V2PRO  = dblarr(NSED,Nbase)
  readvar = dblarr(10)
  for i=1,5 do readf,1,line
  for i=0,NSED-1 do begin
    for j=0,Nbase-1 do begin
      readf,1,readvar
      lamSED(i)  = readvar(2)
      V2PRO(i,j) = readvar(6)
    endfor
  endfor  
  close,1
  haveMCMAX=0
  tmp='0'+STRTRIM(STRING(format='(F4.1)',incl),2)
  len=STRLEN(tmp)
  tmp=STRMID(tmp,len-4)
  file = MCMAXpath+"/visibility"+tmp+"MIDI.dat"
  openr,1,file,ERROR = err
  if (err EQ 0) then begin
    haveMCMAX = 1
    Nlam = 0
    lmicMC = dblarr(1000)
    V2MC   = dblarr(1000,Nbase)
    readvar= dblarr(2*Nbase+2)
    for i=1,5 do readf,1,line
    for i=0,999 do begin
      if (EOF(1)) then break 
      readf,1,readvar
      Nlam = Nlam+1
      lmicMC(i) = readvar(0)             ; lambda[mic]
      for j=0,Nbase-1 do begin 
        V2MC(i,j) = readvar(2+j)^2       ; square(V)
      endfor  
    endfor  
    lmicMC = lmicMC(0:Nlam-1)
    V2MC   = V2MC(0:Nlam-1,*)
  endif  
  close,1  

  xmin = min(lmic)
  xmax = max(lmic)
  ;xmin = 2.5
  ;xmax = 15.0
  ymin = 0.0
  ymax = max([V2obs+sigma,V2mod])+0.1
  loadct,39 
  black   = 0
  orange  = 210
  red     = 250
  yellow  = 195
  green   = 160
  cyan    = 100
  blue    = 70
  magenta = 40
  AA = FINDGEN(17) * (!PI*2/16.)  
  USERSYM, COS(AA), SIN(AA)
  colors = [blue,red,orange,magenta,cyan,green]
  pos = [0.13,0.11,0.95,0.92]  
  for i=0,Nbase-1 do begin
    ind = WHERE(baseline EQ baselines(i) AND basePA EQ basePAs(i),count) 
    if (count GT 1) then begin
      lab1 = "baseline="+STRTRIM(STRING(format='(F10.1)',baselines(i))+"m",2)
      lab2 = "basePA="+STRTRIM(STRING(format='(F10.1)',basePAs(i))+"!Uo!N",2)
      plot,lmic,V2obs,/nodata,position=pos,$
        xrange=[xmin,xmax],yrange=[ymin,ymax],$
        xtitle="!9l!7 [!9m!7m]",ytitle="V!U2!N"
      col = colors(i)
      xyouts,0.5*(xmin+xmax),ymax*1.01,color=col,CHARSIZE=1.4,$
             alignment=0.5,lab1+" ,  "+lab2
      y1val = V2obs(ind)-sigma(ind)
      y2val = V2obs(ind)+sigma(ind)
      errplot,lmic(ind),y1val,y2val,color=col,SYMSIZE=1.2,THICK=1.0
      if (haveMCMAX EQ 1) then begin
        oplot,lmicMC(*),V2MC(*,i),color=green,THICK=3
        plotsym,0,0.8,color=green,/fill
        plots,lmicMC(*),V2MC(*,i),color=green,PSYM=8,SYMSIZE=0.9,noclip=0
      endif  
      plotsym,0,0.8,color=black,/fill
      oplot,lmic(ind),V2mod(ind),color=black,THICK=4
      plots,lamSED,V2PRO(*,i),color=black,PSYM=8,SYMSIZE=0.9,noclip=0
    endif  
    xyouts,xmin+0.83*(xmax-xmin),ymax*0.92,col=black,"ProDiMo" 
    if (haveMCMAX EQ 1) then begin
      xyouts,xmin+0.83*(xmax-xmin),ymax*0.88,col=green,"MCMax" 
    endif  
  endfor   
end

;-----------------------------------------------
PRO PLOT_SED_LINES,folder,NLAM,lam,Rstar,dist,NX
;-----------------------------------------------
  cl    = 2.997924580D+10       ; speed of light
  pc    = 3.085680250D+18       ; 1 parsec
  Rsun  = 6.959900000D+10       ; solar radius
  AU    = 1.495978700D+13       ; 1 astronomical unit in cm
  nm    = 1.D-7                 ; 1 nanometer
  mic   = 1.D-4                 ; 1 micron
  Wm2   = 1.D+3                 ; 1 W/m^2 in [erg/cm^2/s]
  Jansky = 1.D-23               ; 1 Jy in [erg/cm^2/s/Hz]
  black   = 0
  white   = 255
  orange  = 210
  red     = 250
  yellow  = 195
  green   = 160
  cyan    = 100
  blue    = 70
  magenta = 40
  line="blasel"
  ; --- read SED ---
  NLAM1=0
  NLAM2=0
  openr,1,folder+"/SED.out",ERROR = err
  if (err NE 0) then begin
    close,1
    return
  endif
  readf,1,format='(24x,F20)',dist
  readf,1,line
  readf,1,NLAM1
  readf,1,line
  lamb1 = fltarr(NLAM1) 
  nu1   = fltarr(NLAM1) 
  Flam1 = fltarr(NLAM1) 
  for i=0,NLAM1-1 do begin
    readf,1,lamval,nuval,F1val,F2val,F3val
    lamb1(i)=lamval*mic                      ; lambda[cm]
    nu1(i)  =nuval                           ; nu[Hz]
    Flam1(i)=F1val                           ; Fnu[erg/cm^2/s]
  endfor
MCinterpol:
  readf,1,line
  readf,1,format='(24x,F20)',incl
  readf,1,NLAM2
  readf,1,line
  lamb2 = dblarr(NLAM2) 
  Flam2 = dblarr(NLAM2) 
  for i=0,NLAM2-1 do begin
    readf,1,lamval,nuval,F1val,F2val,F3val
    lamb1(i)=lamval*mic                      ; lambda[cm]
    nu1(i)  =nuval                           ; nu[Hz]
    Flam1(i)=F1val                           ; Fnu[erg/cm^2/s]
  endfor
  ;if (~EOF(1)) then goto,MCinterpol
  close,1

  close,1
  ind = WHERE(lamb1/mic GT 1.0*mic)
  Fmin=min(alog10(nu1(ind)*Flam1(ind)))-0.2
  Fmax=max(alog10(nu1*Flam1))+0.2
  ;Fmin=-13.9
  ;Fmax=-9.4
  lmin=min(lamb1)
  lmax=max(lamb1)
  xmin=lmin*0.8
  xmax=lmax*1.2

  ; --- read stellar spectrum ---
  dist  = dist*pc
  Astar = !PI*(Rstar*Rsun)^2
  ; NSPEC = 0 ; with ProDiMo release 2083 and the addition of the new, higher-resolution DriftPhoenix model
              ; spectra, prodimo.pro does not work. NSPEC is written correctly but the number is too high for
              ; IDL to read (??!!). Commenting out the pre-allocation to zero seems to fix it.
  openr,1,folder+"/StarSpectrum.out"
  for i=1,3 do readf,1,line
  readf,1,NSPEC
  readf,1,line
  lambstar = dblarr(NSPEC) 
  Flamstar = dblarr(NSPEC) 
  for i=0,NSPEC-1 do begin
    readf,1,lamval,nuval,Ival
    lambstar(i) = lamval
    Fval = Astar*Ival/dist^2
    Flamstar(i) = nuval * Fval
  endfor
  close,1

  ; --- interpolate cont flux onto high resolution ---
  Rgrid = 100000.0  ; high grid resolution R=lam/dlam
  ;print,"interpolating onto high resolution grid R=",Rgrid," ..."
  del_loglam = alog10(1.0+1.0/Rgrid)  ; log(lam+dlam)-log(lam)
  N = 1+LONG(alog10(xmax/xmin)/del_loglam) 
  llam   = alog10(xmin)+del_loglam*FINDGEN(N)
  lhigh  = 10.0^llam
  nuhigh = cl/lhigh 
  ind1   = where(llam LT alog10(min(lamb1)))
  ind2   = where(llam GE alog10(min(lamb1)))
  Fhigh1 = INTERPOL(alog10(Flam1),alog10(lamb1),llam(ind1))
  Fhigh2 = INTERPOL(alog10(Flam1),alog10(lamb1),llam(ind2),/spline)
  Fhigh  = 10.0^[Fhigh1,Fhigh2]
  Fcont  = Fhigh

  ; --- add line fluxes ---
  openr,1,folder+"/FlineEstimates.out",ERROR = err
  if (err NE 0) then begin
    close,1
    return
  endif   
  readf,1,line
  version = 1
  if (STRPOS(line,"version") GT 0) then version=2
  readf,1,Nlines
  readf,1,line
  if (EOF(1)) then return
  LINELAMB=dblarr(Nlines+1)
  LINEFLUX=dblarr(Nlines+1)
  LINENAME=strarr(Nlines+1)
  LINEQUPP=strarr(Nlines+1)
  LINEQLOW=strarr(Nlines+1)
  name = 'bla'
  lupp = 'bla'
  llow = 'bla'
  Lsun = 3.8260D+33             ; solar luminosity
  lmic = 0.0
  FLINE = 0.0
  LLTOT = 0.0
  Nline = 0L
  frmt = '(A10,F18.8,i4,i4,E12.4)'
  if (version GT 1) then frmt = '(A10,F18.8,i6,i6,E12.4,A32,A32)'
  for i=1L,Nlines do begin
    if (EOF(1)) then break
    if (version EQ 1) then readf,1,format=frmt,name,lmic,u,l,FLINE
    if (version GT 1) then readf,1,format=frmt,name,lmic,u,l,FLINE,lupp,llow
    Nline = Nline+1L
    if (FLINE GT 1.E-10) then FLINE=0.0              ; maser lines?
    if ((STRTRIM(name) eq 'OH-hfs')) then FLINE=0.0  
    ;FLINE = FLINE*0.3 ; fudge factor
    LINELAMB(i)=lmic
    LINEFLUX(i)=FLINE
    LINENAME(i)=name
    if (version GT 1) then begin
      LINEQUPP(i) = STRTRIM(lupp,2) 
      LINEQLOW(i) = STRTRIM(llow,2) 
    endif   
    LLINE = lmic*mic
    FLINE = FLINE*Wm2
    LLTOT = LLTOT + Fline*(4.0*!pi*dist^2) 
    ;print,name,lmic,FLINE/Wm2,LLTOT/Lsun
    for ix=1,NX do readf,1,line
    if ((LLINE GT xmin) AND (LLINE LT xmax)) then begin
      ic  = floor(alog10(LLINE/xmin)/del_loglam)    ; index of line centre 
      dnu = cl/LLINE/Rgrid              ; frequency-spacing of grid @ LLINE[Hz]
      Fhigh(ic) = Fhigh(ic) + FLINE/dnu ; add line flux at central pixel
                                        ; [erg/cm^2/s/Hz]
    endif  
  endfor
  close,1
  print,'     total line L[Lsun] = '+STRING(format='(F12.5)',LLTOT/Lsun)
  print,'----------------------------------------------------------'
  
  ;openw, 12, 'SAFARIspectrum.out'
  ;waverange = where(lhigh GT 4.5d-4 AND lhigh LT 29.d-4, n)
  ;n_waverange = size(waverange)
  ;printf, 12, 'lambda [cm]     flux [Jy]'
  ;if (n GT 0) then begin
  ;  for ix=0L, n_waverange(1)-1 do begin
  ;    printf, 12, lhigh(waverange(ix)), Fhigh(waverange(ix))*1.e23, $
  ;            format='(e13.5,e13.5)'
  ;  endfor
  ;endif
  ;close, 12

  ;openw, 12, 'SAFARIlabels.out'
  ;waverange = where(LINELAMB GT 4.5 AND LINELAMB LT 29., n)
  ;n_waverange = size(waverange)
  ;printf, 12, 'lambda [cm]  name_of_species'
  ;if (n GT 0) then begin
  ;  for i=0L, n_waverange(1)-1 do begin
  ;    printf, 12, LINELAMB(waverange(i))*1.d-4, LINENAME(waverange(i)), $
  ;            format='(e13.5,2x,a10)'
  ;  endfor
  ;endif
  ;close, 12

  ; --- degrading resolution ---
  RR = 3000; 600;               ; spectral resolution, for example Res
                                ; PACS FWHM=0.02mic @ 63mic for
                                ; unresolved line -> R~1200 
  if (RR GT 0.7*Rgrid) then begin
    print,"*** desired spectral resolution too high: RR >~ Rgrid"
    print,"    you must increase Rgrid>>RR if you really want RR=",RR
    stop
  endif  
  print,"convolving with Gaussian R=",RR," ..." 
  Npix = fix(7*Rgrid/RR)        ; number of points for filter function
  FWHMpix = Rgrid/RR            ; FWHM in pixel units
  filter = PSF_GAUSSIAN( NP=Npix, FWHM=FWHMpix, /NORMALIZE, NDIMEN=1 )
  Fnu2 = CONVOL( Fhigh, filter, /CENTER, /EDGE_TRUNCATE)

  ; --- reading FLiTs output ---
  Flits=0
  openr,1,"specFLiTs.out",ERROR=err
  if (err EQ 0) then begin
    close,1
    Flits=1    
    readcol,'specFLiTs.out',format='(D,D,D,D)',$
            lamFlits,fluxFlitsJy,vFlits,FcontFlits,/silent        ; has lambda-gaps!!!
    del_loglam = alog10(lamFlits(30)/lamFlits(0))/30.d0
    Rgrid2     = 1.d0/(10.d0^del_loglam-1.d0)
    lmin       = min(lamFlits)
    lmax       = max(lamFlits)    
    N          = 1+LONG(alog10(lmax/lmin)/del_loglam) 
    del_loglam = alog10(lmax/lmin)/(N-1.d0)
    lamFlits_high  = 10.d0^(alog10(lmin)+del_loglam*FINDGEN(N))   ; [mic] regular grid
    nuFlits        = cl/(lamFlits_high*mic)                       ; [Hz]
    fluxFlits_high = INTERPOL(fluxFlitsJy,lamFlits,lamFlits_high) ; [Jy]
    FcontFlits_high= INTERPOL(FcontFlits,lamFlits,lamFlits_high)  ; [Jy]
    fluxFlits_high = fluxFlits_high*Jansky                        ; [erg/cm^2/s/Hz]
    FcontFlits_high= FcontFlits_high*Jansky                       ; [erg/cm^2/s/Hz]
    Npix    = long(7*Rgrid2/RR)   ; number of points for filter function
    FWHMpix = Rgrid2/RR           ; FWHM in pixel units
    ;print,RR,del_loglam,Rgrid2,lmin,lmax,N,Npix,FWHMpix
    filter  = PSF_GAUSSIAN(NP=Npix,FWHM=FWHMpix,/NORMALIZE,/DOUBLE,NDIMEN=1)
    if (N_ELEMENTS(fluxFlits_high) GT N_ELEMENTS(filter)) then begin 
      fluxFlits_lowres  = CONVOL(fluxFlits_high, filter, /CENTER, /EDGE_TRUNCATE)
      fluxFlits_subcont = CONVOL(fluxFlits_high-FcontFlits_high, $
                                                 filter, /CENTER, /EDGE_TRUNCATE)
    endif else begin
      fluxFlits_lowres  = fluxFlits_high 
      fluxFlits_subcont = fluxFlits_high-FcontFlits_high
    endelse  
    openw,1,'specFLiTs_conv.out'
    i=0L
    repeat begin
      printf,1,format='(F14.10,E14.6,E14.6)',lamFlits_high(i),fluxFlits_lowres(i)/Jansky,fluxFlits_subcont(i)/Jansky
      i=i+1L
    endrep until (i EQ N)
    close,1
  endif  

  print,"now plotting the spectrum ..."
  ; --- highest grid resolution ---
  pos=[0.13,0.11,0.95,0.95]
  plot, lambstar/mic,alog10(Flamstar),/nodata,/xlog,$
        xrange=[xmin,xmax]/mic,yrange=[Fmin,Fmax],$
        thick=2,position=pos,$  
        xtitle="!9l !7[!9m!7m]",$
        ytitle="log !9n !N!7F!9!Ln!N !7[erg/cm!U2!N/s]"
  oplot, lambstar,alog10(Flamstar),color=red,thick=1
  oplot, lhigh/mic,alog10(nuhigh*Fhigh),color=blue,thick=2
  oplot, lhigh/mic,alog10(nuhigh*Fcont),color=black,thick=2
  if (Flits) then oplot,lamFlits_high,alog10(nuFlits*fluxFlits_high),$
                  color=orange,thick=4

  plots,[0.72,0.77],[0.775,0.775],/normal,COLOR=red
  xyouts,0.72,0.85-0.005,/normal,$
         "dist = "+STRTRIM(STRING(format="(F8.1)",dist/pc),2)+"!L !Npc"
  xyouts,0.72,0.81-0.005,/normal,$
         "R = "+STRTRIM(STRING(format="(I8)",Rgrid),2)
  xyouts,0.78,0.775-0.005,/normal,"star + UV"
  if (Flits) then begin
    plots,[0.72,0.77],[0.735,0.735],/normal,color=orange
    xyouts,0.78,0.735-0.005,/normal,"FLiTs"
  endif  

  ; --- desired resolution ---
  plot, lambstar/mic,alog10(Flamstar),/nodata,/xlog,$
        xrange=[xmin,xmax]/mic,yrange=[Fmin,Fmax],$
        thick=2,position=pos,$  
        xtitle="!9l !7[!9m!7m]",$
        ytitle="log !9n !N!7F!9!Ln!N !7[erg/cm!U2!N/s]"
  oplot, lambstar,alog10(Flamstar),color=red,thick=1
  oplot, lhigh/mic,alog10(nuhigh*Fnu2),color=blue,thick=2
  oplot, lhigh/mic,alog10(nuhigh*Fcont),color=black,thick=2
  if (Flits) then oplot,lamFlits_high,alog10(nuFlits*fluxFlits_lowres),$
                  color=orange,thick=4

  plots,[0.72,0.77],[0.775,0.775],/normal,COLOR=red
  xyouts,0.72,0.85-0.005,/normal,$
         "dist = "+STRTRIM(STRING(format="(F8.1)",dist/pc),2)+"!L !Npc"
  xyouts,0.72,0.81-0.005,/normal,$
         "R = "+STRTRIM(STRING(format="(I8)",RR),2)
  xyouts,0.78,0.775-0.005,/normal,"star + UV"
  if (Flits) then begin
    plots,[0.72,0.77],[0.735,0.735],/normal,color=orange
    xyouts,0.78,0.735-0.005,/normal,"FLiTs"
  endif  

  ; ------- overplot IR spectrum -------
  hasIRspek=0
  IRspecFile = "JWSTspec.dat"
  IRspecname = "JWST/MIRI"
  openr,1,IRspecFile,ERROR = err
  close,1 
  if (err NE 0) then begin
    IRspecFile = "SpitzerIRSspec.dat"
    IRspecname = "Spitzer/IRS"
    openr,1,IRspecFile,ERROR = err
    close,1 
  endif
  if (err EQ 0) then begin
    readcol,IRspecFile,lamSpec,FnuSpec,/silent
    hasIRspek=1
  endif  

  ; ------- overplot R/P-branch spectrum -------
  hasCOspek=0
  openr,1,"COspec.dat",ERROR = err
  if (err EQ 0) then begin
    readf,1,line
    readf,1,vsys
    close,1 
    readcol,"COspec.dat",lamSpec2,FnuSpec2,/silent
    cl = 2.997924580D+10
    km = 1.d+5
    lshift = lamSpec2*vsys/(cl/km)
    lamSpec2 = lamSpec2-lshift
    hasCOspek=1
  endif  

  SPAWN,'pwd',pwdline
  haveContSubSpec=0
  isTWHya=0
  isDOTau=0
  if (STRPOS(pwdline,"TWHya") GT 0) then isTWHya=1
  if (STRPOS(pwdline,"DOTau") GT 0) then isDOTau=1
  if (isTWHya) then begin
    openr,1,"~/Clayton_Roberts/Spectra/twhya_resi_sh.dat",ERROR = err
    close,1
    if (err EQ 0) then begin
      haveContSubSpec=1
      readcol,"~/Clayton_Roberts/Spectra/twhya_resi_sh.dat",$
              lamTWHya1,Fdum,FTWHya1
      readcol,"~/Clayton_Roberts/Spectra/twhya_resi_lh.dat",$
              lamTWHya2,Fdum,FTWHya2
      lamTWHya  = [lamTWHya1,lamTWHya2]
      FTWHyaLines = [FTWHya1,FTWHya2]
    endif  
  endif    
  if (isDOTau) then begin
    openr,1,"~/Clayton_Roberts/FinishedProducts/DO_Tau_contsub.tbl",ERROR = err
    close,1
    if (err EQ 0) then begin
      haveContSubSpec=1
      readcol,"~/Clayton_Roberts/FinishedProducts/DO_Tau_contsub.tbl",$
              lamTWHya,Fdum,FTWHyaLines
    endif  
  endif    

  ; --- magnified, linear spectrum ---
  for Nspec=1,32 do begin
    sub_cont=0 
    info = 0
    compFlux=0
    showquant=0
    if (Nspec EQ 1) then begin 
      lmin = 62.8999*mic
      lmax = 63.45*mic
      ;info = 1
    endif   
    if (Nspec EQ 2) then begin 
      lmin = 144.0*mic
      lmax = 147.5*mic
      ;info = 1
    endif   
    if (Nspec EQ 3) then begin
      lmin = 156.8*mic 
      lmax = 159.3*mic 
      ;info = 1
    endif
    if (Nspec EQ 4) then begin 
      lmin = 117.5*mic
      lmax = 121.2*mic
      ;info = 1
    endif   
    if (Nspec EQ 5) then begin 
      lmin = 83.1*mic
      lmax = 85.9*mic
      ;info = 1
    endif   
    if (Nspec EQ 6) then begin 
      lmin = 64.2*mic
      lmax = 66.2*mic
      ;info = 1
    endif   
    if (Nspec EQ 7) then begin   ; 3...10 um
      lmin =  3.0*mic
      lmax = 10.0*mic
    endif   
    if (Nspec EQ 8) then begin 
      lmin =  3.0*mic
      lmax = 10.0*mic
      sub_cont = 1
    endif   
    if (Nspec EQ 9) then begin   ; CO overtone
      lmin = 2.25*mic
      lmax = 2.60*mic
    endif   
    if (Nspec EQ 10) then begin  ; CO fundamental
      lmin = 4.3*mic
      lmax = 5.5*mic
    endif   
    if (Nspec EQ 11) then begin  ; H2O features ~6.62mic  
      lmin = 6.4*mic
      lmax = 6.8*mic
      sub_cont = 1
    endif   
    if (Nspec EQ 12) then begin
      lmin = 10.0*mic
      lmax = 20.0*mic
    endif   
    if (Nspec EQ 13) then begin 
      lmin = 10.0*mic
      lmax = 20.0*mic
      sub_cont = 1
    endif   
    if (Nspec EQ 14) then begin 
      lmin = 20.0*mic
      lmax = 35.0*mic
    endif   
    if (Nspec EQ 15) then begin 
      lmin = 20.0*mic
      lmax = 35.0*mic
      sub_cont = 1
    endif   
    if (Nspec EQ 16) then begin  ; 10...13 mic
      lmin = 10.0*mic
      lmax = 13.0*mic
      ;info = 1
    endif   
    if (Nspec EQ 17) then begin  
      lmin = 10.0*mic
      lmax = 13.0*mic
      sub_cont = 1
    endif   
    if (Nspec EQ 18) then begin  ; 13...17 mic 
      lmin = 13.0*mic
      lmax = 17.0*mic
      ;info = 1
    endif   
    if (Nspec EQ 19) then begin
      lmin = 13.0*mic
      lmax = 17.0*mic
      sub_cont = 1
    endif   
    if (Nspec EQ 20) then begin  ; 17...25 mic 
      lmin = 17.0*mic
      lmax = 25.0*mic
      ;info = 1
    endif   
    if (Nspec EQ 21) then begin
      lmin = 17.0*mic
      lmax = 25.0*mic
      sub_cont = 1
    endif   
    if (Nspec EQ 22) then begin  ; 25...35 mic
      lmin = 25.0*mic
      lmax = 35.0*mic
      ;info = 1
    endif   
    if (Nspec EQ 23) then begin
      lmin = 25.0*mic
      lmax = 35.0*mic
      sub_cont = 1
    endif   
    if (Nspec EQ 24) then begin  ; H2O feature 
      lmin = 34.0*mic  ;25.28*mic  ;27.55*mic  ;20.25*mic  ;23.7*mic  ;21.05*mic
      lmax = 36.0*mic  ;25.45*mic  ;27.80*mic  ;20.40*mic  ;24.0*mic  ;21.25*mic
      sub_cont = 1
      ;info = 1
      compFlux = 1
      showquant = 1
    endif   
    ;if (Nspec EQ 24) then begin  ; OH feature 
    ;  ;lmin = 27.30*mic
    ;  ;lmax = 27.55*mic
    ;  ;lmin = 33.75*mic
    ;  ;lmax = 34.05*mic
    ;  lmin = 30.15*mic
    ;  lmax = 30.45*mic
    ;  sub_cont = 1
    ;  info = 1
    ;  compFlux = 1
    ;  showquant = 1
    ;endif   
    if (Nspec EQ 25) then begin  ; H2O feature 
      lmin = 30.40*mic           ; H2 line (17.034-0.04)*mic
      lmax = 30.60*mic           ;         (17.034+0.04)*mic 
      sub_cont = 1
      ;info = 1
      compFlux = 1
      showquant = 1
    endif   
    if (Nspec EQ 26) then begin  ; H2O feature 
      lmin = 30.80*mic           ; H2 line 12.255*mic
      lmax = 30.97*mic           ;         12.295*mic
      sub_cont = 1
      ;info = 1
      compFlux = 1
      showquant = 1
    endif   
    if (Nspec EQ 27) then begin ; Ne+ 12.815
      lmin = 12.79*mic
      lmax = 12.84*mic
      sub_cont = 1
      ;info = 1
      compFlux = 1
      showquant = 1
    endif   
    if (Nspec EQ 28) then begin ; Ne++ 15.555
      lmin = 15.525*mic
      lmax = 15.585*mic
      sub_cont = 1
      ;info = 1
      compFlux = 1
      showquant = 1
    endif   
    if (Nspec EQ 29) then begin 
      lmin = 800.*mic
      lmax = 1000.*mic
      sub_cont = 1
      ;info = 1
    endif   
    if (Nspec EQ 30) then begin 
      lmin = 1000.*mic
      lmax = 1400.*mic
      sub_cont = 1
      ;info = 1
    endif   
    if (Nspec EQ 31) then begin 
      lmin = 1400.*mic
      lmax = 2000.*mic
      sub_cont = 1
      ;info = 1
    endif   
    if (Nspec EQ 32) then begin 
      lmin = 3000.*mic
      lmax = 4500.*mic
      sub_cont = 1
      ;info = 1
    endif   

    micron_by_micron = (1 EQ 1)
    if (micron_by_micron) then begin
    if (Nspec EQ 14) then begin 
      lmin = 9.95*mic
      lmax = 11.05*mic
      sub_cont = 1
      ;info = 1
      showquant=1
    endif   
    if (Nspec EQ 15) then begin 
      lmin = 10.95*mic
      lmax = 12.05*mic
      sub_cont = 1
      ;info = 1
      showquant=1
    endif   
    if (Nspec EQ 16) then begin 
      lmin = 11.95*mic
      lmax = 13.05*mic
      sub_cont = 1
      ;info = 1
      showquant=1
    endif   
    if (Nspec EQ 17) then begin 
      lmin = 12.95*mic
      lmax = 14.05*mic
      sub_cont = 1
      ;info = 1
      showquant=1
    endif   
    if (Nspec EQ 18) then begin 
      lmin = 13.95*mic
      lmax = 15.05*mic
      sub_cont = 1
      ;info = 1
      showquant=1
    endif   
    if (Nspec EQ 19) then begin 
      lmin = 14.95*mic
      lmax = 16.05*mic
      sub_cont = 1
      ;info = 1
      showquant=1
    endif   
    if (Nspec EQ 20) then begin 
      lmin = 15.95*mic
      lmax = 17.05*mic
      sub_cont = 1
      ;info = 1
      showquant=1
    endif   
    if (Nspec EQ 21) then begin 
      lmin = 16.95*mic
      lmax = 18.05*mic
      sub_cont = 1
      ;info = 1
      showquant=1
    endif   
    if (Nspec EQ 22) then begin 
      lmin = 17.95*mic
      lmax = 19.05*mic
      sub_cont = 1
      ;info = 1
      showquant=1
    endif   
    if (Nspec EQ 23) then begin 
      lmin = 18.95*mic
      lmax = 20.05*mic
      sub_cont = 1
      ;info = 1
      showquant=1
    endif   
    endif

    ind = WHERE((lhigh GT lmin) AND (lhigh LE lmax),count)
    if (count gt 0) then begin
      lwork  = lhigh(ind)
      Fwork  = Fnu2(ind)
      ytitel = "!7F!9!Ln!N !7[Jy]" 
      if (sub_cont EQ 1) then begin
        Fwork=Fwork-Fcont(ind)
        ytitel = "!7F!9!Ln!N!7-F!9!Ln!U!7cont!N [Jy]" 
      endif  
      Fmin = min(Fwork)
      Fmax = max(Fwork)
      haveFlits = 0
      if (Flits) then begin
        ind2 = WHERE((lamFlits_high*mic GT lmin) AND (lamFlits_high*mic LE lmax),count)
        if (count GT 0) then begin
          haveFlits = 1
          lwork2 = lamFlits_high(ind2)
          Fwork2 = fluxFlits_lowres(ind2)
          lwork3 = lamFlits_high(ind2)
          Fwork3 = fluxFlits_high(ind2)
          if (sub_cont EQ 1) then begin
            Fwork2 = fluxFlits_subcont(ind2)
            Fwork3 = fluxFlits_high(ind2)-FcontFlits_high(ind2)
          endif  
          Fmin = min([Fmin,Fwork2])
          Fmax = max([Fmax,Fwork2])
        endif  
      endif  
      if (haveContSubSpec EQ 1 AND sub_cont EQ 1) then begin
        ind2 = WHERE((lamTWHya*mic GT lmin) AND (lamTWHya*mic LE lmax),count)
        if (count GT 0) then begin
          Fmax = max([Fmax,FTWHyaLines(ind2)*Jansky])
        endif  
      endif
      if ((hasIRspek)AND(sub_cont EQ 0)) then begin
        ind3 = WHERE(lamSpec GT lmin/mic AND lamSpec LT lmax/mic,count) 
        if (count GT 0) then begin
          Fmax = max([Fmax,max(FnuSpec(ind3))*Jansky])
          Fmin = min([Fmin,min(FnuSpec(ind3))*Jansky])
        endif
      endif  
      if ((hasCOspek)AND(sub_cont EQ 0)) then begin
        ind3 = WHERE(lamSpec2 GT lmin/mic AND lamSpec2 LT lmax/mic,count) 
        if (count GT 0) then begin
          Fmax = max([Fmax,max(FnuSpec2(ind3))*Jansky])
          Fmin = min([Fmin,min(FnuSpec2(ind3))*Jansky])
        endif
      endif  
      dF = Fmax-Fmin
      Fmin = Fmin-0.1*dF
      Fmax = Fmax+0.2*dF
      phrase1 = "dist = "+STRTRIM(STRING(format="(F8.1)",dist/pc),2)+"!L !Npc"
      phrase2 = "R = "+STRTRIM(STRING(format="(F10.1)",RR),2)
      plot, lwork/mic,Fwork/Jansky,/nodata,$
        xrange=[lmin,lmax]/mic,yrange=[Fmin,Fmax]/Jansky,$
        thick=2,position=pos,$  
        xtitle="!9l !7[!9m!7m]",$
        ytitle=ytitel,$
        title=phrase1+'    '+phrase2
      if ((hasIRspek)AND(sub_cont EQ 0)) then oplot,lamSpec,FnuSpec,color=210
      if ((hasCOspek)AND(sub_cont EQ 0)) then oplot,lamSpec2,FnuSpec2,color=250,$
                                                    psym=10,thick=2
      if (sub_cont EQ 0) then oplot,lhigh/mic,Fcont/Jansky,color=black,thick=2
      if (haveFlits) then begin
        loadct,0,/silent
        oplot,lwork3,Fwork3/Jansky,color=210,thick=1      ; FLiTs, original res.
        loadct,39,/silent
        oplot,lwork2,Fwork2/Jansky,color=magenta,thick=4  ; FLiTs, low res.
      endif  
      if (haveContSubSpec EQ 1 AND sub_cont EQ 1) then oplot,lamTWHya,FTWHyaLines,col=orange
      oplot, lwork/mic,Fwork/Jansky,color=blue,thick=2    ; ProDiMo, low res.
      ;if (haveFlits) then oplot,lamFlits,fluxFlitsJy
      llist = WHERE(LINELAMB GT lmin/mic AND LINELAMB LT lmax/mic)
      FLINEmax=0.0
      for ii=0,N_ELEMENTS(llist)-1 do begin
        i = llist(ii)
        lmic=LINELAMB(i)
        FLINE=LINEFLUX(i)
        if (lmic GT lmin/mic AND lmic LT lmax/mic) then begin
          FLINEmax = max([FLINEmax,ABS(FLINE)*lmic])
        endif    
      endfor
      lmean_mic = sqrt(lmin*lmax)/mic
      ;print,FLINEmax/lmean_mic,1.e-15
      ;FLINEmax = MIN([FLINEmax,1.e-15*lmean_mic])
      FLINEmin = 1.E-4*FLINEmax
      ;if (lmax/lmin GT 1.2) then FLINEmin = 0.01*FLINEmax
      ;if (lmax/lmin GT 2.0) then FLINEmin = 0.1*FLINEmax
      lfluxtmp = LINEFLUX(llist)*LINELAMB(llist)
      for it=1,99 do begin
        tmp = WHERE(ABS(lfluxtmp) GT FLINEmin,count)
        ;print,FLINEmax,FLINEmin,count
        if (count LT 100) then break
        FLINEmin = FLINEmin*1.2
      endfor  
      strongest = 0
      lamstrong = 0
      species   = 'vacuum'
      name_list = strarr(Nline)
      freq_list = fltarr(Nline)
      lamb_list = fltarr(Nline)
      flux_list = fltarr(Nline)
      quan_list = strarr(Nline)
      il = 0L
      for ii=0,N_ELEMENTS(llist)-1 do begin
        i = llist(ii)
        lmic =LINELAMB(i)
        FLINE=LINEFLUX(i)
        name =LINENAME(i)
        if (ABS(FLINE)*lmic GT FLINEmin) then begin
          fGHz = cl/(lmic*mic)/1.e+9
          name_list(il) = STRTRIM(name,2)
          freq_list(il) = fGHz
          lamb_list(il) = lmic
          flux_list(il) = FLINE
          quan_list(il) = LINEQUPP(i)+" -> "+LINEQLOW(i)
          il = il + 1L
          if (ABS(FLINE) GT strongest) then begin
            strongest = ABS(FLINE)
            lamstrong = lmic
            species   = name
          endif    
        endif
      endfor
      iuniq     = uniq(name_list(0:il-1))
      name_uniq = name_list(iuniq)
      wstrongest = where(name_uniq EQ species)
      if(wstrongest GT 0) then begin
         tmp_name = name_uniq(0)
         name_uniq(0) = name_uniq(wstrongest)
         name_uniq(wstrongest) = tmp_name
      endif   
      nuniq = n_elements(iuniq)
      if (nuniq GT 1) then begin
        col_list  = FLOOR((240/(nuniq-1.0))*findgen(nuniq))
      endif else begin
        col_list = [black]
      endelse
      if (info GE 1) then begin
        jlamb = sort(lamb_list(0:il-1))
        for i=0L,il-1 do begin
          i2 = jlamb(i)
          if (showquant) then begin
             print,format='(F14.6,F14.5,2x,A10,E12.4,A64)',freq_list(i2),$
                lamb_list(i2),name_list(i2),flux_list(i2),quan_list(i2)
          endif else begin
             print,format='(F14.6,F14.5,2x,A10,E12.4)',freq_list(i2),$
                lamb_list(i2),name_list(i2),flux_list(i2)
          endelse
        endfor
        if (info GE 2) then begin
          print,'-----'
          print,'increasing flux order'
          jflux = sort(flux_list(0:il-1))
          for i=0L,il-1 do begin
            i2 = jflux(i)
            if (info EQ 2) then begin
              print,format='(F14.6,F14.5,2x,A10,E12.4)',freq_list(i2),$
                    lamb_list(i2),name_list(i2),flux_list(i2)
            endif
            if (info EQ 3) then begin
              print,format='(F14.6,F14.5,2x,A10,E12.4,A)',freq_list(i2),$
                    lamb_list(i2),name_list(i2),$
                    flux_list(i2)*1e26*3e5/(freq_list(i2)*1e9),' Jy km/s'
            endif
          endfor
        endif   
      endif
      for i1=0,nuniq-1 do begin
        col  = col_list(i1)
        name = name_uniq(i1)
        Fplot = 0.92
        if (STRTRIM(name) EQ 'CO')     then Fplot = 0.88
        if (STRTRIM(name) EQ '13CO')   then Fplot = 0.88
        if (STRTRIM(name) EQ 'C17O')   then Fplot = 0.88
        if (STRTRIM(name) EQ 'C18O')   then Fplot = 0.88
        if (STRTRIM(name) EQ 'o-H2O')  then Fplot = 0.84
        if (STRTRIM(name) EQ 'p-H2O')  then Fplot = 0.80
        if (STRPOS(name,'CH3OH') GE 0) then Fplot = 0.76
        if (STRPOS(name,'_H') GE 0)    then Fplot = 0.72
        Fplot1 = Fmin+(Fmax-Fmin)*(Fplot+0.01)
        Fplot2 = Fmin+(Fmax-Fmin)*(Fplot-0.02)
        for i2=0L,il-1 do begin
          if (name_list(i2) eq name) then begin
            lmic = lamb_list(i2)
            oplot,[lmic,lmic],[Fplot1,Fplot2]/Jansky,thick=3,color=col
          endif
        endfor  
        y0 = 0.91
        x0 = 0.5
        if (nuniq GT 1) then begin
          x0 = 0.2+0.6*i1/(nuniq-1.0)
        endif  
        csize=0.9
        if (nuniq GT 5)  then csize=0.8
        if (nuniq GT 10) then csize=0.6
        xyouts,/norm,x0,y0,name,charsize=0.8,charthick=1.5,$
               alignment=0.5,color=col
      endfor
      Fint = 0.0
      i1=min(ind)
      i2=max(ind)
      i=i1+1
      repeat begin  
        nu1 = cl/lhigh(i-1)  
        nu2 = cl/lhigh(i)
        F1  = Fnu2(i-1)-Fcont(i-1)
        F2  = Fnu2(i)-Fcont(i)
        Fint = Fint + 0.5*(F1+F2)*(nu1-nu2)
        i=i+1
      endrep until (i GT i2)
      print,format='("total line flux in [",F8.2," ,",F8.2," ] um:     Fline=",E12.3," W/m2")',$
            lmin/mic,lmax/mic,Fint/Wm2
      print,format='("  strongest line at",F14.8,2x,A10,"Fline=",E12.3," W/m2")',$
            lamstrong,species,strongest

      if (compFlux EQ 1 AND haveContSubSpec EQ 1) then begin
        ind = WHERE(lamTWHya GT lmin/mic AND lamTWHya LT lmax/mic,Ndat)
        if (Ndat GT 1) then begin
          int = 0.0
          for i=0,N_ELEMENTS(ind)-1 do begin
            dlam = lamTWHya(ind[i])-lamTWHya(ind[i]-1)
            int = int + FTWHyaLines(ind(i))*dlam  ; [Jy * mic]
          endfor   
          Fline = int*Jansky                      ; [erg/cm2/s/Hz * mic]
          nuHz  = cl/lmin
          Fline = Fline/(lmin/mic)*nuHz           ; [erg/cm2/s]
          print,format='("  observed feature flux =",E12.3," W/m2")',Fline/Wm2
          dlam = lamTWHya(ind[1])-lamTWHya(ind[0])
          xxx = [lmin/mic-2*dlam,lmin/mic-dlam,lmin/mic,lamTWHya[ind],lmax/mic,lmax/mic+dlam,lmax/mic+2*dlam]
          yyy = [0.0            ,0.0          ,0.0     ,FTWHyaLines[ind], 0.0 ,0.0          ,0.0            ]
          estimates = [max(yyy),(lmin+lmax)/2/mic,lmin/mic/600.0,min(yyy)] 
          fff = GAUSSFIT(xxx,yyy,AAA,NTERMS=4,SIGMA=Aerr,ESTIMATES=estimates)
          print,estimates
          print,AAA
          xxx = lmin/mic + (lmax-lmin)/mic*FINDGEN(61)/60.0
          zzz = (xxx-AAA[1])/AAA[2]
          fff = AAA[0]*exp(-zzz^2/2)+AAA[3]
          oplot,xxx,fff,col=black
          pi = ACOS(-1.d0)
          Fline2 = AAA[0]*ABS(AAA[2])*sqrt(2.d0*pi) ; area [Jy*mic]
          Fline2 = Fline2*Jansky/(lmin/mic)*nuHz    ; [erg/cm2/s]
          print,format='("  observed feature flux =",E12.3," W/m2")',Fline2/Wm2
        endif  
        ind = WHERE(lwork GT lmin AND lwork LT lmax,Ndat)
        if (Ndat GT 1) then begin
          int = 0.0
          for i=1,N_ELEMENTS(ind)-1 do begin
            dlam = lwork(ind[i])-lwork(ind[i]-1)
            int = int + Fwork(ind(i))*dlam        ; [erg/cm2/s/Hz * cm]
          endfor   
          nuHz  = cl/lmin
          Fline = int/lmin*nuHz                   ; [erg/cm2/s]
          print,format='("  control model line flux =",E12.3," W/m2")',Fline/Wm2
        endif  
      endif

    endif  
  endfor  
END

;---------------------------------------------------------------------------------
PRO LINE_ANALYSIS,logr,spname,molname,lam0,NX,NZ,xx,zz,nn,Tgas,Tdust,nHtot,dist,$
                  Tline=Tline,plotTg=plotTg
;---------------------------------------------------------------------------------
  COMMON global, lineinit,LineFileVersion,Nline,linetxt,datatxt,HITRANversion
  cl    = 2.997924580D+10       ; speed of light
  pc    = 3.085680250D+18       ; 1 parsec
  Rsun  = 6.959900000D+10       ; solar radius
  AU    = 1.495978700D+13       ; 1 astronomical unit in cm
  nm    = 1.D-7                 ; 1 nanometer
  mic   = 1.D-4                 ; 1 micron
  Wm2   = 1.D+3                 ; 1 W/m^2 in [erg/cm^2/s]
  Jansky = 1.D-23               ; 1 Jy in [erg/cm^2/s/Hz]
  black   = 0
  white   = 255
  orange  = 210
  red     = 250
  yellow  = 195
  green   = 160
  cyan    = 100
  blue    = 70
  magenta = 40
  line="blasel"
  line1="blasel"

  if (lineinit EQ 1) then begin
    openr,1,"FlineEstimates.out",ERROR = err
    if (err NE 0) then begin
      close,1
      return
    endif   
    print,"read line flux data from FlineEstimates.out"
    readf,1,line1
    readf,1,line
    readf,1,line
    readf,1,line
    readf,1,line
    close,1
    LineFileVersion=0
    if (strlen(line) EQ 68) then LineFileVersion=1
    if (STRPOS(line1,"version 2") GT 0) then LineFileVersion=2
    if (STRPOS(line1,"version 3") GT 0) then LineFileVersion=3
    NLines=0L
    openr,1,"FlineEstimates.out",ERROR = err
    readf,1,line
    HITRANversion = 1
    if(strpos(line,'version') gt 0) then begin
      HITRANversion = 2
    endif
    readf,1,Nlines
    readf,1,line
    linetxt = strarr(Nlines)
    datatxt = strarr(Nlines,NX)
    Nline = 0L
    for i=0L,Nlines-1L do begin
      if (EOF(1)) then break 
      readf,1,line
      linetxt(i) = line
      Nline = Nline+1L
      for ix=0,NX-1 do begin
        readf,1,line
        datatxt(i,ix) = line
      endfor
    endfor
    close,1
    lineinit=0
  endif  

  izmax = intarr(Nx)
  Fcol = fltarr(Nx)
  tauL = fltarr(Nx)
  tauD = fltarr(Nx)
  z15  = fltarr(Nx)
  z85  = fltarr(Nx)
  ztauD1 = fltarr(Nx)
  Ncol = fltarr(Nx)
  name = 'bla'
  u=1
  l=1
  iz=0
  FLINE = 1.E-18
  namefound = ''
  searchname = spname
  if (spname EQ '[OI]')   then searchname='O' 
  if (spname EQ 'OI')     then searchname='O' 
  if (spname EQ '[CII]')  then searchname='C+' 
  if (spname EQ '[NII]')  then searchname='N+' 
  if (spname EQ '[SII]')  then searchname='S+' 
  if (spname EQ '[NeII]') then searchname='Ne+' 
  if (spname EQ '[NeIII]')then searchname='Ne++' 
  if (spname EQ '[ArII]') then searchname='Ar+' 
  if (spname EQ '[ArIII]')then searchname='Ar++' 
  if (spname EQ '[OIII]') then searchname='O++' 
  if (spname EQ '[OII]')  then searchname='O+' 
  if (spname EQ '[SIII]') then searchname='S++' 
  if (spname EQ '[SiII]') then searchname='Si+' 
  if (spname EQ '[FeII]') then searchname='Fe+' 
  if (spname EQ '[NIII]') then searchname='N++'
  if (spname EQ '[CI]')   then searchname='C'
  if (spname EQ 'HS+')    then searchname='SH+'
  lbest = 9.e+99
  found = 0
  frmt = '(A10,F18.8,i4,i4,E12.4)'
  if (LineFileVersion GT 1) then frmt = '(A10,F18.8,i6,i6,E12.4)'
  for i=0L,Nline-1 do begin
    reads,linetxt(i),format=frmt,name,lmic,u,l,FLINE
    ;if (HITRANversion gt 1) then begin
    ;  reads,linetxt(i),format='(A10,F18.8,i6,i6,E12.4,2(A32))',$
    ;                   name,lmic,u,l,FLINE,upper,lower
    ;endif else begin 
    ;  reads,linetxt(i),format='(A10,F18.8,i4,i4,E12.4,2(A32))',$
    ;  name,lmic,u,l,FLINE,upper,lower
    ;endelse
    ;print,name,lmic,u,l,FLINE
    if ((STRTRIM(name,2) EQ STRTRIM(searchname,2)) AND $
        (ABS(lmic-lam0)/lam0 LT 1.E-4) AND $
        (ABS(lmic-lam0) LE lbest)) then begin
      lbest = ABS(lmic-lam0)
      found = 1
      LLINE = lmic*mic
      FLINE = FLINE*Wm2
      namefound = name
      lamsave = lmic  
      Fsave = FLINE/Wm2  
      for ix=0,NX-1 do begin
        if (LineFileVersion EQ 0) then begin
          reads,datatxt(i,ix),ii,iz,Fcolumn,tauLine,tauDust
        endif else if (LineFileVersion LE 2) then begin
          reads,datatxt(i,ix),ii,iz,Fcolumn,tauLine,tauDust,zz15,zz85
          z15(ii-1)=zz15
          z85(ii-1)=zz85
        endif else if (LineFileVersion EQ 3) then begin
          reads,datatxt(i,ix),ii,iz,Fcolumn,tauLine,tauDust,zz15,zz85,zztauD1,NNcol
          z15(ii-1)=zz15
          z85(ii-1)=zz85
          ztauD1(ii-1)=zztauD1
          Ncol(ii-1)=NNcol
        endif  
        izmax(ii-1)=iz
        Fcol(ii-1)=Fcolumn
        tauL(ii-1)=tauLine
        tauD(ii-1)=tauDust
      endfor
    endif
  endfor
  if (max(Fcol) EQ 0.0) then found=0
  if (found EQ 0) then begin
    print,"could not find line in LINE_ANALYSIS"
    print,spname,lam0
    return
  endif else begin
    ;print,searchname,namefound,lam0,lamsave
  endelse

  ; --- 1. cumulative flux ---
  !P.MULTI=[0,1,3]
  !P.REGION = [0.07, 0.73, 0.92, 1.0]
  lamtext=STRING(format="(F10.2)",lamsave)
  if (lamsave LT 10.0) then lamtext=STRING(format="(F10.3)",lamsave)
  if (lamsave LT 1.0) then lamtext=STRING(format="(F10.4)",lamsave)
  xmin=min(xx)
  xmax=max(xx)
  Fcum=fltarr(Nx)
  Ftot=0.0
  for ix=0,Nx-1 do begin
    Ftot = Ftot + Fcol(ix)
    Fcum(ix) = Ftot  
  endfor
  Fcum = Fcum/Ftot*100.0
  if (logr EQ 1) then begin
    plot,xx(*,1),Fcum,/xlog,color=black,thick=3,$
        xrange=[xmin,xmax],yrange=[-4.0,104],ystyle=1,$
        XTICKNAME=[" "," "," "," "," "," "," "],xminor=9,$
        yticks=6,ytickv=[0,20,40,60,80,100],yminor=4,xticklen=0.05,$
        ymargin=[0,2],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        ytitle='!7cumulative F!7!Lline!N !7[%]',$
        title=spname+" "+STRTRIM(lamtext,2)+"!9m!7m"
  endif else begin
    plot,xx(*,1),Fcum,color=black,thick=3,$
        xrange=[xmin,xmax],yrange=[-4.0,104],ystyle=1,$
        XTICKNAME=[" "," "," "," "," "," "," "],$
        yticks=6,ytickv=[0,20,40,60,80,100],yminor=4,xticklen=0.05,$
        ymargin=[0,2],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        ytitle='!7cumulative F!7!Lline!N !7[%]',$
        title=spname+" "+STRTRIM(lamtext,2)+"!9m!7m"
  endelse  
  xyouts,0.17,0.91,/normal,$
        "!7F!Lline!N = "+STRTRIM(STRING(format="(E13.2)",Fsave),2)+" W/m!U2!N"
  ; --- 2. line tau and cont tau, or Ncol above z85 ---
  !P.REGION = [0.07, 0.50, 0.92, 0.73]
  maxtau=max([max(tauL(2:Nx-1)),max(tauD)])*1.5
  mintau=max([0.003,min(tauL(6:Nx-1))/1.2])
  mintau=min([mintau,0.03])
  mintau=max([mintau,maxtau/1000.0])
  mintau=min([mintau,0.5,0.5*min(tauD(4:Nx-1))])
  mintau=min([mintau,max(tauL(2:Nx-1))/40.0])
  if (LineFileVersion LE 2) then begin
    if (logr EQ 1) then begin
      plot,xx(*,1),tauD,/xlog,/ylog,color=black,thick=3,$
        xrange=[xmin,xmax],yrange=[mintau,maxtau],$
        XTICKNAME=[" "," "," "," "," "," "," "],xminor=9,yminor=9,$
        ymargin=[0,0],xmargin=[5,0],xticklen=0.05,$
        ytitle="!9t!7",charsize=2.0,xcharsize=1.3,ycharsize=1.3
    endif else begin  
      plot,xx(*,1),tauD,/ylog,color=black,thick=3,$
        xrange=[xmin,xmax],yrange=[mintau,maxtau],$
        XTICKNAME=[" "," "," "," "," "," "," "],yminor=9,$
        ymargin=[0,0],xmargin=[5,0],xticklen=0.05,$
        ytitle="!9t!7",charsize=2.0,xcharsize=1.3,ycharsize=1.3
    endelse
    oplot,xx(*,1),tauL,color=blue,thick=3      
    xyouts,xx(0.5*Nx,1),max([mintau,tauL(0.5*Nx)])*1.5,"!9t!7!Lline!N",color=blue
    xyouts,xx(0.4*Nx,1),max([mintau,tauD(0.4*Nx)])*1.5,"!9t!7!Lcont!N",color=black
  endif else begin
    Ncolmax = MAX([19.99,0.5+alog10(Ncol)])
    Ncolmin = MIN([10.5,MAX(alog10(Ncol))-2.0])
    if (logr EQ 1) then begin
      plot,xx(*,1),alog10(Ncol),/xlog,color=black,thick=3,xstyle=5,ystyle=9,$
        xrange=[xmin,xmax],yrange=[Ncolmin,Ncolmax],$
        XTICKNAME=[" "," "," "," "," "," "," "],xminor=9,$
        ymargin=[0,0],xmargin=[5,0],xticklen=0.05,$
        ytitle="log N!Lcol!N [cm!U-2!N]",charsize=2.0,xcharsize=1.3,ycharsize=1.3
      axis, yaxis=1,/xlog,color=blue,xrange=[xmin,xmax],yrange=[-4,6],yminor=1,$
        ytitle="log !9t!7!Lline!N",charsize=2.0,ycharsize=1.3
      plot,xx(*,1),alog10(tauL),/xlog,color=blue,/noerase,thick=3,xstyle=5,ystyle=5,$
        xrange=[xmin,xmax],yrange=[-4,6],ymargin=[0,0],xmargin=[5,0],$
        ytitle="log N!Lcol!N [cm!U-2!N]",charsize=2.0,ycharsize=1.3
    endif else begin  
      plot,xx(*,1),alog10(Ncol),color=black,thick=3,xstyle=5,ystyle=9,$
        xrange=[xmin,xmax],yrange=[Ncolmin,Ncolmax],$
        XTICKNAME=[" "," "," "," "," "," "," "],$
        ymargin=[0,0],xmargin=[5,0],xticklen=0.05,$
        ytitle="log N!Lcol!N [cm!U-2!N]",charsize=2.0,xcharsize=1.3,ycharsize=1.3
      axis, yaxis=1,color=blue,xrange=[xmin,xmax],yrange=[-2,4],$
        ytitle="log !9t!7!Lline!N",charsize=2.0,ycharsize=1.3
      plot,xx(*,1),alog10(tauL),color=blue,/noerase,thick=3,xstyle=5,ystyle=5,$
        xrange=[xmin,xmax],yrange=[-4,6],ymargin=[0,0],xmargin=[5,0],$
        ytitle="log N!Lcol!N [cm!U-2!N]",charsize=2.0,ycharsize=1.3
    endelse
  endelse
  ; --- 3. log(n)-contour and height of cell with max. contribution ---
  !P.REGION = [0.07, 0.0, 0.92, 0.50]
  xplot = xx(*,1)
  zplot = xplot
  x05  = interpol(xplot,Fcum,5.0)
  x10  = interpol(xplot,Fcum,10.0)
  x20  = interpol(xplot,Fcum,20.0)
  x50  = interpol(xplot,Fcum,50.0)
  x80  = interpol(xplot,Fcum,80.0)
  x90  = interpol(xplot,Fcum,90.0)
  x95  = interpol(xplot,Fcum,95.0)
  xx3  = [x05,x10,x20,x50,x80,x90,x95]
  zz3  = interpol(z15/AU/xplot,xplot,xx3)  
  ymax = MAX(zz/xx)
  ymax = MIN([ymax,MAX(zz3)*1.5])  ; maximum height that needs to be depicted
  ; ymax = 0.3 ; set manually
  xtmp = xx(*,1)
  ind  = WHERE(xtmp LE x10,Nind)
  x11  = xx(ind[Nind-1])
  ind  = WHERE(xtmp GE x90,Nind)
  x22  = xx(ind[0])
  ind  = WHERE(xx GE x11 AND xx LE x22,Nind)
  zmax = alog10(MAX(nn(ind)))
  zmin = MAX([alog10(MIN(nn(ind))),zmax-15.0])
  zmax = 12.0 ; set manually
  zmin = -5.0
  if (logr EQ 0) then begin
    ymax = MAX(zz/xx)
    zmax = 8.0
    zmin = -9.0
  endif
  ilev = 80
  lev=dblarr(ilev+1)
  col=intarr(ilev+1)      
  colmin=2             
  colmax=253
  for i=0,ilev do begin
    lev(i)=zmin+(zmax-zmin)*i/ilev
    col(i)=fix(colmin+(colmax-colmin)*(lev(i)-zmin)/(zmax-zmin))
  endfor
  nplot = alog10(nn)
  ind=WHERE(nplot LT zmin+0.01,count)
  if (count GT 0) then nplot(ind) = zmin+0.01 
  if (logr EQ 1) then begin
    contour,nplot,xx,zz/xx,/xlog,thick=3,$
        xrange=[xmin,xmax],yrange=[0.0,ymax],xminor=9,yminor=4,xticklen=0.05,$
        ymargin=[4,0],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        levels=lev,c_colors=col,/fill, $
        xtitle="r [au]",ytitle="z/r"
  endif else begin
    contour,nplot,xx,zz,thick=3,$
        xrange=[xmin,xmax],yrange=[0.0,ymax*xmax*0.7],yminor=4,xticklen=0.05,$
        ymargin=[4,0],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        levels=lev,c_colors=col,/fill, $
        xtitle="r [au]",ytitle="z [au]"
  endelse  
  if (KEYWORD_SET(plotTg)) then begin
    Tlev=[30,100,300,1000]
    Tlab=['30K','100K','300K','1000K']
    if ((molname EQ 'O') AND (ABS(lam0-63.18) LT 0.01)) then begin
      Tlev=[40,50,60]
      Tlab=['40K','50K','60K']
    endif   
    if ((molname EQ 'CO') AND (lam0 LT 6)) then begin
      Tlev=[500,1000,2000]
      Tlab=['500K','1000K','2000K']
    endif   
    if ((molname EQ 'CO') AND (ABS(lam0-144.8) LT 0.1)) then begin
      Tlev=[200]
      Tlab=['200K']
    endif   
    if (logr EQ 1) then begin
      contour,Tgas,xx,zz/xx,/xlog,thick=3,/noerase,$
        xrange=[xmin,xmax],yrange=[0.0,ymax],xminor=9,yminor=4,xticklen=0.05,$
        ymargin=[4,0],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        levels=Tlev,c_annotation=Tlab, $
        c_colors=red,xtitle="r [au]",ytitle="z/r" 
    endif else begin
      contour,Tgas,xx,zz,thick=3,/noerase,$
        xrange=[xmin,xmax],yrange=[0.0,ymax*xmax*0.7],xminor=9,yminor=4,xticklen=0.05,$
        ymargin=[4,0],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        levels=Tlev,c_annotation=Tlab,$
        c_colors=red,xtitle="r [au]",ytitle="z [au]" 
    endelse  
  endif
  if (LineFileVersion EQ 3) then begin
    xplot = xx(*,1)
    zplot = ztauD1/AU/xplot
    oplot,xplot,zplot,thick=5,color=white
  endif
  ;if (molname EQ "H2") then begin
  ;  COLUMN_DENS, NX,NZ,zz*AU,nn,cdmol
  ;  contour,cdmol,xx,zz/xx,/xlog,thick=3,/noerase,$
  ;      xrange=[xmin,xmax],yrange=[0.0,ymax],xminor=9,yminor=4,xticklen=0.05,$
  ;      ymargin=[4,0],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
  ;      levels=[1.e+22,1.e+23,1.e+24],c_annotation=['22','23','24'], $
  ;      c_colors=white,xtitle="r [au]",ytitle="z/r"     
  ;endif  
  xplot = xx(*,1)
  zplot = xplot
  x15=interpol(xx(*,1),Fcum,15.0)
  x85=interpol(xx(*,1),Fcum,85.0)
  xxx=[x15,x15]
  yyy=[0.0,ymax]
  oplot,xxx,yyy,linestyle=2,/noclip
  xxx=[x85,x85]
  oplot,xxx,yyy,linestyle=2,/noclip
  for ix=0,Nx-1 do begin
    zplot(ix) = zz(ix,izmax(ix)-1)  
  endfor
  if (LineFileVersion EQ 0) then begin
    oplot,xplot,zplot/xplot,thick=7,color=black
  endif else begin 
    index=where(xplot GE x15 AND xplot LE x85, count)
    if (count GT 0) then begin
      xx1=[x15,xplot(index),x85]
    endif else begin    
      xx1=[x15,x85]
    endelse
    zz1=interpol(z15/AU/xplot,xplot,xx1)
    zz2=interpol(z85/AU/xplot,xplot,xx1)
    xxx=[xx1,xx1]
    yyy=[zz1,zz2]
    Nxxx=N_ELEMENTS(xx1)
    for ix=0,Nxxx-1 do begin
      iix = 2*Nxxx-1-ix  
      xxx(iix) = xx1(ix)
      yyy(iix) = zz2(ix)
    endfor
    if (logr EQ 1) then begin
      ;polyfill,xxx,yyy,color=white,noclip=0
      ;oplot,xplot,zplot/xplot,thick=7,color=black,linestyle=2
      oplot,xplot,z15/AU/xplot,thick=1,color=black,linestyle=2
      oplot,xplot,z85/AU/xplot,thick=1,color=black,linestyle=2
      oplot,[xxx,xxx(0)],[yyy,yyy(0)],thick=7,color=black
    endif else begin
      oplot,xplot,z15/AU,thick=1,color=black,linestyle=2
      oplot,xplot,z85/AU,thick=1,color=black,linestyle=2
      oplot,[xxx,xxx(0)],[yyy*xxx,yyy(0)*xxx(0)],thick=7,color=black
    endelse
  endelse
  if (spname EQ 'CO' and ABS(lam0/1300.40-1.0) LT 1.E-5) then begin
    ;--- overplot 12CO 2-1 surface from AS209 (Law+2021,MAPS) ---
    parsec       = 3.085680250D+18      ; 1 parsec
    distance     = 121*parsec           ; distance of AS209
    pi           = acos(-1.0d0)         ; just pi
    degree       = pi/180.0             ; 1 degree in rad
    arcsec       = degree/3600.0        ; one arc second in rad
    arcsec_to_AU = arcsec*distance/AU   ; length [au] corresponding to 1"
    z00  = 0.219*arcsec_to_AU
    rtap = 1.786*arcsec_to_AU
    Xphi = 1.292
    Xpsi = 4.854
    r_arcsec = xplot/arcsec_to_AU
    COsurf = z00 * (r_arcsec)^Xphi * exp(-(xplot/rtap)^Xpsi)
    oplot,xplot,COsurf,thick=5,color=blue,linestyle=1
    ind = where(ABS(xplot-100) EQ MIN(ABS(xplot-100)))
    print,'12CO 2-1 surface @ 100AU: ',z85(ind)/AU,z15(ind)/AU,COsurf(ind)
  endif
  if (spname EQ '13CO' and ABS(lam0/1360.22-1.0) LT 1.E-5) then begin
    ;--- overplot 13CO 2-1 surface from AS209 (Law+2021,MAPS) ---
    parsec       = 3.085680250D+18      ; 1 parsec
    distance     = 121*parsec           ; distance of AS209
    pi           = acos(-1.0d0)         ; just pi
    degree       = pi/180.0             ; 1 degree in rad
    arcsec       = degree/3600.0        ; one arc second in rad
    arcsec_to_AU = arcsec*distance/AU   ; length [au] corresponding to 1"
    z00  = 0.175*arcsec_to_AU
    rtap = 1.124*arcsec_to_AU
    Xphi = 2.98
    Xpsi = 2.445
    r_arcsec = xplot/arcsec_to_AU
    COsurf = z00 * (r_arcsec)^Xphi * exp(-(xplot/rtap)^Xpsi)
    oplot,xplot,COsurf,thick=5,color=blue,linestyle=1
    ind = where(ABS(xplot-100) EQ MIN(ABS(xplot-100)))
    print,'13CO 2-1 surface @ 100AU: ',z85(ind)/AU,z15(ind)/AU,COsurf(ind)
  endif
;
; get Tgas, Tdust, nHtot in line emitting region
;
  if (KEYWORD_SET(Tline)) then begin
    pi  = acos(-1.d0)
    amu = 1.660531000d-24
    Msun= 1.988922500d+33
    Mearth = 5.974200d+27
    AU  = 1.495978700d+13
    vol = dblarr(NX,NZ)
    for ix=0,NX-1 do begin
      ix1 = max([0,ix-1])
      ix2 = ix
      ix3 = min([NX-1,ix+1])
      x1=sqrt(xx(ix1,0)*xx(ix2,0))*AU  ; does not depend on iz
      x2=sqrt(xx(ix2,0)*xx(ix3,0))*AU  ; does not depend on iz
      for iz=0,NZ-1 do begin
        iz1 = max([0,iz-1])
        iz2 = iz
        iz3 = min([NZ-1,iz+1])
        tanbeta1=0.5*(zz(ix,iz1)+zz(ix,iz2))/xx(ix,0)  ; does not depend on ix
        tanbeta2=0.5*(zz(ix,iz2)+zz(ix,iz3))/xx(ix,0)  ; does not depend on ix
        vol(ix,iz)=4.d0*pi/3.0 * (x2^3-x1^3) * (tanbeta2-tanbeta1)
      endfor
    endfor

    mass=0.
    Tgasline=0.
    Tdustline=0.
    nHtotline=0.
    Ncolline=0.
    Npoints=0
    for ix=0,NX-1 do begin
      if (Ncol(ix) GT 1.E-50) then begin 
         Ncolline = Ncolline + ALOG(Ncol(ix))*Fcol(ix)
      endif   
      if ((xx(ix,1) ge x15) and (xx(ix,1) le x85)) then begin
        for iz=0,NZ-1 do begin
          if ((zz(ix,iz) le z15(ix)/AU) and (zz(ix,iz) ge z85(ix)/AU)) then begin
            mass      = mass      + vol(ix,iz)*nn(ix,iz)
            Tgasline  = Tgasline  + vol(ix,iz)*nn(ix,iz)*Tgas(ix,iz)
            Tdustline = Tdustline + vol(ix,iz)*nn(ix,iz)*Tdust(ix,iz)
            nHtotline = nHtotline + vol(ix,iz)*nn(ix,iz)*nHtot(ix,iz)
            Npoints   = Npoints + 1
          endif
        endfor
      endif  
    endfor
    Ncolline  = EXP(Ncolline/Ftot)
    Tgasline  = Tgasline/mass
    Tdustline = Tdustline/mass
    nHtotline = nHtotline/mass

    print,"--> "+spname+" "+STRTRIM(STRING(format="(F10.2)",lamsave),2)+": "+$
        '70% of the line flux originate from ['+$
        STRTRIM(STRING(format='(F8.3)',x15),2)+","+$
        STRTRIM(STRING(format='(F7.2)',x85),2)+"] AU"
    print,"    <Tgas>="+$
        STRTRIM(STRING(format='(F8.2)',Tgasline),2)+", <Tdust>="+$
        STRTRIM(STRING(format='(F8.2)',Tdustline),2)+", <nHtot>="+$
        STRTRIM(STRING(format='(E11.3)',nHtotline),2)+", <Ncol>="+$
        STRTRIM(STRING(format='(E11.3)',Ncolline),2)+", Npoints="+$
        STRTRIM(STRING(Npoints),2)
  endif else begin
    print,"--> "+spname+" "+STRTRIM(STRING(format="(F10.2)",lamsave),2)+": "+$
        '70% of the line flux originate from ['+$
        STRTRIM(STRING(format='(F8.3)',x15),2)+","+$
        STRTRIM(STRING(format='(F7.2)',x85),2)+"] AU"
  endelse
  
  text = "log n!L"+molname+" !N[cm!U-3!N]"
  ;printf,99, spname, lamsave, Fsave, format='(A10,F12.5,2x,E9.3)'
  ;if (molname EQ "H2") then text = "log H!L2!Nform [s!U-1!Ncm!U-3!N]"  
  xplot = xx(*,1)
  x15 = interpol(xplot,Fcum,15.0)
  x85 = interpol(xplot,Fcum,85.0)
  xm  = 0.5*(xmin+xmax)
  if (logr) then xm=SQRT(xmin*xmax)
  left  = (x15 GT xm)
  right = (x85 LT xm)
  if (NOT(left or right)) then begin
    zz15  = interpol(z15/AU/xplot,xplot,x15)  
    zz85  = interpol(z15/AU/xplot,xplot,x85)  
    left  = (zz15 LE zz85)
    right = (zz15 GT zz85)
  endif
  right = (1 eq 0)
  if (right) then begin
    SKALA2, ilev+1,lev,col,text,[0.65,0.358+0.10,0.93,0.382+0.10],1.9
  endif else begin  
    SKALA2, ilev+1,lev,col,text,[0.17,0.358+0.10,0.45,0.382+0.10],1.9
  endelse  
  !P.MULTI=0
  !P.REGION=0
END

;--------------------------------------------------------------------
PRO PARTNER_ANALYSIS,folder,spname,molname,lam0,NX,NZ,xx,zz, $
                     nn1,nn2,nn3,colname1,colname2,colname3,Tgas,$
                     dist,plotTg=plotTg,zmin=zmin,zmax=zmax
;--------------------------------------------------------------------
  COMMON global, lineinit,LineFileVersion,Nline,linetxt,datatxt,HITRANversion
  cl    = 2.997924580D+10       ; speed of light
  pc    = 3.085680250D+18       ; 1 parsec
  Rsun  = 6.959900000D+10       ; solar radius
  AU    = 1.495978700D+13       ; 1 astronomical unit in cm
  nm    = 1.D-7                 ; 1 nanometer
  mic   = 1.D-4                 ; 1 micron
  Wm2   = 1.D+3                 ; 1 W/m^2 in [erg/cm^2/s]
  Jansky = 1.D-23               ; 1 Jy in [erg/cm^2/s/Hz]
  black   = 0
  white   = 255
  orange  = 210
  red     = 250
  yellow  = 195
  green   = 160
  cyan    = 100
  blue    = 70
  magenta = 40
  line="blasel"
  line1="blasel"

  if (lineinit EQ 1) then begin
    print,"read line flux data from "+folder+"/FlineEstimates.out"
    openr,1,folder+"/FlineEstimates.out",ERROR = err
    if (err NE 0) then begin
      close,1
      return
    endif   
    readf,1,line1
    readf,1,line
    readf,1,line
    readf,1,line
    readf,1,line
    close,1
    LineFileVersion=0
    if (strlen(line) EQ 68) then LineFileVersion=1
    if (STRPOS(line1,"version") GT 0) then LineFileVersion=2
    openr,1,folder+"/FlineEstimates.out",ERROR = err
    readf,1,line
    readf,1,Nlines
    readf,1,line
    linetxt = strarr(Nlines)
    datatxt = strarr(Nlines,NX)
    Nline = 0
    for i=0L,Nlines-1 do begin
      readf,1,line
      linetxt(i) = line
      Nline=Nline+1
      for ix=0,NX-1 do begin
        readf,1,line
        datatxt(i,ix) = line
      endfor
    endfor
    close,1
    lineinit=0
  endif  

  izmax = intarr(Nx)
  Fcol = fltarr(Nx)
  tauL = fltarr(Nx)
  tauD = fltarr(Nx)
  z15  = fltarr(Nx)
  z85  = fltarr(Nx)
  name = 'bla'
  u=1
  l=1
  iz=0
  FLINE = 1.E-18
  namefound = ''
  searchname = spname
  if (spname EQ '[OI]')  then searchname='O' 
  if (spname EQ 'OI')    then searchname='O' 
  if (spname EQ '[CII]') then searchname='C+' 
  if (spname EQ '[NII]') then searchname='N+' 
  if (spname EQ '[SII]') then searchname='S+' 
  if (spname EQ '[NeII]') then searchname='Ne+' 
  if (spname EQ '[NeIII]') then searchname='Ne++' 
  if (spname EQ '[ArII]') then searchname='Ar+' 
  if (spname EQ '[ArIII]') then searchname='Ar++' 
  if (spname EQ '[OIII]') then searchname='O++' 
  if (spname EQ '[OII]') then searchname='O+' 
  if (spname EQ '[SIII]') then searchname='S++' 
  if (spname EQ '[FeII]') then searchname='Fe+' 
  if (spname EQ '[NIII]') then searchname='N++' 
  lbest = 9.e+99
  found = 0
  frmt='(A10,F18.8,i4,i4,E12.4)'
  if (LineFileVersion GT 1) then frmt='(A10,F18.8,i6,i6,E12.4)'
  for i=0L,Nline-1 do begin
    reads,linetxt(i),format=frmt,name,lmic,u,l,FLINE
    ;print,name,lmic,u,l,FLINE
    if ((STRTRIM(name,2) EQ STRTRIM(searchname,2)) AND $
        (ABS(lmic-lam0)/lam0 LT 1.E-4) AND $
        (ABS(lmic-lam0) LE lbest)) then begin
      lbest = ABS(lmic-lam0)
      found = 1
      LLINE = lmic*mic
      FLINE = FLINE*Wm2
      namefound = name
      lamsave = lmic  
      Fsave = FLINE/Wm2  
      for ix=0,NX-1 do begin
        if (LineFileVersion EQ 0) then begin
          reads,datatxt(i,ix),ii,iz,Fcolumn,tauLine,tauDust
        endif else begin  
          reads,datatxt(i,ix),ii,iz,Fcolumn,tauLine,tauDust,zz15,zz85
          z15(ii-1)=zz15
          z85(ii-1)=zz85
        endelse  
        izmax(ii-1)=iz
        Fcol(ii-1)=Fcolumn
        tauL(ii-1)=tauLine
        tauD(ii-1)=tauDust
      endfor
    endif
  endfor
  if (max(Fcol) EQ 0.0) then found=0
  if (found EQ 0) then begin
    print,"could not find line in LINE_ANALYSIS"
    print,spname,lam0
    return
  endif else begin
    ;print,searchname,namefound,lam0,lamsave
  endelse

  ; -----------
  Fcum=fltarr(Nx)
  Ftot=0.0
  for ix=0,Nx-1 do begin
    Ftot = Ftot + Fcol(ix)
    Fcum(ix) = Ftot  
  endfor
  Fcum = Fcum/Ftot*100.0
  ; --- 1.  ---
  !P.MULTI=[0,1,3]
  xmin=min(xx)
  xmax=max(xx)
  nn = [nn1,nn2,nn3]
  ymax = MAX(zz/xx)
  if not(keyword_set(zmax)) then zmax = alog10(MAX(nn))
  if not(keyword_set(zmin)) then zmin = MAX([alog10(MIN(nn)),zmax-15.0])
  ilev = 80
  lev=dblarr(ilev+1)
  col=intarr(ilev+1)      
  colmin=2                    ; use 2/253 for rainbow colors
  colmax=253
  for i=0,ilev do begin
    lev(i)=zmin+(zmax-zmin)*i/ilev
    col(i)=fix(colmin+(colmax-colmin)*(lev(i)-zmin)/(zmax-zmin))
  endfor
  nplot = alog10(nn1)
  ind=WHERE(nplot LT zmin+0.01,count)
  if (count GT 0) then nplot(ind) = zmin+0.01 
  contour,nplot,xx,zz/xx,/xlog,thick=3,$
        xrange=[xmin,xmax],yrange=[0.0,ymax],xminor=9,yminor=4,xticklen=0.05,$
        ymargin=[4,0],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        levels=lev,c_colors=col,/fill, $
        XTICKNAME=[" "," "," "," "," "," "," "],ytitle="z/r",position=[0.10,0.70,0.99,0.99]
  ;plotTg = (molname EQ "H2" OR ABS(lam0-6.300304E-01) LT 0.0001) 
  if (plotTg) then begin
    contour,Tgas,xx,zz/xx,/xlog,thick=3,/noerase,$
        xrange=[xmin,xmax],yrange=[0.0,ymax],xminor=9,yminor=4,xticklen=0.05,$
        ymargin=[4,0],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        levels=[500,1000],c_annotation=['500K','1000K'], $
        c_colors=white,XTICKNAME=[" "," "," "," "," "," "," "],position=[0.10,0.70,0.99,0.99]
  endif   
  xplot = xx(*,1)
  zplot = xplot
  x15=interpol(xx(*,1),Fcum,15.0)
  x85=interpol(xx(*,1),Fcum,85.0)
  xxx=[x15,x15]
  yyy=[0.0,ymax*2.76]
  ;oplot,xxx,yyy,linestyle=2,/noclip
  xxx=[x85,x85]
  ;oplot,xxx,yyy,linestyle=2,/noclip
  for ix=0,Nx-1 do begin
    zplot(ix) = zz(ix,izmax(ix)-1)  
  endfor
  if (LineFileVersion EQ 0) then begin
    oplot,xplot,zplot/xplot,thick=7,color=black
  endif else begin 
    index=where(xplot GE x15 AND xplot LE x85, count)
    if (count GT 0) then begin
      xx1=[x15,xplot(index),x85]
    endif else begin    
      xx1=[x15,x85]
    endelse
    zz1=interpol(z15/AU/xplot,xplot,xx1)
    zz2=interpol(z85/AU/xplot,xplot,xx1)
    xxx=[xx1,xx1]
    yyy=[zz1,zz2]
    Nxxx=N_ELEMENTS(xx1)
    for ix=0,Nxxx-1 do begin
      iix = 2*Nxxx-1-ix  
      xxx(iix) = xx1(ix)
      yyy(iix) = zz2(ix)
    endfor 
    ;polyfill,xxx,yyy,color=white,noclip=0
    ;oplot,xplot,zplot/xplot,thick=7,color=black,linestyle=2
    oplot,xplot,z15/AU/xplot,thick=1,color=black,linestyle=2
    oplot,xplot,z85/AU/xplot,thick=1,color=black,linestyle=2
    oplot,[xxx,xxx(0)],[yyy,yyy(0)],thick=7,color=black
  endelse
  ;print,"--> "+spname+" "+STRTRIM(STRING(format="(F10.2)",lamsave),2)+": "+$
  ;      '70% of the line flux originate from ['+$
  ;      STRTRIM(STRING(format='(F8.3)',x15),2)+","+$
  ;      STRTRIM(STRING(format='(F7.2)',x85),2)+"] AU"
  text = "log n!L"+colname1+" !N[cm!U-3!N]"
  ;if (molname EQ "H2") then text = "log H!L2!Nform [s!U-1!Ncm!U-3!N]"
  SKALA2, ilev+1,lev,col,text,[0.12,0.94,0.4,0.97],1.7
  xyouts,0.6,0.92,/normal,$
        "!7F!Lline!N = "+STRTRIM(STRING(format="(E13.2)",Fsave),2)+" W/m!U2!N"

  ; --- 2. ---
  nplot = alog10(nn2)
  ind=WHERE(nplot LT zmin+0.01,count)
  if (count GT 0) then nplot(ind) = zmin+0.01 
  contour,nplot,xx,zz/xx,/xlog,thick=3,$
        xrange=[xmin,xmax],yrange=[0.0,ymax],xminor=9,yminor=4,xticklen=0.05,$
        ymargin=[4,0],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        levels=lev,c_colors=col,/fill, $
        XTICKNAME=[" "," "," "," "," "," "," "],ytitle="z/r",position=[0.10,0.40,0.99,0.68]
  plotTg = (molname EQ "H2" OR ABS(lam0-6.300304E-01) LT 0.0001) 
  if (plotTg) then begin
    contour,Tgas,xx,zz/xx,/xlog,thick=3,/noerase,$
        xrange=[xmin,xmax],yrange=[0.0,ymax],xminor=9,yminor=4,xticklen=0.05,$
        ymargin=[4,0],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        levels=[1000,5000],c_annotation=['1000K','5000K'], $
        XTICKNAME=[" "," "," "," "," "," "," "],ytitle="z/r" 
  endif   
  xplot = xx(*,1)
  zplot = xplot
  x15=interpol(xx(*,1),Fcum,15.0)
  x85=interpol(xx(*,1),Fcum,85.0)
  xxx=[x15,x15]
  yyy=[0.0,ymax*2.76]
  ;oplot,xxx,yyy,linestyle=2,/noclip
  xxx=[x85,x85]
  ;oplot,xxx,yyy,linestyle=2,/noclip
  for ix=0,Nx-1 do begin
    zplot(ix) = zz(ix,izmax(ix)-1)  
  endfor
  if (LineFileVersion EQ 0) then begin
    oplot,xplot,zplot/xplot,thick=7,color=black
  endif else begin 
    index=where(xplot GE x15 AND xplot LE x85, count)
    if (count GT 0) then begin
      xx1=[x15,xplot(index),x85]
    endif else begin    
      xx1=[x15,x85]
    endelse
    zz1=interpol(z15/AU/xplot,xplot,xx1)
    zz2=interpol(z85/AU/xplot,xplot,xx1)
    xxx=[xx1,xx1]
    yyy=[zz1,zz2]
    Nxxx=N_ELEMENTS(xx1)
    for ix=0,Nxxx-1 do begin
      iix = 2*Nxxx-1-ix  
      xxx(iix) = xx1(ix)
      yyy(iix) = zz2(ix)
    endfor 
    ;polyfill,xxx,yyy,color=white,noclip=0
    ;oplot,xplot,zplot/xplot,thick=7,color=black,linestyle=2
    oplot,xplot,z15/AU/xplot,thick=1,color=black,linestyle=2
    oplot,xplot,z85/AU/xplot,thick=1,color=black,linestyle=2
    oplot,[xxx,xxx(0)],[yyy,yyy(0)],thick=7,color=black
  endelse
  ;print,"--> "+spname+" "+STRTRIM(STRING(format="(F10.2)",lamsave),2)+": "+$
  ;      '70% of the line flux originate from ['+$
  ;      STRTRIM(STRING(format='(F8.3)',x15),2)+","+$
  ;      STRTRIM(STRING(format='(F7.2)',x85),2)+"] AU"
  text = "log n!L"+colname2+" !N[cm!U-3!N]"
  ;if (molname EQ "H2") then text = "log H!L2!Nform [s!U-1!Ncm!U-3!N]"
  SKALA2, ilev+1,lev,col,text,[0.12,0.63,0.4,0.66],1.7

  ; --- 3. log(n)-contour and height of cell with max. contribution ---
  nplot = alog10(nn3)
  ind=WHERE(nplot LT zmin+0.01,count)
  if (count GT 0) then nplot(ind) = zmin+0.01 
  contour,nplot,xx,zz/xx,/xlog,thick=3,$
        xrange=[xmin,xmax],yrange=[0.0,ymax],xminor=9,yminor=4,xticklen=0.05,$
        ymargin=[4,0],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        levels=lev,c_colors=col,/fill, $
        xtitle="r [au]",ytitle="z/r",position=[0.10,0.10,0.99,0.38]
  plotTg = (molname EQ "H2" OR ABS(lam0-6.300304E-01) LT 0.0001) 
  if (plotTg) then begin
    contour,Tgas,xx,zz/xx,/xlog,thick=3,/noerase,$
        xrange=[xmin,xmax],yrange=[0.0,ymax],xminor=9,yminor=4,xticklen=0.05,$
        ymargin=[4,0],xmargin=[5,0],charsize=2.0,xcharsize=1.3,ycharsize=1.3,$
        levels=[1000,5000],c_annotation=['1000K','5000K'], $
        c_colors=red,xtitle="r [au]",ytitle="z/r" 
  endif   
  xplot = xx(*,1)
  zplot = xplot
  x15=interpol(xx(*,1),Fcum,15.0)
  x85=interpol(xx(*,1),Fcum,85.0)
  xxx=[x15,x15]
  yyy=[0.0,ymax*2.76]
  ;oplot,xxx,yyy,linestyle=2,/noclip
  xxx=[x85,x85]
  ;oplot,xxx,yyy,linestyle=2,/noclip
  for ix=0,Nx-1 do begin
    zplot(ix) = zz(ix,izmax(ix)-1)  
  endfor
  if (LineFileVersion EQ 0) then begin
    oplot,xplot,zplot/xplot,thick=7,color=black
  endif else begin 
    index=where(xplot GE x15 AND xplot LE x85, count)
    if (count GT 0) then begin
      xx1=[x15,xplot(index),x85]
    endif else begin    
      xx1=[x15,x85]
    endelse
    zz1=interpol(z15/AU/xplot,xplot,xx1)
    zz2=interpol(z85/AU/xplot,xplot,xx1)
    xxx=[xx1,xx1]
    yyy=[zz1,zz2]
    Nxxx=N_ELEMENTS(xx1)
    for ix=0,Nxxx-1 do begin
      iix = 2*Nxxx-1-ix  
      xxx(iix) = xx1(ix)
      yyy(iix) = zz2(ix)
    endfor 
    ;polyfill,xxx,yyy,color=white,noclip=0
    ;oplot,xplot,zplot/xplot,thick=7,color=black,linestyle=2
    oplot,xplot,z15/AU/xplot,thick=1,color=black,linestyle=2
    oplot,xplot,z85/AU/xplot,thick=1,color=black,linestyle=2
    oplot,[xxx,xxx(0)],[yyy,yyy(0)],thick=7,color=black
  endelse
  ;print,"--> "+spname+" "+STRTRIM(STRING(format="(F10.2)",lamsave),2)+": "+$
  ;      '70% of the line flux originate from ['+$
  ;      STRTRIM(STRING(format='(F8.3)',x15),2)+","+$
  ;      STRTRIM(STRING(format='(F7.2)',x85),2)+"] AU"
  text = "log n!L"+colname3+" !N[cm!U-3!N]"
  ;if (molname EQ "H2") then text = "log H!L2!Nform [s!U-1!Ncm!U-3!N]"
  SKALA2, ilev+1,lev,col,text,[0.12,0.33,0.4,0.36],1.7
  lamtext=STRING(format="(F10.2)",lamsave)
  if (lamsave LT 10.0) then lamtext=STRING(format="(F10.3)",lamsave)
  if (lamsave LT 1.0) then lamtext=STRING(format="(F10.4)",lamsave)
  xyouts,0.6,0.12,spname+" "+STRTRIM(lamtext,2)+"!9m!7m",/norm
  !P.MULTI=0
  !P.REGION=0
END


;--------------------------------------------------------
PRO PLOT_BEAM,Rmax,x0,y0,bmin,bmaj,PA    ; [au]
;--------------------------------------------------------
  xx = dblarr(51,51)
  yy = dblarr(51,51)
  zz = dblarr(51,51)
  xmin = x0-2*bmaj
  xmax = x0+2*bmaj
  ymin = y0-2*bmaj
  ymax = y0+2*bmaj
  cc = 4.0*ALOG(2.0)        ; exp(-cc*(0.5*FWHM)^2/FWHM^2) != 0.5
  pi = acos(-1.0d0)       
  cosPA = COS(PA*pi/180.d0)
  sinPA = SIN(PA*pi/180.d0)
  for i=0,50 do begin
    for j=0,50 do begin
      xx(i,j) = xmin + i/50.0*(xmax-xmin) 
      yy(i,j) = ymin + j/50.0*(ymax-ymin)
      xrot = (xx(i,j)-x0)*cosPA - (yy(i,j)-y0)*sinPA  
      yrot = (xx(i,j)-x0)*sinPA + (yy(i,j)-y0)*cosPA  
      zz(i,j) = exp(-cc*(xrot/bmin)^2 -cc*(yrot/bmaj)^2) 
    endfor
  endfor  
  contour,zz,xx,yy,/overplot,c_color=255,levels=[0.15,0.5],thick=2,$
          c_annotation=['15%','50%'],c_charsize=0.9
  if (bmaj GT 0.2*Rmax) then begin
    xyouts,x0,y0+5,"PSF",color=255,charthick=2,charsize=1.0,$
          alignment=0.5,orientation=-PA-90.0
  endif else begin
    xyouts,x0,y0+0.8*bmaj,"PSF",color=255,charthick=2,charsize=1.0,$
          alignment=0.5,orientation=0.0
  endelse  
END

;--------------------------------------------------------------
PRO PLOT_IMAGE,folder,lam_image,Rstar,Rin,Rout,zmax,dist,FluxJy
;--------------------------------------------------------------
  pi           = acos(-1.0d0)            ; just pi
  degree       = pi/180.d0               ; one degree in rad
  arcsec       = degree/3600.d0          ; one arc second in rad
  AU           = 1.495978700D+13         ; 1 astronomical unit in cm
  Rsun         = 6.959900000D+10         ; solar radius
  pc           = 3.085680250D+18         ; 1 parsec in cm
  Jansky       = 1.D-23                  ; 1 Jy in [erg/cm^2/s/Hz]
  arcsec_to_AU = arcsec*dist/AU          ; length [au] corresponding to 1"
  line="blasel"
  incl=-1.0
  Nr=0
  Nth=0
  NLAM=0
  openr,1,folder+"/image.out"
  readf,1,incl
  readf,1,Nr,Nth
  readf,1,NLAM
  lamb  = fltarr(NLAM) 
  Istar = fltarr(NLAM)
  NLAM  = min([995,NLAM])
  Iread = dblarr(NLAM)
  Inu   = fltarr(Nr+1,Nth+1,NLAM) 
  readf,1,lamb
  readf,1,Istar
  readf,1,line
  xp = fltarr(Nr+1,Nth+1) 
  yp = fltarr(Nr+1,Nth+1) 
  x = 1.0
  y = 1.0
  ix = 0
  iy = 0
  i = 0L
  while (i LE 1L*Nr*Nth-1L ) do begin
    line_old=line 
    readf,1,line
    if (strlen(line) LT NLAM*10) then readf,1,line
    reads,line,ix,iy,x,y,Iread
    xp(ix-1,iy-1) = x
    yp(ix-1,iy-1) = y
    Inu(ix-1,iy-1,*) = Iread(*)
    i = i+1
  endwhile
  close,1
  ilam = NLAM/4
  Imax = max(Inu(Nr/10:Nr-1,*,ilam))
  for i=1,Nr-2 do begin         ; check spikes
    for j=1,Nth-2 do begin         
      Inu1 = Inu(i-1,j,ilam)
      Inu2 = Inu(i+1,j,ilam)
      Inu3 = Inu(i,j-1,ilam)
      Inu4 = Inu(i,j+1,ilam)
      Ireg1 = max([Inu1,Inu2,Inu3,Inu4]) 
      Ireg2 = min([Inu1,Inu2,Inu3,Inu4]) 
      if ((Inu(i,j,ilam) LT 0.1*Ireg2) AND $
          (Ireg1 GT 1.E-10*Imax)) then begin
        print,"*** image ray ",i+1,j+1," possibly faulty"  
        print,Inu(i,j,ilam),Ireg1,Ireg2,Imax
      endif
    endfor
  endfor
  for i=0,Nr-1 do begin         ; close rings
    xp(i,Nth) = xp(i,0)
    yp(i,Nth) = yp(i,0)
    Inu(i,Nth,*) = Inu(i,0,*) 
  endfor  
  for j=0,Nth do begin          ; add outside points
    xp(Nr,j) = xp(Nr-1,j)*2.0
    yp(Nr,j) = yp(Nr-1,j)*2.0
    Inu(Nr,j,*) = Inu(Nr-1,j,*) 
  endfor  
  rmean = sqrt(xp(*,0)^2+yp(*,0)^2)
  for j=1,Nth-1 do begin         
    rmean = rmean + sqrt(xp(*,j)^2+yp(*,j)^2)
  endfor
  rmean = rmean/Nth
  rrbound = dblarr(Nr+1)
  thbound = dblarr(Nth+1)
  rrbound(0) = 0.d0
  for i=1,Nr  do rrbound(i) = 2*rmean(i-1)-rrbound(i-1) ; r(i-1)+2(rm-r(i-1))
  dA = dblarr(Nr,Nth)
  for i=0,Nr-1 do begin
    Aring = pi*(rrbound(i+1)^2-rrbound(i)^2)
    for j=0,Nth-1 do begin
      dA(i,j) = Aring/Nth 
    endfor
  endfor
  Rmax1=sqrt(Rout^2+zmax^2)
  beta=atan(zmax/Rout)
  Rmax2=cos(incl/180.0*!PI-beta)*Rmax1
  Rmax3=sqrt(Rout^2+(zmax*sin(incl/180.0*pi))^2)
  Rmax0=max([Rmax2,Rmax3])    
  ;print,incl,Rmax1,Rmax2,Rmax3,Rmax0
  myloadct, rred,ggreen,bblue
  rr = sqrt(xp^2+yp^2)
  logImage = (1 EQ 1)           ; you want linear of log image?
  ind = WHERE(lamb GT 0.2,count)
  ind = WHERE((lamb GT 1.6) AND (lamb LE 3000.0),count)
  ilammin  = min(ind)
  ilammax  = max(ind)
  STEP = 1
  if (ilammax-ilammin gt 40) then STEP=(ilammax-ilammin+40)/40
  for ilam=ilammin,ilammax,STEP do begin
    print,"plotting image lam[mic]=",lamb[ilam]," Jnu[Jy]=",FluxJy(ilam)
    fdisk = 0.d0
    fstar = 0.d0
    IISM  = Inu(Nr,0,ilam)
    fluxr = 0.0*Inu(*,0,ilam) 
    fcumm = fluxr
    istar = MAX(WHERE(rmean LT 1.5*Rstar*Rsun/AU))
    for i=0,Nr-1 do begin
      for j=0,Nth-1 do begin
        fluxr(i) = fluxr(i) + max([0,Inu(i,j,ilam)-IISM])*dA(i,j)  
      endfor
      if (i GT istar) then begin
        fdisk = fdisk + fluxr(i)
      endif else begin
        fstar = fstar + fluxr(i)
      endelse  
      fcumm(i)=fdisk
    endfor
    fcumm = fcumm/fdisk      ; cummulative flux without the star
    idum = WHERE(fcumm GT 0.0 AND fcumm LE 1.0)
    rtmp = rmean(idum)
    ftmp = fcumm(idum)
    R15 = INTERPOL(rtmp,ftmp,0.15)
    R25 = INTERPOL(rtmp,ftmp,0.25)
    R50 = INTERPOL(rtmp,ftmp,0.5)
    R70 = INTERPOL(rtmp,ftmp,0.7)
    R80 = INTERPOL(rtmp,ftmp,0.8)
    R90 = INTERPOL(rtmp,ftmp,0.9)
    R95 = INTERPOL(rtmp,ftmp,0.95)
    R98 = INTERPOL(rtmp,ftmp,0.98)
    Iplot = Inu(*,*,ilam)                    ; the image at this mavelength
    Iback = Inu(Nr,1,ilam)                   ; the background
    ind   = WHERE(rr GT 1.5*Rstar*Rsun/AU)
    Imax1 = max(Iplot(WHERE(rr LT Rstar)))   ; maximum across the star
    Imax2 = max(Iplot(ind))                  ; maximum across the disk
    Rmin  = 1.5*Rstar*Rsun/AU  ; was 0.0
    for it=1,10 do begin
      Imax = max(Iplot(WHERE(rr GT Rmin)))   ; maximum
      Imax = Imax-Iback                      ; subtract background
      Imin = 0.005*Imax                      ; visible minimum
      Rmax = max(rr(WHERE(Iplot-Iback GT Imin)))   ; image size
      Rmax = max([Rmax,7.0*Rstar*Rsun/AU])   ; at least 7 radii
      Rmax = min([Rmax,Rmax0])               ; biggest square in circular image
      Rmin = 0.5*(Rmin+Rmax*0.03)            ; we won't see those tiny
                                             ; regions in the image anyway!
      Rmin = max([Rmin,1.5*Rstar*Rsun/AU])
      Rmax = max([Rmax,R90])
      ;print,it,Imax,Rmin,Rmax
    endfor
    Rmax = Rmax*1.2
    Imax = Imax+Iback
    Imin = Imin+Iback
    if (logImage) then begin
      IImax = max(Iplot(WHERE(rr GT Rmin)))
      IImin = max(Iplot(WHERE(rr GT Rmax)))*0.3
      ;if (IImin LT IImax*1.E-4) then begin
      ;  IImin = IImax*1.E-5
      ;  Rmax  = max(rr(WHERE(Iplot-Iback GT IImin-Iback)))
      ;endif
      Imax  = alog10(IImax)
      Imin  = alog10(IImin)
      ;Imin  = MAX([Imin,Imax-4])
      ;IImin = 10.0^Imin
      Imax  = MIN([Imax,Imin+3])
      IImax = 10.0^Imax
    endif else begin
      Imin  = 0.0 
      IImin = Imin 
      IImax = Imax 
    endelse
    Rmax = Rmax*1.2
    print,"fstar,fdisk=",(fstar)*AU^2/dist^2/Jansky,(fdisk)*AU^2/dist^2/Jansky
    print," flux check:",(fstar+fdisk)*AU^2/dist^2/Jansky,FluxJy(ilam)
    print,format='(" size (50% 80% 90% 95% 98%) = ",5(F9.3))',$
          R50,R80,R90,R95,R98
    angle = 2.d0*Rmax/arcsec_to_AU  ; image size in arcsec 
    bem4  = STRTRIM(STRING(format='(F5.2)',angle),2)+""" x "$
          + STRTRIM(STRING(format='(F5.2)',angle),2)+""""
    if (angle LT 0.1) then begin
      bem4  = STRTRIM(STRING(format='(F5.3)',angle),2)+""" x "$
            + STRTRIM(STRING(format='(F5.3)',angle),2)+""""
    endif  
    if (angle LT 0.01) then begin
      bem4  = STRTRIM(STRING(format='(F6.4)',angle),2)+""" x "$
            + STRTRIM(STRING(format='(F6.4)',angle),2)+""""
    endif
    xmin=-Rmax
    xmax= Rmax
    ymin=-Rmax
    ymax= Rmax
    for i=0,Nr do begin
      for j=0,Nth do begin
        Iplot(i,j) = max([Iplot(i,j),IImin])
        Iplot(i,j) = min([Iplot(i,j),IImax])
      endfor
    endfor
    ilev=120
    lev=dblarr(ilev+1)
    col=intarr(ilev+1)      
    colmin=2                    ; use 2/253 for rainbow colors
    colmax=253
    for i=0,ilev do begin
      lev(i)=Imin+(Imax-Imin)*i/ilev
      col(i)=fix(colmin+(colmax-colmin)*(lev(i)-Imin)/(Imax-Imin))
    endfor
    if (logImage) then begin
      contour,alog10(Iplot),xp,yp,$
          xrange=[xmin,xmax],yrange=[ymin,ymax], $
          levels=lev,c_colors=col,/fill,position=[0.13,0.14,0.83,0.88], $
          xtitle="x [au]",ytitle="y [au]"
    endif else begin
      contour,Iplot,xp,yp,$
          xrange=[xmin,xmax],yrange=[ymin,ymax], $
          levels=lev,c_colors=col,/fill,position=[0.13,0.14,0.83,0.88], $
          xtitle="x [au]",ytitle="y [au]"
    endelse
    ;------- overplot rays? ---------
    ;usersym, [1,0,-1,0,1], [0,1,0,-1,0] 
    ;oplot,xp,yp,PSYM=8,SYMSIZE=0.01,THICK=0.01,color=255
    ;------- annotations ------------
    bem1="!9l!7 = "+STRTRIM(STRING(format="(f10.2)",lamb(ilam)),2)$
        +"!L !N!9m!7m"
    bem2="inclination = "+STRTRIM(STRING(format="(i3)",incl+0.5),2)+"!Uo!N"
    bem3="max I!L*!N / I!Ldisk!N = " $
        + STRTRIM(STRING(format="(E11.1)",Imax1),2) + " / " $
        + STRTRIM(STRING(format="(E11.1)",Imax2),2)
    xyouts,0.0,0.9*Rmax,bem1,color=255,ALIGNMENT=0.5,CHARSIZE=1.4,CHARTHICK=3.0
    xyouts,0.0,0.8*Rmax,bem2,color=255,ALIGNMENT=0.5,CHARSIZE=1.4,CHARTHICK=3.0
    xyouts,0.95*Rmax,-1.20*Rmax,bem3,color=0,ALIGNMENT=0.5,CHARSIZE=1.0
    xyouts,0.0,-0.95*Rmax,bem4,color=255,ALIGNMENT=0.5,$
           CHARSIZE=1.4,CHARTHICK=3.0
    if (logImage) then begin
      label="log I!L!9n!7!N [erg/s/cm!U2!N/Hz/sr]"
    endif else begin
      iscale= floor(alog10(Imax)-0.5)
      scale = 10.0^iscale
      label = "I!L!9n!7!N [10!U "+strtrim(string(iscale),2)+"!Nerg/s/cm!U2!N/Hz/sr]"
      lev = lev/scale
    endelse  
    SKALA_VERT, ilev+1, lev, col, label, [0.91,0.2,0.94,0.8]
  endfor  

  openr,1,"image.in",ERROR = err
  if (err EQ 0) then begin
    line = ' '
    Nimage = 0
    readf,1,line 
    readf,1,line 
    readf,1,Nimage
    lread = fltarr(Nimage)
    xread = fltarr(Nimage)
    yread = fltarr(Nimage)
    Pread = fltarr(Nimage)
    Cread = fltarr(Nimage)
    Ifile = strarr(Nimage)
    Rin_valid  = fltarr(Nimage)
    Rout_valid = fltarr(Nimage)
    readf,1,line 
    readf,1,lread
    readf,1,xread
    readf,1,yread
    readf,1,Pread
    readf,1,Cread
    readf,1,line
    readf,1,line
    readf,1,Rin_valid
    readf,1,Rout_valid
    for im=1,Nimage do readf,1,line    ; filter
    for im=0,Nimage-1 do begin
      readf,1,line
      i=strpos(line,".dat")
      Ifile(im) = "nodata"
      if (i GT 0) then Ifile(im)=strmid(line,0,i+4)
    endfor  
    close,1
    for im=0,Nimage-1 do begin
      myloadct, rred,ggreen,bblue
      xFWHM = xread(im)*arcsec_to_AU
      yFWHM = yread(im)*arcsec_to_AU
      PA    = Pread(im)
      filename="/image_conv_"+STRTRIM(STRING(format='(I2.2)',im+1),2)+".out"
      openr,1,folder+filename
      readf,1,Nr,Nth
      readf,1,lambda_image
      readf,1,xmaxi,ymaxi
      Inu   = fltarr(Nr+1,Nth+1) 
      Iconv = fltarr(Nr+1,Nth+1) 
      readf,1,line
      xp = fltarr(Nr+1,Nth+1) 
      yp = fltarr(Nr+1,Nth+1) 
      i = 0L
      while (i LE 1L*Nr*Nth-1L) do begin
        readf,1,ix,iy,x,y,Iread1,Iread2
        xp(ix-1,iy-1) = x
        yp(ix-1,iy-1) = y
        Inu  (ix-1,iy-1) = Iread1
        Iconv(ix-1,iy-1) = Iread2
        i = i+1
      endwhile
      close,1
      for i=0,Nr-1 do begin         ; close rings
        xp(i,Nth) = xp(i,0)
        yp(i,Nth) = yp(i,0)
        Inu(i,Nth) = Inu(i,0) 
        Iconv(i,Nth) = Iconv(i,0) 
      endfor  
      for j=0,Nth do begin          ; add outside points
        xp(Nr,j) = xp(Nr-1,j)*2.0
        yp(Nr,j) = yp(Nr-1,j)*2.0
        Inu(Nr,j) = Inu(Nr-1,j) 
        Iconv(Nr,j) = Iconv(Nr-1,j) 
      endfor  
      rmin  = Rin_valid(im)
      Rzoom = Rout_valid(im)
      file  = Ifile(im)
      openr,1,file,ERROR = err
      if (err EQ 0) then begin
        close,1
        readcol,file,robs,Iobs,Ierr,/silent
        rmin  = 0.8*min(robs)
        Rzoom = 1.2*max(robs)
      endif  
      rr    = sqrt(xp^2+yp^2)
      ind   = WHERE(rr GT Rin AND rr LT Rout)
      Imax1=alog10(max(Inu(0:1,*)))     ; the star
      Imax2=alog10(max(Iconv(ind)))     ; the disk
      ;Imax=max([Imax1-8.0,Imax2+0.2])
      ;Imin=alog10(min(Inu(ind))) 
      ;Imin=max([Imin-0.5,Imax-10.0])
      Imax=Imax2+0.2
      Imin=Imax-3.0
      IImin=10.0^Imin
      IImax=10.0^Imax
      ind = WHERE(rr GT Rout/20.0 AND rr LT Rout)
      IImin=0.0
      IImax=max(Inu(ind))
      for i=0,ilev do begin
        lev(i)=IImin+(IImax-IImin)*i/ilev
        col(i)=fix(colmin+(colmax-colmin)*(lev(i)-IImin)/(IImax-IImin))
      endfor
      ;for i=0,ilev do begin
      ;  lev(i)=Imin+(Imax-Imin)*i/ilev
      ;  col(i)=fix(colmin+(colmax-colmin)*(lev(i)-Imin)/(Imax-Imin))
      ;endfor
      Iplot = Inu
      for i=0,Nr do begin
        for j=0,Nth do begin
          Iplot(i,j) = max([Iplot(i,j),IImin])
          Iplot(i,j) = min([Iplot(i,j),IImax])
        endfor
      endfor
      bem1="!9l!7 = "+STRTRIM(STRING(format="(f10.2)",lambda_image),2)$
          +"!L !N!9m!7m"
      angle = 2.d0*Rzoom/arcsec_to_AU  ; image size in arcsec 
      bem4 = STRTRIM(STRING(format='(F5.2)',angle),2)+""" x "$
           + STRTRIM(STRING(format='(F5.2)',angle),2)+""""
      contour,Iplot,xp,yp,$
          xrange=[-Rzoom,Rzoom],yrange=[-Rzoom,Rzoom], $
          levels=lev,c_colors=col,/fill,position=[0.13,0.14,0.83,0.88], $
          xtitle="x [au]",ytitle="y [au]"
      ;contour,alog10(Iplot),xp,yp,$
      ;    xrange=[-Rzoom,Rzoom],yrange=[-Rzoom,Rzoom], $
      ;    levels=lev,c_colors=col,/fill,position=[0.13,0.14,0.83,0.88], $
      ;    xtitle="x [au]",ytitle="y [au]"
      xyouts,0.0,0.9*Rzoom,bem1,color=255,ALIGNMENT=0.5,CHARSIZE=1.4,$
             CHARTHICK=3.0
      xyouts,0.0,0.8*Rzoom,bem2,color=255,ALIGNMENT=0.5,CHARSIZE=1.4,$
             CHARTHICK=3.0
      xyouts,0.95*Rzoom,-1.20*Rzoom,bem3,color=0,ALIGNMENT=0.5,CHARSIZE=1.0
      xyouts,0.0,-0.95*Rzoom,bem4,color=255,ALIGNMENT=0.5,$
             CHARSIZE=1.4,CHARTHICK=3.0
      iscale= floor(alog10(IImax)-0.5)
      scale = 10.0^iscale
      label = "I!L!9n!7!N [10!U "+strtrim(string(iscale),2)+"!Nerg/s/cm!U2!N/Hz/sr]"
      SKALA_VERT, ilev+1, lev/scale, col, label, [0.91,0.2,0.94,0.8]
      ;--- plot convolved image ---
      Iplot = Iconv
      IImin=0.0
      IImax=max(Iconv)*0.95
      for i=0,Nr do begin
        for j=0,Nth do begin
          Iplot(i,j) = max([Iplot(i,j),IImin])
          Iplot(i,j) = min([Iplot(i,j),IImax])
        endfor
      endfor
      for i=0,ilev do begin
        lev(i)=IImin+(IImax-IImin)*i/ilev
        col(i)=fix(colmin+(colmax-colmin)*(lev(i)-IImin)/(IImax-IImin))
      endfor
      contour,Iplot,xp,yp,$
          xrange=[-Rzoom,Rzoom],yrange=[-Rzoom,Rzoom], $
          levels=lev,c_colors=col,/fill,position=[0.13,0.14,0.83,0.88], $
          xtitle="x [au]",ytitle="y [au]"
      ;contour,alog10(Iplot),xp,yp,$
      ;    xrange=[-Rzoom,Rzoom],yrange=[-Rzoom,Rzoom], $
      ;    levels=lev,c_colors=col,/fill,position=[0.13,0.14,0.83,0.88], $
      ;    xtitle="x [au]",ytitle="y [au]"
      ;contour,Iconv,xp,yp,/overplot,c_colors=[255,255],$
      ;    levels=max(Iconv)*[0.15,0.5],thick=2,c_annotation=['15%','50%']
      xyouts,0.0,0.9*Rzoom,bem1,color=255,ALIGNMENT=0.5,CHARSIZE=1.4,$
             CHARTHICK=3.0
      xyouts,0.0,0.8*Rzoom,bem2,color=255,ALIGNMENT=0.5,CHARSIZE=1.4,$
             CHARTHICK=3.0
      xyouts,0.95*Rzoom,-1.20*Rzoom,bem3,color=0,ALIGNMENT=0.5,CHARSIZE=1.0
      xyouts,0.0,-0.95*Rzoom,bem4,color=255,ALIGNMENT=0.5,$
             CHARSIZE=1.4,CHARTHICK=3.0
      del = max([xFWHM,yFWHM])*0.55
      PLOT_BEAM,Rzoom,-0.85*Rzoom+del,-0.85*Rzoom+del,xFWHM,yFWHM,PA
      iscale= floor(alog10(IImax)-0.5)
      scale = 10.0^iscale
      label = "I!L!9n!7!N [10!U "+strtrim(string(iscale),2)+"!Nerg/s/cm!U2!N/Hz/sr]"
      SKALA_VERT, ilev+1, lev/scale, col, label, [0.91,0.2,0.94,0.8]

      ;--- plot lin-log intensity profiles ---
      loadct,39,/silent 
      black   = 0
      red     = 250
      yellow  = 195
      green   = 160
      cyan    = 100
      blue    = 70
      magenta = 40
      Imean  = Inu(*,0)
      Imeanc = Iconv(*,0)
      IISM = Inu(Nr,0)
      for j=1,Nth-1 do begin         
        Imean  = Imean  + Inu(*,j)-IISM
        Imeanc = Imeanc + Iconv(*,j)-IISM
      endfor
      Imean = Imean/Nth      ; straight azimuthal mean
      Imeanc= Imeanc/Nth     ; straight azimuthal mean    
      ind   = WHERE(rmean GT rmin AND rmean LT Rout)
      Imin  = min(alog10(Imean(ind)))
      Imax  = max(alog10(Imean(ind)))
      Imin  = max([Imin,Imax-4.0])
      dd    = 0.05*(Imax-Imin)
      Imin  = Imin-dd
      Imax  = Imax+dd
      pos = [0.15,0.15,0.9,0.9]
      titel ="!9l!7 = "+STRTRIM(STRING(format="(f10.2)",lambda_image),2)$
            +"!L !N!9m!7m"
      plot,rmean(ind),alog10(Imean(ind)),$
        xrange=[0,Rzoom],yrange=[Imin,Imax],position=pos,$
        xtitle="!7r [au]",$
        ytitle="!7log <I!L!9n!7!N> [erg/s/cm!U2!N/Hz/sr]"
      xyouts,0.55,0.83,titel,/normal,$
             CHARTHICK=3,CHARSIZE=1.4,ALIGNMENT=0.5
      ;oplot,rmean(ind),alog10(Imean(ind)),psym=6,symsize=0.35
      file  = Ifile(im)
      j=STRPOS(file,".dat") 
      file2 = STRMID(file,0,j)+".out"
      openr,1,file2,ERROR = err1
      if (err1 EQ 0) then begin
        readf,1,format='(19x,F,F)',xmaxi,ymaxi
        close,1        
        readcol,file2,rmod,Imod,/silent
        oplot,rmod,alog10(Imod),color=yellow,thick=2
      endif  
      oplot,rmean(ind),alog10(Imeanc(ind)),linestyle=2,thick=5,color=blue
      openr,1,file,ERROR = err2
      if (err2 EQ 0) then begin
        close,1
        readcol,file,robs,Iobs,Ierr,/silent
        ind   = WHERE(robs GT rmin AND robs LT Rzoom)
        lIerr = alog10(Iobs+Ierr)-alog10(Iobs)
        ;oplots,robs(ind),alog10(Iobs(ind)),psym=6,symsize=0.5,color=150
        oploterror,robs(ind),alog10(Iobs(ind)),0.0*robs(ind),lIerr(ind),$
                 errcolor=red,psym=6,symsize=0.5,color=red
      endif   
      Nbem=3
      bcol=intarr(Nbem)
      blin=intarr(Nbem)
      bthi=intarr(Nbem)
      bbem=strarr(Nbem)
      bcol(0)=black & blin(0)=0 & bthi(0)=3 & bbem(0)="model profile"
      bcol(1)=blue  & blin(1)=2 & bthi(1)=4 & bbem(1)="model after convolution"
      bcol(2)=red   & blin(2)=0 & bthi(2)=3 & bbem(2)="observations"
      x0=0.20
      y0=0.15+Nbem*0.03
      for i=0,Nbem-1 do begin
        plots,[x0,x0+0.05],[y0,y0]-0.03*(i-1),/normal,$
              color=bcol(i),linestyle=blin(i),thick=bthi(i)
        xyouts,x0+0.06,y0-0.03*(i-1)-0.01,bbem(i),/normal
      endfor  
      ;----- lin-lin profile -----
      ind = WHERE(rmean GT rmin AND rmean LT Rout)
      Imax=1.1*max([Imeanc(ind),Imod,Iobs])
      pos = [0.18,0.15,0.9,0.9]
      plot,rmean(ind),Imean(ind),$
        xrange=[0,Rzoom],yrange=[0,Imax],position=pos,$
        xtitle="!7r [au]",$
        ytitle="!7<I!L!9n!7!N> [erg/s/cm!U2!N/Hz/sr]"
      if (err1 EQ 0) then begin
        oplot,rmod,Imod,color=yellow,thick=2
      endif  
      oplot,rmean(ind),Imeanc(ind),linestyle=2,thick=5,color=blue
      if (err2 EQ 0) then begin
        ind = WHERE(robs LT Rzoom)
        oploterror,robs(ind),Iobs(ind),0.0*robs(ind),Ierr(ind),$
                 errcolor=red,psym=6,symsize=0.5,color=red
      endif   
      xyouts,0.55,0.83,titel,/normal,$
             CHARTHICK=3,CHARSIZE=1.4,ALIGNMENT=0.5
      x0=0.50
      y0=0.7
      for i=0,Nbem-1 do begin
        plots,[x0,x0+0.05],[y0,y0]+0.03*(Nbem-1-i),/normal,$
              color=bcol(i),linestyle=blin(i),thick=bthi(i)
        xyouts,x0+0.06,y0+0.03*(Nbem-1-i)-0.01,bbem(i),/normal
      endfor  
    endfor
  endif  
end

;-------------------------------------------------------------------------------
PRO PLOT_LINES, folder,Rstar,Rin,Rout,dist,zmax,xxp,zzp,logI,AV_ver,AV_rad,NX,NZ
;-------------------------------------------------------------------------------
  txt="blasel"
  molname="blasel"
  aline="blasel"
  Nline=0
  Nvelo=0
  Nr=0
  Nth=0
  lwmic=0.d0
  nu=0.d0

  ; ------- read line data -------
  openr,1,folder+"/line_flux.out"
  readf,1,format='(24x,F25)',dist
  readf,1,format='(24x,F25)',incl
  readf,1,format='(25x,I25)',Nline
  readf,1,format='(25x,I25)',Nvelo
  if (Nline EQ 0) then return

  pi     = acos(-1.0d0)           ; just pi
  degree = pi/180.d0              ; one degree in rad
  arc_sec= degree/3600.d0         ; one arc second in rad
  AU     = 1.495978700D+13        ; 1 astronomical unit in cm
  pc     = 3.085680250D+18        ; 1 parsec in cm
  km     = 1.D+5                  ; 1 km/s in [cm/s]
  Wm2    = 1.D+3                  ; 1 W/m^2 in [erg/cm^2/s]
  Jansky = 1.D-23                 ; 1 Jy in [erg/cm^2/s/Hz]
  cl     = 2.99792458D+10         ; speed of light
  mic    = 1.D-4                  ; 1 micron
  GHz    = 1.D+9
  arcsec_to_AU = arc_sec*dist*pc/AU  ; length [au] corresponding to 1"

  ; ------- read LINEobs.dat ------
  Fcen   = intarr(Nline)
  Freso  = dblarr(Nline)
  Favail = intarr(NLine) 
  Iavail = intarr(Nline)
  FveloName = strarr(Nline)
  IprofName = strarr(Nline)
  openr,2,folder+"/LINEobs.dat",ERROR = err
  line="blasel"
  if (err EQ 0) then begin
    readf,2,line
    if (STRPOS(line,"! version") GT 0) then begin
      reads,line,version
      readf,2,line
      readf,2,line
    endif else begin
      version=1
    endelse
    for i=2L,Nline do begin
      if (EOF(2)) then break 
      readf,2,txt
    endfor  
    if (~EOF(2)) then begin
      for i=1,2 do readf,2,txt
      readf,2,aline
      readf,2,txt
      N = STRLEN(aline)
      i = 0
      for j=0,N-1 do begin
        c = STRMID(aline,j,1)
        if (c EQ 'F') then begin
          Fcen(i) = 0
          i = i+1
        endif
        if (c EQ 'T') then begin
          Fcen(i) = 1
          i = i+1
        endif
        if (i EQ Nline-1) then break
      endfor  
      Freso(*) = 1.E+99
      if (version GE 3.0) then begin
        readf,2,Freso
      endif  
      for i=0L,Nline-1 do begin
        readf,2,txt
        if (STRTRIM(txt,2) EQ 'nodata') then begin
          Favail(i) = 0
        endif else begin  
          Favail(i) = 1
          FveloName(i) = txt
        endelse
      endfor
    endif
    if (~EOF(2)) then begin
      for i=1,9 do begin
        readf,2,txt
        if (EOF(2)) then break
      endfor
    endif 
    if (~EOF(2)) then begin 
      for i=0L,Nline-1 do begin
        readf,2,txt
        if (STRTRIM(txt,2) EQ 'nodata') then begin
          Iavail(i) = 0
        endif else begin  
          Iavail(i) = 1
          IprofName(i) = txt
        endelse
      endfor
    endif
    close,2 
  endif

  ; ------- read image data -------
  openr,2,folder+"/line_image.out"
  readf,2,Nr,Nth
  readf,2,txt
  xp = fltarr(Nr+1,Nth+1) 
  yp = fltarr(Nr+1,Nth+1) 
  Iread = fltarr(Nline)
  Iline = fltarr(Nr+1,Nth+1,Nline) 
  Iconv = fltarr(Nr+1,Nth+1,Nline)
  xcenter = fltarr(Nline)
  ycenter = fltarr(Nline)
  convolved = intarr(Nline)
  linfo = strarr(Nline)
  bmin = fltarr(Nline)
  bmaj = fltarr(Nline)
  PA_PSF = fltarr(Nline)
  convolved(*) = 0
  xcenter(*) = 0.0
  ycenter(*) = 0.0
  II = 0.0
  ix = 0
  iy = 0
  xx = 0.0
  yy = 0.0
  for i=0L,Nline-1 do begin
    readf,2,txt
    linfo(i)=txt
  endfor  
  readf,2,txt
  readf,2,txt
  for ir=0,Nr-1 do begin
    for ith=0,Nth-1 do begin
      readf,2,ix,iy,xx,yy,Iread            ; \int (Inu-Icont) dnu
      xp(ir,ith) = xx                      
      yp(ir,ith) = yy
      Iline(ir,ith,*) = Iread(*)
    endfor
  endfor  
  while ~EOF(2) do begin
    Iread = fltarr(2)
    readf,2,format='(23x,I2.2)',lineNo
    convolved(lineNo-1) = 1
    readf,2,format='(23x,F,F)',xcen,ycen
    xcenter(lineNo-1) = xcen
    ycenter(lineNo-1) = ycen
    readf,2,txt
    reads,txt,format='(23x,3(E11.3))',bbx,bby,PA
    bmin(lineNo-1) = bbx
    bmaj(lineNo-1) = bby
    PA_PSF(lineNo-1) = PA
    for ir=0,Nr-1 do begin
      for ith=0,Nth-1 do begin
        readf,2,ix,iy,xx,yy,Iread            
        xp(ir,ith) = xx                      
        yp(ir,ith) = yy
        Iline(ir,ith,lineNo-1) = Iread(0)
        Iconv(ir,ith,lineNo-1) = Iread(1)
      endfor
    endfor  
  endwhile   
  close,2
  ; ------- close image data -------
  for ir=0,Nr-1 do begin          ; close rings
    xp(ir,Nth) = xp(ir,0)
    yp(ir,Nth) = yp(ir,0)
    Iline(ir,Nth,*) = Iline(ir,0,*) 
    Iconv(ir,Nth,*) = Iconv(ir,0,*) 
  endfor  
  for ith=0,Nth do begin          ; add outside points
    xp(Nr,ith) = xp(Nr-1,ith)*2.0
    yp(Nr,ith) = yp(Nr-1,ith)*2.0
    Iline(Nr,ith,*) = Iline(Nr-1,ith,*) 
    Iconv(Nr,ith,*) = Iconv(Nr-1,ith,*) 
  endfor  
  Rmax1=sqrt(Rout^2+zmax^2)
  beta=atan(zmax/Rout)
  Rmax2=cos(incl/180.0*!PI-beta)*Rmax1
  Rmax3=sqrt(Rout^2+(zmax*sin(incl/180.0*!PI))^2)
  Rmax0=max([Rmax2,Rmax3])
  myloadct, rred,ggreen,bblue
  vkms=dblarr(Nvelo-1)
  Fnu=dblarr(Nvelo-1)
  Fconv=dblarr(Nvelo-1)

  ; ---------- having escape probability fluxes? --------------
  Nlines=0L
  openr,5,"FlineEstimates.out",ERROR = err
  if (err EQ 0) then begin
    print
    print,"reading FlineEstimates.out to cross-check against line transfer ..."
    readf,5,line
    readf,5,Nlines
    readf,5,line
    linetxt = strarr(Nlines)
    for i=0L,Nlines-1L do begin
      if (EOF(5)) then break 
      readf,5,line
      linetxt(i) = " "+line
      for ix=0,NX-1 do begin
        readf,5,line
      endfor
    endfor
    close,5
  endif
  
  ; ---------- having a FLiTs spectrum? --------------
  openr,5,"specFLiTs.out",ERROR=err
  Flits=0
  if (err EQ 0) then begin
    close,5 
    Flits=1    
    readcol,'specFLiTs.out',format='(D,D,D,D)',$
            lamFlits,fluxFlits,vFlits,FcontFlits,/silent 
  endif  
  firstLine=1
  for i=0L,Nline-1 do begin
    ; ------- plot flux -------  
    myloadct, rred,ggreen,bblue
    readf,1,txt
    wlmic = 1.D+0
    nuGHz = 1.D+0
    if (firstLine EQ 1) then begin
      readf,1,txt
      if (strlen(txt) EQ 70) then frmt='(10x,a6,23x,F9.3,11x,F9.3)'
      if (strlen(txt) EQ 75) then frmt='(10x,a11,22x,F9.3,9x,F11.3)'
      if (strlen(txt) EQ 79) then frmt='(10x,a11,22x,F11.5,9x,F13.5)'
      if (strlen(txt) EQ 93) then frmt='(10x,a11,26x,E17.10,9x,E17.10)'
      ; this is for the new format having the ident lengh consistently with SPLen (ie. SPlen+4)
      ; which is currently 16
      if (strlen(txt) EQ 99) then frmt='(10x,a17,26x,E17.10,9x,E17.10)'
      reads,txt,format=frmt,molname,wlmic,nuGHz
      firstLine=0       
    endif else begin
      readf,1,format=frmt,molname,wlmic,nuGHz
    endelse
    if (nuGHz GT wlmic) then begin  ;more significant digits
      wlmic = cl/(nuGHz*GHz)/mic
    endif else begin
      nuGHz = cl/(wlmic*mic)/GHz 
    endelse
    ;print,wlmic,nuGHz
    readf,1,format='(24x,E30)',Fline  
    readf,1,format='(24x,F30)',Fcont
    readf,1,txt
    Fconvolved=(STRPOS(txt,'fconv') GT 0)
    if (Fline EQ 0) then return
    vv=0.d0
    FF=0.d0
    FC=0.d0
    readf,1,vv,FF
    for j=0,Nvelo-2 do begin
      if (Fconvolved) then begin 
        readf,1,vv,FF,FC
        vkms(j) = vv   ; [km/s]
        Fnu(j) = FF    ; [Jy]
        Fconv(j) = FC  ; [Jy] convolved with instrument resolution
      endif else begin
        readf,1,vv,FF
        vkms(j) = vv   ; [km/s]
        Fnu(j) = FF    ; [Jy]
        Fconv(j) = FF
      endelse  
    endfor
    vmax = max(vkms)
    ;vmax = 10.0
    vmin = -vmax
    dv = 0.05*(vmax-vmin)
    vmin = vmin-5*dv
    vmax = vmax+dv
    ;Fmin = 0.0
    ;Fmax = max([1.2*max(Fnu),3.0*Fcont])
    ; --- rescale flux to see something? ---
    Fmin = min(Fnu)-0.1*max(Fnu-Fcont)
    Fmax = Fcont+1.35*max(Fnu-Fcont)
    Fmax = max([Fmax,Fcont+1.5*(Fcont-Fmin)])
    ; --- having observed spectrum? ---
    file = FveloName(i)
    openr,12,file,ERROR = err
    close,12
    print
    if (err EQ 0) then begin
      print,file
      readcol,file,vobs,Fobs,/silent
      vomin = min(vobs)
      vomax = max(vobs)
      dv    = vomax-vomin
      vomin = vomin-0.1*dv 
      vmax = max([vmax,vomax])
      vmin = min([vmin,vomin])
      Fmax = max([Fmax,Fcont+1.5*max(Fobs)])      
      Fmin = min([Fmin,Fcont+0.8*min(Fobs)])      
    endif  
    pos=[0.17,0.12,0.97,0.95]
    titel = ''
    if (Freso(i) LT 1.E+10) then begin
      titel = "R="+STRTRIM(STRING(format='(I8)',Freso(i)),2)
    endif
    PLOT, vkms,Fconv, position=pos,$
        CHARTHICK=2,XCHARSIZE=1.2,YCHARSIZE=1.2,$
        THICK=7,XMARGIN=[12,2],YMARGIN=[6,2],$
        XTITLE="!7v [km/s]",$
        YTITLE="!7F!L!9n!N!7 [Jy]",$
        TITLE=titel,$  
        xrange=[vmin,vmax],xstyle=1,$
        yrange=[Fmin,Fmax],ystyle=1
    if (err EQ 0) then begin
      int1 = 0.d0
      int2 = 0.d0
      for j=0,N_ELEMENTS(Fobs)-2 do begin
        v1 = vobs(j)  
        v2 = vobs(j+1)  
        F1 = Fobs(j)  
        F2 = Fobs(j+1)  
        int1 = int1 + (F1+F2)*(v2-v1)
        int2 = int2 + (v1*F1+v2*F2)*(v2-v1)
      endfor  
      vshift = 0.0
      if (Fcen[i] EQ 1) then vshift=int2/int1
      vbreak = 0.0
      vdist  = (max(vobs)-min(vobs))/N_ELEMENTS(Fobs)     
      for j=0,N_ELEMENTS(Fobs)-2 do begin
        if (ABS(vobs[j]-vobs[j+1]) GT 2.0*vdist) then begin
          vbreak = 0.5*(vobs[j]+vobs[j+1])
        endif
      endfor
      if (vbreak EQ 0.0) then begin
        oplot,vobs-vshift,Fobs+Fcont,psym=10,thick=3,color=50
      endif else begin  
        ind=WHERE(vobs LT vbreak) 
        oplot,vobs[ind],Fobs[ind]+Fcont,psym=10,thick=3,color=50
        ind=WHERE(vobs GT vbreak) 
        oplot,vobs[ind]-vshift,Fobs[ind]+Fcont,psym=10,thick=3,color=50
      endelse  
    endif
    oplot,vkms,Fnu,PSYM=1,SYMSIZE=0.6,color=150
    ; --- derive FWHM and velo-separation ---
    vc = vkms*10.0
    Fc = 0.0*Fnu+Fcont
    oplot, vc,Fc,THICK=3,LINESTYLE=1
    Nhigh=20*Nvelo
    vhigh=DBLARR(Nhigh)
    for j=0,Nhigh-1 do begin
      vhigh[j]=-vmax+2.d0*vmax*j/(Nhigh-1.d0)
    endfor
    Fhigh=INTERPOL(Fconv,vkms,vhigh,/SPLINE)
    Fhalf=Fcont+0.5*max(Fconv-Fcont)
    ;OPLOT,vhigh,Fhigh,THICK=1,LINESTYLE=0,color=150
    v1=0.d0
    v2=0.d0
    v3=0.d0
    v4=0.d0
    for it=0,999 do begin
      maxF=max(Fhigh)
      index=WHERE(Fhigh EQ maxF)
      vpos=vhigh(index[0])
      Fhigh(index[0])=0.d0
      if((v1 EQ 0.d0)AND(vpos LT 0.d0)) then v1=vpos
      if((v2 EQ 0.d0)AND(vpos GT 0.d0)) then v2=vpos
      index=WHERE(Fhigh GT Fhalf)
      Nhalf=N_ELEMENTS(index)
      vpos1=vhigh(index[0]) 
      vpos2=vhigh(index[Nhalf-1]) 
      Fhigh(index[0])=0.d0
      Fhigh(index[Nhalf-1])=0.d0
      if((v3 EQ 0.d0)AND(vpos1 LT 0.d0)) then v3=vpos1
      if((v4 EQ 0.d0)AND(vpos2 GT 0.d0)) then v4=vpos2
      if((v1 LT 0.0)AND(v2 GT 0.0)AND(v3 LT 0.0)AND(v4 GT 0.0)) then break
    endfor
    vsep=(v2-v1)
    fwhm=(v4-v3)
    if (wlmic GT 10.0) then begin
      Titel = STRTRIM(molname,2)+" @ "+$
              STRTRIM(STRING(format='(F13.2)',wlmic),2)+" !9m!7m"
    endif else begin
      Titel = STRTRIM(molname,2)+" @ "+$
              STRTRIM(STRING(format='(F13.3)',wlmic),2)+" !9m!7m"
    endelse
    linf1 = "F!Lline !N= "+STRTRIM(STRING(format='(E10.2)',Fline),2)+" !7W/m!U2!N" 
    linf2 = "F!Lcont !N= "+STRTRIM(STRING(format='(E10.2)',Fcont),2)+" !7Jy"
    linf3 = "i = "+STRTRIM(STRING(format='(F5.1)',incl),2)+"!Uo!N" $
        +"   d = "+STRTRIM(STRING(format='(I5)',dist),2)+" pc"
    linf4 = "FWHM!L !N=!L !N"+STRTRIM(STRING(format='(F5.2)',fwhm),2)$
        +"!L !Nkm/s"
    linf5 = "!9D!7v!Lsep !N=!L !N"+STRTRIM(STRING(format='(F5.2)',vsep),2)$
        +"!L !Nkm/s"
    if (fwhm GT 99.9) then linf4 = "FWHM!L !N=!L !N"+$
        STRTRIM(STRING(format='(F5.1)',fwhm),2) +"!L !Nkm/s"
    XYOUTS, 0.955,0.910,Titel,$
          CHARTHICK=3,CHARSIZE=1.3,ALIGNMENT=1.0, /normal
    XYOUTS, 0.955,0.875,linf3,$
          CHARTHICK=3,CHARSIZE=1.3,ALIGNMENT=1.0, /normal
    XYOUTS, 0.955,0.840,STRTRIM(linf1,1),$
          CHARTHICK=3,CHARSIZE=1.3,ALIGNMENT=1.0, /normal
    XYOUTS, 0.955,0.805,STRTRIM(linf2,1),$
          CHARTHICK=3,CHARSIZE=1.3,ALIGNMENT=1.0, /normal
    XYOUTS, 0.955,0.765,STRTRIM(linf4,1),$
          CHARTHICK=3,CHARSIZE=1.3,ALIGNMENT=1.0, /normal
    XYOUTS, 0.955,0.730,STRTRIM(linf5,1),$
          CHARTHICK=3,CHARSIZE=1.3,ALIGNMENT=1.0, /normal
    Fcheck = 0.0
    for j=1,Nvelo-2 do begin
      dv = vkms(j)-vkms(j-1)    
      F1 = Fnu(j-1)-Fcont
      F2 = Fnu(j)-Fcont
      Fcheck = Fcheck + 0.5*(F1+F2)*dv   ;[Jy km/s]
    endfor
    nuHz = cl/(wlmic*mic)
    print,linfo(i)
    print,"Fline[Jy km/s]=",Fcheck

    ibest = 0L
    qqual = 9.d+99
    ntest = ' '
    wtest = 0.d0
    utest = 0
    ltest = 0
    for j=0L,Nlines-1L do begin
      txt = linetxt(j)
      if (STRPOS(txt,' '+STRTRIM(molname)+' ') GE 0) then begin
        reads,format='(A12,F)',txt,ntest,wtest
        qual = ABS(wtest/wlmic-1.d0)
        if (qual LT qqual) then begin
          ibest = j
          qqual = qual
        endif
        ;print,txt
        ;print,ltest,j,ibest
      endif  
    endfor
    if (ibest GT 0) then begin
      txt = STRMID(linetxt(ibest),13) 
      reads,txt,wtest,utest,ltest,Fescpro
      ;print,linetxt(ibest)
      ;print,ntest,wtest,utest,ltest,Fescpro
      rem=" "
      badness = ABS(Fescpro/Fline-1.d0)
      if (badness GT 0.8) then rem=" (!) esc.prob. is off" 
      print,"Fline[ W/m^2 ]=",Fline,Fcheck*Jansky*nuHz/(cl/km)/Wm2,Fescpro,rem
   endif
    
    ;------- overplot FLiTs spectrum? ----------
    if (Flits) then begin
      vFlits2 = cl*(lamFlits-wlmic)/wlmic/km
      ind = WHERE((vFlits2 GT 1.5*vmin) AND (vFlits2 LT 1.5*vmax),count)
      if (count GT 0) then begin
        ;vwork = vFlits(ind) 
        vwork  = vFlits2(ind)
        Fwork  = fluxFlits(ind)+Fcont-FcontFlits(ind)
        orange = 210
        oplot,vwork,Fwork,color=orange,thick=4
        Fcheck = 0.0
        Ftest = 0.0
        Nj = N_ELEMENTS(ind)
        for j=1,Nj-2 do begin
          dv = vwork(j)-vwork(j-1)    
          F1 = Fwork(j-1)-Fcont
          F2 = Fwork(j)-Fcont
          Fcheck = Fcheck + 0.5*(F1+F2)*dv ;[Jy km/s]
          Ftest  = Ftest + FcontFlits(ind(j))
        endfor
        Ftest = Ftest/(Nj-1)
        print,"FLiTs Fline[ W/m^2 ]=",Fcheck*Jansky*nuHz/(cl/km)/Wm2
        print,"continuum[Jy]=",Fcont,Ftest
      endif  
    endif  
   
    ; ------- insert image --------  
    if (convolved(i) EQ 1) then begin
      Iplot=Iconv(*,*,i)
    endif else begin  
      Iplot=Iline(*,*,i)
    endelse
    rad=sqrt(xp^2+yp^2)
    ; ---- adjust size to cumulative flux ----
    Rsun = 6.959900000D+10
    imin = min(where(rad(*,0) GT 1.5*Rstar*Rsun/AU))
    fcumm = dblarr(Nr)
    rmean = dblarr(Nr)
    fcumm(0:imin) = 0.0
    for ir=imin,Nr-1 do begin
      rmean(ir) = MEAN(rad(ir,*)) 
      fcumm(ir) = fcumm(ir-1) 
      dA = pi*(rad(ir,0)^2-rad(ir-1,0)^2)/Nth
      for ith=0,Nth do begin
        fcumm(ir) = fcumm(ir) + dA*max([0.0,Iplot(ir,ith)])
      endfor
    endfor
    fcumm = fcumm/fcumm(Nr-1)
    idum = WHERE(fcumm GT 0.0 AND fcumm LE 1.0)
    rtmp = rmean(idum)
    ftmp = fcumm(idum)
    R15 = INTERPOL(rtmp,ftmp,0.15)
    R25 = INTERPOL(rtmp,ftmp,0.25)
    R70 = INTERPOL(rtmp,ftmp,0.7)
    R80 = INTERPOL(rtmp,ftmp,0.8)
    R85 = INTERPOL(rtmp,ftmp,0.8)
    R90 = INTERPOL(rtmp,ftmp,0.9)
    R95 = INTERPOL(rtmp,ftmp,0.95)
    R98 = INTERPOL(rtmp,ftmp,0.98)
    if (logI) then begin
      Rmax = 1.1*R95
      Rmin = 0.9*R15
    endif else begin  
      Rmax = 1.2*R85
      Rmin = 0.9*R25
    endelse 
    Rmax = min([Rmax0,Rmax])
    ind1=WHERE((rad GT Rmin) AND (rad LE Rmax))
    ind2=WHERE((rad GT Rmin) AND (rad LE Rmax) AND (Iplot GT 0.0))
    Imax=alog10(max(Iplot[ind1]))
    Imin=alog10(min(Iplot[ind2]))
    Imin=min([Imin,Imax-1.0])
    Imin=max([Imin,Imax-4.0])
    IImin=10.0^Imin
    IImax=10.0^Imax
    print,format='(" size (70% 80% 90% 95% 98%) = ",5(F9.3))',$
            R70,R80,R90,R95,R98
    if (R98 GT 0.8*Rmax0) then Rmax=Rmax0
    ;print,"Rmin,Rmax=",Rmin,Rmax
    ;print,"Imin,Imax=",IImin,IImax
    ;if(ABS(wlmic-6.300304E-01) LT 0.001) then Rmax=10.0
    ;if(ABS(wlmic-2.122) LT 0.001)  then Rmax=30.0
    xmin=-Rmax
    xmax=Rmax
    ymin=-Rmax
    ymax=Rmax
    ;index=WHERE(rad GT max([0.05*Rmax,1.5*Rstar/AU]))
    ;Imax=alog10(max(Iplot[index]))   
    ;Imin=Imax-1.5
    ;IImin=10.0^Imin
    ;IImax=10.0^Imax
    for ir=0,Nr do begin
      for ith=0,Nth do begin
        Iplot(ir,ith) = max([Iplot(ir,ith),IImin])
        Iplot(ir,ith) = min([Iplot(ir,ith),IImax])
      endfor
    endfor
    Nlev=80
    lev=dblarr(Nlev+1)
    col=intarr(Nlev+1)      
    colmin=2                 
    colmax=253
    dI = 0.01*(Imax-Imin)
    Imin = Imin-dI
    Imax = Imax+dI
    posi=[0.175,0.6,0.49,0.946]
    if (logI EQ 1) then begin
      for ilev=0,Nlev do begin
        lev(ilev)=Imin+(Imax-Imin)*ilev/Nlev
        col(ilev)=fix(colmin+(colmax-colmin)*(lev(ilev)-Imin)/(Imax-Imin))
      endfor
      CONTOUR,alog10(Iplot),xp,yp,/noerase,pos=posi,$
          xrange=[xmin,xmax],yrange=[ymin,ymax], $
          xstyle=5,ystyle=5, $
          XCHARSIZE=0.5,YCHARSIZE=0.5, $
          levels=lev,c_colors=col,/fill, $
          xtitle="x [au]",ytitle="y [au]"
    endif else begin          
      ;--- for linear image ---
      pi     = acos(-1.0d0)            ; just pi
      degree = pi/180.d0               ; one degree in rad
      arcsec = degree/3600.d0          ; one arc second in rad
      Jansky = 1.D-23                  ; 1 Jy in [erg/cm^2/s/Hz]
      dv     = 1.0*km                  ; dv=1km/s
      dnu    = dv/cl*nuHz              ; dnu
      new_unit = Jansky*dnu/arcsec^2   ; erg/cm^2/s/Hz * Hz/sr
      Iplot = Iplot/new_unit           ; erg/cm2/s/sr => Jy km/s arcsec-2
      Imax  = max(IImax)/new_unit
      if (convolved(i)) then begin
        Iplot=Iconv(*,*,i)/new_unit
        Imax=max(Iplot)
        ;file = IprofName(i)
        ;openr,12,file,ERROR = err
        ;close,12
        ;if (err EQ 0) then begin
        ;  readcol,file,robs,Iobs,/silent
        ;  Imax = max([Imax,Iobs/new_unit])
        ;endif  
      endif  
      Imin = 0.0
      Imax = MAX([Imax,1.E-9])
      ;print,Imin,Imax
      for ilev=0,Nlev do begin
        lev(ilev)=Imin+(Imax-Imin)*ilev/Nlev
        col(ilev)=fix(colmin+(colmax-colmin)*(lev(ilev)-Imin)/(Imax-Imin))
      endfor
      CONTOUR,Iplot,xp,yp,/noerase,pos=posi,$
          xrange=[xmin,xmax],yrange=[ymin,ymax], $
          xstyle=5,ystyle=5, $
          XCHARSIZE=0.5,YCHARSIZE=0.5, $
          levels=lev,c_colors=col,/fill, $
          xtitle="x [au]",ytitle="y [au]"
    endelse
    ;------- overplot rays? ---------
    ;usersym, [1,0,-1,0,1], [0,1,0,-1,0] 
    ;oplot,xp,yp,PSYM=8,SYMSIZE=0.01,THICK=0.01,color=255
    ;------- overplot image center? --------
    if ((xcenter(i) NE 0.0) OR (ycenter(i) NE 0.0)) then begin
      oplot,[xcenter(i)],[ycenter(i)],psym=7,color=1,symsize=0.5
    endif
    ;------- overplot something else? --------
    loadct,39,/silent 
    black   = 0
    red     = 250
    orange  = 210
    yellow  = 195
    green   = 160
    cyan    = 100
    blue    = 70
    magenta = 40
    white   = 255
    ;CONTOUR,AV_rad,xxp,zzp,/overplot,LEVEL=[10.0,100.0],$
    ;  C_ANNOTATION=[' ',' '],C_CHARSIZE=1.E-5,C_COLORS=green,$
    ;  C_LINESTYLE=0,C_THICK=1
    ;CONTOUR,AV_rad,-xxp,zzp,/overplot,LEVEL=[10.0,100.0],$
    ;  C_ANNOTATION=[' ',' '],C_CHARSIZE=1.E-5,C_COLORS=green,$
    ;  C_LINESTYLE=0,C_THICK=1
    ;CONTOUR,AV_rad,xxp,-zzp,/overplot,LEVEL=[10.0,100.0],$
    ;  C_ANNOTATION=[' ',' '],C_CHARSIZE=1.E-5,C_COLORS=green,$
    ;  C_LINESTYLE=0,C_THICK=1
    ;CONTOUR,AV_rad,-xxp,-zzp,/overplot,LEVEL=[10.0,100.0],$
    ;  C_ANNOTATION=[' ',' '],C_CHARSIZE=1.E-5,C_COLORS=green,$
    ;  C_LINESTYLE=0,C_THICK=1
    line = 'bla'
    file = "Parameter.in"
    openr,12,file,ERROR = err
    close,12
    if ((1 EQ 0) AND (err EQ 0)) then begin
      openr,12,file
      while (~EOF(12)) do begin
        readf,12,line
        if (STRPOS(line,"! MCFOST_H0")   GT 0) then reads,line,H0
        if (STRPOS(line,"! MCFOST_RREF") GT 0) then reads,line,r0
        if (STRPOS(line,"! MCFOST_BETA") GT 0) then reads,line,beta
      endwhile
      close,12
      yyp = H0*(xxp(*,0)/r0)^beta
      oplot, xxp(*,0), yyp(*),color=green
      oplot,-xxp(*,0), yyp(*),color=green
      oplot, xxp(*,0),-yyp(*),color=green
      oplot,-xxp(*,0),-yyp(*),color=green
      oplot, xxp(*,0), 2.0*yyp(*),color=green
      oplot,-xxp(*,0), 2.0*yyp(*),color=green
      oplot, xxp(*,0),-2.0*yyp(*),color=green
      oplot,-xxp(*,0),-2.0*yyp(*),color=green
    endif  
    size = (xmax-xmin)*AU/(dist*pc)/arc_sec
    tfrmt = '(F5.1)'
    if (size LT 1.0)  then tfrmt = '(F5.2)'
    if (size LT 0.1)  then tfrmt = '(F6.3)'
    if (size LT 0.01) then tfrmt = '(F7.4)'
    bem = STRTRIM(STRING(format=tfrmt,size),2)+""" x "$
        + STRTRIM(STRING(format=tfrmt,size),2)+""""
    XYOUTS,0.34,0.92,"!7"+bem,color=white,$
           CHARTHICK=3,CHARSIZE=1.0,ALIGNMENT=0.5, /normal
    myloadct, rred,ggreen,bblue
    AXIS,xaxis=0,xrange=[xmin,xmax],XCHARSIZE=0.55
    AXIS,yaxis=1,yrange=[ymin,ymax],YCHARSIZE=0.55
    if (convolved(i) EQ 1) then begin
      xFWHM = bmin(i)*arcsec_to_AU 
      yFWHM = bmaj(i)*arcsec_to_AU 
      PA    = PA_PSF(i)
      del = max([xFWHM,yFWHM])*0.55
      PLOT_BEAM,xmax,-0.85*xmax+del,-0.85*xmax+del,xFWHM,yFWHM,PA
    endif  
    if (logI EQ 1) then begin
      label="!7log!L !NI!Lline !N[erg/cm!U2!N/s/sr]"
    endif else begin  
      label="!7I!Lline !N[Jy!L !Nkm/s/arcsec!U2!N]"
    endelse  
    SKALA3, Nlev+1, lev, col, label, [0.21,0.545,0.46,0.565], 1.2

    ;--- plot intensity-profile ---
    file = IprofName(i)
    openr,12,file,ERROR = err
    close,12
    loadct,39,/silent
    if (err EQ 0) then begin
      readcol,file,robs,Iobs,Ierr,/silent
      rmin = 0.8*min(robs)
      rmean  = dblarr(Nr)
      Imean1 = dblarr(Nr)
      Imean2 = dblarr(Nr)
      rr = sqrt(xp^2+yp^2)
      for ir=0,Nr-1 do begin
        Imean1(ir) = MEAN(Iline(ir,*,i))
        Imean2(ir) = MEAN(Iconv(ir,*,i))
        rmean(ir)  = MEAN(rr(ir,*))
      endfor  
      Fcheck1 = 0.d0
      Fcheck2 = 0.d0
      for ir=0,Nr-2 do begin
        Ar = pi*(rmean(ir+1)^2-rmean(ir)^2)*AU^2 
        I1 = Imean1(ir)                   
        I2 = Imean1(ir+1)                  ; [erg/cm2/s/sr]
        Fcheck1 = Fcheck1 + Ar*0.5*(I1+I2)
        I1 = Imean2(ir)                   
        I2 = Imean2(ir+1)                  ; [erg/cm2/s/sr]
        Fcheck2 = Fcheck2 + Ar*0.5*(I1+I2)
      endfor  
      Fcheck1 = Fcheck1/(dist*pc)^2        ; [erg/cm2/s]
      Fcheck2 = Fcheck2/(dist*pc)^2        ; [erg/cm2/s]
      print,"Fline[ W/m^2 ]=",Fline,Fcheck1/Wm2,Fcheck2/Wm2
      ind1 = where((rmean GT rmin) AND (rmean LT Rout))
      ind2 = where((robs GT rmin) AND (robs LT Rout) AND (Iobs GT 0))
      Imin1 = min(Imean1(ind1))
      Imax1 = max(Imean1(ind1))
      Imin2 = min(Iobs(ind2))
      Imax2 = max(Iobs(ind2)+Ierr(ind2))
      Imin  = max([Imin1,0.5*Imin2])/1.1
      Imax  = max([Imax1,Imax2])*1.1
      ind   = WHERE(Imean2 GT Imin,count)
      Rmax  = Rmax0  
      if (count GT 0) then Rmax=max(rmean(ind))
      ;--- linear-log plot ---
      plot,rmean(ind1),Imean1(ind1),/nodata,position=pos,/ylog,$
         xrange=[0,Rmax],yrange=[Imin,Imax],$
         xtitle="!7r [au]",$
         ytitle="!7log I!Lline !N[erg/s/cm!U2!N/sr]"
      j=STRPOS(file,".dat") 
      file2=STRMID(file,0,j)+".out"
      openr,2,file2,ERROR = err
      if (err EQ 0) then begin
        readf,2,format='(19x,F,F)',xmaxi,ymaxi
        close,2        
        readcol,file2,rmod,Imod,/silent
        oplot,rmod,Imod,color=yellow,thick=2
      endif  
      oploterror,robs,Iobs,0.0*robs,Ierr,$
                 errcolor=red,psym=6,symsize=0.3,color=red
      oplot,rmean(ind1),Imean1(ind1),thick=3
      oplot,rmean(ind1),Imean2(ind1),thick=5,linestyle=2,color=blue
      Nbem=3
      bcol=intarr(Nbem)
      blin=intarr(Nbem)
      bthi=intarr(Nbem)
      bbem=strarr(Nbem)
      bcol(0)=black & blin(0)=0 & bthi(0)=3 & bbem(0)="model profile"
      bcol(1)=blue  & blin(1)=2 & bthi(1)=4 & bbem(1)="model after convolution"
      bcol(2)=red   & blin(2)=0 & bthi(2)=3 & bbem(2)="observations"
      x0=0.20
      y0=0.15+Nbem*0.03
      for j=0,Nbem-1 do begin
        plots,[x0,x0+0.05],[y0,y0]-0.03*(j-1),/normal,$
              color=bcol(j),linestyle=blin(j),thick=bthi(j)
        xyouts,x0+0.06,y0-0.03*(j-1)-0.01,bbem(j),/normal
      endfor  
      ;--- linear-linear plot ---
      plot,rmean(ind1),Imean1(ind1),/nodata,position=pos,$
         xrange=[0,Rmax],yrange=[0,Imax],$
         xtitle="!7r [au]",$
         ytitle="!7I!Lline !N[erg/s/cm!U2!N/sr]"
      if (err EQ 0) then oplot,rmod,Imod,color=yellow,thick=2
      oploterror,robs,Iobs,0.0*robs,Ierr,$
                 errcolor=red,psym=6,symsize=0.3,color=red
      oplot,rmean(ind1),Imean1(ind1),thick=3
      oplot,rmean(ind1),Imean2(ind1),thick=5,linestyle=2,color=blue
      x0=0.20
      y0=0.15+Nbem*0.03
      for j=0,Nbem-1 do begin
        plots,[x0,x0+0.05],[y0,y0]-0.03*(j-1),/normal,$
              color=bcol(j),linestyle=blin(j),thick=bthi(j)
        xyouts,x0+0.06,y0-0.03*(j-1)-0.01,bbem(j),/normal
      endfor          
    endif  
  endfor
  close,1
END

;--------------------------------------------------------------------
PRO CONTFILL, r, z, fplot, SPname, log_grid, y_log, type, $
              NSMOOTH=Nsmooth, XMIN=xxmin, XMAX=xxmax, YMIN=yymin, YMAX=yymax,$
              ZMAX=zzmax, $
              OVERCONT=overcont, OVERVAL=overval, $
              OVERLABEL=overlabel, OVERCOLOR=overcolor, $
              OVER2=over2,OVERV2=overv2, $
              OVERL2=overl2,OVERC2=overc2, $
              VERT=vert,GRIDON=gridon
;--------------------------------------------------------------------
  ;print,"plotting contour of ",SPname," log_grid",log_grid,$
  ;      " y_log=",y_log," type=",type
  !p.multi=[0,2,1]
  !x.margin=[11,1]
  !y.margin=[4,2]
  !x.style=1
  !y.style=1
  dens = fplot      ; work copy

  ; --- calculate depicted range and put minimum dens ---
  ;print,"... min=",MIN(dens)," max=",MAX(dens)  
  if (y_log) then begin
    dmin=min(alog10(dens))
    dmax=max(alog10(dens))
    if (KEYWORD_SET(yymax)) then dmax=yymax
    if (KEYWORD_SET(yymin)) then dmin=yymin
    if ((KEYWORD_SET(yymin) EQ 0) AND (dmin LT dmax-10.5)) then dmin=dmax-10.5
    if ((KEYWORD_SET(yymin) EQ 0) AND (dmin LE dmax-10.5)) then begin
    ;if (min(alog10(dens)) LT dmin) then begin
      for ix=0,N_ELEMENTS(dens(*,0))-1 do begin
        for iy=0,N_ELEMENTS(dens(0,*))-1 do begin
          if (alog10(dens(ix,iy)) LT dmin) then begin
            dens(ix,iy)=10.0^dmin
          endif   
        endfor
      endfor
    endif
  endif else begin
    dmin=min(dens)
    dmax=max(dens)
    if (KEYWORD_SET(yymax)) then dmax=yymax
    if (KEYWORD_SET(yymin)) then dmin=yymin
  endelse
  if (KEYWORD_SET(yymax)) then begin
    dd = (dmax-dmin)*0.01
    dmax = dmax+dd
    dmin = dmin-dd
  endif else begin
    dd = (dmax-dmin)*0.05
    dmax = dmax+dd
    dmin = dmin-dd
  endelse
  ;if(dmax-3.0 GT dmin) then dmax=dmax-3.0
  ilev=80            ;120  
  if((dmax EQ dmin) OR (ABS((dmax-dmin)/dmax) LT 1.E-3)) then begin
    print,"***",dmin,dmax
    ddd=MAX([0.05*ABS(dmin),1.e-99])
    if (y_log) then ddd=0.1 
    dmax=dmin+ddd
    dmin=dmin-ddd
  endif
  ddd=(dmax-dmin)/ilev
  lev=dblarr(ilev+1)
  col=intarr(ilev+1)      
  colmin=2       ; use 2/253 for rainbow colors
  colmax=253
  ;colmin=255    ; use 255/0 for B&W output
  ;colmax=0
  for i=0, ilev do begin
     lev(i)=dmin+ddd*i
     col(i)=fix(colmin+(colmax-colmin)*(lev(i)-dmin)/(dmax-dmin))
  endfor
  ;print, col, lev
  ;print, dmin, dmax

  case y_log of
    0: y=dens 
    1: y=alog10(dens)
  endcase  
  y(where(y LT dmin))=dmin
  
  ; --- interpolate on high resolution grid to produce nicer images ---
  ; ---             (does not work very well though)                ---
  if (KEYWORD_SET(Nsmooth)) then begin    
    Nx=N_ELEMENTS(z(*,0))
    Nz=N_ELEMENTS(z(0,*))
    Nxdim=Nx+(Nx-1)*(Nsmooth-1)      ;Nsmooth=factor to increase point density
    Nzdim=Nz+(Nz-1)*(Nsmooth-1)
    rhigh=dblarr(Nxdim,Nzdim)
    zhigh=dblarr(Nxdim,Nzdim)
    yhigh=dblarr(Nxdim,Nzdim)
    i=0
    for ix=0,Nx-2 do begin
      r1=r(ix,0)
      r2=r(ix+1,0)
      secbeta=z(ix,Nz-1)/r1
      ; --- reconstruct pot ---
      iz1=Nz-1
      iz2=Nz/2
      zi=z(ix,iz1)
      zj=z(ix,iz2)
      pot=alog(zi/zj)/alog((1.d0*iz1)/(1.d0*iz2))
      for ii=0,Nsmooth do begin
        rtmp=exp(alog(r1)+alog(r2/r1)*ii/Nsmooth)
        rhigh(i,*) = rtmp
        zhigh(i,*) = rtmp*secbeta*(DINDGEN(Nzdim)/(Nzdim-1))^pot
        for j=0,Nzdim-1 do begin
          rind = (1.0*i)/Nsmooth
          zind = (1.0*j)/Nsmooth
          yhigh(i,j) = INTERPOLATE(y, rind, zind, cubic=-0.5)
        endfor  
        ;print,ix,i,rtmp
        i=i+1
      endfor
      i=i-1
    endfor  
    ; --- check interpolation ---
    ;for ix=0,Nx-2 do begin
    ;  for iz=0,Nz-1 do begin
    ;    if (y(ix+1,iz) LT y(ix,iz)-1.0) then begin
    ;      print,y(ix,iz),y(ix+1,iz)
    ;      print,y(ix,iz+1),y(ix+1,iz+1)
    ;      for j=0,Nsmooth do begin
    ;        print,yhigh(ix*Nsmooth+0:ix*Nsmooth+Nsmooth,iz*Nsmooth+j)
    ;      endfor  
    ;      stop
    ;    endif
    ;  endfor
    ;endfor
    ;SHOWGRID, rhigh,zhigh,0
    ; --- smooth interpolated data ---
    ynew = SMOOTH(yhigh,2*Nsmooth+1,/EDGE_TRUNCATE)
    ;kernel = [[ 1,  8, 15,  8, 1], $  
    ;          [ 8, 63,127, 63, 8], $  
    ;          [15,127,255,127,15], $  
    ;          [ 8, 63,127, 63, 8], $  
    ;          [ 1,  8, 15,  8, 1]]  
    ;ynew = CONVOL( yhigh, kernel, INVALID=255, /NORMALIZE )  
    yhigh = ynew

  endif else begin
    zhigh=z
    rhigh=r
    yhigh=y
  endelse  

  ; --- do the contour plot ---
  xmin=min(r)
  xmax=max(r)
  ymin=min(z)
  ymax=max(z)
  ;pos=[0.11,0.22,0.97,0.97]
  pos=[0.12,0.1,0.965,0.98]
  if (log_grid) then begin
    ymin1=min(r)*0.03
    ymin2=max(z(0,*))*0.01
    ;ymin=min([ymin1,ymin2])
    ;print,ymin1,ymin2
    ;stop
    ymin=(ymin1*ymin1*ymin2)^(1.0/3.0)
    ymax=max(z)
    ymax=max([ymax,ymin*1.01])
    if(ymin LT 10.0) then begin
      ytname=['10','100','1E3','1E4','1E5','1E6']
    endif
    if(ymin LT 1.0) then begin
      ytname=['1','10','100','1E3','1E4','1E5']
    endif
    if(ymin LT 0.1) then begin
      ytname=['0.1','1','10','100','1E3','1E4']
    endif 
    if(ymin LT 0.01) then begin
      ytname=['0.01','0.1','1','10','100','1E3']
    endif 
    if(ymin LT 0.001) then begin
      ytname=['1E-3','0.01','0.1','1','10','100']
    endif 
    CONTOUR, yhigh, rhigh, zhigh, /xlog, /ylog, $
             xtitle='!7r [au]',ytitle='!7z [au]', $
             levels=lev, /fill, c_colors=col, position=pos, $
             ytickname=ytname, $
             xrange=[xmin,xmax], yrange=[ymin,ymax], $
             thick=3.0,charthick=3.0
  endif else begin
    if (KEYWORD_SET(xxmin)) then begin
      xmin=xxmin
    endif  
    if (KEYWORD_SET(xxmax)) then begin
      xmax=xxmax
    endif
    if (KEYWORD_SET(zzmax)) then begin
      ymin=0.0
      ymax=zzmax
    endif  
    CONTOUR, yhigh, rhigh, zhigh, $
             xtitle='!7r [au]',ytitle='!7z [au]', $
             levels=lev, /fill, c_colors=col, position=pos, $
             xrange=[xmin,xmax], yrange=[ymin,ymax], $
             thick=4.0,charthick=4.0,charsize=1.5
  endelse  

  ; --- show grid points ---
  if (KEYWORD_SET(gridon)) then begin  
    ;oplot, r,z, PSYM=3, color=255
    oplot, r,z, PSYM=1, SYMSIZE=1.0, color=0
  endif

  ; --- add contours ---
  if (KEYWORD_SET(overcont)) then begin
    ztmp = z  
    if (log_grid) then begin
      Nx=N_ELEMENTS(z(*,0))
      Nz=N_ELEMENTS(z(0,*))
      for ix=0,Nx-1 do for iz=0,Nz-1 do begin
        ztmp(ix,iz) = MAX([ymin,z(ix,iz)])
      endfor  
    endif 
    CONTOUR,overcont,r,ztmp,/overplot,LEVEL=overval,$
      C_ANNOTATION=overlabel,C_COLORS=overcolor,$
      C_LINESTYLE=2,C_CHARSIZE=1.3,C_THICK=3
    if (KEYWORD_SET(over2)) then begin
      CONTOUR,over2,r,ztmp,/overplot,LEVEL=overv2,$
      C_ANNOTATION=overl2,C_COLORS=overc2,$
      C_LINESTYLE=2,C_CHARSIZE=1.3,C_THICK=3
    endif  
  endif  

  case type of
    ;0: label = '!7n!L'+SPname+'!N [cm!U-3!N]!X'
    ;1: label = '!9e!L'+SPname+'!N!X'
    0: label = '!7n!7 ('+SPname+') [cm!U-3!N]!X'
    1: label = '!9e!7 ('+SPname+')!X'
    2: label = '!7'+SPname+'!N!X'
    3: label = SPname+' charge'
    4: label = SPname
  endcase
  if (y_log) then label = '!7log '+label

  if(KEYWORD_SET(vert)) then begin
    if (vert EQ 1) then begin
      SKALA_VERT, ilev+1, lev, col, label, [0.86,0.55,0.90,0.95]
    endif else begin  
      SKALA_VERT, ilev+1, lev, col, label, [0.18,0.55,0.22,0.95]
    endelse  
  endif else begin
    SKALA, ilev+1, lev, col, label, [0.14,0.9,0.6,0.95], 1.3
  endelse  
  !p.multi=[0,0,1]

end; CONTFILL


;--------------------------------------------------------------------
PRO CONTFILL2, r, z, fplot, SPname, log_grid, y_log, type, $
               XMAX=xxmax,YMIN=yymin,YMAX=yymax,ZMAX=zzmax,$
               NSMOOTH=Nsmooth,CENTER_ZERO=center_zero,$
               OVERCONT=overcont,OVERVAL=overval, $
               OVERLABEL=overlabel,OVERCOLOR=overcolor, $
               OVER2=over2,OVERV2=overv2, $
               OVERL2=overl2,OVERC2=overc2, $
               OVER3=over3,OVERV3=overv3, $
               OVERL3=overl3,OVERC3=overc3, $
               OVER4=over4,OVERV4=overv4, $
               OVERL4=overl4,OVERC4=overc4, $
               VERT=vert,GRIDON=gridon
;--------------------------------------------------------------------
  if (max(fplot) LT 1.E-40) then return
  ;if (max(fplot) EQ min(fplot)) then return
  ;print,"plotting contour2 of ",SPname," y_log=",y_log," type=",type
  !p.multi=[0,2,1]
  !x.margin=[11,1]
  !y.margin=[4,2]
  !x.style=1
  !y.style=1
  dens = fplot      ; work copy

  ; --- calculate depicted range and put minimum dens ---
  ;print,"... min=",MIN(dens)," max=",MAX(dens)  
  if (y_log) then begin
    dmin=min(alog10(dens))
    dmax=max(alog10(dens))
    if (KEYWORD_SET(yymax)) then dmax=yymax
    if (KEYWORD_SET(yymin)) then begin
      dmin=yymin
    endif else begin  
      if (dmin LT dmax-10.5) then dmin=dmax-10.5
    endelse  
    if (min(alog10(dens)) LT dmin) then begin
      for ix=0,N_ELEMENTS(dens(*,0))-1 do begin
        for iy=0,N_ELEMENTS(dens(0,*))-1 do begin
          if (dens(ix,iy) LT 10.0^dmin) then begin
            dens(ix,iy)=10.0^dmin
          endif   
          if (dens(ix,iy) GT 10.0^dmax) then begin
            dens(ix,iy)=10.0^dmax
          endif   
        endfor
      endfor
    endif
    ;print,SPname,dmin,dmax
    ;print,MIN(dens),MAX(dens)  
  endif else begin
    dmin=min(dens)
    dmax=max(dens)
  endelse
  if (KEYWORD_SET(yymin)) then dmin=yymin
  if (KEYWORD_SET(yymax)) then dmax=yymax
  if (KEYWORD_SET(yymax)) then begin
    dd = (dmax-dmin)*0.01
    dmax = dmax+dd
    dmin = dmin-dd
  endif else begin
    dd = (dmax-dmin)*0.05
    dmax = dmax+dd
    dmin = dmin-dd
  endelse
  ilev=80            ;80        ;120  
  if (KEYWORD_SET(center_zero)) then begin
    tmp = min(dens(*,0))
    ind = where(z/r LT 0.2, Nind)
    for i=0,Nind-1 do begin
      dens(ind[i]) = max([dens(ind[i]),tmp])
    endfor
    dmin = min(dens)
    ilev=250
  endif  
  if((dmax EQ dmin) OR (ABS((dmax-dmin)/dmax) LT 1.E-3)) then begin
    print,"***",dmin,dmax
    ddd=MAX([0.05*ABS(dmin),1.e-99])
    if (y_log) then ddd=0.1 
    dmax=dmin+ddd
    dmin=dmin-ddd
  endif
  ddd=(dmax-dmin)/ilev
  if (ddd LE 0.0) then return
  lev=dblarr(ilev+1)
  col=intarr(ilev+1)      
  colmin=1       ; use 1/253 for rainbow colors
  colmax=253
  ;colmin=255    ; use 255/0 for B&W output
  ;colmax=0
  for i=0, ilev do begin
    lev(i)=dmin+ddd*i
    col(i)=fix(colmin+(colmax-colmin)*(lev(i)-dmin)/(dmax-dmin))
  endfor
  if (KEYWORD_SET(center_zero)) then begin
    ind = where(ABS(lev) EQ MIN(ABS(lev)))
    dmax= dmax-lev(ind[0])
    dmin= dmin-lev(ind[0])
    lev = lev-lev(ind[0])
    colmid = (colmax+colmin)/2 
    for i=0, ilev do begin
      if (lev(i) GT 0) then begin
        col(i) = colmid $
               + (colmax-colmid)*ALOG( lev(i)*0.2+1.0)/ALOG( dmax*0.2+1.0) 
      endif else begin  
        col(i) = colmid $
               + (colmin-colmid)*ALOG(-lev(i)*0.2+1.0)/ALOG(-dmin*0.2+1.0) 
      endelse  
    endfor  
  endif  

  case y_log of
    0: y=dens 
    1: y=alog10(dens)
  endcase  

  ; --- interpolate on high resolution grid to produce nicer images ---
  ; ---             (does not work very well though)                ---
  if (KEYWORD_SET(Nsmooth)) then begin    
    Nx=N_ELEMENTS(z(*,0))
    Nz=N_ELEMENTS(z(0,*))
    Nxdim=Nx+(Nx-1)*(Nsmooth-1)      ;Nsmooth=factor to increase point density
    Nzdim=Nz+(Nz-1)*(Nsmooth-1)
    rhigh=dblarr(Nxdim,Nzdim)
    zhigh=dblarr(Nxdim,Nzdim)
    yhigh=dblarr(Nxdim,Nzdim)
    i=0
    for ix=0,Nx-2 do begin
      r1=r(ix,0)
      r2=r(ix+1,0)
      secbeta=z(ix,Nz-1)/r1
      ; --- reconstruct pot ---
      iz1=Nz-1
      iz2=Nz/2
      zi=z(ix,iz1)
      zj=z(ix,iz2)
      pot=alog(zi/zj)/alog((1.d0*iz1)/(1.d0*iz2))
      for ii=0,Nsmooth do begin
        rtmp=exp(alog(r1)+alog(r2/r1)*ii/Nsmooth)
        rhigh(i,*) = rtmp
        zhigh(i,*) = rtmp*secbeta*(DINDGEN(Nzdim)/(Nzdim-1))^pot
        for j=0,Nzdim-1 do begin
          rind = (1.0*i)/Nsmooth
          zind = (1.0*j)/Nsmooth
          yhigh(i,j) = INTERPOLATE(y, rind, zind, cubic=-0.5)
        endfor  
        ;print,ix,i,rtmp
        i=i+1
      endfor
      i=i-1
    endfor  
    ynew = SMOOTH(yhigh,4*Nsmooth+1,/EDGE_TRUNCATE)
    yhigh = ynew

  endif else begin
    zhigh=z
    rhigh=r
    yhigh=y
  endelse  

  ; --- do the contour plot ---
  xmin=min(r)
  xmax=max(r)
  ymin=0.0
  ymax=max(z/r)
  if (KEYWORD_SET(zzmax)) then ymax=zzmax
  if (KEYWORD_SET(xxmax)) then xmax=xxmax
  ;pos=[0.11,0.22,0.97,0.97]
  pos=[0.11,0.09,0.965,0.98]
  contour, yhigh, rhigh, zhigh/rhigh, /xlog, $
           xtitle='!7r [au]',ytitle='!7z / r', $
           levels=lev, /fill, c_colors=col, position=pos, $
           xrange=[xmin,xmax], yrange=[ymin,ymax], $
           thick=3,charthick=3

  ; --- show grid points ---
  if (KEYWORD_SET(gridon)) then begin  
    oplot, r,z/r, PSYM=3, SYMSIZE=0.5, color=255
  endif

  ; --- add contours ---
  if (KEYWORD_SET(overcont)) then begin
    CONTOUR,overcont,r,z/r,/overplot,LEVEL=overval,$
      C_ANNOTATION=overlabel,C_COLORS=overcolor,$
      C_LINESTYLE=2,C_CHARSIZE=1.3,C_THICK=3,noclip=1
  endif  
  if (KEYWORD_SET(over2)) then begin
    CONTOUR,over2,r,z/r,/overplot,LEVEL=overv2,$
      C_ANNOTATION=overl2,C_COLORS=overc2,$
      C_LINESTYLE=2,C_CHARSIZE=1.3,C_THICK=3,noclip=1
  endif  
  if (KEYWORD_SET(over3)) then begin
    CONTOUR,over3,r,z/r,/overplot,LEVEL=overv3,$
      C_ANNOTATION=overl3,C_COLORS=overc3,$
      C_LINESTYLE=2,C_CHARSIZE=1.3,C_THICK=3,noclip=1
  endif  
  if (KEYWORD_SET(over4)) then begin
    CONTOUR,over4,r,z/r,/overplot,LEVEL=overv4,$
      C_ANNOTATION=overl4,C_COLORS=overc4,$
      C_LINESTYLE=2,C_CHARSIZE=1.3,C_THICK=3,noclip=1
  endif  

  case type of
    ;0: label = '!7n!L'+SPname+'!N [cm!U-3!N]!X'
    ;1: label = '!9e!L'+SPname+'!N!X'
    0: label = '!7n!7 ('+SPname+') [cm!U-3!N]!X'
    1: label = '!9e!7 ('+SPname+')!X'
    2: label = '!7'+SPname+'!N!X'
    3: label = SPname+' charge'
    4: label = SPname
  endcase
  if (y_log) then label = '!7log '+label

  if (KEYWORD_SET(vert)) then begin
    if (vert EQ 1) then begin
      SKALA_VERT, ilev+1, lev, col, label, [0.86,0.55,0.90,0.95]
    endif else begin  
      SKALA_VERT, ilev+1, lev, col, label, [0.18,0.55,0.22,0.95]
    endelse
  endif else begin
    SKALA, ilev+1, lev, col, label, [0.14,0.89,0.6,0.95], 1.3
  endelse
  !p.multi=[0,0,1]

end; CONTFILL2

;--------------------------------------------------------------------
pro CONTFILL2_nolegend, r, z, fplot, SPname, log_grid, y_log, type, $
               YMIN=yymin,YMAX=yymax,ZMAX=zzmax,NSMOOTH=Nsmooth,$
               OVERCONT=overcont,OVERVAL=overval, $
               OVERLABEL=overlabel,OVERCOLOR=overcolor, $
               OVER2=over2,OVERV2=overv2, $
               OVERL2=overl2,OVERC2=overc2, $
               VERT=vert,GRIDON=gridon
;--------------------------------------------------------------------
  ;print,"plotting contour2 of ",SPname," y_log=",y_log," type=",type
  !p.multi=[0,0,1]
  !x.margin=[11,1]
  !y.margin=[4,2]
  !x.style=1
  !y.style=1
  dens = fplot      ; work copy

  ; --- calculate depicted range and put minimum dens ---
  ;print,"... min=",MIN(dens)," max=",MAX(dens)  
  if (y_log) then begin
    dmin=min(alog10(dens))
    dmax=max(alog10(dens))
    if (KEYWORD_SET(yymax)) then dmax=yymax
    if (KEYWORD_SET(yymin)) then begin
      dmin=yymin
    endif else begin  
      if (dmin LT dmax-10.5) then dmin=dmax-10.5
    endelse  
    if (min(alog10(dens)) LT dmin) then begin
      for ix=0,N_ELEMENTS(dens(*,0))-1 do begin
        for iy=0,N_ELEMENTS(dens(0,*))-1 do begin
          if (dens(ix,iy) LT 10.0^dmin) then begin
            dens(ix,iy)=10.0^dmin
          endif   
          if (dens(ix,iy) GT 10.0^dmax) then begin
            dens(ix,iy)=10.0^dmax
          endif   
        endfor
      endfor
    endif
    ;print,SPname,dmin,dmax
    ;print,MIN(dens),MAX(dens)  
  endif else begin
    dmin=min(dens)
    dmax=max(dens)
    if (KEYWORD_SET(yymin)) then dmin=yymin
    if (KEYWORD_SET(yymax)) then dmax=yymax
  endelse
  if (KEYWORD_SET(yymax)) then begin
    dd = (dmax-dmin)*0.01
    dmax = dmax+dd
    dmin = dmin-dd
  endif else begin
    dd = (dmax-dmin)*0.05
    dmax = dmax+dd
    dmin = dmin-dd
  endelse
  ilev=80            ;80        ;120  
  if((dmax EQ dmin) OR (ABS((dmax-dmin)/dmax) LT 1.E-3)) then begin
    print,"***",dmin,dmax
    ddd=MAX([0.05*ABS(dmin),1.e-99])
    if (y_log) then ddd=0.1 
    dmax=dmin+ddd
    dmin=dmin-ddd
  endif
  ddd=(dmax-dmin)/ilev
  if (ddd LE 0.0) then return
  lev=fltarr(ilev+1)
  col=intarr(ilev+1)      
  colmin=2       ; use 2/253 for rainbow colors
  colmax=253
  ;colmin=255    ; use 255/0 for B&W output
  ;colmax=0
  for i=0, ilev do begin
     lev(i)=dmin+ddd*i
     col(i)=fix(colmin+(colmax-colmin)*(lev(i)-dmin)/(dmax-dmin))
  endfor

  case y_log of
    0: y=dens 
    1: y=alog10(dens)
  endcase  

  ; --- interpolate on high resolution grid to produce nicer images ---
  ; ---             (does not work very well though)                ---
  if (KEYWORD_SET(Nsmooth)) then begin    
    Nx=N_ELEMENTS(z(*,0))
    Nz=N_ELEMENTS(z(0,*))
    Nxdim=Nx+(Nx-1)*(Nsmooth-1)      ;Nsmooth=factor to increase point density
    Nzdim=Nz+(Nz-1)*(Nsmooth-1)
    rhigh=dblarr(Nxdim,Nzdim)
    zhigh=dblarr(Nxdim,Nzdim)
    yhigh=dblarr(Nxdim,Nzdim)
    i=0
    for ix=0,Nx-2 do begin
      r1=r(ix,0)
      r2=r(ix+1,0)
      secbeta=z(ix,Nz-1)/r1
      ; --- reconstruct pot ---
      iz1=Nz-1
      iz2=Nz/2
      zi=z(ix,iz1)
      zj=z(ix,iz2)
      pot=alog(zi/zj)/alog((1.d0*iz1)/(1.d0*iz2))
      for ii=0,Nsmooth do begin
        rtmp=exp(alog(r1)+alog(r2/r1)*ii/Nsmooth)
        rhigh(i,*) = rtmp
        zhigh(i,*) = rtmp*secbeta*(DINDGEN(Nzdim)/(Nzdim-1))^pot
        for j=0,Nzdim-1 do begin
          rind = (1.0*i)/Nsmooth
          zind = (1.0*j)/Nsmooth
          yhigh(i,j) = INTERPOLATE(y, rind, zind, cubic=-0.5)
        endfor  
        ;print,ix,i,rtmp
        i=i+1
      endfor
      i=i-1
    endfor  
    ynew = SMOOTH(yhigh,4*Nsmooth+1,/EDGE_TRUNCATE)
    yhigh = ynew

  endif else begin
    zhigh=z
    rhigh=r
    yhigh=y
  endelse  

  ; --- do the contour plot ---
  xmin=min(r)
  xmax=max(r)
  ymin=0.0
  ymax=max(z/r)
  if (KEYWORD_SET(zzmax)) then ymax=zzmax
  ;pos=[0.11,0.22,0.97,0.97]
  pos=[0.11,0.09,0.965,0.98]
  contour, yhigh, rhigh, zhigh/rhigh, /xlog, $
           xtitle='!7r [au]',ytitle='!7z / r', $
           levels=lev, /fill, c_colors=col, position=pos, $
           xrange=[xmin,xmax], yrange=[ymin,ymax], $
           thick=3,charthick=3

  ; --- show grid points ---
  if (KEYWORD_SET(gridon)) then begin  
    oplot, r,z/r, PSYM=3, SYMSIZE=0.5, color=255
  endif

  ; --- add contours ---
  if (KEYWORD_SET(overcont)) then begin
    CONTOUR,overcont,r,z/r,/overplot,LEVEL=overval,$
      C_ANNOTATION=overlabel,C_COLORS=overcolor,$
      C_LINESTYLE=2,C_CHARSIZE=1.3,C_THICK=3
  endif  
  if (KEYWORD_SET(over2)) then begin
    CONTOUR,over2,r,z/r,/overplot,LEVEL=overv2,$
      C_ANNOTATION=overl2,C_COLORS=overc2,$
      C_LINESTYLE=2,C_CHARSIZE=1.3,C_THICK=3
  endif  

  case type of
    ;0: label = '!7n!L'+SPname+'!N [cm!U-3!N]!X'
    ;1: label = '!9e!L'+SPname+'!N!X'
    0: label = '!7n!7 ('+SPname+') [cm!U-3!N]!X'
    1: label = '!9e!7 ('+SPname+')!X'
    2: label = '!7'+SPname+'!N!X'
    3: label = SPname+' charge'
    4: label = SPname
  endcase
  if (y_log) then label = '!7log '+label

end; CONTFILL2_nolegend

;--------------------------------------------------------------------
PRO CONTFILL3, r, z, fplot, SPname, log_grid, y_log, type, $
               YMIN=yymin,YMAX=yymax,ZMAX=zzmax,NSMOOTH=Nsmooth,$
               OVER1=over1,OVERV1=overv1, $
               OVERL1=overl1,OVERC1=overc1, $
               OVER2=over2,OVERV2=overv2, $
               OVERL2=overl2,OVERC2=overc2, $
               OVER3=over3,OVERV3=overv3, $
               OVERL3=overl3,OVERC3=overc3, $
               VERT=vert,GRIDON=gridon
;--------------------------------------------------------------------
  ;print,"plotting contour2 of ",SPname," y_log=",y_log," type=",type
  !p.multi=[0,2,1]
  !x.margin=[11,1]
  !y.margin=[4,2]
  !x.style=1
  !y.style=1
  dens = fplot      ; work copy

  ; --- calculate depicted range and put minimum dens ---
  ;print,"... min=",MIN(dens)," max=",MAX(dens)  
  if (y_log) then begin
    dmin=min(alog10(dens))
    dmax=max(alog10(dens))
    if (KEYWORD_SET(yymax)) then dmax=yymax
    if (KEYWORD_SET(yymin)) then begin
      dmin=yymin
    endif else begin  
      if (dmin LT dmax-10.5) then dmin=dmax-10.5
    endelse  
    if (min(alog10(dens)) LT dmin) then begin
      for ix=0,N_ELEMENTS(dens(*,0))-1 do begin
        for iy=0,N_ELEMENTS(dens(0,*))-1 do begin
          if (dens(ix,iy) LT 10.0^dmin) then begin
            dens(ix,iy)=10.0^dmin
          endif   
          if (dens(ix,iy) GT 10.0^dmax) then begin
            dens(ix,iy)=10.0^dmax
          endif   
        endfor
      endfor
    endif
    ;print,SPname,dmin,dmax
    ;print,MIN(dens),MAX(dens)  
  endif else begin
    dmin=min(dens)
    dmax=max(dens)
    if (KEYWORD_SET(yymin)) then dmin=yymin
    if (KEYWORD_SET(yymax)) then dmax=yymax
  endelse
  if (KEYWORD_SET(yymax)) then begin
    dd = (dmax-dmin)*0.01
    dmax = dmax+dd
    dmin = dmin-dd
  endif else begin
    dd = (dmax-dmin)*0.05
    dmax = dmax+dd
    dmin = dmin-dd
  endelse
  ilev=80            ;80        ;120  
  if((dmax EQ dmin) OR (ABS((dmax-dmin)/dmax) LT 1.E-3)) then begin
    print,"***",dmin,dmax
    ddd=MAX([0.05*ABS(dmin),1.e-99])
    if (y_log) then ddd=0.1 
    dmax=dmin+ddd
    dmin=dmin-ddd
  endif
  ddd=(dmax-dmin)/ilev
  if (ddd LE 0.0) then return
  lev=dblarr(ilev+1)
  col=intarr(ilev+1)      
  colmin=2       ; use 2/253 for rainbow colors
  colmax=253
  ;colmin=255    ; use 255/0 for B&W output
  ;colmax=0
  for i=0, ilev do begin
     lev(i)=dmin+ddd*i
     col(i)=fix(colmin+(colmax-colmin)*(lev(i)-dmin)/(dmax-dmin))
  endfor

  case y_log of
    0: y=dens 
    1: y=alog10(dens)
  endcase  

  ; --- interpolate on high resolution grid to produce nicer images ---
  ; ---             (does not work very well though)                ---
  if (KEYWORD_SET(Nsmooth)) then begin    
    Nx=N_ELEMENTS(z(*,0))
    Nz=N_ELEMENTS(z(0,*))
    Nxdim=Nx+(Nx-1)*(Nsmooth-1)      ;Nsmooth=factor to increase point density
    Nzdim=Nz+(Nz-1)*(Nsmooth-1)
    rhigh=dblarr(Nxdim,Nzdim)
    zhigh=dblarr(Nxdim,Nzdim)
    yhigh=dblarr(Nxdim,Nzdim)
    i=0
    for ix=0,Nx-2 do begin
      r1=r(ix,0)
      r2=r(ix+1,0)
      secbeta=z(ix,Nz-1)/r1
      ; --- reconstruct pot ---
      iz1=Nz-1
      iz2=Nz/2
      zi=z(ix,iz1)
      zj=z(ix,iz2)
      pot=alog(zi/zj)/alog((1.d0*iz1)/(1.d0*iz2))
      for ii=0,Nsmooth do begin
        rtmp=exp(alog(r1)+alog(r2/r1)*ii/Nsmooth)
        rhigh(i,*) = rtmp
        zhigh(i,*) = rtmp*secbeta*(DINDGEN(Nzdim)/(Nzdim-1))^pot
        for j=0,Nzdim-1 do begin
          rind = (1.0*i)/Nsmooth
          zind = (1.0*j)/Nsmooth
          yhigh(i,j) = INTERPOLATE(y, rind, zind, cubic=-0.5)
        endfor  
        ;print,ix,i,rtmp
        i=i+1
      endfor
      i=i-1
    endfor  
    ynew = SMOOTH(yhigh,4*Nsmooth+1,/EDGE_TRUNCATE)
    yhigh = ynew

  endif else begin
    zhigh=z
    rhigh=r
    yhigh=y
  endelse  

  ; --- do the contour plot ---
  xmin=min(r)
  xmax=max(r)
  ymin=0.0
  ymax=max(z/r)
  if (KEYWORD_SET(zzmax)) then ymax=zzmax
  ;pos=[0.11,0.22,0.97,0.97]
  pos=[0.11,0.09,0.965,0.98]
  contour, yhigh, rhigh, zhigh/rhigh, /xlog, $
           xtitle='!7r [au]',ytitle='!7z / r', $
           levels=lev, /fill, c_colors=col, position=pos, $
           xrange=[xmin,xmax], yrange=[ymin,ymax], $
           thick=3,charthick=3

  ; --- show grid points ---
  if (KEYWORD_SET(gridon)) then begin  
    oplot, r,z/r, PSYM=3, SYMSIZE=0.5, color=255
  endif

  ; --- add contours ---
  if (KEYWORD_SET(over1)) then begin
    CONTOUR,over1,r,z/r,/overplot,LEVEL=overv1,$
      C_ANNOTATION=overl1,C_COLORS=overc1,$
      C_LINESTYLE=2,C_CHARSIZE=1.3,C_THICK=3
  endif  
  if (KEYWORD_SET(over2)) then begin
    CONTOUR,over2,r,z/r,/overplot,LEVEL=overv2,$
      C_ANNOTATION=overl2,C_COLORS=overc2,$
      C_LINESTYLE=0,C_CHARSIZE=1.3,C_THICK=3
  endif  
  if (KEYWORD_SET(over3)) then begin
    CONTOUR,over3,r,z/r,/overplot,LEVEL=overv3,$
      C_ANNOTATION=overl3,C_COLORS=overc3,$
      C_LINESTYLE=2,C_CHARSIZE=1.3,C_THICK=3
  endif  

  case type of
    ;0: label = '!7n!L'+SPname+'!N [cm!U-3!N]!X'
    ;1: label = '!9e!L'+SPname+'!N!X'
    0: label = '!7n!7 ('+SPname+') [cm!U-3!N]!X'
    1: label = '!9e!7 ('+SPname+')!X'
    2: label = '!7'+SPname+'!N!X'
    3: label = SPname+' charge'
    4: label = SPname
  endcase
  if (y_log) then label = '!7log '+label

  if(KEYWORD_SET(vert)) then begin
    if (vert EQ 1) then begin
      SKALA_VERT, ilev+1, lev, col, label, [0.86,0.55,0.90,0.95]
    endif else begin  
      SKALA_VERT, ilev+1, lev, col, label, [0.18,0.55,0.22,0.95]
    endelse
  endif else begin
    SKALA, ilev+1, lev, col, label, [0.14,0.89,0.6,0.95], 1.3
  endelse
  !p.multi=[0,0,1]

end; CONTFILL3


;------------------------------------------------------
PRO SHOWGRID, r, z, log_grid, zxshow
;------------------------------------------------------
  !p.multi=[0,2,1]
  !x.margin=[11,1]
  !y.margin=[4,2]
  ;pos=[0.11,0.22,0.97,0.97]
  pos=[0.11,0.09,0.97,0.97]

  xmin=min(r)
  xmax=max(r)*1.002
  if (log_grid) then begin
    ymin=0.0
    ymax=max(z/r)*1.05
    ymax=min([ymax,zxshow])
    contour, r, r, z/r, /xlog, /nodata, $
             xtitle='!7r [au]',ytitle='!7z/r [au]', $
             ;ytickname=['0.1','1.0','10','100'], $
             position=pos, $
             xrange=[xmin,xmax], yrange=[ymin,ymax]
    oplot, r,z/r, PSYM=4, SYMSIZE=0.2
  endif else begin
    ymin=min(z)
    ymax=max(z)
    contour, r, r, z, /nodata, $
             xtitle='!7r [au]',ytitle='!7z [au]', $
             position=pos, $
             xrange=[xmin,xmax], yrange=[ymin,ymax]
    oplot, r,z, PSYM=4, SYMSIZE=0.2
  endelse  

  !p.multi=[0,0,1]

end; SHOWGRID


;--------------------------------------------------------
PRO SKALA, ni, lev, col, tit, pos, csize
;--------------------------------------------------------
  xmin=min(lev)
  xmax=max(lev)
  yhh=[0,1,2,3,4,5,6,7,8,9,10]
  ahh=fltarr(ni,11)
  for i=0,ni-1 do begin
    for j=0,10 do begin
      ahh(i,j)=lev(i)
    endfor
  endfor
  wide_pos=pos
  wide_pos[0]=wide_pos[0]-0.01
  wide_pos[1]=wide_pos[1]-0.10
  wide_pos[2]=wide_pos[2]+0.01
  wide_pos[3]=wide_pos[3]+0.01
  contour, ahh, lev, yhh, /nodata, /noerase,$
           xrange=[0,1], yrange=[0,1], $
           xstyle=5, ystyle=5, yticks=5, position=wide_pos 
  x=[0.0,1.0,1.0,0.0]
  y=[0.31,0.31,1.0,1.0]
  polyfill,x,y,color=255,noclip=0
  slen = STRLEN(tit)
  for i=0,STRLEN(tit)-1 do begin
    if (strmid(tit,i,1) EQ "!") then slen=slen-2
    if (strmid(tit,i,2) EQ "!L") then slen=slen-1
    if (strmid(tit,i,2) EQ "!U") then slen=slen-1
  endfor  
  w=csize*slen/19.5*0.28
  x=[0.5-w,0.5+w,0.5+w,0.5-w]
  y=[0.03,0.03,0.32,0.32]
  polyfill,x,y,color=255,noclip=0
  contour, ahh, lev, yhh, $
           xrange=[xmin,xmax], yrange=[0,5], xtitle=tit, CHARSIZE=csize, $
           xstyle=1, ystyle=1, yticks=1, ytickname=[' ',' '], $
           levels=lev, /fill, /noerase, c_colors=col, position=pos, $
           noclip=0, xticklen=0.1
end; SKALA

;--------------------------------------------------------
PRO SKALA3, ni, lev, col, tit, pos, csize0
;--------------------------------------------------------
  xmin=min(lev)
  xmax=max(lev)
  yhh=[0,1,2,3,4,5,6,7,8,9,10]
  ahh=fltarr(ni,11)
  for i=0,ni-1 do begin
    for j=0,10 do begin
      ahh(i,j)=lev(i)
    endfor
  endfor
  wide_pos=pos
  wide_pos[0]=wide_pos[0]-0.01
  wide_pos[1]=wide_pos[1]-0.10
  wide_pos[2]=wide_pos[2]+0.01
  wide_pos[3]=wide_pos[3]+0.01
  contour, ahh, lev, yhh, /nodata, /noerase,$
           xrange=[0,1], yrange=[0,1], $
           xstyle=5, ystyle=5, yticks=5, position=wide_pos 
  x=[0.0,1.0,1.0,0.0]
  y=[0.31,0.31,1.0,1.0]
  polyfill,x,y,color=255,noclip=0
  x=[0.24,0.76,0.76,0.24]
  y=[0.03,0.03,0.32,0.32]
  polyfill,x,y,color=255,noclip=0
  tfrmt = '(F5.1)'
  csize = csize0
  yoff  = -18.0
  if ((min(lev) EQ 0.0) AND max(lev) LT 0.1) then tfrmt = '(F5.3)'
  if ((min(lev) EQ 0.0) AND max(lev) LT 1.0) then tfrmt = '(F5.2)'
  if ((min(lev) EQ 0.0) AND max(lev) GE 10.0)  then begin
     tfrmt='(F5.1)'   & csize=csize0*0.8 &  yoff=-16.0
  endif   
  if ((min(lev) EQ 0.0) AND max(lev) GE 100.0) then begin
     tfrmt='(I4)'     & csize=csize0*0.8 &  yoff=-16.0
  endif   
  if ((min(lev) EQ 0.0) AND max(lev) GE 1000.0) then begin
     tfrmt='(I5)' & csize=csize0*0.7 &  yoff=-15.0
  endif   
  if ((min(lev) EQ 0.0) AND max(lev) GE 10000.0) then begin
     tfrmt='(E8.1E1)' & csize=csize0*0.5 &  yoff=-13.0
  endif   
  contour, ahh, lev, yhh, $
           xrange=[xmin,xmax], yrange=[0,5], $
           xstyle=1, ystyle=1, yticks=1, ytickname=[' ',' '], $
           levels=lev, /fill, /noerase, c_colors=col, position=pos, $
           noclip=0, xticks=4, xtickformat=tfrmt, xticklen=0.2, $
           CHARSIZE=csize
  xyouts, /noclip,(xmin+xmax)/2,yoff,alignment=0.5,CHARSIZE=csize0,tit
end; SKALA3

;--------------------------------------------------------
PRO SKALA2, ni, lev, col, tit, pos, csize
;--------------------------------------------------------
  xmin=min(lev)
  xmax=max(lev)
  yhh=[0,1,2,3,4,5,6,7,8,9,10]
  ahh=fltarr(ni,11)
  for i=0,ni-1 do begin
    for j=0,10 do begin
      ahh(i,j)=lev(i)
    endfor
  endfor
  wide_pos=pos
  wide_pos[0]=wide_pos[0]-0.01
  wide_pos[1]=wide_pos[1]-0.10
  wide_pos[2]=wide_pos[2]+0.01
  wide_pos[3]=wide_pos[3]+0.01
  contour, ahh, lev, yhh, /nodata, /noerase,$
           xrange=[0,1], yrange=[0,1], $
           xstyle=5, ystyle=5, yticks=5, position=wide_pos 
  x=[0.0,1.0,1.0,0.0]
  y=[0.45,0.45,1.0,1.0]
  polyfill,x,y,color=255,noclip=0
  w=0.22*csize*STRLEN(tit)/(1.9*21)
  x=[0.5-w,0.5+w,0.5+w,0.5-w]
  y=[0.24,0.24,0.46,0.46]
  polyfill,x,y,color=255,noclip=0
  contour, ahh, lev, yhh, $
           xrange=[xmin,xmax], yrange=[0,5], xtitle=tit, CHARSIZE=csize, $
           xstyle=1, ystyle=1, yticks=1, ytickname=[' ',' '], $
           levels=lev, /fill, /noerase, c_colors=col, position=pos, $
           noclip=0, xticklen=0.1
end; SKALA2

;--------------------------------------------------------
PRO SKALA_VERT, ni, lev, col, tit, pos
;--------------------------------------------------------
  xmin=min(lev)
  xmax=max(lev)
  xhh=[0,1,2,3,4,5,6,7,8,9,10]
  ahh=fltarr(11,ni)
  for i=0,10 do begin
    for j=0,ni-1 do begin
      ahh(i,j)=lev(j)
    endfor
  endfor
  ;
  wide_pos=pos
  wide_pos[0]=wide_pos[0]-0.05
  wide_pos[1]=wide_pos[1]-0.01
  wide_pos[2]=wide_pos[2]+0.05
  wide_pos[3]=wide_pos[3]+0.01
  contour, ahh, xhh, lev, /nodata, /noerase,$
           xrange=[0,1], yrange=[0,1], $
           xstyle=5, ystyle=5, yticks=5, position=wide_pos 
  x=[0,1,1,0]
  y=[0,0,1,1]
  polyfill,x,y,color=255,noclip=0
  contour, ahh, xhh, lev, $
           xrange=[0,5], yrange=[xmin,xmax], CHARSIZE=1.3, $
           xstyle=1, ystyle=1, xticks=1, xtickname=[' ',' '], $
           levels=lev, /fill, /noerase, c_colors=col, position=pos, $
           noclip=0, xticklen=0.1
  xyouts,/normal,pos[2]+0.031,0.5*(pos[1]+pos[3]),tit,$
         orientation=90,alignment=0.5
end; SKALA_VERT


;-----------------------------------------------------------------
PRO COOLPLOT, xx,zzin,cool,maincool,NCOOL,coolname,log_grid,info,$
              XMIN=xxmin,XMAX=xxmax,ZMIN=zzmin,ZMAX=zzmax,$
              OVERCONT=overcont,OVERVAL=overval,$
              OVERLABEL=overlabel,OVERCOLOR=overcolor,$
              OVER2=over2,OVERV2=overv2,$
              OVERL2=overl2,OVERC2=overc2
;-----------------------------------------------------------------
  coolused=lonarr(NCOOL+1)
  coolind =intarr(NCOOL+1)
  indcool =intarr(NCOOL+1)
  ix=0
  iy=0
  i=0
  Nx=N_ELEMENTS(xx(*,0))
  Nz=N_ELEMENTS(xx(0,*))
  ixmin = 999
  ixmax = 0
  izmin = intarr(Nx)
  izmax = intarr(Nx)
  ;--- set zoom box ---
  zz = zzin
  if (log_grid EQ 2) then zz=zzin/xx
  xmin = MIN(xx)
  xmax = MAX(xx)
  zmin = MIN(zz)
  zmax = MAX(zz)
  if (KEYWORD_SET(xxmin)) then xmin=xxmin
  if (KEYWORD_SET(xxmax)) then xmax=xxmax
  if (KEYWORD_SET(zzmin)) then zmin=zzmin
  if (KEYWORD_SET(zzmax)) then zmax=zzmax
  Ncell = 0L
  for ix=0,Nx-1 do begin
    izmin(ix)=999
    izmax(ix)=0
    r1 = xx(MAX([ix-1,0]),0)
    r2 = xx(MIN([ix+1,Nx-1]),0)  
    ;print,ix,r1,r2,xmin,xmax
    if ((r2 GE xmin) AND (r1 LE xmax)) then begin
      ixmin = MIN([ix,ixmin])  
      ixmax = MAX([ix,ixmax])  
      for iz=0,Nz-1 do begin
        z1 = zz(ix,MAX([iz-1,0]))
        z2 = zz(ix,MIN([iz+1,Nz-1]))
        ;print,iz,z1,z2,zmin,zmax 
        if ((z2 GE zmin) AND (z1 LE zmax)) then begin 
          izmin(ix) = MIN([iz,izmin(ix)])  
          izmax(ix) = MAX([iz,izmax(ix)])
          Ncell = Ncell+1L
        endif
      endfor
      ;print,ix,izmin(ix),izmax(ix)
    endif  
  endfor
  ;print,Ncell
  black   = 0
  white   = 255
  orange  = 210
  red     = 250
  yellow  = 195
  green   = 160
  cyan    = 100
  blue    = 70
  magenta = 40
  itmax = 99
  threshold = MAX([10L,Ncell/100L])
  print,format='("plotting ",A25," itmax,threshold=",I4,",",I5,",",I7)',info,itmax,threshold,Ncell
  for it=1,itmax do begin
    coolused(*,*)=0L
    for ix=ixmin,ixmax do begin
      for iz=izmin(ix),izmax(ix) do begin
        coolused(maincool(ix,iz))=coolused(maincool(ix,iz))+1
      endfor
    endfor
    maxcool=0
    for i=1,NCOOL do begin
      if (coolused(i) GT 0) then begin
        maxcool=maxcool+1
        coolind(i)=maxcool
        indcool(maxcool)=i
      endif  
    endfor
    if (it EQ itmax) then break
    ;------------------------------------------------------------------
    ; ***  switch off some rarely important processes for plotting  ***
    ;-------------------------------------------------------------------
    maxused = MAX(coolused)
    threshold = MAX([10L,Ncell/100L])
    dthreshold = threshold/10
    for i=1,NCOOL do begin
      if (coolused(i) GT 0) then threshold=min([threshold,coolused(i)+dthreshold])
    endfor  
    changed = 0
    for i=1,NCOOL do begin
      if (coolused(i) GT 0) then begin
        if (coolused(i) LE threshold) then begin
          cool(*,*,i)=0.0
          changed = changed + 1
          print,format='(" - not showing ",A45,I4," /",I6)',coolname(i),coolused(i),Ncell
        endif  
      endif
    endfor 
    print,"it=",it,"  max=",maxused,"  threshold=",threshold,"  changed=",changed
    if (changed EQ 0) then break 
    for ix=0,Nx-1 do begin
      for iz=0,Nz-1 do begin
        maincool(ix,iz)=0
        coolmax=0.0
        for i=1,NCOOL do begin
          if(cool(ix,iz,i) GT coolmax) then begin
            maincool(ix,iz)=i
            coolmax=cool(ix,iz,i)
          endif
        endfor
      endfor
    endfor
  endfor
  if (maxcool EQ 0) then return

  !p.multi=[0,2,1]
  !x.margin=[11,1]
  !y.margin=[8,2]

  yy=coolind(maincool)-1.0
  ilev=maxcool
  lev=dblarr(ilev)
  col=intarr(ilev)      
  colmin=20
  colmax=230
  lmin=0
  lmax=ilev-1
  for i=lmin,lmax do begin
    lev(i)=i
    col(i)=fix(colmin+(colmax-colmin)*(lev(i)-lmin)/(lmax-lmin))
  endfor
  if (lmax EQ 7) then begin
    col = [yellow,orange,red,magenta,blue,cyan,green,black]  
  endif  
  if (lmax EQ 8) then begin
    col = [yellow,orange,red,magenta,blue,(blue+cyan)/2,cyan,green,black]  
  endif  
  if (lmax EQ 9) then begin
    col = [yellow,(yellow+orange)/2,orange,red,magenta,blue,(blue+cyan)/2,cyan,green,black]  
  endif
  
  pos=[0.15,0.35,0.92,0.98]
  if (log_grid EQ 0) then begin
    zz = zzin
    contour, yy, xx, zz, xrange=[xmin,xmax], yrange=[zmin,zmax],$
             xtitle='!7r [au]',ytitle='!7z [au]', $
             position=pos, /nodata
  endif
  if (log_grid EQ 1) then begin
    zz = zzin
    ymin1=min(xx)*0.04
    ymin2=max(zz(0,*))*0.04
    ymin=min([ymin1,ymin2])
    ymax=max(zz)
    if(ymin LT 0.1) then begin
      ytname=['0.1','1.0','10','100','1E3']
    endif else begin
      ytname=['1.0','10','100','1E3','1E4']
    endelse
    contour, yy, xx, zz, /xlog, /ylog, xrange=[xmin,xmax], yrange=[zmin,zmax],$
             xtitle='!7r [au]',ytitle='!7z [au]', $
             ytickname=ytname, $
             position=pos, /nodata
  endif
  if (log_grid EQ 2) then begin
    zz = zzin/xx
    contour, yy, xx, zz, /xlog, xrange=[xmin,xmax], yrange=[zmin,zmax],$
             xtitle='!7r [au]',ytitle='z/r', $
             position=pos, /nodata
  endif

  ; --- define cells and borders of cells ---
  xb=dblarr(Nx+1,Nz+1)
  yb=dblarr(Nx+1,Nz+1)
  for ix=1,Nx-1 do begin
    xtmp = sqrt(xx(ix-1,0)*xx(ix,0))         
    if (log_grid EQ 1) then begin
      for iz=1,Nz-1 do begin
        ztmp = 0.5d0*(zz(ix,iz-1)+zz(ix,iz))  
        xb(ix,iz) = xtmp                           ; interior  
        yb(ix,iz) = xtmp/xx(ix,iz)*ztmp
      endfor
      xb(ix,0)  = xtmp                             ; bottom 
      yb(ix,0)  = xtmp/xx(ix,0)*zz(ix,0)
      xb(ix,Nz) = xtmp                             ; top            
      yb(ix,Nz) = xtmp/xx(ix,0)*zz(ix,Nz-1)
    endif else begin
      for iz=1,Nz-1 do begin
        ztmp = 0.5d0*(zz(ix,iz-1)+zz(ix,iz))  
        xb(ix,iz) = xtmp                           ; interior  
        yb(ix,iz) = ztmp
      endfor
      xb(ix,0)  = xtmp                             ; bottom 
      yb(ix,0)  = zz(ix,0)
      xb(ix,Nz) = xtmp                             ; top            
      yb(ix,Nz) = zz(ix,Nz-1)
    endelse
  endfor
  for iz=1,Nz-1 do begin
    xb(0,iz)  = xx(0,0)                            ; left
    yb(0,iz)  = 0.5d0*(zz(0,iz-1)+zz(0,iz))
    xb(Nx,iz) = xx(Nx-1,iz)                        ; right
    yb(Nx,iz) = 0.5d0*(zz(Nx-1,iz-1)+zz(Nx-1,iz))
  endfor
  xb(0,0)   = xx(0,0)        ; lower-left corner
  yb(0,0)   = zz(0,0)
  xb(Nx,0)  = xx(Nx-1,0)     ; lower-right corner
  yb(Nx,0)  = zz(Nx-1,0)
  xb(0,Nz)  = xx(0,Nz-1)     ; upper-left corner
  yb(0,Nz)  = zz(0,Nz-1)
  xb(Nx,Nz) = xx(Nx-1,Nz-1)  ; lower-right corner
  yb(Nx,Nz) = zz(Nx-1,Nz-1)

  ;--- 21 distinguishable colours ---
  TVLCT, 0,0,0,      0          ; black
  TVLCT, 255,165,0,  1          ; orange
  TVLCT, 0,255,255,  2          ; cyan
  TVLCT, 255,0,0,    3          ; red
  TVLCT, 184,134,11, 4          ; dark golden rod
  TVLCT, 255,192,203,5          ; pink
  TVLCT, 0,100,0,    6          ; dark green
  TVLCT, 30,144,255, 7          ; dodger blue  
  TVLCT, 135,206,235,8          ; light sky blue
  TVLCT, 50,205,50,  9          ; lime green
  TVLCT, 255,0,255,  10         ; magenta
  TVLCT, 238,232,170,11         ; pale golden rod
  TVLCT, 139,0,139,  12         ; dark magenta
  TVLCT, 0,255,127,  13         ; spring green
  TVLCT, 255,215,0,  14         ; gold
  TVLCT, 0,0,255,    15         ; blue
  TVLCT, 255,255,255,16         ; white
  TVLCT, 128,128,128,17         ; silver
  TVLCT, 240,128,128,18         ; light coral
  TVLCT, 127,255,212,19         ; aqua marine
  TVLCT, 255,255,0,  20         ; yellow

  lev = floor(lev+0.5)
  col = lev*0-1
  if (info EQ "main heating processes") then begin
    for i=1,maxcool do begin
      ind = indcool(i)
      ic  = coolind(ind)-1
      if (ind EQ  37) then col(ic)=7  ; X-ray Coulomb heating        : dodger blue
      if (ind EQ  12) then col(ic)=15 ; PAH heating                  : blue
      if (ind EQ   4) then col(ic)=10 ; formation of H2 on dust      : magenta
      if (ind EQ   5) then col(ic)=1  ; dust thermal accomodation    : orange
      if (ind EQ  39) then col(ic)=14 ; chemical heating             : gold
      if (ind EQ 103) then col(ic)=3  ; photodissociation heating    : red
      if (ind EQ   2) then col(ic)=17 ; coll. de-excitation of H2exc : silver
      if (ind EQ   8) then col(ic)=9  ; cosmic ray heating lime      : lime green
      if (ind EQ   6) then col(ic)=0  ; C photo-ionisation           : black
      if (ind EQ  20) then col(ic)=2  ; H2O ro-vib                   : cyan
      if (ind EQ  10) then col(ic)=5  ; CO ro-vib                    : pink
      if (ind EQ  21) then col(ic)=13 ; backgr/form heating by H2    : spring green
      print,i,ind," ",coolname(ind),coolused(ind)
    endfor
  endif else begin  
    for i=1,maxcool do begin
      ind = indcool(i)
      ic  = coolind(ind)-1
      if (ind EQ  46) then col(ic)=7  ; OIII line cooling            : dodger blue
      if (ind EQ   6) then col(ic)=15 ; Ly-alpha line cooling        : blue
      if (ind EQ   3) then col(ic)=3  ; OI line cooling              : red
      if (ind EQ   2) then col(ic)=0  ; CII line coolingn            : black
      if (ind EQ  10) then col(ic)=5  ; CO ro-vib                    : pink
      if (ind EQ  16) then col(ic)=2  ; H2O ro-vib                   : cyan
      if (ind EQ   5) then col(ic)=1  ; dust thermal accomodation    : orange
      if (ind EQ  57) then col(ic)=10 ; C2H2 ro-vib cooling          : magenta
      if (ind EQ  61) then col(ic)=6  ; NH3 ro-vib cooling           : dark green
      if (ind EQ  21) then col(ic)=9  ; OH rot cooling               : lime green
      print,i,ind," ",coolname(ind),coolused(ind)
    endfor
  endelse
  remain = []
  for i=0,20 do begin
    if (where(col EQ i) EQ -1) then remain=[remain,i]
  endfor
  ii = 0
  for i=1,maxcool do begin
    ind = indcool(i)
    ic  = coolind(ind)-1
    if (col[ic] EQ -1) then begin
      col[ic] = remain[ii]
      ii = ii+1
    endif
  endfor
  ;print,remain
  ;print,col
  
  for ix=ixmin,ixmax do begin
    for iz=izmin(ix),izmax(ix) do begin
      x=[xb(ix,iz),xb(ix+1,iz)*1.005,xb(ix+1,iz+1)*1.005,xb(ix,iz+1)]
      y=[yb(ix,iz),yb(ix+1,iz),yb(ix+1,iz+1)*1.005,yb(ix,iz+1)*1.005]
      polyfill,x,y,color=col(max([0,coolind(maincool(ix,iz))-1])),noclip=0
      ;oplot,x,y
    endfor
  endfor

  ; --- redraw the axes ---
  if (log_grid EQ 1) then begin
    contour, yy, xx, zz, /xlog, /ylog, /noerase, $
             xrange=[xmin,xmax], yrange=[zmin,zmax],$
             xtitle='!7r [au]',ytitle='!7z [au]', $
             ytickname=ytname, $
             position=pos, /nodata
  endif  
  if (log_grid EQ 2) then begin
    contour, yy, xx, zz, /xlog, /noerase, $
             xrange=[xmin,xmax], yrange=[zmin,zmax],$
             xtitle='!7r [au]',ytitle='z/r', $
             position=pos, /nodata
  endif

  if (KEYWORD_SET(overcont)) then begin
    CONTOUR,overcont,xx,zz,/overplot,LEVEL=overval,$
      C_ANNOTATION=overlabel,C_COLORS=overcolor,$
      C_LINESTYLE=2,C_THICK=2.0,C_CHARSIZE=1.1
  endif  
  if (KEYWORD_SET(over2)) then begin
    CONTOUR,over2,xx,zz,/overplot,LEVEL=overv2,$
      C_ANNOTATION=overl2,C_COLORS=overc2,$
      C_LINESTYLE=2,C_THICK=2.0,C_CHARSIZE=1.1
  endif  

  pos=[0.22,0.01,0.32,0.27]
  c=fltarr(11,ilev+1)
  x=fltarr(11,ilev+1)
  y=fltarr(11,ilev+1)
  for iy=0,ilev do begin
    for ix=0,10 do begin
      x(ix,iy)=ix
      y(ix,iy)=iy+0.5
      c(ix,iy)=iy
    endfor
  endfor
  contour, c, x, y, xrange=[0,10], yrange=[maxcool+0.5,0.5], $
           levels=lev, /cell_fill, c_colors=col, position=pos, $
           xstyle=5, ystyle=5
  for i=1,maxcool do begin
    xyouts,12,y(0,i), coolname(indcool(i)),CHARSIZE=1.0
  endfor
  !p.multi=[0,0,1]
  loadct,39,/silent 

end; COOLPLOT


;-----------------------------------------------------------------------------------------
PRO SPECIES_MASSES,Nx,Nz,Nsp,xx,zz,nHtot,rho,dustgas,nmol,Tgas,Tdust,SPname,Mgas,Mdust,vol
;-----------------------------------------------------------------------------------------
  pi  = acos(-1.d0)
  amu = 1.660531000d-24
  Msun= 1.988922500d+33
  Mearth = 5.974200d+27
  AU  = 1.495978700d+13
  vol = dblarr(Nx,Nz)
  for ix=0,Nx-1 do begin
    ix1 = max([0,ix-1])
    ix2 = ix
    ix3 = min([Nx-1,ix+1])
    x1=sqrt(xx(ix1,0)*xx(ix2,0))*AU      ; does not depend on iz
    x2=sqrt(xx(ix2,0)*xx(ix3,0))*AU      ; does not depend on iz
    for iz=0,Nz-1 do begin
      iz1 = max([0,iz-1])
      iz2 = iz
      iz3 = min([Nz-1,iz+1])
      tanbeta1=0.5*(zz(ix,iz1)+zz(ix,iz2))/xx(ix,0)  ; does not depend on ix
      tanbeta2=0.5*(zz(ix,iz2)+zz(ix,iz3))/xx(ix,0)  ; does not depend on ix
      vol(ix,iz)=4.d0*pi/3.0 * (x2^3-x1^3) * (tanbeta2-tanbeta1)
    endfor
  endfor
  NN = Nsp+1
  bla=' '
  isp= intarr(NN)
  msp= dblarr(NN)
  mass=dblarr(NN)
  Tgmass=dblarr(NN)
  Tdmass=dblarr(NN)
  ma=0.d0
  sum=0.d0
  ;--- get species masses ---
  ; CHR 20220318 changes to readcol
  mspdum=dblarr(NN) ; couldn't find a smarter way
  readcol,'Species.out',format='(A,I,A,F)',skip=1,dum1,dum2,dum3,mspdum
  msp(0) = 9.109389754E-28  ; electron mass
  print,mspdum
  for i=1, Nsp do begin
    msp(i)=mspdum(i-1)*amu  
    print,i,' ',Spname(i),msp(i)
  endfor
  
  Mgas=0.d0
  Mdust=0.d0
;--- get gas mass in 5K-temperature bins ---
  NT = 20
  Mgas_cum=dblarr(NT)
  Tmin=findgen(NT)*5.
  Tmax=(findgen(NT)+1)*5.
  Tmax(NT-1)=1.e5
  openw,1,'Cumulativemass_Tgas.out'
  for ix=0,Nx-1 do begin
    for iz=0,Nz-1 do begin
      Tg=Tgas(ix,iz)
      for j=0, NT-1 do begin
          if (Tg ge Tmin(j) and Tg lt Tmax(j)) then Mgas_cum(j) = Mgas_cum(j) + vol(ix,iz)*rho(ix,iz)
      endfor
      Mgas  = Mgas  + vol(ix,iz)*rho(ix,iz)
      Mdust = Mdust + vol(ix,iz)*rho(ix,iz)*dustgas(ix,iz)
      ;print,ix,iz,rho(ix,iz),nHtot(ix,iz),nHtot(ix,iz)*amu,rho(ix,iz)/nHtot(ix,iz)
    endfor
  endfor
  for j=0, NT-1 do begin
     printf,1,Tmax(j),Mgas_cum(j)/Msun, format='(F9.1,E11.3)' 
  endfor 
  close,1
  !y.range = [0,100]
  !y.style=-1 
  Tmax_name=string(Tmax, format='(f7.1)')
  for i=0, NT-1 do begin & $
      if ((i mod 2) eq 0) then Tmax_name(i)=' ' & $
  endfor
  Tmax_name(NT-1)='>100'
  cut=findgen(NT)*0.;+(1.e-3*Mgas/Msun)
  colbars=indgen(NT)*0.+50.
  bar_plot, 100.*(Mgas_cum/Mgas), BarNames=Tmax_name, baselines=cut, $
    YTITLE='M!Dgas!N[T-5K,T]!N/M!Dgas!N [%]', $
    XTITLE='T!Dgas!N [K]', colors=colbars
  xyouts, 6., 80., 'M!Dgas!N(total) ='+string(Mgas/Msun, format='(f7.2)')+'M!DSun!N'
  temperature_barplot,'dust',Tdust,Nx,Nz,vol,rho,dustgas,Mgas,/absolut

  openw,1,'Speciesmasses.out'
  for i=0,Nsp do begin
    mass(i)=0.d0  
    for ix=0,Nx-1 do begin
      for iz=0,Nz-1 do begin
        n1=nmol(ix,iz,i)
        Tg=Tgas(ix,iz)
        Td=Tdust(ix,iz)
        mass(i)   = mass(i)   + vol(ix,iz)*n1
        Tgmass(i) = Tgmass(i) + vol(ix,iz)*n1*Tg
        Tdmass(i) = Tdmass(i) + vol(ix,iz)*n1*Td
      endfor
    endfor 
    mass(i)   = mass(i)*msp(i)
    Tgmass(i) = Tgmass(i)*msp(i)
    Tdmass(i) = Tdmass(i)*msp(i)
    text = STRING(format="(a9,a4)","Mass of ",SPname(i))
    ;print,format="(a13,a2,E11.3,a5,E11.3,a13,F7.2,a8,F7.2,a1,E11.3)",$
    ;      text," = ",mass(i)/Msun," Msun",$
    ;      mass(i)/Mearth," Mearth  <Tg>=",Tgmass(i)/mass(i),$
    ;      "K  <Td>=",Tdmass(i)/mass(i),"K ",mass(i)/mgas
    printf,1,format="(a7,99(E11.3))",$
             SPname(i),mass(i)/Msun,Tgmass(i)/mass(i),Tdmass(i)/mass(i)
    sum = sum + mass(i)
  endfor
  close,1
  print, '-------------------------------------------------------------'
  print,format="(a15,E11.3,a5,E11.3,a7)",$
        " Mdust        = ",Mdust/Msun," Msun",Mdust/Mearth," Mearth"
  print,format="(a15,E11.3,a5,E11.3,a7)",$
        " Mgas         = ",Mgas/Msun," Msun",Mgas/Mearth," Mearth"
  print,format="(a15,E11.3,A5,E11.3,a7)",$
        " Mgas from sp = ",sum/Msun," Msun",sum/Mearth," Mearth"
  print,format="(a15,E11.3)",$
        " error [%]    = ",abs(Mgas-sum)/Mgas*100.d0
  print, '-------------------------------------------------------------'
  Tgmean= 0.d0
  Tdmean= 0.d0
  for ix=0,Nx-1 do begin
    for iz=0,Nz-1 do begin
      Tgmean = Tgmean+ vol(ix,iz)*rho(ix,iz)*Tgas(ix,iz)
      Tdmean = Tdmean+ vol(ix,iz)*rho(ix,iz)*dustgas(ix,iz)*Tdust(ix,iz)
    endfor
  endfor 
  Tgmean = Tgmean/Mgas
  Tdmean = Tdmean/Mdust
  print,format='("  minimum gas temperature Tg,min =",F8.2,"K")',min(Tgas)
  print,format='("  maximum gas temperature Tg,max =",F8.2,"K")',max(Tgas)
  print,format='("  mean gas temperature  <Tg>_rho =",F8.2,"K")',Tgmean
  print,format='(" minimum dust temperature Td,min =",F8.2,"K")',min(Tdust)
  print,format='(" maximum dust temperature Td,max =",F8.2,"K")',max(Tdust)
  print,format='(" mean dust temperature <Td>_rhod =",F8.2,"K")',Tdmean
  print, '-------------------------------------------------------------'
end ; SPECIES_MASSES


;-------------------------------------------------------------
PRO TEXC_PLOT,Nx,Nz,nmol,Tgas,Tdust,AV_ver,rr,xx,zz,Titel
;-------------------------------------------------------------
  NN=N_ELEMENTS(rr)
  z  = dblarr(Nz)
  Tg = dblarr(Nz)
  Td = dblarr(Nz)
  n  = dblarr(Nz)
  AV = dblarr(Nz)
  Ncol = dblarr(Nz)
  Tcol = dblarr(Nz)
  Tdol = dblarr(Nz)
  AU = 1.495978700d+13
  xmin=1.E+10
  xmax=1.E+22
  if (Titel EQ "H2") then begin
    xmin=xmin*1.e+4  
    xmax=xmax*1.e+4  
  endif
  ymin=10.0
  ymax=10000.0
  plot,Tcol,Ncol,/xlog,/ylog,/nodata,position=[0.15,0.1,0.95,0.95],$
       xrange=[xmin,xmax],yrange=[ymin,ymax],$
       title=Titel,xtitle="!7N!S!Uver!R!L"+Titel+" !N[cm!U2!N]",$
       ytitle="<T> [K]"
  for i=0,NN-1 do begin
    xsearch=rr(i)
    if((xsearch GE xx(0,0)) AND (xsearch LE xx(Nx-1,0))) then begin
    for iz=0,Nz-1 do begin
      xtmp = xx(*,iz)
      ztmp = zz(*,iz)
      Ttmp = Tgas(*,iz)
      Tdmp = Tdust(*,iz)
      ntmp = nmol(*,iz)
      AVtmp= AV_ver(*,iz)
      z(iz) = INTERPOL(ztmp, xtmp, xsearch)  
      Tg(iz)= INTERPOL(Ttmp, xtmp, xsearch)  
      Td(iz)= INTERPOL(Tdmp, xtmp, xsearch)  
      n(iz) = INTERPOL(ntmp, xtmp, xsearch)  
      AV(iz)= INTERPOL(AVtmp,xtmp, xsearch)  
    endfor  
    Ncol(Nz-1)=1.E+5
    Tcol(Nz-1)=Tg(Nz-1)  ; ganz oben
    Tdol(Nz-1)=Td(Nz-1)  
    for iz=Nz-2,0,-1 do begin
      dz=(z(iz+1)-z(iz))*AU
      Ncol(iz) = Ncol(iz+1) + 0.5*(n(iz+1)+n(iz))*dz
      Tcol(iz) = Tcol(iz+1) + 0.5*(n(iz+1)*Tg(iz+1)+n(iz)*Tg(iz))*dz
      Tdol(iz) = Tdol(iz+1) + 0.5*(n(iz+1)*Td(iz+1)+n(iz)*Td(iz))*dz
    endfor  
    for iz=Nz-2,0,-1 do begin
      Tcol(iz) = Tcol(iz)/Ncol(iz)
      Tdol(iz) = Tdol(iz)/Ncol(iz)
    endfor  
    oplot,Ncol(0:Nz-2),Tcol(0:Nz-2),THICK=3
    oplot,Ncol(0:Nz-2),Tdol(0:Nz-2),LINESTYLE=1,THICK=1
    bem=STRTRIM(STRING(format="(i3)",xsearch),2)
    if (xsearch LT 2.0) then begin
      bem=STRTRIM(STRING(format="(f3.1)",xsearch),2)
    endif    
    xyouts,Ncol(0)*1.2,Tcol(0)*0.9,bem,$
           CHARSIZE=1.0,ALIGNMENT=0.0,$
           CLIP=[xmin,ymin,xmax,ymax], NOCLIP=0
    if(Ncol(Nz-2) GT xmin) then begin
    xyouts,Ncol(Nz-2)*0.8,Tcol(Nz-2)*0.9,$
           STRTRIM(STRING(format="(i3)",xsearch),2),$
           CHARSIZE=1.0,ALIGNMENT=1.0,$
           CLIP=[xmin,ymin,xmax,ymax], NOCLIP=0
    endif
    if(max(AV) GT 0.1) then begin
      N1 = INTERPOL(Ncol,AV,[0.1,0.1])
      T1 = INTERPOL(Tcol,AV,[0.1,0.1])
      if(max(Ncol)/N1(0) GT 1.5) then begin   ; 
        ; define an open circle symbol with 16 points,   
        AA = FINDGEN(17) * (!PI*2/16.)  
        USERSYM, COS(AA), SIN(AA)
        oplot,N1,T1,color=blue,PSYM=8,SYMSIZE=0.6
      endif
    endif  
    if(max(AV) GT 1.0) then begin
      N2 = INTERPOL(Ncol,AV,[1.0,1.0])
      T2 = INTERPOL(Tcol,AV,[1.0,1.0])
      if(N2(0)/N1(0) GT 1.5) then begin    ; sonst sieht man nix
        ; define an open circle symbol with 16 points,   
        AA = FINDGEN(17) * (!PI*2/16.)  
        USERSYM, COS(AA), SIN(AA)
        oplot,N2,T2,color=blue,PSYM=8,SYMSIZE=1.0
      endif
    endif  
    if(max(AV) GT 10.0) then begin
      N3 = INTERPOL(Ncol,AV,[10.0,10.0])
      T3 = INTERPOL(Tcol,AV,[10.0,10.0])
      if(N3(0)/N2(0) GT 1.5) then begin    ; sonst sieht man nix
        ; define a filled circle symbol with 16 points,   
        AA = FINDGEN(17) * (!PI*2/16.)  
        USERSYM, COS(AA), SIN(AA), /FILL  
        oplot,N3,T3,color=blue,PSYM=8,SYMSIZE=1.0
      endif  
    endif
    endif 
  endfor

  if(Titel EQ "CO") then begin
    x1=1.E+15
    x2=1.E+15
    y1=8500
    y2=4000
    ARROW,x1,y1,x1,y1*0.6,/data,HSIZE=500.0,THICK=7.0
    ARROW,x2,y2,x2,y2*0.6,/data,HSIZE=500.0,THICK=7.0
    xyouts,x1*2.0,y1*0.85,/data,"rotational"
    xyouts,x2*2.0,y2*0.85,/data,"ro-vibrational"
    ARROW,1.6E+17,y1*0.9,1.6E+17*10.0,y1*0.9,/data,HSIZE=250.0,THICK=3.0
    ARROW,1.0E+18,y2*0.9,1.0E+18*10.0,y2*0.9,/data,HSIZE=250.0,THICK=3.0
    x1=3.E+20
    x2=x1*20.0
    xm=x1*sqrt(20.0)
    y1=3100.0/5.0
    ARROW,x2,y1,x1,y1,/data,HSIZE=500.0,THICK=7.0
    xyouts,xm,y1*1.2,ALIGNMENT=0.5,'ro-vib'
    ;ARROW,xm,y1*1.65,xm,y1*6,/data,HSIZE=250.0,THICK=3.0
    y1=55.0/5.0
    ARROW,x2,y1,x1,y1,/data,HSIZE=500.0,THICK=7.0
    xyouts,xm,y1*1.05,ALIGNMENT=0.2,'4->3'
    y1=83.0/5.0
    ARROW,x2,y1,x1,y1,/data,HSIZE=500.0,THICK=7.0
    xyouts,xm,y1*1.05,ALIGNMENT=0.2,'5->4'
    y1=116.0/5.0
    ARROW,x2,y1,x1,y1,/data,HSIZE=500.0,THICK=7.0
    xyouts,xm,y1*1.05,ALIGNMENT=0.2,'6->5'
    y1=155.0/5.0
    ARROW,x2,y1,x1,y1,/data,HSIZE=500.0,THICK=7.0
    xyouts,xm,y1*1.05,ALIGNMENT=0.2,'7->6'
    ARROW,xm,y1*1.5,xm,y1*6,/data,HSIZE=250.0,THICK=3.0
  endif    
  if(Titel EQ "H2O") then begin
    x1=1.E+13
    x2=1.E+15
    y1=8500
    ARROW,x1,y1,x1,y1*0.6,/data,HSIZE=500.0,THICK=7.0
    xyouts,1.E+14,y1*0.75,/data,ALIGNMENT=0.5,CHARSIZE=2.0,". . ."
    ARROW,x2,y1,x2,y1*0.6,/data,HSIZE=500.0,THICK=7.0
    xyouts,x2*2.0,y1*0.85,/data,"rotational"
    ARROW,1.8E+17,y1*0.9,1.8E+17*10.0,y1*0.9,/data,HSIZE=250.0,THICK=3.0
    x1=3.E+20
    x2=x1*20.0
    xm=x1*sqrt(20.0)
    y1=60.0/5.0
    ARROW,x2,y1,x1,y1,/data,HSIZE=500.0,THICK=7.0
    xyouts,xm,y1*1.25,ALIGNMENT=0.5,'5kT!L !N=!L !NE!Lu!N'
    xyouts,xm,40.0,/data,ORIENTATION=90,CHARSIZE=2.0,". . ."
    y2=1000.0/5.0
    ARROW,x2,y2,x1,y2,/data,HSIZE=500.0,THICK=7.0
    xyouts,xm,y2*1.25,ALIGNMENT=0.5,'5kT!L !N=!L !NE!Lu!N'
    ;ARROW,xm,y2*1.7,xm,y2*20,/data,HSIZE=250.0,THICK=3.0
  endif    
  if(Titel EQ "OI") then begin
    x1=3.E+17
    y1=8500
    ARROW,x1,y1,x1,y1*0.6,/data,HSIZE=500.0,THICK=7.0
    xyouts,x1*2.0,y1*0.85,/data,"!763!9m!7m"
    x1=3.E+20
    x2=x1*20.0
    xm=x1*sqrt(20.0)
    y1=230.0/5.0
    ARROW,x2,y1,x1,y1,/data,HSIZE=500.0,THICK=7.0
    xyouts,xm,y1*1.25,ALIGNMENT=0.5,'5kT!L !N=!L !NE!Lu!N'
    ;ARROW,xm,y1*1.7,xm,y1*40,/data,HSIZE=250.0,THICK=3.0
  endif    
  if(Titel EQ "CII") then begin
    x1=2.E+17
    y1=8500
    ARROW,x1,y1,x1,y1*0.6,/data,HSIZE=500.0,THICK=7.0
    xyouts,x1*2.0,y1*0.85,/data,"!7158!9m!7m"
    x1=3.E+20
    x2=x1*20.0
    xm=x1*sqrt(20.0)
    y1=91.0/5.0
    ARROW,x2,y1,x1,y1,/data,HSIZE=500.0,THICK=7.0
    xyouts,xm,y1*1.25,ALIGNMENT=0.5,'5kT!L !N=!L !NE!Lu!N'
    ;ARROW,xm,y1*1.7,xm,y1*40,/data,HSIZE=250.0,THICK=3.0
  endif    

end; TEXC_PLOT

PRO plot_heating_cooling,xx,zz,nHtot,nheat,heat,heatname,ncool,cool,coolname

for i=1,Nheat do begin
   name = strtrim(heatname(i))+' (erg/s)'
   CONTFILL,xx,zz,heat(*,*,i)/nHtot,name,1,1,4
endfor
for i=1,Ncool do begin
   name = strtrim(coolname(i))+' (erg/s)'
   CONTFILL,xx,zz,cool(*,*,i)/nHtot,name,1,1,4
endfor

end
; ---------------------------------------------------------
; *** alpha viscosity ***
; ---------------------------------------------------------
pro plot_alpha,folder,xx,zz,nx,nz,rho,press,Tgas,cT,mstar,NH_ver,nsp,SPname,nmol,nHtot,AV_rad,AV_ver,chiRT

 loadct,39,/silent
; --------------------------------------------------
  black   = 0
  white   = 255
  orange  = 210
  red     = 250
  yellow  = 195
  green   = 160
  cyan    = 100
  blue    = 70
  magenta = 40
; --------------------------------------------------
grav = 6.672598500D-08     ; gravitational constant
Msun = 1.988922500D+33     ; solar mass
AU   = 1.495978700D+13     ; 1 astronomical unit
yr   = 3600.*24.*365.
mH   = 1.67e-24            ; g
amu  = 1.660531000d-24
; --------------------------------------------------

openr, 1,folder+"/alpha_viscosity.out",ERROR = err
Ngrid = NX*NZ
alpha_vis = fltarr(NX,NZ)
Rem       = fltarr(NX,NZ)
ElOhm     = fltarr(NX,NZ)
Am        = fltarr(NX,NZ)
Hall      = fltarr(NX,NZ)
Induction = fltarr(NX,NZ)
alpha_am  = fltarr(NX,NZ)
vturb     = fltarr(Nx,Nz)
VA        = fltarr(Nx,Nz)
Eacc      = fltarr(Nx,Nz)
Binduc    = fltarr(Nx,Nz)
B2        = fltarr(Nx,Nz)
viscosity = fltarr(Nx,Nz)
viscosity_mol = fltarr(Nx,Nz)
Mdot      = fltarr(Nx)
alpha_viscosity_from_Mdot = fltarr(Nx,Nz)
Prm       = fltarr(Nx,Nz)
eta       = fltarr(Nx,Nz)
beta      = fltarr(Nx,Nz)
Rem_elec  = fltarr(Nx,Nz)

print,'Reading viscosity data'
line =""
readf,1,format='(7x,D30)',Mdot_in ; g/s
readf,1,line
for i=1,Ngrid do begin
    readf,1,format='(I4,I4,9(E13.5))',ix,iz,tmp1,tmp2,tmp3,tmp4,tmp5,tmp6,tmp7,tmp8,tmp9
    print,i,ix,iz,tmp1,tmp2,tmp3,tmp4,tmp5,tmp6,tmp7,tmp8,tmp9
    ix = ix - 1
    iz = iz - 1
    alpha_vis(ix,iz) = tmp1
    ElOhm(ix,iz)     = tmp2
    Rem_elec(ix,iz)  = tmp3
    Am(ix,iz)        = tmp4
    Hall(ix,iz)      = tmp5
    Induction(ix,iz) = tmp6
    vturb(ix,iz)     = tmp7*1e-5
    VA(ix,iz)        = tmp8*1e-5
    beta(ix,iz)      = tmp9
 endfor
for i=1,Nx do begin
    readf,1,format='(I4,E13.5)',ix,tmp10
    Mdot(ix-1) = tmp10
    ;print,ix,tmp10
endfor
close,1
; ---------------------------------
; Magnetic Reynolds number
Rem = (cT/(1e5*Va))*ElOhm
; ----------------------------------

; ---------------------------------
print,'max alpha =',max(alpha_vis)
print,'min alpha =',min(alpha_vis)
; ----------------------------------
; computing accretion heating rate
ms=mstar*Msun
x=xx*AU
z=zz*AU
delta = 1.0
for i = 0L, nx-1 do begin
  SurfDens = NH_ver(i,0)*mH   ; g cm^-2
  for j = 0L, nz-1 do begin
    ;kepler velocity
    omega=sqrt(grav*ms/((sqrt(x(i)^2+z(i,j)^2))^3))
    Eacc(i,j) = 9./4.*alpha_vis(i,j)*press(i,j)*omega
    Hp = cT(i,0)/omega
    if(Mdot_in gt 1e-16) then begin
       alpha_viscosity_from_Mdot(i,j) = Mdot_in/(6.*!pi*SurfDens*cT(i,j)*Hp)
    endif else begin
       alpha_viscosity_from_Mdot(i,j) = (VA(i,j)/cT(i,j))^(2.*delta)
    endelse
    B2(i,j)=Mdot(i)*omega/(2.*Hp)
    viscosity(i,j) = alpha_vis(i,j)*cT(i,j)*Hp ; cm^2/s
    ;print,i,j,Hp/AU
  endfor  
endfor
;stop
; ----------------------------------
rHall = Hall/Induction
rHall_ElOhm=Hall*ElOhm/Induction
rHall_Am = Hall/Am
rHall_ELOhm_Am=(Hall/Induction)/(1./ElOhm+Am/Induction)
OA_I = 1/ElOhm+Am/Induction
alpha_am = 0.5/sqrt((50./Am^(1.2))^2+((8./Am^0.3)+1.)^2)
Binduc = sqrt(4*!pi*rho)*VA*1e5
Pmag   = Binduc^2/(8.*!pi)
rPress = Pmag/press
; magnetically-driven wind
;beta   = Press/Pmag ; beta<1 if beta~1 then there is a disc wind
; ----------
; if revival of MRI according to Lesur's model
for ix=0,Nx-1 do begin
   for iz=0,Nz-1 do begin
      if(alpha_vis(ix,iz) gt alpha_am(ix,iz)) then begin
         print,ix,iz,alpha_vis(ix,iz),alpha_am(ix,iz)
      endif   
   endfor   
endfor
; ----------
; magnetic Prandtl number
; ne = nmol(*,*,0)
dH2 = 0.7*1e-10*1e2 ; cm bond distance
sigH2 = !dpi*dH2^2 ; cm^2 cross section
mH2 = 2.*amu ; g
eta   = mH2*cT/(3.*sqrt(2)*sigH2) ; g cm/s/cm^2 = g/s/cm 
viscosity_mol = eta/rho ; rho : g/cm3 -> eta/rho = s^-1 cm2
;viscosity_mol = cT/sigH2/nHtot
Prm = viscosity_mol/(234.*(nHtot/nmol(*,*,0))*sqrt(Tgas))
;stop
; ----------
Dv = sqrt(vturb^2+(1e-5*cT)^2) ;km/s
; ----------
dMdot=alpha_vis*cT*rho
; ----------------------------------
ymin1=max([alog10(min(alpha_vis)),-4.])
CONTFILL,xx,zz,alpha_vis,'[!9a!7(turbulent viscosity)]',1,1,4,OVERCONT=rHall,OVERVAL=[1.,3.],OVERCOLOR=black,OVERLABEL=['Hall/Induc=1','3'],NSMOOTH=3,OVER2=alog10(ElOhm),OVERV2=1,OVERC2=red,OVERL2=['El(Ohm)=1'],ymax=0.,ymin=ymin1
CONTFILL,xx,zz,alpha_vis,'[!9a!7(turbulent viscosity)]',0,1,4,NSMOOTH=3,ymax=-1.0,ymin=-6.,OVERCONT=Am,OVERVAL=[1.],OVERCOLOR=black,OVER2=Av_ver,OVERV2=1.,OVERC2=red,OVERL2=['Av=1']
CONTFILL2,xx,zz,alpha_vis,'[!9a!7]',1,1,4,NSMOOTH=3,ymax=-1.0,ymin=-6,OVERCONT=alog10(ElOhm),OVERVAL=[1.],OVERCOLOR=white,OVERLABEL=['El(Ohm)=1'],OVER2=rHall,OVERV2=1.,OVERC2=red,OVERL2=['Hall/Induc=1']

;CONTFILL,xx,zz,alpha_viscosity_from_Mdot,'[!9a!7!IMRI!N]',1,1,4,OVERCONT=rHall,OVERVAL=1,OVERCOLOR=black,NSMOOTH=3,OVER2=alog10(ElOhm),OVERV2=1,OVERC2=red,OVERL2=['El(Ohm)=1']
;print,'max non-MRI alpha=',max(alpha_viscosity_from_Mdot)
;print,'min(El(Ohm))=',min(ElOhm)
;print,'max(El(Ohm))=',max(ElOhm)
; ---------
;ralpha = alpha_vis/alpha_viscosity_from_Mdot
;CONTFILL,xx,zz,ralpha,'!9a!7 ratio',1,1,4
CONTFILL,xx,zz,viscosity,'!9n!7 [cm!E2!N s!E-1!N]',1,1,4,NSMOOTH=3,OVERCONT=Av_ver,OVERVAL=[1.],OVERCOLOR=black,OVERLABEL=['AV=1']
CONTFILL,xx,zz,viscosity_mol,'!9m!7 [cm!E2!N s!E-1!N]',1,1,4,NSMOOTH=3,OVERCONT=Av_ver,OVERVAL=[1.],OVERCOLOR=black,OVERLABEL=['AV=1']
CONTFILL,xx,zz,viscosity_mol/viscosity,'!9m!7/!9n!7',1,1,4,NSMOOTH=3,OVERCONT=viscosity_mol/viscosity,OVERVAL=[1],OVERCOLOR=black,OVERLABEL=['1']
CONTFILL,xx,zz,viscosity,'!9n!7 [cm!E2!N s!E-1!N]',0,1,4,NSMOOTH=3,OVERCONT=Av_ver,OVERVAL=[1.],OVERCOLOR=black,OVERLABEL=['AV=1']
CONTFILL,xx,zz,viscosity_mol,'!9m!7 [cm!E2!N s!E-1!N]',0,1,4,NSMOOTH=3,OVERCONT=Av_ver,OVERVAL=[1.],OVERCOLOR=black,OVERLABEL=['AV=1']
CONTFILL,xx,zz,viscosity_mol/viscosity,'!9m!7/!9n!7',0,1,4,NSMOOTH=3,OVERCONT=viscosity_mol/viscosity,OVERVAL=[1],OVERCOLOR=black,OVERLABEL=['1']

; -----
CONTFILL,xx,zz,ElOhm,'[El(Ohm)]',1,1,4,OVERCONT=alog10(ElOhm),OVERVAL=0,OVERLABEL=['1'],OVERCOLOR=white,OVER2=rHall,OVERV2=1,OVERC2=black,NSMOOTH=3,ymin=min(alog10(ElOhm)),ymax=max(alog10(ElOhm)),OVERL2=['Hall/Induc=1']
CONTFILL,xx,zz,Rem,'[Rem]',1,1,4,OVERCONT=alog10(ElOhm),OVERVAL=0,OVERLABEL=['El(Ohm)=1'],OVERCOLOR=white,OVER2=ReM,OVERV2=100.,OVERC2=yellow,NSMOOTH=3

CONTFILL,xx,zz,ElOhm,'[El(Ohm)]',0,1,4,OVERCONT=alog10(ElOhm),OVERVAL=0,OVERLABEL=['El(Ohm)=1'],OVERCOLOR=white,OVER2=rHall,OVERV2=1,OVERC2=black,NSMOOTH=3,ymin=min(alog10(ElOhm)),ymax=max(alog10(ElOhm)),OVERL2=['Hall/Induc=1']

CONTFILL,xx,zz,ElOhm,'[El(Ohm)]',0,1,4,OVERCONT=Av_ver,OVERVAL=[1.],OVERCOLOR=red
; -----
;CONTFILL,xx,zz,Am/Induction,'[Am/Induction]',1,1,4,NSMOOTH=3

isp=SPindex(Nsp,Spname,"C+")
wpos=where(strpos(SPname(0:nsp-1),'+') gt 0,npos)
wneg=where(strpos(SPname(1:nsp-1),'-') gt 0,nneg)+1
nb_ions=npos+nneg
nions=fltarr(Nx,Nz)
for i=0,npos-1 do begin
   nions = nions+nmol(*,*,wpos(i))
endfor
for i=0,nneg-1 do begin
   nions = nions+nmol(*,*,wneg(i))
endfor
CONTFILL,xx,zz,nmol(*,*,isp)/nHtot(*,*),'C+',1,1,1,OVERCONT=alog10(chiRT/nHtot),OVERVAL=[-6,-5,-4,-3,-2,-1],$
OVERLABEL=['-6','-5','-4','-3','-2','-1'],OVERCOLOR=white
yy=nions/nHtot(*,*)
CONTFILL,xx,zz,yy,'ions',1,1,1,OVERCONT=yy,OVERVAL=[1e-6,1e-5,1e-4]
CONTFILL,xx,zz,nions,'ions',1,1,0,OVERCONT=Av_ver,OVERVAL=[1.],OVERCOLOR=red
CONTFILL,xx,zz,Am,'[Am]',1,1,4,NSMOOTH=3,OVERCONT=Av_ver,OVERVAL=[1.],OVERCOLOR=red
;OVERCONT=nions,OVERCOLOR=red,OVERVAL=[1e2,1e4]
CONTFILL,xx,zz,Am/Induction,'[Am/Induction]',1,1,4,NSMOOTH=3,OVERCONT=Av_ver,OVERVAL=[1.],OVERCOLOR=red
; -----
CONTFILL,xx,zz,alpha_am,'[max(!9a!7!IAm!N)]',1,1,4,OVERCONT=rHall,OVERVAL=1,OVERCOLOR=white,NSMOOTH=3 
CONTFILL,xx,zz,alpha_am,'[max(!9a!7!IAm!N)]',0,1,4,OVERCONT=rHall,OVERVAL=1,OVERCOLOR=white,NSMOOTH=3 
; -----
CONTFILL,xx,zz,rHall,'[Hall/Induction]',1,1,4,OVERCONT=rHall,OVERVAL=1,OVERCOLOR=white,NSMOOTH=3
CONTFILL,xx,zz,rHall,'[Hall/Induction]',0,1,4,OVERCONT=rHall,OVERVAL=1,OVERCOLOR=white,NSMOOTH=3

;CONTFILL,xx,zz,rHall_ElOhm,'[Hall/Ohm]',1,1,4,OVERCONT=rHall_ElOhm,OVERVAL=1,OVERCOLOR=white,NSMOOTH=3,OVERLABEL=['Hall/Ohm=1'],OVERC2=alog10(ElOhm),OVERV2=0,OVERL2=['El(Ohm)=1']

;CONTFILL,xx,zz,rHall_Am,'[Hall/Am]',1,1,4,OVERCONT=rHall_Am,OVERVAL=1,OVERCOLOR=white,NSMOOTH=3,OVERLABEL=['Hall/Am=1'],OVER2=rHall,OVERV2=1,OVERC2=black
;CONTFILL,xx,zz,rHall_ElOhm_Am,'[Hall/(Ohm+Am)]',1,1,4,OVERCONT=OA_I,OVERVAL=1,OVERCOLOR=white,NSMOOTH=3,OVERLABEL=['(Ohm+Am)/Induc=1'],OVER2=rHall,OVERV2=1,OVERC2=black
;CONTFILL,xx,zz,OA_I,'(Ohm+Am)/Induc',1,1,4,OVERCONT=rHall,OVERVAL=[1]
; -----
CONTFILL,xx,zz,vturb,'v!Lturb!N [km/s]',1,1,4,NSMOOTH=3
CONTFILL2,xx,zz,vturb,'v!Lturb!N [km/s]',1,0,4,NSMOOTH=3
CONTFILL,xx,zz,vturb,'v!Lturb!N [km/s]',0,0,4,NSMOOTH=3,OVERCONT=Av_ver,OVERVAL=[1.],OVERCOLOR=red
CONTFILL,xx,zz,cT*1e-5,'cs [km/s]',0,0,4,NSMOOTH=3;,OVERCONT=Av_ver,OVERVAL=[1.],OVERCOLOR=red
CONTFILL2,xx,zz,cT*1e-5,'cs [km/s]',1,0,4,NSMOOTH=3 ;,OVERCONT=Av_ver,OVERVAL=[1.],OVERCOLOR=red
; ------- velocity turbulence/speed of sound
isp = SPindex(Nsp,SPname,"CO")
rCO=alog10(nmol(*,*,isp)/nHtot)
CONTFILL2,xx,zz,vturb*1e5/cT,'v!Lturb!N/c!Lsound!N',1,1,4,NSMOOTH=3,ymin=-4.,ymax=-1
CONTFILL,xx,zz,vturb*1e5/cT,'v!Lturb!N/c!Lsound!N',0,0,4,NSMOOTH=3
CONTFILL2,xx,zz,vturb*1e5/cT,'v!Lturb!N/c!Lsound!N',0,0,4,NSMOOTH=3,OVERCONT=rCO,OVERVAL=[-5.,-4.],OVERCOLOR=black,OVERLABEL=['1E-5','n(CO)/nH=1E-4']
;CONTFILL,xx,zz,dv,'dv [km/s]',1,1,4,NSMOOTH=3
;CONTFILL,xx,zz,dv,'dv [km/s]',0,1,4,NSMOOTH=3
;CONTFILL2,xx,zz,dv,'dv [km/s]',1,1,4,NSMOOTH=3
;CONTFILL2,xx,zz,dv,'dv [km/s]',0,0,4,NSMOOTH=3
; ----------
CONTFILL,xx,zz,VA,'v!LAlfven!N [km/s]',1,1,4,NSMOOTH=3
CONTFILL,xx,zz,VA*1e5/cT,'v!LAlfven!N/c!Lsound!N',1,1,4,NSMOOTH=3,OVERCONT=VA*1e5/cT,OVERVAL=[1.],OVERCOLOR=red,OVERLABEL=['1']
CONTFILL2,xx,zz,VA*1e5/cT,'v!LAlfven!N/c!Lsound!N',1,1,4,NSMOOTH=3,OVERCONT=VA*1e5/cT,OVERVAL=[1.],OVERCOLOR=red,OVERLABEL=['1']
;CONTFILL,xx,zz,cT/(VA*1e5),'c!Lsound!N/v!LAlfven!N',1,1,4,NSMOOTH=3
CONTFILL,xx,zz,Eacc,'E!Lacc!N [erg/cm^3/s]',1,1,4,NSMOOTH=3
CONTFILL,xx,zz,Binduc,'B induction [Gauss]',1,1,4,NSMOOTH=3
CONTFILL2,xx,zz,Binduc,'B induction [Gauss]',1,1,4,NSMOOTH=3
CONTFILL,xx,zz,beta,'!9b!7!Imag!N=P!Itherm!N/P!IB!N',1,1,4,NSMOOTH=3,OVERCONT=beta,OVERVAL=[1.,1e3],OVERCOLOR=red,OVERLABEL=['1','10!E3!N']
CONTFILL,xx,zz,beta,'!9b!7!Imag!N=P!Itherm!N/P!IB!N',0,1,4,NSMOOTH=3,OVERCON=beta,OVERVAL=[1.],OVERCOLOR=re
CONTFILL2,xx,zz,beta,'!9b!7!Imag!N=P!Itherm!N/P!IB!N',1,1,4,NSMOOTH=3,OVERCONT=beta,OVERVAL=[1.,1e3],OVERCOLOR=red,OVERLABEL=['1','10!E3!N']
; ----------
r= alpha_vis/beta
CONTFILL2,xx,zz,r,'!9a!7/!9b!7!Imag!N',1,1,4,NSMOOTH=3
plot,beta,alpha_vis,psym=3,/xlog,/ylog,yr=[1e-8,2.],/ys,xtitle='!9b!7!Imag!N',ytitle='!9a!7',charsize=1.5
; ----------
CONTFILL,xx,zz,Prm,'Magnetic Prandtl',1,1,4,NSMOOTH=3,YMIN=-10.,OVERCONT=Prm,OVERVAL=[1]
CONTFILL,xx,zz,Prm,'Magnetic Prandtl',0,1,4,NSMOOTH=3,YMIN=-10.,OVERCONT=Prm,OVERVAL=[1]
CONTFILL,xx,zz,dMdot,'!9a!7c!Is!N!9r!7 [g cm!E-2!N s!E-1!N]',1,1,4,NSMOOTH=3
CONTFILL2,xx,zz,dMdot,'!9a!7c!Is!N!9r!7 [g cm!E-2!N s!E-1!N]',1,1,4,NSMOOTH=3
yM=Mdot*(yr/Msun)
plot,xx,yM,xtitle='r [au]',/xlog,ytitle='Mdot MSun/yr'
;print,yM
;print,xx(1,0),xx(9,0),xx(19,0),xx(26,0)
;!p.multi=[0,2,2]
;!x.margin=[7,3]
;!y.margin=[3,3]
;xtit='z (AU)'
;ytit='!9a!7c!Is!N!9r!7 [g cm!E-2!N s!E-1!N]'
;r1=['1 AU','1.8 AU','26.4 AU','153 AU']
;plot,zz(1,*),dMdot(1,*),/ylog,xtitle=xtit,ytitle=ytit,title='1 AU'
;plot,zz(9,*),dMdot(9,*),/ylog,xtitle=xtit,ytitle=ytit,title='1.8 AU'
;plot,zz(19,*),dMdot(19,*),/ylog,xtitle=xtit,ytitle=ytit,title='26.4 AU'
;plot,zz(26,*),dMdot(26,*),/ylog,xtitle=xtit,ytitle=ytit,title='153 AU'
;!p.multi=0
;i=5
;plot,zz(i,*),Rem(i,*),/ylog,/xlog,xr=[1e-1,max(zz(i,*))],/xs
;plot,zz(i,*),Am(i,*),/ylog,/xlog,xr=[1e-1,max(zz(i,*))],/xs 
;!x.margin=[10,3]
;!y.margin=[4,2]
;stop
end

; ---------------------------------------------------------
pro plot_charges,xx,zz,ndust,dust_charge

nxx=0
nzz=0
nsize=0
ix=0
iz=0
folder='.'
openr,1,folder+"/dust_charge.out"
readf,1,format='(3(I4))',NXX,NZZ,Nsize
Ngrid = NXX*NZZ
charge = fltarr(NXX,NZZ)
min_charge = fltarr(NXX,NZZ)
max_charge = fltarr(NXX,NZZ)
Zmin   = fltarr(Nsize)
Zmax   = fltarr(Nsize)
asize  = fltarr(Nsize)
for i=1,Ngrid do begin
   readf,1,format='(I4,I4,E13.5)',ix,iz,tmp
   charge(ix-1,iz-1) = tmp
endfor
for i=1,Ngrid do begin
   readf,1,format='(I4,I4,E13.5)',ix,iz,tmp
   min_charge(ix-1,iz-1) = tmp
endfor
for i=1,Ngrid do begin
   readf,1,format='(I4,I4,E13.5)',ix,iz,tmp
   max_charge(ix-1,iz-1) = tmp
endfor
for i=0,Nsize-1 do begin
   readf,1,format='(E13.5,E13.5)',agrain,tmp
   asize(i) = agrain
   Zmin(i)  = tmp
endfor
for i=0,Nsize-1 do begin
   readf,1,format='(E13.5,E13.5)',agrain,tmp
   asize(i) = agrain
   Zmax(i)  = tmp
endfor
close,1
!p.multi=0
!p.region=0
!p.position=0
;plot,asize*1e4,-Zmin,/xlog,/ylog,xtitle='radius (micron)',ytitle='|Minimum charge|'
;plot,asize*1e4,Zmax,/xlog,/ylog,xtitle='radius (micron)',ytitle='Maximum charge'
ymin = floor(min(charge))
ymax = ceil(max(charge))
center_zero = (max([ymax,-ymin]) GT 10)
CONTFILL2,xx,zz,charge,'<dust charge>',1,0,4,$
          YMIN=ymin,YMAX=ymax,CENTER_ZERO=center_zero
;CONTFILL2,xx,zz,charge*ndust,'Dust grain charge',1,0,3  
;CONTFILL2,xx,zz,charge,'Mean dust grain',1,0,3   

;CONTFILL,xx,zz,min_charge,'min grain',1,0,3  
;CONTFILL,xx,zz,max_charge,'max grain',1,0,3  
;CONTFILL,xx,zz,max_charge-min_charge,'max-min grain',1,1,3  
dust_charge = charge 
;stop
end

;-----------------------------------------------------------
; Plots a given value y(ix,iz) againts the H-column-density
; (NH_ver) at a radial position r.
;
; no iterpolation is done so far, just the nearest grid 
; point to r is used.
;
;-----------------------------------------------------------
pro plot_columnd,r,xx,zz,NH_ver,y,ytitle

; r is the Radius in AU
i=0
nx=N_ELEMENTS(xx)
nz=N_ELEMENTS(nz)
for i = 0L, nx-1 do begin
  if (xx[i] ge r) then break
endfor

r_txt="R="+STRTRIM(STRING(r,FORMAT="(F12.2)"),2)+" AU"

ymax=max(y[i,*])*20.0
ymin=min(y[i,*])*0.5
xmax=max(Nh_ver[i,*])*20.0
tmp=nh_ver[i,*]
xmin=min(tmp(where(Nh_ver[i,*] gt 0.0)))*0.5
;print, Nh_ver[i,*]

plot,nh_ver[i,*],y[i,*],/xlog,/ylog,xtitle='N!L<H> !N[cm!U-2!N]',ytitle=ytitle,$
  YRANGE=[ymin,ymax],xrange=[xmin,xmax], THICK=2
xyouts,0.8,0.9,r_txt, /NORMAL

;print,zz[i,nz-1],zz[i,0]
;print,zz[i,*]
;xr=[zz[i,nz-1],zz[i,0]]
;axis,XAXIS=1, XRANGE=xr,xlog=1

;plot,zz[i,*],y[i,*],/ylog
end;

; -----------------------------------------------------------------------
; Calculate the Magnetic Reynoldsnumber and Ambipolar diffusion parameter
; for each position in the disk according to Walsch 2012 and Gammi 1996
; 
; OUTPUT: mrem(ix,iz) ... the magnetic reynolds number
;         am(ix,iz) ..... the ambipolar diffusion parameter
;         
;         if the alpha_vis parameter is not set 0.01 as default ist used.
; ------------------------------------------------------------------------
pro CALC_MREM_AM,xx,zz,nx,nz,nh,nmol,spname,cs,alpha_vis,mstar,mrem,am

grav = 6.672598500D-08     ; gravitational constant
Msun = 1.988922500D+33     ; solar mass
AU   = 1.495978700D+13     ; 1 astronomical unit

; see Walsch 2012
beta=2.0*1.d-9

nelec=nmol[*,*,0]
ms=mstar*Msun

x=xx*AU
z=zz*AU

alpha=alpha_vis
if (alpha_vis le 1.d-10) then begin
  print, "use default alpha=0.01 for the calculation of the magnetic reynolds number (CALC_MREM)"
  alpha=0.01
endif

; calc the number density of all neutral elements.
nsp=N_ELEMENTS(spname)
nneutral=DBLARR(nx,nz)
ntotal=DBLARR(nx,nz)
for i = 0L, nsp-1 do begin
  spn=spname(i)
  if (STRPOS(spn,"PAH") eq -1 and STRPOS(spn,'#') eq -1) then begin 
    if ((STRPOS(spn,'+') eq -1) and (STRPOS(spn,'-') eq -1)) then begin
      nneutral=nneutral+nmol[*,*,i]
    endif
    ntotal=ntotal+nmol[*,*,i]  
  endif
endfor

mrem=DBLARR(nx,nz)
am=DBLARR(nx,nz)
for i = 0L, nx-1 do begin
  for j = 0L, nz-1 do begin
    ;kepler velocity
    omega=sqrt(grav*ms/((sqrt(x(i)^2+z(i,j)^2))^3))
    ; alven velocity
    av=sqrt(alpha)*cs[i,j]
    ;scale height
    h=cs[i,j]/omega
    ; magnetic resistiviy (cm^2s^⁻1)
    eta=(6.5*1.d3)/(nelec[i,j]/nh[i,j])
    mrem[i,j]=av*h/eta

    ;electron fraction
    xe=nelec[i,j]/ntotal[i,j]

    am[i,j]=xe*nneutral[i,j]*beta/omega
  endfor
endfor
end;calc_mrem

; ----------------------------------------------------------------
PRO EQUIL_COND,Nx,Nz,xx,zz,nHtot,Tg,Td
; ----------------------------------------------------------------
  openr,1,'EqChem.out',ERROR = err
  if (err NE 0) then return
  print,"reading EqChem.out ..."
  Ncond=0
  line=''
  readf,1,NELM,NMOLE,Ncond
  readf,1,line
  close,1
  ename = STRARR(NELM)
  mname = STRARR(1+NELM+NMOLE)
  dname = STRARR(Ncond)
  names = strsplit(line,' ',/extract)
  for i=0,NELM-1 do begin
    name = names[i+3]
    ename[i] = strmid(name,4)
  endfor
  for i=0,NELM+NMOLE do begin
    name = names[i+3+NELM] 
    mname[i] = strmid(name,1)
  endfor
  for i=0,Ncond-1 do begin
    name = names[i+4+2*NELM+NMOLE]
    dname[i] = strmid(name,1)
  endfor
  ;print,ename
  ;print,mname
  ;print,dname
  rmax = max(xx(where(Td GT 100.0)))
  arr = READ_TABLE('EqChem.out',head=2,nrows=3+Nx*(Nz*1L),/double)
  SSd = DBLARR(Nx,Nz)
  eps = DBLARR(Nx,Nz)
  rr  = DBLARR(1,Nx*(Nz*1L))
  for i=0L,Nx*(Nz*1L)-1 do begin
    ix = floor(arr(0,i))-1
    iz = floor(arr(1,i))-1
    rr(0,i) = xx(ix,iz)  
  endfor
  dum = where(rr LE rmax,Ndat)
  print,"rmax=",rmax,Ndat
  for j=0,NELM-1 do begin
    dat = arr(j+3,*)
    for i=0L,Nx*(Nz*1L)-1 do begin
      ix = floor(arr(0,i))-1
      iz = floor(arr(1,i))-1
      eps(ix,iz) = max([1.d-99,dat(i)])
    endfor
    white = 255
    yellow = 195
    ymax = ALOG10(MAX(eps))
    ymin = ALOG10(MIN(eps))
    ymin = MAX([ymin,ymax-10.0])
    ymin = MIN([ymin,ymax-1.0])
    label = '!9e!7!L'+ename(j)+'!X'
    CONTFILL2, xx,zz,eps,label,1,1,4,XMAX=rmax,YMAX=ymax,YMIN=ymin,$
        OVERCONT=Td,OVERVAL=[100,300,1000],OVERCOLOR=[white,white,white],$
        OVERLABEL=['150K','300K','1000K']
  endfor
  nH = arr(2,*)
  ymax = 0.0
  for j=0,Ncond-1 do begin
    dat = arr(j+4+2*NELM+NMOLE,*)/nH(0,*)
    ymax = MAX([ymax,MAX(dat)])
  endfor
  ymax = ALOG10(ymax)+0.5
  ymin = -9.0
  for j=0,Ncond-1 do begin
    label = dname(j)
    dat = arr(j+4+2*NELM+NMOLE,*)/nH(0,*)
    ind = where((dat GT 1.E-15) AND (rr LT rmax),count)
    ;print,dname(j),count/(Ndat*1.0),(count GT 1.E-3*Ndat) 
    if (count GT 0.01*Ndat) then begin
      for i=0L,Nx*(Nz*1L)-1 do begin
        ix = floor(arr(0,i))-1
        iz = floor(arr(1,i))-1
        eps(ix,iz) = max([1.d-99,dat(i)])
      endfor
      label = dname(j)
      white = 255
      yellow = 195
      CONTFILL2, xx,zz,eps,label,1,1,1,XMAX=rmax,YMAX=ymax,YMIN=ymin,$
        OVERCONT=Td,OVERVAL=[100,300,1000],OVERCOLOR=[white,white,white],$
        OVERLABEL=['150K','300K','1000K']
    endif
  endfor
end


; ----------------------------------------------------------------
; --------------------- main program -----------------------------
; ----------------------------------------------------------------
!p.font=0
!x.style=1
!y.style=1
!z.style=1
!x.margin=[10,3]
!y.margin=[4,2]
!p.charsize=1.3
!x.thick=4
!y.thick=4

;---------------- for screen output -------------------
set_plot,'x'
;WINDOW,XSIZE=832,YSIZE=640         ;mpeg
;WINDOW,XSIZE=880,YSIZE=880         ;Bildschirm
;WINDOW,XSIZE=650,YSIZE=880         ;schlanke Figur

;---------------- for ps-output -------------------
xx1=18.0
xx2=17.0
xx3=1.0
xx4=1.0
;set_plot,'ps'
;device,filename='out.ps'
;device,xsize=xx1,ysize=xx2,xoffset=xx3,yoffset=xx4,/color
loadct,39      ; use 0 for B&W output, 39 for rainbow
black   = 0
white   = 255
orange  = 210
red     = 250
yellow  = 195
green   = 160
cyan    = 100
blue    = 70
magenta = 40
TVLCT, red1, green1, blue1, /GET
;openw, 1, "colors.pro"
;printf,1, red1
;printf,1, green1
;printf,1, blue1
;close,1
red1  = 256 * (  red1/256.0)^0.7
blue1 = 256 * ( blue1/256.0)^0.7
green1= 256 * (green1/256.0)^1.2
TVLCT, red1, green1, blue1

folder="."
MCMAXpath="MCMAXout" 
MCFOSTpath="MCFOSTout" 

READDATA, folder,"ProDiMo.out",Nx,Nz,Nsp,SPname,xx,zz,mainheat,maincool,$
          rho_gr,NH_rad,NH_ver,AV_rad,AV_ver,$
          chi,TgRE,Tgas,Tdust,rho,press,cT,nHtot,nmol,ndust,$
          NHEAT,NCOOL,heatname,coolname,$
          tauchem,taucool,taudiff,heat,cool,$
          NLAM,lam,Jlam,urad,chiRT,solved,Rstar,Rin,Rout,Mstar,$
          kapR,tauR,amean,dust_to_gas_c,dustgas,version,zrelevant,$
          fPAH,H_X,$
          tau_1keV,tau_10keV,zeta_HX,rH2form,rH2diss,alpha_vis,CRI_rz

;---------------------------------------------------
; ***  determine abundance relative to elements  ***
;---------------------------------------------------
; SPECIES_MASSES,Nx,Nz,Nsp,xx,zz,nHtot,rho,dustgas,nmol,Tgas,Tdust,SPname,Mgas,Mdust,vol

;------------------------------------------------
; ***  determine dust and ice mass densities  ***
;------------------------------------------------
pi = ACOS(-1.d0)
mic = 1.D-4                 
amu = 1.660531000d-24
rhodust=rho*dustgas                                            
rhodust=ndust*4.d0*pi/3.0*(amean*mic)^3*rho_gr                     
; the latter is actually also correct, because output has (a3mean)^1/3 
; the latter avoids plotting problems because of nH_surround
rho_ice = rho*0.0
READCHARGE,SPname2,SPcharge,SPmass 
for ir=0,Nx-1 do begin
  for iz=0,Nz-1 do begin
    sum = 0.0
    for isp=0,Nsp-1 do begin
      if (strpos(SPname2(isp),'#') GT 0) then begin
        if (SPname2(isp) EQ 'PAH#') then continue
        if (SPname2(isp) EQ 'H2#') then continue
        sum = sum+nmol(ir,iz,isp)*SPmass(isp)*amu
        ;if (ir EQ 2*Nx/3 AND iz EQ 0) then print,isp,SPname2(isp),SPmass(isp),nmol(ir,iz,isp)/nHtot(ir,iz)
      endif  
    endfor
    ;if (ir EQ 2*Nx/3 AND iz EQ 0) then stop
    rho_ice(ir,iz) = sum
  endfor
  ;print,rhodust(ir,0)/rho(ir,0),rho_ice(ir,0)/rho(ir,0)
endfor

;----------------------------------------------
; ***  log n<H>, chi, Tgas, Tdust and grid  ***
;----------------------------------------------
AV = 0.0*AV_rad
for ix=0,Nx-1 do for iz=0,Nz-1 do begin
  ;AV(ix,iz) = MIN([AV_ver(ix,iz),AV_rad(ix,iz),AV_rad(Nx-1,iz)-AV_rad(ix,iz)])
  AV(ix,iz) = MIN([AV_ver(ix,iz),AV_rad(ix,iz)])
endfor
Xray = (max(tau_1keV) GT 0.d0)
InnerRim = (1 EQ 0)
zxshow=0.85
zmax=zxshow
zmax=min([max(zz/xx),zxshow])
lnHmax=max(alog10(nHtot))
lnHmin=min([3.0,lnHmax-8.0])

;----- gas density -----
CONTFILL2, xx,zz,nHtot,'!7n!L<H> !N[cm!U-3!N]!X',1,1,2,ZMAX=zmax,$
          YMIN=lnHmin,YMAX=lnHmax,$ 
          OVERCONT=AV,OVERVAL=[1,10],OVERCOLOR=[black,black],$
          OVERLABEL=[' ',' '],$
          ;OVERLABEL=['A!LV!N=1','A!LV!N=10'],
          OVER2=AV_rad,OVERV2=[0.01,1],OVERC2=[red,red],$
          OVERL2=[' ',' ']
          ;OVERL2=['A!LV,rad!N=0.01','A!LV,rad!N=1']

;----- dust density -----
ymax = max(alog10(rhodust))
ymin = min(alog10(rhodust))
ymin = MAX([ymin,ymax-14.0])
CONTFILL2, xx,zz,rhodust,'!9r!L!7dust !N[g/cm!U3!N]!X',1,1,2,ZMAX=zmax,$
       YMIN=ymin,YMAX=ymax,$ 
       OVERCONT=AV,OVERVAL=[1,10],OVERLABEL=['A!LV!N=1','A!LV!N=10'],$
       OVERCOLOR=black,$
       OVER2=AV_rad,OVERV2=[0.01,1],OVERL2=['0.01','A!LV,rad!N=1'],$
       OVERC2=red

;----- ice density -----
CONTFILL2, xx,zz,rho_ice,'!9r!L!7ice !N[g/cm!U3!N]!X',1,1,2,ZMAX=zmax,$
       YMIN=ymin,YMAX=ymax,$ 
       OVERCONT=AV,OVERVAL=[1,10],OVERLABEL=['A!LV!N=1','A!LV!N=10'],$
       OVERCOLOR=black,$
       OVER2=AV_rad,OVERV2=[0.01,1],OVERL2=['0.01','A!LV,rad!N=1'],$
       OVERC2=red
  
;----- dust/gas ratio -----
ymin = alog10(min(1.0/dustgas))-0.2
ymax = alog10(max(1.0/dustgas))+0.2
ymax = min(8.0,ymax)
ymax = 4.0
CONTFILL2, xx,zz,1.0/dustgas,'!7gas/dust',1,1,2,$
       YMIN=ymin,YMAX=ymax,ZMAX=zmax,$
       OVERCONT=AV,OVERVAL=[1],OVERLABEL=[' ',' '],OVERCOLOR=black,$
       OVER2=AV_rad,OVERV2=[0.01,1],OVERL2=[' ',' '],OVERC2=red

;----- ice/dust ratio -----
icedust = rho_ice/rhodust
ymax = alog10(max(icedust))+0.2
ymin = ymax-5.0
CONTFILL2, xx,zz,icedust,'!7ice/dust',1,1,2,$
       YMIN=ymin,YMAX=ymax,ZMAX=zmax,$
       OVERCONT=AV,OVERVAL=[1],OVERLABEL=['Av,ver=1'],OVERCOLOR=white,$
       OVER2=AV_rad,OVERV2=[0.01,1],OVERL2=[' ',' '],OVERC2=red

;----- mean particle size -----
;if (min(amean) NE max(amean)) then begin      ; settled model?
  ymin = alog10(min(amean))-0.2
  ymax = alog10(max(amean))+0.2
  CONTFILL2, xx,zz,amean,'!7<a!U3!N>!U1/3!N [mic]',1,1,2,$
       YMIN=ymin,YMAX=ymax,ZMAX=zmax,$
       OVERCONT=AV,OVERVAL=[1],OVERLABEL=[' ',' '],OVERCOLOR=black,$
       OVER2=AV_rad,OVERV2=[0.01,1],OVERL2=[' ',' '],OVERC2=red
;endif 
;----- column densities -----
Nd_ver = NH_ver              ; dust mass column density / muH
Sig_ice = NH_ver             ; ice column density [g/cm2]
AU = 1.495978700D+13
for ir=0,Nx-1 do begin
  sum1 = 0.0
  sum2 = 0.0
  sum3 = 0.0
  sum4 = 0.0
  Nd_ver(ir,Nz-1) = 0.d0
  Sig_ice(ir,Nz-1) = 0.d0
  for iz=Nz-2,0,-1 do begin
    dz   = (zz(ir,iz+1)-zz(ir,iz))*AU
    sum1 = sum1 + 0.5*(  nHtot(ir,iz+1)+  nHtot(ir,iz))*dz
    sum2 = sum2 + 0.5*(    rho(ir,iz+1)+    rho(ir,iz))*dz
    sum3 = sum3 + 0.5*(rhodust(ir,iz+1)+rhodust(ir,iz))*dz
    sum4 = sum4 + 0.5*(rho_ice(ir,iz+1)+rho_ice(ir,iz))*dz
    Nd_ver(ir,iz) = sum3
    Sig_ice(ir,iz) = sum4
  endfor  
  if (ir EQ 0) then muH = sum2/sum1    
  Nd_ver(ir,*) = Nd_ver(ir,*) / muH  
endfor
ymax = max(NH_ver(*,0))*2
ymin = min([NH_ver(*,0),Nd_ver(*,0)])/2
plot,xx(*,0),NH_ver(*,0),yrange=[ymin,ymax],/xlog,/ylog,THICK=3,$
     xtitle='r [au]',ytitle='half disk N!L<H> !N[cm!U-2!N]'
oplot,xx(*,0),Nd_ver(*,0),color=red
AA = FINDGEN(17) * (!PI*2/16.)  
USERSYM, COS(AA), SIN(AA), /FILL  
oplot,xx(*,0),NH_ver(*,0),color=blue,PSYM=8,SYMSIZE=0.5
hfile=MCMAXpath+"/surfacedens.dat"
openr,1,hfile,ERROR = err
close,1  
if (err EQ 0) then begin
  readcol,hfile,x6,MH6,/silent ; [AU, g(dust)/cm^2]
  amu = 1.660531000d-24
  NH6 = MH6/(1.315*amu)/dust_to_gas_c  ; (rho~1.315*amu*n<H>)
  NH6 = NH6/2.0                        ; MCMax has full surfdens across disc
  oplot,x6,NH6,thick=3,color=green,linestyle=0
 ;xyouts,xp3,yp6*f,charsize=1.1,color=green ,"from MCMax"
endif 
Sig_gas  = 2*NH_ver*muH        ; mass column density accross disk
Sig_dust = 2*Nd_ver*muH
Sig_ice  = 2*Sig_ice
ymax = max(Sig_gas(*,0))*2
ymin = min([Sig_gas(*,0),Sig_dust(*,0)])/2
ymin = max([ymin,ymax*1.E-12])
plot,xx(*,0),Sig_gas(*,0),yrange=[ymin,ymax],$
     /xlog,/ylog,THICK=3,$
     xtitle='r [AU]',ytitle='full disk !9S!7 [g cm!U-2!N]'
oplot,xx(*,0),Sig_dust(*,0),color=red
oplot,xx(*,0),Sig_gas(*,0),color=blue,PSYM=8,SYMSIZE=0.5
oplot,xx(*,0),Sig_ice(*,0),color=cyan
oplot,[1.0],[1700],color=green,PSYM=8,SYMSIZE=1.5  ; common MMSN value
if (err EQ 0) then begin
  oplot,x6,NH6*(1.315*amu),thick=3,color=green,linestyle=0
endif
xyouts,0.9,0.90,/NORMAL,charsize=1.4,color=blue,'gas'
xyouts,0.9,0.86,/NORMAL,charsize=1.4,color=red,'dust'
xyouts,0.9,0.82,/NORMAL,charsize=1.4,color=cyan,'ice'

;----- scale heights -----
SCALEHEIGHTS, Nx,Nz,xx,zz,AV_rad,rho,press,cT,Mstar,Tgas,Tdust,MCMAXpath

if (Xray) then begin
  CONTFILL3, xx,zz,nHtot,'!7n!L<H> !N[cm!U-3!N]!X',1,1,2,ZMAX=zmax,$
          YMIN=3.0,YMAX=max([max(alog10(nHtot)),13]),$ 
          OVER1=tau_10keV,OVERV1=[10],OVERL1=['!9t!7!L10keV!N=10'],$
          OVERC1=blue,$
          OVER3=tau_1keV,OVERV3=[10],OVERL3=['  !9t!7!L1keV!N=10  '],$
          OVERC3=black,$
          OVER2=AV_rad,OVERV2=[10],OVERL2=['A!LV!N=10'],OVERC2=red
  CONTFILL2, xx,zz,zeta_HX,'!9z!X!LX!N[1/s]',1,1,2,ZMAX=zmax,$
          YMIN=-22.0,YMAX=-3.0,$
          OVERCONT=zeta_HX,OVERVAL=[2.E-17],OVERLABEL=['!9z!X!LCR!N=2.E-17'],$
          OVERCOLOR=white 
  CONTFILL2, xx,zz,H_X,'!7H!LX!N[1/s]',1,1,2,ZMAX=zmax,$
          YMIN=-32.0,YMAX=-18.0
  if (min(CRI_rz) NE max(CRI_rz)) then begin
    CONTFILL2, xx,zz,CRI_rz,'!9z!X!LCR!N[1/s]',1,1,2,ZMAX=zmax,$
          YMIN=alog10(min(CRI_rz)),YMAX=alog10(max(CRI_rz))
  endif
  ;plot_columnd,1.0,xx,zz,nh_ver,zeta_HX,'!9z!X!LX!N[1/s]'
  ;plot_columnd,1.0,xx,zz,nh_ver,Tgas,"Tgas [1/s]"
  ;calc_mrem_am,xx,zz,nx,nz,nhtot,nmol,spname,ct,alpha_vis,mstar,mrem,am
  ;ymax=3.0
  ;CONTFILL2, xx,zz,mrem,'Re!LM',1,1,2,ZMAX=zmax,OVERCONT=mrem,OVERVAL=[100.0],$
  ;           OVERLABEL=['Re!LM =100'],ymax=ymax
  ;CONTFILL2, xx,zz,am,'Am',1,1,2,ZMAX=zmax,OVERCONT=am,OVERVAL=[1.0,100.0],$
  ;           OVERLABEL=['Am=1','Am=100'],ymax=ymax
endif

;----- UV radiation field strength -----
CONTFILL2,xx,zz,chi,'!9c!7!Ugeo!X',1,1,2,ZMAX=zmax,$   ;NSMOOTH=5,$
          OVERCONT=AV,OVERVAL=[1,10],OVERLABEL=['AV=1','AV=10'],$
          OVERCOLOR=[white,white]
CONTFILL2,xx,zz,chiRT,'!9c!X'     ,1,1,2,ZMAX=zmax,$   ;NSMOOTH=5,$
          OVERCONT=AV,OVERVAL=[1,10],OVERLABEL=['AV=1','AV=10'],$
          OVERCOLOR=[white,white]
CONTFILL2,xx,zz,chiRT/chi,'!9c!X/!9c!7!Ugeo!X' ,1,1,2,ZMAX=zmax,YMAX=6.0,$
          OVERCONT=AV,OVERVAL=[1,10],OVERLABEL=['AV=1','AV=10'],$
          OVERCOLOR=[white,white]

;----- dust and gas temperatures -----
Tgmax=0.0
Tdmax=0.0
for ix=3,Nx-1 do begin
  Tgtmp=max(Tgas(ix,*))
  Tdtmp=max(Tdust(ix,*))
  Tgmax=max([Tgmax,Tgtmp])
  Tdmax=max([Tdmax,Tdtmp])
endfor
Tgmin=min(Tgas)
Tdmin=min(Tdust)
Tgmax=min([max(Tgas),10.0^3.95])
Tdmax=max(Tdust)
;Tmin=min([Tgmin,Tdmin,10.0^1.1])
Tmin=min([Tgmin,Tdmin])
Tmax=min([Tgmax,Tdmax])
logx=1
logT=1
if (logT) then begin
  Tmin=alog10(Tmin) 
  Tmax=alog10(Tmax) 
  Tdmin=alog10(Tdmin) 
  Tdmax=alog10(Tdmax) 
  Tgmin=alog10(Tgmin) 
  Tgmax=alog10(Tgmax)
endif 
CONTFILL2, xx,zz,Tdust,'T!Ldust !N[K]',logx,logT,2,ZMAX=zmax,$
          YMIN=Tmin,YMAX=Tgmax,$                                       ;log Td
          OVERCONT=Tdust,OVERVAL=[10,20,40,100,300,700,1400],$
          OVERLABEL=['10K','20K','40K','100K','300K','700K','1400K'],$
          OVERCOLOR=[white,white,black,black,black,black,black],$
          OVER2=AV,OVERV2=[1,10],OVERL2=['1','10'],OVERC2=red

CONTFILL2, xx,zz,Tgas,'T!Lgas !N[K]',logx,logT,2,ZMAX=zmax,$           ;log Tg
          YMIN=Tmin,YMAX=Tgmax,$                   
          OVERCONT=Tgas,OVERVAL=[10,20,40,100,300,1000,5000],$
          OVERLABEL=['10K','20K','40K','100K','300K','1000K','5000K'],$
          OVERCOLOR=[white,white,black,black,black,black,black],$
          OVER2=AV,OVERV2=[1,10],OVERL2=['1','10'],OVERC2=red

CONTFILL2, xx,zz,Tgas/Tdust,'T!Lgas!N/T!Ldust!N',logx,0,2,ZMAX=zmax,$ 
          YMIN=0.95,YMAX=1.05,$                   
          OVERCONT=AV,OVERVAL=[2,5,10],$
          OVERLABEL=['2','5','10'],OVERCOLOR=white,$
          OVER2=AV_rad,OVERV2=[0.01,0.1,0.5],$
          OVERL2=['0.01','0.1','0.5'],OVERC2=black

if (max(TgRE) GT 10.0) then begin
  CONTFILL2, xx,zz,TgRE,'T!Lg,RE !N[K]',logx,logT,2,ZMAX=zmax,$  
          YMIN=Tmin,YMAX=Tgmax,$                   
          OVERCONT=TgRE,OVERVAL=[10,20,40,100,300,1000,2000],$
          OVERLABEL=['10K','20K','40K','100K','300K','1000K','2000K'],$
          OVERCOLOR=[white,white,black,black,black,black,black],$
          OVER2=AV,OVERV2=[1,10],OVERL2=['1','10'],OVERC2=red
endif

TDUST_GRAD, Nx,Nz,xx,zz,Tdust,AV_rad,AV_ver   ; fit like Tdust ~ r^-q

;----- tau_rosseland -----
ymax = max(tauR(*,0))*2
ymin = 1.E-4
plot,xx(*,0),tauR(*,0),yrange=[ymin,ymax],/xlog,/ylog,THICK=5,$
     xtitle='r [au]',ytitle='midplane Rosseland optical depth'

;----- interface to photoevaporation winds -----
if (1 EQ 0) then begin       
   AU       = 1.495978700D+13
   grav     = 6.672598500D-8
   Msun     = 1.988922500d+33
   amu      = 1.660531000E-24           
   bk       = 1.380658120E-16           
   nH2   = nmol(*,*,SPindex(Nsp,SPname,"H2"))
   nH    = nmol(*,*,SPindex(Nsp,SPname,"H"))
   nHp   = nmol(*,*,SPindex(Nsp,SPname,"H+"))
   nHe   = nmol(*,*,SPindex(Nsp,SPname,"He"))
   nHep  = nmol(*,*,SPindex(Nsp,SPname,"He+"))
   nel   = nmol(*,*,SPindex(Nsp,SPname,"e-"))
   Egrav = grav*rho*Mstar*Msun/(SQRT(xx^2+zz^2)*AU) ;grav.pot [erg/cm3]
   Ether = 0.5*bk*Tgas*(5*nH2 + 3*(nH+nHp) + 3*(nHe+nHep) + 3*nel)
   CONTFILL2,xx,zz,Tgas,'T!Lgas !N[K]',1,1,2,$
          ZMAX=zmax,YMIN=Tmin,YMAX=Tgmax,$                   
          OVERCONT=Egrav/Ether,OVERVAL=[1.0,10.0,100.0]
          OVERLABEL=['1','10','Egrav/Eth=100']
   CONTFILL2,xx,zz,Egrav/Ether,'E!Lgrav!N/E!Ltherm!N',1,1,2,$
          ZMAX=zmax,YMIN=-2,YMAX=+4,$
          OVERCONT=Tgas,OVERVAL=[300.0,1000.,3000.,10000.],$
          OVERLABEL=['300','1000','3000','10000']
endif

;--- magnify inner rim? ---
if (InnerRim) then begin
  xxmax=Rin*5 
  CONTFILL2, xx,zz,nHtot,'!7n!L<H> !N[cm!U-3!N]!X',1,1,2,$
          XMAX=xxmax, ZMAX=0.35,$
          YMIN=3.0,YMAX=max(alog10(nHtot)),$ 
          OVERCONT=AV,OVERVAL=[1,10],OVERLABEL=['A!LV!N=1','A!LV!N=10'],$
          OVERCOLOR=[black,black],$
          OVER2=AV_rad,OVERV2=[0.01,1],OVERL2=['0.1','A!LV,rad!N=1'],$
          OVERC2=[red] ,GRIDON=1
  CONTFILL2, xx,zz,rhodust,'!9r!L!7dust !N[g/cm!U3!N]!X',1,1,2,$
          XMAX=xxmax, ZMAX=0.35,$
          YMIN=max(alog10(rhodust))-14,YMAX=max(alog10(rhodust)),$ 
          OVERCONT=AV,OVERVAL=[1,10],OVERLABEL=['A!LV!N=1','A!LV!N=10'],$
          OVERCOLOR=[black,black],$
          OVER2=AV_rad,OVERV2=[0.01,1],OVERL2=['0.1','A!LV,rad!N=1'],$
          OVERC2=[red] ,GRIDON=1
  CONTFILL2, xx,zz,Tdust,'T!Ldust !N[K]',1,1,2,$
          XMAX=xxmax, ZMAX=0.35,$
          YMIN=alog10(150.0),YMAX=alog10(5000.0),$
          OVERCONT=Tdust,OVERVAL=[300,400,600,1000,1400,1800,5000],$
          OVERLABEL=['300K','400K','600K','1000K','1400K','1800K','5000K'],$
          OVERCOLOR=[white,white,black,black,black,black,black],$
          OVER2=AV,OVERV2=[1,10],OVERL2=['1','10'],OVERC2=red ,GRIDON=1
  CONTFILL2, xx,zz,Tgas,'T!Lgas !N[K]',1,1,2,$
          XMAX=xxmax, ZMAX=0.35,$
          YMIN=alog10(150.0),YMAX=alog10(5000.0),$
          OVERCONT=Tdust,OVERVAL=[300,500,700,1000,1400,1800,5000],$
          OVERLABEL=['300K','400K','600K','1000K','1400K','1800K','5000K'],$
          OVERCOLOR=[white,white,black,black,black,black,black],$
          OVER2=AV,OVERV2=[1,10],OVERL2=['1','10'],OVERC2=red ,GRIDON=1
endif


;----- numerical grid -----
SHOWGRID, xx,zz,1,zxshow
SHOWGRID, xx,zz,0,zxshow

;-----------------------
; *** Grain charging ***
;-----------------------
openr, 1,folder+"/dust_charge.out",ERROR = err
close,1
dust_charge = 0.
if (err EQ 0) then begin
  plot_charges,xx,zz,ndust,dust_charge
endif

;CHARGE_STATISTICS,Nx,Nz,xx,zz,Nsp,nmol,SPname,nHtot,NH_ver,$
;                  ndust,dust_charge,Zcharge

DUST_MEANCHARGE,Nx,Nz,ndust,nmol,SPname,Zmean,computed
if (computed) then begin
  ymin = floor(min(Zmean)+0.01)
  ymax = ceil(max(Zmean)-0.01)
  iH2=SPindex(Nsp,SPname,"H2")
  iH=SPindex(Nsp,SPname,"H")
  iCp=SPindex(Nsp,SPname,"C+")
  iC=SPindex(Nsp,SPname,"C")
  transition1 = nmol(*,*,iH2)/nmol(*,*,iH)
  transition2 = nmol(*,*,iCp)/nmol(*,*,iC)
  transition2(where(AV GT 0.1)) = 0.1
  center_zero = (max([ymax,-ymin]) GT 10)
  CONTFILL2, xx,zz,Zmean,'<dust charge>',1,0,4,$
           YMIN=ymin,YMAX=ymax,CENTER_ZERO=center_zero,$
           NSMOOTH=5,$  
           OVERCONT=AV,OVERVAL=[10],OVERLABEL=['AV=10'],$
           OVERCOLOR=[white], $
           OVER2=transition2,OVERV2=[1],OVERL2=['C=C+'],$
           OVERC2=[black]

endif

;------------ escape probabilities ----------------
;iOI=SPindex(Nsp,SPname,"O")
;iH2O=SPindex(Nsp,SPname,"H2O")
;ESCPRO,xx,zz,NH_rad,NH_ver,nmol(*,*,iOI),nmol(*,*,iH2O)

;-----------------------------
; ***  log concentrations  ***
;-----------------------------
;w = where(Elname eq 'H') & ieH = w(0)
;w = where(Elname eq 'C') & ieC = w(0)
;w = where(Elname eq 'N') & ieN = w(0)
;w = where(Elname eq 'O') & ieO = w(0)
;w = where(Elname eq 'S') & ieS = w(0)

;plot_element_carriers,Nx,Nz,xx,zz,ieC,Nsp,Spname,main_carrier,Elname,''
;plot_element_carriers,Nx,Nz,xx,zz,ieO,Nsp,Spname,main_carrier,Elname,''
;plot_element_carriers,Nx,Nz,xx,zz,ieN,Nsp,Spname,main_carrier,Elname,''

;-----------------------
; ****  T-histogram  ***
;-----------------------
;isp=SPindex(Nsp,SPname,"H2")
;rho_H2 = fltarr(Nx,Nz)
;rho_H2(*,*) = 2.*amu
;temperature_barplot,"H2",Tgas,Nx,Nz,vol,rho_H2,nmol(*,*,isp),Mgas,Tbin=10.,NT=20

iC =SPindex(Nsp,SPname,"C")
iCp=SPindex(Nsp,SPname,"C+")
iCO=SPindex(Nsp,SPname,"CO")
iCOice=SPindex(Nsp,SPname,"CO#")
iH =SPindex(Nsp,SPname,"H")
iH2=SPindex(Nsp,SPname,"H2")
iN =SPindex(Nsp,SPname,"N")
iN2=SPindex(Nsp,SPname,"N2")
ymin = -12.3
ymax = -3.2
;----------  electron density -------------
CONTFILL2, xx,zz,nmol(*,*,0)/nHtot(*,*),'e!U-!N',1,1,1,$        ;electrons
           OVERCONT=AV,OVERVAL=[1,10],OVERLABEL=['AV=1','AV=10'],$
           OVERCOLOR=[black,white]

;----------  hydrogen chemistry -----------
isp=SPindex(Nsp,SPname,"H+") 
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1   ; H+
isp=SPindex(Nsp,SPname,"H")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1   ; H
isp=SPindex(Nsp,SPname,"D+")
if (isp GT 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1   ; D+
isp1=SPindex(Nsp,SPname,"H+")
isp2=SPindex(Nsp,SPname,"D+")                                 ; D+/H+
r=nmol(*,*,isp2)/(nmol(*,*,isp1)+1.E-10*nHtot(*,*))
CONTFILL2, xx,zz,r,SPname(isp2)+'/'+SPname(isp1),1,1,4,$
           ZMAX=zmax,YMAX=0.1,YMIN=-6.1
endif
isp=SPindex(Nsp,SPname,"D")
if (isp GT 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1   ; D
isp1=SPindex(Nsp,SPname,"H")
isp2=SPindex(Nsp,SPname,"D")                                  ; D/H
r=nmol(*,*,isp2)/(nmol(*,*,isp1)+1.E-10*nHtot(*,*))
CONTFILL2, xx,zz,r,SPname(isp2)+'/'+SPname(isp1),1,1,4,$
           ZMAX=zmax,YMAX=0.1,YMIN=-6.1
endif
isp=SPindex(Nsp,SPname,"H-")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,$ ; H-
           YMAX=ymax,YMIN=ymin
isp=SPindex(Nsp,SPname,"H2")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1   ; H2
           ;OVERCONT=Tdust,OVERVAL=[100.0]
           ;OVERLABEL=['Td=100K'],OVERCOLOR=[black],NSMOOTH=2
isp=SPindex(Nsp,SPname,"HD")
if (isp GT 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1   ; HD
endif
isp1=SPindex(Nsp,SPname,"H2")
isp2=SPindex(Nsp,SPname,"HD")
if (isp1 GT 0 and isp2 GT 0) then begin
r=nmol(*,*,isp2)/(nmol(*,*,isp1)+1.E-10*nHtot(*,*))           ; HD/H2
CONTFILL2, xx,zz,r,SPname(isp2)+'/'+SPname(isp1),1,1,4,$
           ZMAX=zmax,YMAX=0.1,YMIN=-6.1
endif
;isp=SPindex(Nsp,SPname,"HD")
;if (isp GT 0) then begin
;  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,$ ; HD
;             OVERCONT=Tdust,OVERVAL=[100.0],$
;             OVERLABEL=['Td=100K'],OVERCOLOR=[black]
;  rho_HD = fltarr(Nx,Nz)
;  rho_HD(*,*) = (1.+2.)*amu
;  temperature_barplot,"HD",Tgas,Nx,Nz,vol,rho_HD,nmol(*,*,isp),Mgas,Tbin=5.,NT=20

isp=SPindex(Nsp,SPname,"H2exc")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,$              ; H2exc
           YMAX=ymax,YMIN=ymin   
isp2=SPindex(Nsp,SPname,"HDexc")
if (isp2 GT 0) then begin
r=nmol(*,*,isp2)/(nmol(*,*,isp)+1.E-10*nHtot(*,*))                         ; HDexc/H2exc
CONTFILL2, xx,zz,r,SPname(isp2)+'/'+SPname(isp),1,1,4,$
           ZMAX=zmax,YMAX=0.1,YMIN=-6.1
endif

; ----------  oxygen chemistry -------------
isp=SPindex(Nsp,SPname,"O")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; O
           YMAX=ymax,YMIN=ymin
;rho_O = fltarr(Nx,Nz)
;rho_O(*,*) = 16.*amu
;temperature_barplot,"O",Tgas,Nx,Nz,vol,rho_O,nmol(*,*,isp),Mgas,Tbin=10.,NT=20
isp=SPindex(Nsp,SPname,"OH")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; OH
           YMAX=ymax,YMIN=ymin,VERT=0,$
           OVERCONT=Tgas,OVERVAL=[4000.0],OVERLABEL=['Tg=4000K']
isp2=SPindex(Nsp,SPname,"OD")
if (isp2 GT 0) then begin
r=nmol(*,*,isp2)/(nmol(*,*,isp)+1.E-10*nHtot(*,*))                         ; OD/OH
CONTFILL2, xx,zz,r,SPname(isp2)+'/'+SPname(isp),1,1,4,$
           ZMAX=zmax,YMAX=0.1,YMIN=-6.1
endif

isp=SPindex(Nsp,SPname,"H2O")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; H2O
           YMAX=ymax, YMIN=ymin,$ 
           OVERCONT=Tdust,OVERVAL=[100],OVERLABEL=['Td=100K'],OVERCOLOR=[cyan],$
           OVER2=alog10(chiRT/nHtot),OVERV2=[-12],$
           OVERL2=['log!L !N!9c!X/n=-12'],OVERC2=[red],$
           OVER3=Tgas,OVERV3=[2000],$
           OVERL3=['Tg=2000'],OVERC3=white,$
           OVER4=nmol(*,*,iH2)/nmol(*,*,iH),OVERV4=[0.1],$
           OVERL4=['H2=H/10'],OVERC4=red
isp=SPindex(Nsp,SPname,"HDO")
if(isp gt 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; HDO
           YMAX=-3.2, YMIN=ymin,VERT=0,$
           OVERCONT=Tdust,OVERVAL=[100],OVERLABEL=['Td=100K'],OVERCOLOR=[cyan],$
           OVER2=alog10(chiRT/nHtot),OVERV2=[-12],$
           OVERL2=['log!L !N!9c!X/n=-12'],OVERC2=[red],$
           OVER3=Tgas,OVERV3=[2000],$
           OVERL3=['Tg=2000'],OVERC3=white,$
           OVER4=nmol(*,*,iH2)/nmol(*,*,iH),OVERV4=[0.1],$
           OVERL4=['H2=H/10'],OVERC4=red
endif
isp1=SPindex(Nsp,SPname,"H2O")
isp2=SPindex(Nsp,SPname,"HDO")
if (isp1 GT 0 and isp2 GT 0) then begin
r=nmol(*,*,isp2)/(nmol(*,*,isp1)+1.E-10*nHtot(*,*))                        ; HDO/H2O
CONTFILL2, xx,zz,r,SPname(isp2)+'/'+SPname(isp1),1,1,4,$
           ZMAX=zmax,YMAX=0.1,YMIN=-6.1
endif
; ----- computing LTE o/p for water ----------
;dE=34.235
;gu=3.0
;gl=1.0
;fpara=1.0/(1.0+gu/gl*exp(-dE/tgas))
;fortho=1.0-fpara
;CONTFILL2, xx,zz,fortho/fpara,'H2O o/p',1,0,4,ZMAX=zmax
isp=SPindex(Nsp,SPname,"O2")                                               ; O2
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$   
           YMAX=ymax,YMIN=ymin,VERT=0

; -------------- basic carbon chemistry --------------------
isp=SPindex(Nsp,SPname,"C+")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; C+
           YMAX=ymax,YMIN=ymin,$
           OVERCONT=alog10(chiRT/nHtot),OVERVAL=[-6,-5,-4,-3,-2,-1],$
           OVERLABEL=['-6','-5','-4','-3','-2','log!L !N!9c!7/n!L !N=!L !N-1'],$
           OVERCOLOR=white
CoverCO = nmol(*,*,iC)
CoverCO(where(chiRT/nHtot LT 1.E-10))=0.0
CoverCO = CoverCO/nmol(*,*,iCO)
CpoverCO = nmol(*,*,iCp)
CpoverCO(where(chiRT/nHtot LT 1.E-10))=0.0
CpoverCO = CpoverCO/nmol(*,*,iCO)
NoverN2 = nmol(*,*,iN)
NoverN2(where(chiRT/nHtot LT 1.E-10))=0.0
NoverN2 = NoverN2/nmol(*,*,iN2)
CONTFILL2, xx,zz,nmol(*,*,iC)/nHtot(*,*),SPname(iC),1,1,1,ZMAX=zmax,$      ; C
           YMAX=ymax,YMIN=ymin,$
           OVERCONT=nmol(*,*,iC)/nmol(*,*,iCp),OVERVAL=[0.01],$
           OVERLABEL=['C=C+/100'],OVERCOLOR=black,$
           OVER2=CoverCO,OVERV2=[0.01],$
           OVERL2=['C=CO/100'],OVERC2=blue,$
           OVER3=nmol(*,*,iH2)/nmol(*,*,iH),OVERV3=[1.0],$
           OVERL3=['H=H2'],OVERC3=white
isp=SPindex(Nsp,SPname,"CH")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; CH
           YMAX=ymax,YMIN=ymin,VERT=0
isp=SPindex(Nsp,SPname,"CO")
iH2=SPindex(Nsp,SPname,"H2")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; CO
           YMAX=ymax,YMIN=ymin, $
           OVERCONT=alog10(chiRT/nHtot),OVERVAL=[-4],$
           OVERLABEL=['log!L !N!9c!X/n!L !N=!L !N-4'],OVERCOLOR=black,$
           OVER2=Tdust,OVERV2=[23], $
           OVERL2=['Tdust=23K'],OVERC2=[blue]
CONTFILL,  xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),0,1,1,$              ; CO linear
           YMAX=ymax,YMIN=ymin-1,ZMAX=max(zz)*0.7, $
           OVERCONT=alog10(chiRT/nHtot),OVERVAL=[-4],$
           OVERLABEL=['log!L !N!9c!X/n!L !N=!L !N-4'],OVERCOLOR=black,$
           OVER2=Tdust,OVERV2=[23], $
           OVERL2=['Tdust = 23K'],OVERC2=[blue]

isp=SPindex(Nsp,SPname,"H2")
CONTFILL, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),0,1,1,$              ; H2 linear
          YMAX=0.2,YMIN=ymin+3,ZMAX=max(zz)*0.7
iel=SPindex(Nsp,SPname,"e-")
iSplus=SPindex(Nsp,SPname,"S+")
iCplus=SPindex(Nsp,SPname,"C+")
iC=SPindex(Nsp,SPname,"C")
iCO=SPindex(Nsp,SPname,"CO")
nsmall=nHtot*1.E-10
CONTFILL, xx,zz,nmol(*,*,iel)/nHtot(*,*),SPname(iel),0,1,1,$              ; e- linear
          YMAX=0.2,YMIN=ymin+3,ZMAX=max(zz)*0.7
CONTFILL, xx,zz,Tgas,'T!Lgas !N[K]',0,1,1,$                               ; Tgas linear
          YMIN=alog10(5.0),YMAX=alog10(5000),ZMAX=max(zz)*0.7
isp=SPindex(Nsp,SPname,"CN")
CONTFILL, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),0,1,1,$              ; CN linear
          YMAX=ymax,YMIN=ymin-1,ZMAX=max(zz)*0.7, $
          OVERCONT=nmol(*,*,iel)/(nmol(*,*,iSplus)+nsmall),OVERVAL=[5.0],$
          OVERLABEL=['e-=5xS+'],OVERCOLOR=white,$
          OVER2=nmol(*,*,iH)/nmol(*,*,iH2),OVERV2=[10.0],$
          OVERL2=['H=10xH2'],OVERC2=white
isp=SPindex(Nsp,SPname,"HCN")
CONTFILL, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),0,1,1,$              ; HCN linear
          YMAX=ymax,YMIN=ymin-1,ZMAX=max(zz)*0.7,$
          OVERCONT=nmol(*,*,iel)/(nmol(*,*,iSplus)+nsmall),OVERVAL=[5.0],$
          OVERLABEL=['e-=5xS+'],OVERCOLOR=white,$
          OVER2=nmol(*,*,iH)/nmol(*,*,iH2),OVERV2=[10.0],$
          OVERL2=['H=10xH2'],OVERC2=white
isp=SPindex(Nsp,SPname,"H2CO")
CONTFILL, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),0,1,1,$              ; H2CO linear
          YMAX=ymax,YMIN=ymin-1,ZMAX=max(zz)*0.7
isp=SPindex(Nsp,SPname,"C2H")
CONTFILL, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),0,1,1,$              ; C2H linear
          YMAX=ymax,YMIN=ymin-1,ZMAX=max(zz)*0.7
isp=SPindex(Nsp,SPname,"HCO+")
CONTFILL, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),0,1,1,$              ; HCO+ linear
          YMAX=ymax-2,YMIN=ymin-3,ZMAX=max(zz)*0.7,$
          OVERCONT=nmol(*,*,iH)/nmol(*,*,iH2),OVERVAL=[1000.0],$
          OVERLABEL=['H2=H/1000'],OVERCOLOR=red,$
          OVER2=nmol(*,*,iCplus)/nHtot,OVERV2=[1.E-7],$
          OVERL2=['C+/<H>=1.E-7'],OVERC2=red
isp=SPindex(Nsp,SPname,"HN2+")
CONTFILL, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),0,1,1,$              ; N2H+ linear
          YMAX=ymax-2,YMIN=ymin-3,ZMAX=max(zz)*0.7

isp=SPindex(Nsp,SPname,"CO2")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; CO2
           YMAX=ymax,YMIN=ymin,$
           OVERCONT=alog10(chiRT/nHtot),OVERVAL=[-10],$
           OVERLABEL=['log!L !N!9c!X/n!L !N=!L !N-10'],OVERCOLOR=red,$
           OVER4=nmol(*,*,iH2)/nmol(*,*,iH),OVERV4=[1],$
           OVERL4=['H=H2'],OVERC4=white
isp=SPindex(Nsp,SPname,"HCO+")       
if(isp gt 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; HCO+
           YMAX=ymax,YMIN=ymin 
endif
isp2=SPindex(Nsp,SPname,"DCO+")
if(isp2 gt 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp2)/nHtot(*,*),SPname(isp2),1,1,1,ZMAX=zmax,$  ; DCO+
           YMAX=ymax,YMIN=ymin
CONTFILL2, xx,zz,nmol(*,*,isp2)/nmol(*,*,isp),SPname(isp2)+'/'+SPname(isp),1,1,1,$ 
           ZMAX=zmax,YMAX=0.1,YMIN=-6.1
endif
isp=SPindex(Nsp,SPname,"H2CO")
if(isp GT 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=0
endif


; ------- nitrogen chemistry ---------
isp=SPindex(Nsp,SPname,"N")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; N
           YMAX=ymax,YMIN=ymin,VERT=0
isp=SPindex(Nsp,SPname,"NH")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; NH
           YMAX=ymax,YMIN=ymin,VERT=0
isp=SPindex(Nsp,SPname,"NH3")
if (isp GT 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; NH3
           YMAX=ymax,YMIN=ymin,VERT=0
endif
isp=SPindex(Nsp,SPname,"N2")
if (isp GT 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; N2
           YMAX=ymax,YMIN=ymin,VERT=0,$
           OVERCONT=alog10(chiRT/nHtot),OVERVAL=[-4],$
           OVERLABEL=['log!L !N!9c!X/n!L !N=!L !N-4'],OVERCOLOR=black
endif
isp=SPindex(Nsp,SPname,"HN2+")
if (isp GT 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; HN2+
           YMAX=ymax-3,YMIN=ymin-3,VERT=0
endif
isp=SPindex(Nsp,SPname,"N2D+")
if (isp GT 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; N2D+
           YMAX=ymax-3,YMIN=ymin-3,VERT=0
endif
isp=SPindex(Nsp,SPname,"CN")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; CN
           YMAX=ymax,YMIN=ymin,VERT=0
isp=SPindex(Nsp,SPname,"HCN")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; HCN
           YMAX=ymax,YMIN=ymin,$    
           OVER3=nmol(*,*,iH)/nmol(*,*,iH2),OVERV3=[1000],$
           OVERL3=['H/H2=1000'],OVERC3=white,$
           OVER4=NoverN2,OVERV4=[0.1],$
           OVERL4=['N2/N=10'],OVERC4=red
isp=SPindex(Nsp,SPname,"HNC")
if (isp GT 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; HNC
           YMAX=ymax,YMIN=ymin,VERT=0
endif
isp=SPindex(Nsp,SPname,"DCN")
if (isp GT 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; DCN
           YMAX=ymax-3,YMIN=ymin-3,VERT=0
endif

;-----------  sulphur chemistry -----------
isp=SPindex(Nsp,SPname,"S+")
if (isp gt 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; S+
           YMAX=ymax,YMIN=ymin,VERT=0
endif
isp=SPindex(Nsp,SPname,"S")
if (isp gt 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; S
           YMAX=ymax,YMIN=ymin,VERT=0
endif
isp=SPindex(Nsp,SPname,"HS")
if (isp gt 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; HS
           YMAX=ymax,YMIN=ymin,VERT=0
endif
isp=SPindex(Nsp,SPname,"H2S")
if (isp gt 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; H2S
           YMAX=ymax,YMIN=ymin,VERT=0
endif
isp=SPindex(Nsp,SPname,"SO2")
if (isp gt 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; SO2
           YMAX=ymax,YMIN=ymin,VERT=0
endif
isp=SPindex(Nsp,SPname,"CS")
if (isp GT 0) then begin
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; CS
           YMAX=ymax,YMIN=ymin,VERT=0
endif


; ------ hydro-carbon chemistry ------
isp=SPindex(Nsp,SPname,"CH+")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; CH+
           YMAX=ymax,YMIN=ymin,VERT=-1
isp=SPindex(Nsp,SPname,"CH")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$    ; CH
           YMAX=ymax,YMIN=ymin,VERT=-1
isp=SPindex(Nsp,SPname,"CH4")
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=-1
isp=SPindex(Nsp,SPname,"CH3OH")
if (isp GT 0) then begin
  isp=SPindex(Nsp,SPname,"C2")
  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=-1
  isp=SPindex(Nsp,SPname,"C2H")
  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=-1
  isp=SPindex(Nsp,SPname,"C2H2")
    CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
             YMAX=ymax,YMIN=ymin,$ ;VERT=-1,$
             OVER2=CoverCO,OVERV2=[1.0/10.0],$
             OVERL2=['CO/C=10'],OVERC2=red,$
             OVER3=nmol(*,*,iH)/nmol(*,*,iH2),OVERV3=[100.0],$
             OVERL3=['H/H2=100'],OVERC3=white
  isp=SPindex(Nsp,SPname,"C3")
  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=-1
  isp=SPindex(Nsp,SPname,"C3H")
  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=-1
  isp=SPindex(Nsp,SPname,"C3H2")
  if (isp GT 0) then begin
  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
             YMAX=ymax,YMIN=ymin,VERT=-1
  endif
  isp=SPindex(Nsp,SPname,"H2CCC")
  if (isp GT 0) then begin
  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=-1
  endif
  isp=SPindex(Nsp,SPname,"CH3CCH")
  if (isp GT 0) then begin
  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=-1
  endif
  isp=SPindex(Nsp,SPname,"HC4H")
  if (isp GT 0) then begin
  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=-1
  endif
  isp=SPindex(Nsp,SPname,"CH3CH3")
  if (isp GT 0) then begin
  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
             YMAX=ymax,YMIN=ymin,VERT=-1
  endif
  isp=SPindex(Nsp,SPname,"C6H6")
  if (isp GT 0) then begin
  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
             YMAX=ymax,YMIN=ymin,VERT=-1
  endif
  isp=SPindex(Nsp,SPname,"CH3OH")
  CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
             YMAX=ymax,YMIN=ymin,VERT=-1
endif


;---------- number of ice layers ---------
nice = 0.0
for isp=1,Nsp do begin
  if (strpos(SPname(isp),'#') GT 0) then begin
    if (strpos(SPname(isp),'*') LT 0) then begin
       nice = nice + nmol(*,*,isp)
       ;print,SPname(isp),MAX(nmol(*,*,isp)/nHtot(*,*))
    endif
  endif  
endfor
AA   = ndust*4.d0*pi*(amean*mic)^2          ; total dust area per volume
nsurf= 1.5E+15                              ; density of adsorption sites
Nlayers = nice/(AA*nsurf)                   ; number of ice layers
CONTFILL2, xx,zz,Nlayers,'ice layers',1,1,4,$
           ZMAX=zmax,YMIN=-2,YMAX=8,VERT=0,$
           OVERCONT=Nlayers,OVERVAL=[2,1000],$
           OVERLABEL=['2','1000'],OVERCOLOR=black
;---------- H2O#/H2O ---------
iH2O=SPindex(Nsp,SPname,"H2O")
isp=SPindex(Nsp,SPname,"H2O#")
tmp=nmol(*,*,isp)/nmol(*,*,iH2O)
CONTFILL2, xx,zz,tmp,'n!LH2O#!N/n!LH2O!N',1,1,4,$
           ZMAX=zmax,YMAX=5,YMIN=-5,VERT=0,$
           OVERCONT=tmp,OVERVAL=[1],$
           OVERLABEL=['1'],OVERCOLOR=black
;---------- H2O#/n#tot ---------
;tmp=nmol(*,*,isp)/nice
;CONTFILL2, xx,zz,tmp,'H2O#/n#tot',1,0,4,$
;           ZMAX=zmax,YMIN=0.0,VERT=-1,$
;           OVERCONT=tmp,OVERVAL=[1],$
;           OVERLABEL=['1'],OVERCOLOR=black
;---------- H2O ice ---------
bk    = 1.380658120E-16           
amu   = 1.660531000d-24
Nlay  = 2.d0                                 ; number of UV-active layers
mH2O  = 18*amu                               ; mass of H2O
Eads  = 5700.0                               ; adsorption energy water
yield = 3.e-3                                ; photo-yield
FDraine = 1.921E+8                           ; UV photons/cm^2/s for chiRT=1
fosc  = SQRT(2*nsurf*bk*Eads/(pi^2*mH2O))    ; oscillator frequency water
vth   = SQRT(bk*Tgas/(2.0*pi*mH2O))          ; thermal velocity
Tsnow = Eads/(alog(fosc/vth)-alog(AA))      
;Tsnow = 175/(1.0-0.1*alog10(nHtot/1.E+14))   ; simplified
csnow = (vth*4.0*AA*nsurf*Nlay)/(FDraine*yield)
;csnow = 5.8*(nHtot/1.E+8)                    ; simplified
;
; ice line from Min et al. (2014) in prep. 
gamma = 1.e-20                                ; in g/cm^3 (calibrated on ProDiMo models) - for Herbigs
GH    = 5.33e-14                              ; Habing UV field strength in erg/cm^3 
AA    = 7.7205
BB    = 2827.7
;pH2O  = nmol(*,*,isp)*bk*Tgas                ; partial pressure of water vapor
;pH2O  = nmol(*,*,isp)*bk*Tdust               ; partial pressure of water vapor - many models have only Tdust
ptot = nHtot(*,*)*bk*Tdust
;pcrit = bk*Tgas/mH2O * ( (10.^(AA-(BB/Tgas))/Tgas) + gamma*(chiRT)/sqrt(Tgas) )
pcrit = bk*Tdust/mH2O * ( (10.^(AA-(BB/Tdust))/Tdust) + gamma*(chiRT)/sqrt(Tdust) ) ; - many models have only Tdust
;pcrit = pcrit / pH2O
pcrit = pcrit / ptot / 1.e-4
;
; ice line from Stefano - rates
nsurf=1.5E+15
ads=4*!PI*(amean*mic)^2*ndust*SQRT((bk*Tgas)/(2*!pi*mH2O))
termico=fosc*EXP(-Eads/Tdust)
nactive=4.0*!PI*(amean*mic)^2*ndust*nsurf*Nlay
foto=!PI*(amean*mic)^2*(ndust/nactive)*yield*FDraine*chiRT
CRI=1.7E-017
cosmico=3.16d-19*(CRI/5.0E-17)*termico*EXP(Tdust/70.0)
;scudo=EXP(-)
rateo=alog10(ads/(termico+foto*0.1+cosmico))
;
;CONTFILL2, xx,zz,nmol(*,*,isp)/nmol(*,*,isp1),'n!LH2O#!N/n!LH2O!N',1,1,4,ZMAX=zmax,$
;;nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;            YMAX=5.,YMIN=-5.,VERT=0,$
;;           OVERCONT=chiRT/csnow,OVERVAL=[1],$
;;           OVERLABEL=['!9c!7=!9c!7snow'],OVERCOLOR=white,$
;            OVERCONT=rateo,OVERVAL=[0],$
;            OVERLABEL=['Ice line'],OVERCOLOR=black, $
;;OVER2=nmol(*,*,isp)/nmol(*,*,isp1),OVERV2=1,OVERL2=['1'],OVERC2=[yellow]
;            OVER2=Tdust,OVERV2=[152],$
;            OVERL2=['    T!Ldust!N=152K'],OVERC2=[yellow]
;
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=0,$
;           OVERCONT=chiRT/csnow,OVERVAL=[1],$
;           OVERLABEL=['!9c!7=!9c!7snow'],OVERCOLOR=white,$
           OVERCONT=pcrit,OVERVAL=[1],$
           OVERLABEL=['ice line - Min et al'],OVERCOLOR=white, $
           OVER2=rateo,OVERV2=[0],$
           OVERL2=['ice line - Antonellini et al'],OVERC2=[yellow]
;           OVER2=Tdust/Tsnow,OVERV2=[1],$
;           OVERL2=['Tdust=Tsnow'],OVERC2=[yellow]

;--------- HDO# ----------
isp1=SPindex(Nsp,SPname,"H2O#")
isp2=SPindex(Nsp,SPname,"HDO#")                       ; HDO# and HDO#/H2O#
if (isp GT 0 and isp2 GT 0) then begin       
CONTFILL2, xx,zz,nmol(*,*,isp2)/nHtot(*,*),SPname(isp2),1,1,1,$
           YMAX=ymax,YMIN=ymin,ZMAX=zmax,VERT=0
r = nmol(*,*,isp2)/(nmol(*,*,isp1)+1.E-10*nHtot(*,*))  
CONTFILL2, xx,zz,r,SPname(isp2)+'/'+SPname(isp1),1,1,4,$
           YMAX=0.1,YMIN=-6.1,ZMAX=zmax,VERT=0
endif


;---------- CO ice ---------
isp=SPindex(Nsp,SPname,"CO#")
; ice line from Stefano Antonellini 
mCO=28*amu
gamma = 1.e-20                                ; in g/cm^3 (calibrated on ProDiMo models) - for Herbigs
GH    = 5.33e-14                              ; Habing UV field strength in erg/cm^3 
AA    = 16.063
BB    = 947.687
pCO   = nmol(*,*,isp)*bk*Tgas                 ; partial pressure of water vapor
pcrit = bk*Tgas/mCO * ( (10.^(AA-(BB/Tgas))/Tgas) + gamma*(chiRT)/sqrt(Tgas) )
pcrit = pcrit / pCO
CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=-1,$
           OVERCONT=Tdust,OVERVAL=[15.0,20.0,25.0],$
           OVERLABEL=['15','20','25'],OVERCOLOR=yellow, $
           OVER2=pcrit, OVERV2=[1], OVERL2=['CO ice line'], OVERC2=[white]

;---------- other ices ---------
ices = ["*H2O#","!H2O#","NH3#","CH4#","C2H6#","O2#","CO2#","C2H2#","CH3OH#","OH#","HNO#","N2#","HCN#","SO2#","H2S#"]
Nice = N_ELEMENTS(ices)
for i=0,Nice-1 do begin
  isp=SPindex(Nsp,SPname,ices(i))
  if (isp GT 0) then begin
    sname = SPname(isp)
    if (STRMID(sname,0,1) EQ "!") then sname="!"+sname
    CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),sname,1,1,1,ZMAX=zmax,$
           YMAX=ymax,YMIN=ymin,VERT=-1
  endif
endfor

;--------- ice plots DIANA III paper ----------
CONTFILL2_nolegend, xx,zz,nHtot,'!7n!L<H> !N[cm!U-3!N]!X',1,1,2,ZMAX=zmax,$
          YMIN=3.0,YMA=max([max(alog10(nHtot)),13])
          ;OVERCONT=AV,OVERVAL=[0.1,1],OVERLABEL=['A!LV!N=0.1','A!LV!N=1'],$
          ;OVERCOLOR=[black],$
          ;OVER2=Tdust,OVERV2=[25,110],OVERL2=['Td=25K','Td=110K'],OVERC2=[red]
blue=60
yellow=190
orange=210
green=140
magenta=100
red=240
ival = -5.5
isp=SPindex(Nsp,SPname,"NH3#")
contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival],$
    C_ANNOTATION=[''],C_COLORS=[red],$     
    C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4, /fill, C_ORIENTATION=45, C_SPACING=0.3
contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival],$
    C_ANNOTATION=[''],C_COLORS=[red],C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4
xyouts, 0.2, 0.776*zmax, '!7NH3 ice!X', color=red, charsize=1.6, alignment=0.5

isp=SPindex(Nsp,SPname,"H2O#")
contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival],$
    C_ANNOTATION=[''],C_COLORS=[blue],$
    C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4, /fill, C_ORIENTATION=45, C_SPACING=0.3
contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival],$
    C_ANNOTATION=[''],C_COLORS=[blue],C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4
xyouts, 0.2, 0.959*zmax, '!7H2O ice!X', color=blue, charsize=1.6, alignment=0.5

isp=SPindex(Nsp,SPname,"CO#")
contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival],$
    C_ANNOTATION=[''],C_COLORS=[orange],$     
    C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4, /fill, C_ORIENTATION=-45, C_SPACING=0.3
contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival],$
    C_ANNOTATION=[''],C_COLORS=[orange],C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4
xyouts, 0.2, 0.837*zmax, '!7CO ice!X', color=orange, charsize=1.6, alignment=0.5

isp=SPindex(Nsp,SPname,"CO2#")
contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival-0.4],$
    C_ANNOTATION=[''],C_COLORS=[yellow],$     
    C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4, /fill, C_ORIENTATION=45, C_SPACING=0.3
contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival-0.4],$
    C_ANNOTATION=[''],C_COLORS=[yellow],C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4
xyouts, 0.2, 0.898*zmax, '!7CO2 ice!X', color=yellow, charsize=1.6, alignment=0.5

;isp=SPindex(Nsp,SPname,"HCN#")
;contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival],$
;    C_ANNOTATION=['!9e!7!DHCNice!N=10!U-4.5!N'],C_COLORS=[magenta],$     
;    C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4, /fill, C_ORIENTATION=-45, C_SPACING;=0.3
;contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival],$
;    C_ANNOTATION=['!9e!7!DHCNice!N=10!U-4.5!N'],C_COLORS=[magenta],$     
;    C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4
;xyouts, 0.2, 0.35, '!7HCN ice!X', color=magenta, charsize=1.2, alignment=0.5

isp=SPindex(Nsp,SPname,"CH4#")
contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival],$
    C_ANNOTATION=[''],C_COLORS=[green],$     
    C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4, /fill, C_ORIENTATION=45, C_SPACING=0.3
contour,alog10(nmol(*,*,isp)/nHtot(*,*)),xx,zz/xx,/overplot,level=[ival],$
    C_ANNOTATION=[''],C_COLORS=[green],C_LINESTYLE=0,C_CHARSIZE=1.2,C_THICK=4
xyouts, 0.2, 0.714*zmax, '!7CH4 ice!X', color=green, charsize=1.6, alignment=0.5

contour,AV_ver,xx,zz/xx,/overplot,LEVEL=[1],$
      C_ANNOTATION=['AV!Lver!N=1'],C_COLORS=black,$
      C_LINESTYLE=2,C_CHARSIZE=1.6,C_THICK=3
contour,AV_rad,xx,zz/xx,/overplot,LEVEL=[1],$
      C_ANNOTATION=['AV!Lrad!N=1'],C_COLORS=black,$
      C_LINESTYLE=2,C_CHARSIZE=1.6,C_THICK=3
contour,Tdust,xx,zz/xx,/overplot,LEVEL=[25,150],$
      C_ANNOTATION=['T!Ld!N=25K','T!Ld!N=150K'],C_COLORS=red,$
      C_LINESTYLE=2,C_CHARSIZE=1.6,C_THICK=3

;------  equilibrium condensation plots  -----
EQUIL_COND, Nx,Nz,xx,zz,nHtot,Tgas,Tdust

;------  X-ray influenced atoms/ions  -------
isp=SPindex(Nsp,SPname,"Ne")
if (isp GT 0) then begin 
;isp=SPindex(Nsp,SPname,"H2O+")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=-3, YMIN=-12,$ ;NSMOOTH=5,$
;           OVERCONT=Tgas,OVERVAL=[250,2000],OVERLABEL=['250K','2000K'],$
;                    OVERCOLOR=[white,white],$
;            OVER2=alog10(chiRT/nHtot),OVERV2=[-11,-7.5],OVERL2=['-11','-7.5'],$
;            OVERC2=[red]  ;GRIDON=1
;isp=SPindex(Nsp,SPname,"Ne")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
;isp=SPindex(Nsp,SPname,"Ne+")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
;isp=SPindex(Nsp,SPname,"Ne++")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
;isp=SPindex(Nsp,SPname,"Ar")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
;isp=SPindex(Nsp,SPname,"Ar+")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
;isp=SPindex(Nsp,SPname,"Ar++")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
;isp=SPindex(Nsp,SPname,"Fe")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
;isp=SPindex(Nsp,SPname,"Fe+")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
;isp=SPindex(Nsp,SPname,"O+")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
;isp=SPindex(Nsp,SPname,"O++")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
;isp=SPindex(Nsp,SPname,"N+")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
;isp=SPindex(Nsp,SPname,"N++")
;CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,ZMAX=zmax,$
;           YMAX=ymax,YMIN=ymin,VERT=-1
endif

; ------- grain surfarce charges -------
ncharge =0.0
i0=SPindex(Nsp,SPname,"Z----")
if (i0 GT 0) then begin
   y1=ALOG10(max(nmol(*,*,i0)/nHtot(*,*)))
   y2=y1-6.0
   CONTFILL2, xx,zz,nmol(*,*,i0)/nHtot(*,*),SPname(i0),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
   ncharge = -4*nmol(*,*,i0)
endif
i1=SPindex(Nsp,SPname,"Z---")
if (i1 GT 0) then begin
   y1=ALOG10(max(nmol(*,*,i1)/nHtot(*,*)))
   y2=y1-6.0
   CONTFILL2, xx,zz,nmol(*,*,i1)/nHtot(*,*),SPname(i1),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
   ncharge = ncharge-3*nmol(*,*,i1)
endif
i2=SPindex(Nsp,SPname,"Z--")
if (i2 GT 0) then begin
   y1=ALOG10(max(nmol(*,*,i2)/nHtot(*,*)))
   y2=y1-6.0
   CONTFILL2, xx,zz,nmol(*,*,i2)/nHtot(*,*),SPname(i2),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
   ncharge = ncharge-2*nmol(*,*,i2)
endif
i3=SPindex(Nsp,SPname,"Z-")
if (i3 GT 0) then begin
   y1=ALOG10(max(nmol(*,*,i3)/nHtot(*,*)))
   y2=y1-6.0
   CONTFILL2, xx,zz,nmol(*,*,i3)/nHtot(*,*),SPname(i3),1,1,1,$
              YMAX=y1,YMIN=y2,ZMAX=zmax  
   ncharge = ncharge-1*nmol(*,*,i3)
endif
i4=SPindex(Nsp,SPname,"Z")
if (i4 GT 0) then begin
   y1=ALOG10(max(nmol(*,*,i4)/nHtot(*,*)))
   y2=y1-6.0
   CONTFILL2, xx,zz,nmol(*,*,i4)/nHtot(*,*),SPname(i4),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
   ncharge = ncharge+0*nmol(*,*,i4)
endif
i5=SPindex(Nsp,SPname,"Z+")
if (i5 GT 0) then begin
   y1=ALOG10(max(nmol(*,*,i5)/nHtot(*,*)))
   y2=y1-6.0
   CONTFILL2, xx,zz,nmol(*,*,i5)/nHtot(*,*),SPname(i5),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
   ncharge = ncharge+1*nmol(*,*,i5)
endif
i6=SPindex(Nsp,SPname,"Z++")
if (i6 GT 0) then begin
   y1=ALOG10(max(nmol(*,*,i6)/nHtot(*,*)))
   y2=y1-6.0
   CONTFILL2, xx,zz,nmol(*,*,i6)/nHtot(*,*),SPname(i6),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
   ncharge = ncharge+2*nmol(*,*,i6)
endif
i7=SPindex(Nsp,SPname,"Z+++")
if (i7 GT 0) then begin
   y1=ALOG10(max(nmol(*,*,i7)/nHtot(*,*)))
   y2=y1-6.0
   CONTFILL2, xx,zz,nmol(*,*,i7)/nHtot(*,*),SPname(i7),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
   ncharge = ncharge+3*nmol(*,*,i7)
endif
i8=SPindex(Nsp,SPname,"Z++++")
if (i8 GT 0) then begin
   y1=ALOG10(max(nmol(*,*,i8)/nHtot(*,*)))
   y2=y1-6.0
   CONTFILL2, xx,zz,nmol(*,*,i8)/nHtot(*,*),SPname(i8),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
   ncharge = ncharge+4*nmol(*,*,i8)
endif

i1=SPindex(Nsp,SPname,"Z")
if (i1 GT 0) then begin
   y1= 200.
   y2=-200.
   CONTFILL2, xx,zz,ncharge/ndust(*,*),'<Z>/grain',1,0,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
endif

;-------- PAHs and mean charge --------
i1=SPindex(Nsp,SPname,"PAH-")
if ((i1 GT 0) AND (fPAH GT 0.0)) then begin
y1=-4.5+ALOG10(fPAH)
y2=y1-12.0

CONTFILL2, xx,zz,nmol(*,*,i1)/nHtot(*,*),SPname(i1),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
i2=SPindex(Nsp,SPname,"PAH")
CONTFILL2, xx,zz,nmol(*,*,i2)/nHtot(*,*),SPname(i2),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
i3=SPindex(Nsp,SPname,"PAH+")
CONTFILL2, xx,zz,nmol(*,*,i3)/nHtot(*,*),SPname(i3),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
i4=SPindex(Nsp,SPname,"PAH++")
CONTFILL2, xx,zz,nmol(*,*,i4)/nHtot(*,*),SPname(i4),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
i5=SPindex(Nsp,SPname,"PAH+++")
CONTFILL2, xx,zz,nmol(*,*,i5)/nHtot(*,*),SPname(i5),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
PAHgas    = (nmol(*,*,i1)+nmol(*,*,i2)+nmol(*,*,i3)+nmol(*,*,i4)+nmol(*,*,i5))
PAHcharge = (-nmol(*,*,i1)+nmol(*,*,i3)+2*nmol(*,*,i4)+3*nmol(*,*,i5))/PAHgas
PAHcharge(where(PAHgas lt 1.D-75*nHtot)) = !values.d_nan
CONTFILL2, xx,zz,PAHcharge,"<PAHcharge>",1,0,2,$
           YMIN=-1.0,YMAX=3.0,ZMAX=zmax
CONTFILL2, xx,zz,PAHgas/nHtot(*,*),'PAH gas',1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
i6=SPindex(Nsp,SPname,"PAH#")
CONTFILL2, xx,zz,nmol(*,*,i6)/nHtot(*,*),SPname(i6),1,1,1,$
           YMAX=y1,YMIN=y2,ZMAX=zmax
endif

;----------- CH+ special ------------
isp=SPindex(Nsp,SPname,"CH+")
if ((isp GT 0)AND(0 EQ 1)) then begin       
  isp=SPindex(Nsp,SPname,"H2")
  nH2=nmol(*,*,isp)
  isp=SPindex(Nsp,SPname,"CH+")
  nchp=nmol(*,*,isp)
  CONTFILL2, xx,zz,nchp/nHtot(*,*),SPname(isp),1,1,1,$
           YMAX=ymax,YMIN=ymin,ZMAX=zmax,NSMOOTH=3, $
           OVERCONT=alog10(nH2/NHtot),OVERVAL=[-6.,-4.,-2.,-1], $
           OVERLABEL=['-6','-4','-2','-1'],OVERCOLOR=[blue], $
           OVER2=Tgas,OVERV2=[300.,3000.0], $
           OVERL2=['300','3000'],OVERC2=[white]
  x1=xx(*,0)
  inc=90.-42.
  inc=inc*(!pi/180.)
  z1=x1*tan(inc)
  oplot,x1,z1/x1,col=150,thick=2
  nx=n_elements(x1)
  nchp_interp=fltarr(nx)
  Tgas_interp=fltarr(nx)
  for i=0,nx-1 do nchp_interp(i)=interpol(nchp(i,*),zz(i,*),z1(i))
  for i=0,nx-1 do Tgas_interp(i)=interpol(Tgas(i,*),zz(i,*),z1(i))
  plot,x1,nchp_interp,/xlog,/ylog
  CD_chp=int_tabulated(x1,nchp_interp)*1.5e13
  print,'N(CH+)=',CD_chp,' cm-2'
  ; ------
  isp=SPindex(Nsp,SPname,"CH")
  nCH=nmol(*,*,isp)
  nCH_interp=fltarr(nx)
  for i=0,nx-1 do nCH_interp(i)=interpol(nCH(i,*),zz(i,*),z1(i))
  plot,x1,nCH_interp,/xlog,/ylog
  CD_CH=int_tabulated(x1,nCH_interp)*1.5e13
  print,'N(CH)=',CD_CH,' cm-2'
  ; -----
  isp=SPindex(Nsp,SPname,"H2")
  nH2=nmol(*,*,isp)
  nH2_interp=fltarr(nx)
  for i=0,nx-1 do nH2_interp(i)=interpol(nH2(i,*),zz(i,*),z1(i))
  plot,x1,nH2_interp,/xlog,/ylog
  CD_H2=int_tabulated(x1,nH2_interp)*1.5e13
  print,'N(H2)=',CD_H2,' cm-2'
  mTgas=int_tabulated(x1,nh2_interp*Tgas_interp)/(CD_H2/1.5e13)
  print,'mean los H2 temperature=',mTgas,' K'
endif

;----------- HS+ special ------------
;isp=SPindex(Nsp,SPname,"HS+")
;if ((isp GT 0)) then begin
;   y1=ALOG10(max(nmol(*,*,isp)/nHtot(*,*)))
;   y2=y1-6.0
;   CONTFILL2, xx,zz,nmol(*,*,isp)/nHtot(*,*),SPname(isp),1,1,1,$
;              YMAX=y1,YMIN=y2,ZMAX=zmax
;endif

;--------------------------------------------
; ***  pressure and linear GASPS species  ***
;--------------------------------------------
CONTFILL, xx,zz,press,'!7p [dyn cm!U-2!N]!X',1,1,2      ;pressure
ymax = ALOG10(MAX(nHtot(where(xx GT 0.05*max(xx)))))    ;linear n<H>
ymin = MIN([3.0,ymax-2.0])
CONTFILL, xx,zz,nHtot,'!7n<H> [cm!U-3!N]!X',$
          YMIN=ymin,YMAX=ymax,0,1,2  

;----- friction and settling -----
yr       = 3.155760000D+7  
AU       = 1.495978700D+13
grav     = 6.672598500D-8
Msun     = 1.988922500d+33
amu      = 1.660531000E-24           
bk       = 1.380658120E-16           
mic      = 1.E-4
rho_dust = 2.5                       ; material density, typical value [g/cm^3]
r        = xx*AU                     ; unit conversions -> [cgs]
z        = zz*AU
a        = amean*mic                 ; mean size <a^3>^(1/3)
mmean    = 2.3*amu                   ; mean molecular weight (H2-rich)
vth      = sqrt(bk*Tdust/mmean)      ; thermal velocity (or use proper cT, but that
                                     ;                produces wrinkles in figures)
Omega    = sqrt(grav*Mstar*Msun/r^3) ; Keplerian orbital frequency
tau_dyn  = 2.0*!pi/Omega             ; dynamical timescale = orbit time
nukin    = 5.877E-6*SQRT(Tdust)      ; kinematic viscosity (Woitke&Helling 2006)
                                     ; [g/cm/s] (Tgas -> wrinkles)
smean    = 2.1E-15                   ; mean cross section for friction (H2+He) 
lmean    = 1.0/(nHtot*smean)         ; mean free path [cm] 
Kn       = lmean/(2.0*a)             ; Knudsen number (>>1 for Epstein to be valid)
tau_fric = a*rho_dust/(vth*rho)      ; frictional timescale (Epstein)
St       = tau_fric/tau_dyn          ; Stokes number (>>1 means decoupled)
tsettle  = 1.0/tau_fric/Omega^2      ; settling timescale z/vdrift (Epstein)
ymin=alog10(min(Kn))
ymax=alog10(max(Kn))
CONTFILL2,xx,zz,Kn,'Knudsen number',0,1,2,YMIN=ymin,YMAX=ymax
ymin=alog10(min(St))
ymax=alog10(max(St))
CONTFILL2,xx,zz,St,'Stokes number',0,1,2,YMIN=ymin,YMAX=ymax,$
          OVERCONT=alog10(St),OVERVAL=[-2,0,2], $
          OVERLABEL=['-2','0','2'], $
          OVERCOLOR=[black,black,black]
;----- settling timescale (mean size) ------
ymin=alog10(min(tsettle/yr))
ymax=alog10(max(tsettle/yr))
CONTFILL2,xx,zz,tsettle/yr,'!9t!L!7settling !N[yrs]',0,1,2,$
          YMIN=ymin,YMAX=ymax,$
          OVERCONT=alog10(tsettle/yr),OVERVAL=[5,6,7], $
          OVERLABEL=['5','6','7'],$
          OVERCOLOR=[black,black,black]
;----- critical dust size acrit where tsettle=age -----
age      = 2.E+6*yr   
tau_fric = 1.0/age/Omega^2
acrit    = tau_fric*(vth*rho)/rho_dust/mic
ymax=alog10(max(acrit))
ymin=min([ymax-6,-6])
CONTFILL2,xx,zz,acrit,'a!Lcrit!N [!9m!7m]',0,1,2,$
          YMIN=ymin,YMAX=ymax,$
          OVERCONT=alog10(acrit),OVERVAL=[-2,-1,0,1,2], $
          OVERLABEL=['-2','-1','0','1','2'],$
          OVERCOLOR=[black,black,black,black,black]

;------------------------------------------
; ***  chemical and cooling timescales  ***
;------------------------------------------
grav = 6.672598500D-08     ; gravitational constant
Msun = 1.988922500D+33     ; solar mass
AU   = 1.495978700D+13     ; 1 astronomical unit
yr   = 3.155760000D+7      ; 1 year
rr   = sqrt(xx^2+zz^2)
vKepler = sqrt(grav*Mstar*Msun * (xx*AU)^2/(rr*AU)^3)
Period  = 2.0*!PI*(xx*AU)/vKepler

CONTFILL2, xx,zz,tauchem,'!9t!L!7chem !N[yrs]',1,1,2,$      ;chemical timescale
           YMAX=8

CONTFILL2, xx,zz,taucool,'!9t!L!7cool !N[yrs]',1,1,2        ;cooling timescale

if (version GE 3) then begin
  CONTFILL2, xx,zz,kapR,'!9k!L!7Ross !N[1/cm]',1,1,2,$      ;kappa_Ross
           OVERCONT=tauR,OVERVAL=[1.E-4,0.001,0.01,0.1,1.0,10.0,$
                                  100.0,1000.0,1.E+4,1.E+5,1.E+6],$
           OVERLABEL=['1E-4','0.001','0.01','0.1','1','10',$
                      '100','1000','1E+4','1E+5','1E+6'], OVERCOLOR=[black]
  AA = FINDGEN(17) * (!PI*2/16.)  
  USERSYM, COS(AA), SIN(AA)
  PLOT,Tdust,kapR/(rho*dustgas),/xlog,/ylog,thick=4,position=pos,$
       xstyle=1,ystyle=1,PSYM=8,SYMSIZE=0.4,$
       xrange=[5,2000],yrange=[5,2000],$
       xtitle="!7T [K]",ytitle="!9k!L!7Ross !N[cm!U2!N/g(dust)]"
endif

if (version GE 2) then begin
  ugas = 5.0/2.0*press
  zmax=min([max(zz/xx),zxshow])
  CONTFILL2, xx,zz,ugas/urad,'Ugas/Urad',1,1,2,ZMAX=zmax,$ 
          OVERCONT=Ugas/Urad,OVERVAL=[1,100,10000],$
          OVERLABEL=['1','100','10000'],OVERCOLOR=black
  taudiff2=taudiff*(ugas+urad)/urad
  CONTFILL2, xx,zz,taudiff2,'!9t!L!7diff !N[yrs]',1,1,2,$   ;rad.diff. time
             ZMAX=zmax
  taueff = taucool
  for ix=0,Nx-1 do for iz=0,Nz-1 do begin
    taueff(ix,iz)=max([taudiff2(ix,iz),taucool(ix,iz)])
  endfor
  func = taueff*yr/Period
  CONTFILL2, xx,zz,func,'!9t!L!7eff!N/P',1,1,2,$            ;effective time
             OVERCONT=func,OVERVAL=[1,100,10000],$          ;per orbital P
             OVERLABEL=['1','100','10000'],ZMAX=zmax
endif

;------- isothermal sound speed -------
CONTFILL2, xx,zz,cT*1.E-5,'cT [km/s]',1,0,2                 ;sound speed

;---------------------------------------
; ***  heating & coooling processes  ***
;---------------------------------------
rzoom1 = MIN(xx)
rzoom2 = MAX(xx)
zzoom1 = 0.0
zzoom2 = zmax
;rzoom1 = 0.1
;rzoom2 = 20.0
;zzoom1 = 0.07
;zzoom2 = 0.33
COOLPLOT, xx,zz,heat,mainheat,NHEAT,heatname,2,"main heating processes",$
          XMIN=rzoom1,XMAX=rzoom2,ZMIN=zzoom1,ZMAX=zzoom2,$
          OVERCONT=AV_rad,OVERVAL=[1],OVERLABEL=[''],OVERCOLOR=[black],$
          OVER2=AV_ver,OVERV2=[10],OVERL2=[''],OVERC2=[black]
COOLPLOT, xx,zz,cool,maincool,NCOOL,coolname,2,"main cooling processes",$
          XMIN=rzoom1,XMAX=rzoom2,ZMIN=zzoom1,ZMAX=zzoom2,$
          OVERCONT=AV_rad,OVERVAL=[1],OVERLABEL=[''],OVERCOLOR=[black],$
          OVER2=AV_ver,OVERV2=[10],OVERL2=[''],OVERC2=[black]

;--------------------------
; ***  radiation field  ***
;--------------------------
if (1 EQ 0) then begin
  for i=1,NLAM do begin
    yst=string(format="(F4.2)",lam(i))
    if (lam(i) LT 0.1)    then yst=string(format="(F5.3)",lam(i))
    if (lam(i) LT 0.01)   then yst=string(format="(F6.4)",lam(i))
    if (lam(i) LT 0.001)  then yst=string(format="(F7.5)",lam(i))
    if (lam(i) GE 10.0)   then yst=string(format="(F5.2)",lam(i))
    if (lam(i) GE 100.0)  then yst=string(format="(F5.1)",lam(i))
    if (lam(i) GE 1000.0) then yst=string(format="(I4)",lam(i))
    ybez = '!7J!L' + yst + '!N [erg cm!U-2!N s!U-1!N Hz!U-1!N]!X'
    CONTFILL2, xx,zz,Jlam(*,*,i),ybez,1,1,2,ZMAX=zmax
  endfor
endif
;--- overprint numbers of photons ---
if (0 EQ 1) then begin
blasel='blasel'
filename = folder+"/Jstat_" + string(format="(I3.3)",1)
openr,1,filename
readf,1,blasel
for ix=0,Nx-1 do begin
  for iz=0,Nz-1 do begin
    readf,1,ixx,izz,nnn
    solved(ixx-1,izz-1)=nnn
  endfor
endfor  
close,1
filename = folder+"/Jstat_" + string(format="(I3.3)",2)
openr,1,filename
readf,1,blasel
for ix=0,Nx-1 do begin
  for iz=0,Nz-1 do begin
    readf,1,ixx,izz,nnn
    solved(ixx-1,izz-1)=solved(ixx-1,izz-1)+nnn
  endfor
endfor  
close,1
filename = folder+"/Jstat_" + string(format="(I3.3)",3)
openr,1,filename
readf,1,blasel
for ix=0,Nx-1 do begin
  for iz=0,Nz-1 do begin
    readf,1,ixx,izz,nnn
    solved(ixx-1,izz-1)=solved(ixx-1,izz-1)+nnn
    if(solved(ixx-1,izz-1) GT 99) then solved(ixx-1,izz-1)=99
  endfor
endfor  
close,1
filename = folder+"/Jstat_" + string(format="(I3.3)",ilam)
openr,1,filename
readf,1,blasel
for ix=0,Nx-1 do begin
  for iz=0,Nz-1 do begin
    readf,1,ixx,izz,nnn
    solved(ixx-1,izz-1)=nnn
    if(solved(ixx-1,izz-1) GT 999) then solved(ixx-1,izz-1)=999
  endfor
endfor  
close,1
endif

;--------------------------------
; ***  some quanity on grid   ***
;--------------------------------
yy = ALOG10(Tgas)
titel = "log(Tgas)"
dmax=max(yy)+0.1
dmin=min(yy)-0.1
dmin=max([dmin,dmax-15])
pos=[0.12,0.1,0.96,0.93]
xb=fltarr(Nx+1,Nz+1)
yb=fltarr(Nx+1,Nz+1)
for ix=0,Nx do begin
  for iz=0,Nz do begin
    xb(ix,iz) = ix+0.5
    yb(ix,iz) = iz+0.5
  endfor
endfor
CONTOUR,yy,/nodata,xrange=[0.001,Nx+1],yrange=[0.001,Nz+1],$
        pos=pos,title=titel+" on numerical grid"
for ix=0,Nx-1 do begin
  for iz=0,Nz-1 do begin
    x=[xb(ix,iz),xb(ix+1,iz)+0.04,xb(ix+1,iz+1)+0.04,xb(ix,iz+1)]
    y=[yb(ix,iz),yb(ix+1,iz),yb(ix+1,iz+1)+0.04,yb(ix,iz+1)+0.04]
    col=2+253*(yy(ix,iz)-dmin)/(dmax-dmin)
    col=max([col,2])
    col=min([col,253])
    polyfill,x,y,color=col,noclip=0
    if (col GT 70) then begin
      col=black
    endif else begin
      col=white
    endelse
    csize = 0.4*80.0/Nx 
    xyouts,ix-0.22,iz+0.68,/data,solved(ix,iz),ALIGNMENT=0.5,$
           CHARSIZE=csize,color=col
  endfor
endfor
CONTOUR,/overplot,AV,levels=[10,50],c_colors=white,$
        pos=pos,c_annotation=['AV=10','AV=50']

isp=SPindex(Nsp,SPname,"CO")
yy = ALOG10(nmol(*,*,isp)/nHtot(*,*))
titel = "log(CO/n<H>)"      
dmax=max(yy)+0.1
dmin=min(yy)-0.1
dmin=max([dmin,dmax-15])
pos=[0.12,0.1,0.96,0.93]
xb=fltarr(Nx+1,Nz+1)
yb=fltarr(Nx+1,Nz+1)
for ix=0,Nx do begin
  for iz=0,Nz do begin
    xb(ix,iz) = ix+0.5
    yb(ix,iz) = iz+0.5
  endfor
endfor
CONTOUR,yy,/nodata,xrange=[0.001,Nx+1],yrange=[0.001,Nz+1],$
        pos=pos,title=titel+" on numerical grid"
for ix=0,Nx-1 do begin
  for iz=0,Nz-1 do begin
    x=[xb(ix,iz),xb(ix+1,iz)+0.04,xb(ix+1,iz+1)+0.04,xb(ix,iz+1)]
    y=[yb(ix,iz),yb(ix+1,iz),yb(ix+1,iz+1)+0.04,yb(ix,iz+1)+0.04]
    col=2+253*(yy(ix,iz)-dmin)/(dmax-dmin)
    col=max([col,2])
    col=min([col,253])
    polyfill,x,y,color=col,noclip=0
    if (col GT 70) then begin
      col=black
    endif else begin
      col=white
    endelse
    csize = 0.4*80.0/Nx 
    xyouts,ix-0.22,iz+0.68,/data,solved(ix,iz),ALIGNMENT=0.5,$
           CHARSIZE=csize,color=col
  endfor
endfor
CONTOUR,/overplot,AV,levels=[10,50],c_colors=white,$
        pos=pos,c_annotation=['AV=10','AV=50']

;-------------------------
; ***  SED and images  ***
;-------------------------
openr, 1,folder+"/dust_opac.out",ERROR = err
close,1
if (err EQ 0) then begin
  PLOT_OPACITY,folder,MCFOSTpath,MCMAXpath,Rin,Rout
endif
openr, 1,folder+"/SED.out",ERROR = err
close,1
if (err EQ 0) then begin
  PLOT_SED,folder,NLAM,lam,Rstar,dist,red,FluxJy,$
           MCFOSTpath,MCMAXpath,ebv=ebv,r_v=r_v
  PLOT_SED_ANALYSIS,folder,Nx,Nz,xx,zz,nHtot,AV,NH_ver(*,0)
  PLOT_VISIB_MIDI,MCMAXpath
  PLOT_SED_LINES,folder,NLAM,lam,Rstar,dist,NX
endif

;----------------------------------
; ***  Analyses of line origin  ***
;----------------------------------
COMMON global, lineinit,LineFileVersion,Nline,linetxt,datatxt,HITRANversion
lineinit = 1
isp=SPindex(Nsp,SPname,"O")
nOI = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"H")
nHI = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"C+")
nCII= nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"C")
nCI= nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"N+")
nNII= nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"N++")
nNIII= nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"CO")
nCO = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"H2O")
nH2O = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"H2")
nH2 = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"H")
nH = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"OH")
nOH = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"Si")
nSi = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"Si+")
nSip = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"nel")
nel = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"CH+")
nCHp = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"HS+")
nHSp = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"Ne+")
nNeII = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"Ne++")
nNeIII = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"Ar+")
nArII = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"Ar++")
nArIII = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"O++")
nOIII = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"O+")
nOII = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"S++")
nSIII = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"S+")
nSII = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"Fe+")
nFeII = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"HCO+")
nHCOp = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"HN2+")
nN2Hp = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"HCN")
nHCN = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"CN")
nCN = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"CS")
nCS = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"C2H")
nC2H = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"NH3")
nNH3 = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"H2CO")
nH2CO = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"CO2")
nCO2 = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"e-")
nelec = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"HD")
nHD = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"O2")
nO2 = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"SO")
nSO = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"SO2")
nSO2=nmol(*,*,isp)
isp=SPindex(Nsp,Spname,"H2S")
nH2S=nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"NO")
nNO=nmol(*,*,isp)
isp=SPindex(Nsp,Spname,"SiO")
nSiO=nmol(*,*,isp)
isp=SPindex(Nsp,Spname,"C2H")
nC2H=nmol(*,*,isp)
isp=SPindex(Nsp,Spname,"C3H2")
nC3H2=nmol(*,*,isp)
isp=SPindex(Nsp,Spname,"C2H2")
nC2H2=nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"HDO")   ; 112.1019998, 99.42283839, 82.34168346, 80.80508625, 72.24261041, 67.74494254
; 63.54531779, 83.58457932
nHDO = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"DCO+")   
nDCOp = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"N2D+")
nN2Dp = nmol(*,*,isp)
isp=SPindex(Nsp,SPname,"DCN")
nDCN = nmol(*,*,isp)
logr = 1

;goto,end_SLOW
;openw,99,'Fluxes.out'
  ;LINE_ANALYSIS,logr,'CO','CO',  2600.75,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,0,'CO','CO',   1300.40,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline
  LINE_ANALYSIS,0,'13CO','CO', 1360.22,NX,NZ,xx,zz,0.014*nCO,Tgas,Tdust,nHtot,dist,/Tline
  LINE_ANALYSIS,0,'C18O','CO', 1365.42,NX,NZ,xx,zz,nCO/498.7,Tgas,Tdust,nHtot,dist,/Tline
  LINE_ANALYSIS,0,'CO','CO',    866.96,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline
  LINE_ANALYSIS,0,'13CO','CO',  906.84,NX,NZ,xx,zz,0.014*nCO,Tgas,Tdust,nHtot,dist,/Tline
  LINE_ANALYSIS,0,'C18O','CO',  910.3087,NX,NZ,xx,zz,nCO/498.7,Tgas,Tdust,nHtot,dist,/Tline
  ;LINE_ANALYSIS,logr,'CO','CO',   650.25,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   520.23,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   433.56,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   371.65,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   325.23,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   289.12,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   260.24,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline
  ;LINE_ANALYSIS,logr,'CO','CO',   236.61,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   216.93,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   200.27,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',  1.859993E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',  1.736314E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',  1.628116E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',  1.532667E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'CO','CO',   144.78,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline,/plotTg
  ;LINE_ANALYSIS,logr,'CO','CO',   1.371963E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   1.303689E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   1.241934E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   1.185807E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   1.134576E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   1.087628E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   1.044450E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   1.004605E+02,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   9.677251E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   9.334912E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   9.016300E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline
  ;LINE_ANALYSIS,logr,'CO','CO',   8.719042E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   8.441072E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   8.180581E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   7.935981E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline
  ;LINE_ANALYSIS,logr,'CO','CO',   7.705870E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   7.489006E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'CO','CO',   72.84285,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline
  ;LINE_ANALYSIS,logr,'CO','CO',   7.090724E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   6.907441E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   6.733645E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CO','CO',   6.568626E+01,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'CO','CO',  4.6999496,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline,/plotTg  ; v=1-0 P(4)
  LINE_ANALYSIS,logr,'CO','CO',  5.040484 ,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline,/plotTg  ; v=1-0 P(36)
  LINE_ANALYSIS,logr,'CO','CO',  4.758863 ,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline,/plotTg  ; v=2-1 P(4)
  ;LINE_ANALYSIS,logr,'CO','CO',  5.0532393,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline,/plotTg
  ;LINE_ANALYSIS,logr,'CO','CO',  4.7931241,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline,/plotTg
  ;LINE_ANALYSIS,logr,'CO','CO',   4.920405,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline,/plotTg ; P(26)
  ;LINE_ANALYSIS,logr,'CO','CO',   4.633276,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist,/Tline,/plotTg ; R(3)
  ;PARTNER_ANALYSIS,logr,'CO','CO',4.625414,NX,NZ,xx,zz,nH,nH2,nelec,$
  ;               'H','H!I2!N','elec',Tgas,dist,/plotTg,zmin=-3.0,zmax=12.0
  ;LINE_ANALYSIS,logr,'CO','CO',   2.337413,NX,NZ,xx,zz,nCO,Tgas,Tdust,nHtot,dist                ; v=2->0 R(4)
  LINE_ANALYSIS,logr,'[OI]','O',    63.18,NX,NZ,xx,zz,nOI,Tgas,Tdust,nHtot,dist,/Tline,/plotTg
  LINE_ANALYSIS,logr,'[OI]','O',   145.53,NX,NZ,xx,zz,nOI,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'[OI]','OH',6.300304E-01,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'[CII]','C+', 157.74,NX,NZ,xx,zz,nCII,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,0,'[CI]','C', 609.14,NX,NZ,xx,zz,nCI,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,0,'[CI]','C', 370.42,NX,NZ,xx,zz,nCI,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[NII]','N+', 205.24,NX,NZ,xx,zz,nNII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[NIII]','N++', 57.29978173,NX,NZ,xx,zz,nNIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[NeII]','Ne+', 0.046,NX,NZ,xx,zz,nNeII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[NeII]','Ne+', 12.815,NX,NZ,xx,zz,nNeII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[NeIII]','Ne++',0.1813303,NX,NZ,xx,zz,nNeIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[NeIII]','Ne++',0.3867184,NX,NZ,xx,zz,nNeIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[NeIII]','Ne++',0.3965848,NX,NZ,xx,zz,nNeIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[NeIII]','Ne++',0.4010037,NX,NZ,xx,zz,nNeIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[NeIII]','Ne++',10.855555,NX,NZ,xx,zz,nNeIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[NeIII]','Ne++',15.555,NX,NZ,xx,zz,nNeIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[NeIII]','Ne++',35.988540,NX,NZ,xx,zz,nNeIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[OIII]','O++',88.2952,NX,NZ,xx,zz,nOIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[OIII]','O++',51.7787,NX,NZ,xx,zz,nOIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[OIII]','O++',32.6126,NX,NZ,xx,zz,nOIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[OIII]','O++',0.50047748,NX,NZ,xx,zz,nOIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[OIII]','O++',0.49568633,NX,NZ,xx,zz,nOIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[OIII]','O++',0.4361,NX,NZ,xx,zz,nOIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[OII]','O+',0.37272946,NX,NZ,xx,zz,nOII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[OII]','O+',0.37245135,NX,NZ,xx,zz,nOII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[OII]','O+',499.15494172,NX,NZ,xx,zz,nOII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[SII]','el',0.673081,NX,NZ,xx,zz,nel,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[SII]','S+',0.671644,NX,NZ,xx,zz,nSII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[SIII]','S++',33.45683830,NX,NZ,xx,zz,nSIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[SIII]','S++',18.71604326,NX,NZ,xx,zz,nSIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[SIII]','S++',11.99529691,NX,NZ,xx,zz,nSIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[ArII]','Ar+',6.98527,NX,NZ,xx,zz,nArII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[ArIII]','Ar++', 21.81609,NX,NZ,xx,zz,nArIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[ArIII]','Ar++', 8.985210,NX,NZ,xx,zz,nArIII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[FeII]','Fe+',35.34905600,NX,NZ,xx,zz,nFeII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[FeII]','Fe+',25.98820200,NX,NZ,xx,zz,nFeII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[FeII]','Fe+', 5.34026300,NX,NZ,xx,zz,nFeII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[FeII]','Fe+', 4.11506200,NX,NZ,xx,zz,nFeII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[FeII]','Fe+', 1.25702400,NX,NZ,xx,zz,nFeII,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'[SiII]','Si+',34.80782500,NX,NZ,xx,zz,nSip,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'OH','OH'    , 71.21543374,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'OH','OH'    , 71.17083134,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'OH','OH'    , 79.12,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'OH','OH'    , 79.18,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'OH','OH'    , 84.42,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'OH','OH'    , 84.59664,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'OH','OH'    ,119.23,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'OH','OH'    ,119.44,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'OH','OH'    ,163.02,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'OH','OH'    ,163.39,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'OH','OH'    ,98.73,NX,NZ,xx,zz,nOH,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'o-H2O','H2O',538.29,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;PARTNER_ANALYSIS,logr,'o-H2O','H2O',538.29,NX,NZ,xx,zz,nH,nH2,nelec,$
  ;              'H','H!I2!N','elec',Tgas,dist,/plotTg,zmin=-3.0,zmax=12.0
  LINE_ANALYSIS,logr,'o-H2O','H2O',179.53,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'o-H2O','H2O',78.741,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'o-H2O','H2O',63.32355,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'p-H2O','H2O',269.27,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;PARTNER_ANALYSIS,logr,'p-H2O','H2O',269.27,NX,NZ,xx,zz,nH,nH2,nelec,$
  ;              'H','H!I2!N','elec',Tgas,dist,/plotTg,zmin=-3.0,zmax=12.0
  ;LINE_ANALYSIS,logr,'p-H2O','H2O',187.110,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'o-H2O','H2O',180.49,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'p-H2O','H2O',158.31,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'p-H2O','H2O',144.52,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'p-H2O','H2O',138.53,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'p-H2O','H2O',89.988,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;PARTNER_ANALYSIS,logr,'p-H2O','H2O',89.988,NX,NZ,xx,zz,nH,nH2,nelec,$
  ;              'H','H!I2!N','elec',Tgas,dist,/plotTg,zmin=-3.0,zmax=12.0
  ;LINE_ANALYSIS,logr,'o-H2O','H2O',71.947,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'o-H2O','H2O',174.63,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'o-H2O','H2O',136,496,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'o-H2O','H2O',113.537,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'o-H2O','H2O',30.52542,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'o-H2O','H2O',23.85980,NX,NZ,xx,zz,nH2O,Tgas,Tdust,nHtot,dist,/Tline
  LINE_ANALYSIS,logr,'o-H2','H2',  2.12173796,NX,NZ,xx,zz,nH2,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'p-H2','H2',  2.22320135,NX,NZ,xx,zz,nH2,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'o-H2','H2',  2.24762211,NX,NZ,xx,zz,nH2,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'o-H2','H2',  4.694499,NX,NZ,xx,zz,nH2,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'o-H2','H2',  5.51122 ,NX,NZ,xx,zz,nH2,Tgas,Tdust,nHtot,dist   ;H2(0-0)S(7)
  LINE_ANALYSIS,logr,'p-H2','H2',  6.10858 ,NX,NZ,xx,zz,nH2,Tgas,Tdust,nHtot,dist   ;H2(0-0)S(6)
  LINE_ANALYSIS,logr,'o-H2','H2',  6.90883 ,NX,NZ,xx,zz,nH2,Tgas,Tdust,nHtot,dist   ;H2(0-0)S(5)
  LINE_ANALYSIS,logr,'p-H2','H2',  8.02546 ,NX,NZ,xx,zz,nH2,Tgas,Tdust,nHtot,dist   ;H2(0-0)S(4)
  LINE_ANALYSIS,logr,'o-H2','H2',  9.66449 ,NX,NZ,xx,zz,nH2,Tgas,Tdust,nHtot,dist   ;H2(0-0)S(3)
  LINE_ANALYSIS,logr,'p-H2','H2',  12.2780 ,NX,NZ,xx,zz,nH2,Tgas,Tdust,nHtot,dist   ;H2(0-0)S(2)
  LINE_ANALYSIS,logr,'o-H2','H2',  17.0339 ,NX,NZ,xx,zz,nH2,Tgas,Tdust,nHtot,dist   ;H2(0-0)S(1)
  LINE_ANALYSIS,logr,'HD','HD',   112.07252904,NX,NZ,xx,zz,nHD,Tgas,Tdust,nHtot,dist,/Tline
  LINE_ANALYSIS,logr,'H','H',      0.6562819,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;Balmer alpha 3-2
  LINE_ANALYSIS,logr,'H','H',       1.875613,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;Paschen alpha 4-3
  LINE_ANALYSIS,logr,'H','H',       4.052262,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;Brakett alpha 4-3
  LINE_ANALYSIS,logr,'H','H',       2.166121,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(7-4)
  ;LINE_ANALYSIS,logr,'H','H',       5.128657,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(10-6)
  ;LINE_ANALYSIS,logr,'H','H',       5.908213,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(9-6)
  ;LINE_ANALYSIS,logr,'H','H',       5.956843,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(14-7)
  ;LINE_ANALYSIS,logr,'H','H',       6.291916,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(13-7)
  ;LINE_ANALYSIS,logr,'H','H',       6.771990,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(12-7)
  ;LINE_ANALYSIS,logr,'H','H',       7.459857,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(6-5)
  ;LINE_ANALYSIS,logr,'H','H',       7.502493,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(11-7)
  ;LINE_ANALYSIS,logr,'H','H',       8.760064,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(10-7)
  ;LINE_ANALYSIS,logr,'H','H',       9.392017,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(13-8)
  ;LINE_ANALYSIS,logr,'H','H',       10.50350,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(12-8)
  ;LINE_ANALYSIS,logr,'H','H',       11.30870,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(9-7)
  ;LINE_ANALYSIS,logr,'H','H',       12.37190,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(7-6)
  ;LINE_ANALYSIS,logr,'H','H',       12.38716,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(11-8)
  ;LINE_ANALYSIS,logr,'H','H',       14.18308,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(13-9)
  ;LINE_ANALYSIS,logr,'H','H',       16.20910,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(10-8)
  ;LINE_ANALYSIS,logr,'H','H',       19.06190,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(8-7)
  ;LINE_ANALYSIS,logr,'H','H',       22.34046,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(11-9)
  ;LINE_ANALYSIS,logr,'H','H',       27.80338,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(9-8)
  LINE_ANALYSIS,logr,'H','H',       29.83950,NX,NZ,xx,zz,nHI,Tgas,Tdust,nHtot,dist  ;HI(12-10)
  ;LINE_ANALYSIS,0,'HCO+','HCO+', 3361.334,NX,NZ,xx,zz,nHCOp,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,0,'HCO+','HCO+',  1120.478,NX,NZ,xx,zz,nHCOp,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,0,'HCO+','HCO+',  840.380,NX,NZ,xx,zz,nHCOp,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,0,'N2H+','N2H+', 3217.5652,NX,NZ,xx,zz,nN2Hp,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,0,'N2H+','N2H+',  1072.558,NX,NZ,xx,zz,nN2Hp,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'N2D+','N2D+',  3887.8926,NX,NZ,xx,zz,nN2Dp,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'N2D+','N2D+',  1295.997,NX,NZ,xx,zz,nN2Dp,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,0,'CN','CN',     2641.461,NX,NZ,xx,zz,nCN,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,0,'CN','CN',      1321.380,NX,NZ,xx,zz,nCN,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,0,'CN','CN',      528.78,NX,NZ,xx,zz,nCN,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,0,'HCN','HCN',    1127.521,NX,NZ,xx,zz,nHCN,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,0,'HCN','HCN',    845.66,NX,NZ,xx,zz,nHCN,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'DCN','DCN', 828.0513,NX,NZ,xx,zz,nDCN,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,0,'C2H','C2H',    1144.228,NX,NZ,xx,zz,nC2H,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CH+','CH+',  179.61,NX,NZ,xx,zz,nCHp,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CH+','CH+',  119.848,NX,NZ,xx,zz,nCHp,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CH+','CH+',  90.01,NX,NZ,xx,zz,nCHp,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'CH+','CH+',  72.14,NX,NZ,xx,zz,nCHp,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'HS+','HS+',  866.62799,NX,NZ,xx,zz,nHSp,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'HS+','HS+',  866.844045,NX,NZ,xx,zz,nHSp,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,0,'p-H2CO','H2CO',1373.795,NX,NZ,xx,zz,nH2CO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,0,'o-H2CO','H2CO',1064.880,NX,NZ,xx,zz,nH2CO,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,0,'CS','CS',      3059.701,NX,NZ,xx,zz,nCS,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,0,'CS','CS',      1020.007,NX,NZ,xx,zz,nCS,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,0,'o-C3H2','C3H2',1191.888,NX,NZ,xx,zz,nC3H2,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'HDO','HDO', 112.101999,NX,NZ,xx,zz,nHDO,Tgas,Tdust,nHtot,dist,/Tline
  ;LINE_ANALYSIS,logr,'o-H2S','H2S',160.69316,NX,NZ,xx,zz,nH2S,Tgas,Tdust,nHtot,dist
  ;LINE_ANALYSIS,logr,'o-NH3','NH3',  523.6567,NX,NZ,xx,zz,nNH3,Tgas,Tdust,nHtot,dist
  LINE_ANALYSIS,logr,'o-H2O','H2O',  12.4448323,NX,NZ,xx,zz,nH2O, Tgas,Tdust,nHtot,dist,/Tline    
  LINE_ANALYSIS,logr,'p-H2O','H2O',  18.7177666,NX,NZ,xx,zz,nH2O, Tgas,Tdust,nHtot,dist,/Tline    
  LINE_ANALYSIS,logr,'OH','OH',    25.035138005,NX,NZ,xx,zz,nOH,  Tgas,Tdust,nHtot,dist,/Tline    
  LINE_ANALYSIS,logr,'OH','OH',    31.484899785,NX,NZ,xx,zz,nOH,  Tgas,Tdust,nHtot,dist,/Tline    
  LINE_ANALYSIS,logr,'CO2_H','CO2',  14.861795019,NX,NZ,xx,zz,nCO2, Tgas,Tdust,nHtot,dist,/Tline 
  LINE_ANALYSIS,logr,'CO2_H','CO2',  15.267275101,NX,NZ,xx,zz,nCO2, Tgas,Tdust,nHtot,dist,/Tline 
  LINE_ANALYSIS,logr,'HCN_H','HCN',  13.539823623,NX,NZ,xx,zz,nHCN, Tgas,Tdust,nHtot,dist,/Tline  
  LINE_ANALYSIS,logr,'HCN_H','HCN',  14.978314008,NX,NZ,xx,zz,nHCN, Tgas,Tdust,nHtot,dist,/Tline  
  LINE_ANALYSIS,logr,'C2H2_H','C2H2',13.706925268,NX,NZ,xx,zz,nC2H2,Tgas,Tdust,nHtot,dist,/Tline
  LINE_ANALYSIS,logr,'C2H2_H','C2H2',14.031646864,NX,NZ,xx,zz,nC2H2,Tgas,Tdust,nHtot,dist,/Tline
  LINE_ANALYSIS,logr,'NH3_H','NH3',  10.732221330,NX,NZ,xx,zz,nNH3, Tgas,Tdust,nHtot,dist,/Tline
  LINE_ANALYSIS,logr,'NH3_H','NH3',  10.380306540,NX,NZ,xx,zz,nNH3, Tgas,Tdust,nHtot,dist,/Tline

  ;---------- O2 lines ----------
  ;isp=SPindex(Nsp,SPname,"O2")
  ;if (1 EQ 0) then begin ;(isp gt 0) then begin
  ;  lamb_O2=[2524.56081,813.55192,387.40908,267.50110,204.38437]
  ;  nlamb_O2=n_elements(lamb_O2)
  ;  for i=0,nlamb_O2-1 do begin
  ;    LINE_ANALYSIS,logr,'O2','O2',lamb_O2(i),NX,NZ,xx,zz,nSO,Tgas,Tdust,nHtot,dist
  ;  endfor
  ;endif   
  ;---------- SO lines ----------
  ;isp=SPindex(Nsp,SPname,"SO")
  ;if (1 EQ 0) then begin ;(isp gt 0) then begin
  ;  lamb_SO=[1678.51841,1454.06085446,1392.95394666,1363.00622213,1144.92895554, $ 
  ;         1190.47569278,1160.83521816,985.90694428,1010.93371539,995.04236710, $ 
  ;         865.13078848,879.89434428,870.70350884,770.43518697,779.63897088, $
  ;         773.99992428,694.27227361,700.26847098,696.64166861,631.72772154, $
  ;         635.77606410,633.35252690,579.47198621,582.28663136]
  ;  nlamb_SO=n_elements(lamb_SO)
  ;  for i=0,nlamb_SO-1 do begin
  ;    LINE_ANALYSIS,logr,'SO','SO',lamb_SO(i),NX,NZ,xx,zz,nSO,Tgas,Tdust,nHtot,dist
  ;  endfor
  ;endif   
  ;---------- SO2 lines ----------
  ;isp=SPindex(Nsp,SPname,"SO2")
  ;if (1 EQ 0) then begin ;(isp gt 0) then begin
  ;  lamb_SO2=[956.94816784,928.07400114,853.48408543,837.66080710,837.37847777 , $
  ;          807.69054588,772.01865689, $
  ;          660.74758221,730.11802207,634.00994561,707.86955959,609.41511962, $
  ;          586.57504380,539.51879728,521.55290986,504.74783745,488.99703155, $
  ;          474.21007124,443.16242781,460.29862075,460.29862075] 
  ;  nlamb_SO2=n_elements(lamb_SO2)
  ;  for i=0,nlamb_SO2-1 do begin
  ;    LINE_ANALYSIS,logr,'SO2','SO2',lamb_SO2(i),NX,NZ,xx,zz,nSO2,Tgas,Tdust,nHtot,dist
  ;  endfor
  ;endif
  ;--------- NO lines ----------
  ;isp=SPindex(Nsp,SPname,"NO")
  ;if (1 EQ 0) then begin ;(isp gt 0) then begin
  ;  lamb_NO = [854.86580901,854.86270830,854.85294317]
  ;  nlamb_NO = n_elements(lamb_NO)
  ;  for i=0,nlamb_NO-1 do begin
  ;    LINE_ANALYSIS,logr,'NO','NO',lamb_NO(i),NX,NZ,xx,zz,nNO,Tgas,Tdust,nHtot,dist
  ;  endfor
  ;endif  
  ;---------- SiO lines ----------
  ;isp=SPindex(Nsp,SPname,"SiO")
  ;if (1 EQ 0) then begin ;(isp gt 0) then begin
  ;  lamb_SiO = [3451.96260180,2301.34072974,1726.03704878,1380.86403177,1150.75516849,986.39688545,863.13292428]
  ;  nlamb_SiO = n_elements(lamb_SiO)
  ;  for i=0,nlamb_SiO-1 do begin
  ;    LINE_ANALYSIS,logr,'SiO','SiO',lamb_SiO(i),NX,NZ,xx,zz,nSiO,Tgas,Tdust,nHtot,dist
  ;  endfor   
  ;endif  
close, 99

;---------------------------
; ***  continuum images  ***
;---------------------------
zmax=zrelevant
openr, 1,folder+"/image.out",ERROR = err
close,1
if (err EQ 0) then begin
  ;PLOT_IMAGE,folder,[870.1],Rstar,Rin,Rout,zmax,dist,FluxJy
  PLOT_IMAGE,folder,[1.12,1.65,870.0],Rstar,Rin,Rout,zmax,dist,FluxJy
endif
end_SLOW:

;---------------------------------
; ***  line fluxes and images  ***
;---------------------------------
openr, 1,folder+"/line_flux.out",ERROR = err
close,1
if (err EQ 0) then begin
  logI = 0
  PLOT_LINES,folder,Rstar,Rin,Rout,dist,zmax,xx,zz,logI,AV_ver,AV_rad,Nx,Nz
endif

;------------------------
; *** alpha viscosity ***
;------------------------
openr, 1,folder+"/alpha_viscosity.out",ERROR = err
close,1
if (err EQ 0) then begin
   plot_alpha,folder,xx,zz,nx,nz,rho,press,Tgas,cT,mstar,NH_ver,nsp,SPname,nmol,nHtot,AV_rad,AV_ver,chiRT
endif

;plot_heating_cooling,xx,zz,nHtot,nheat,heat,heatname,ncool,cool,coolname

device,/close
set_plot,'x'
print,"... output written to out.ps"
stop

END
