      subroutine ToLeafGasOptimization(ic3c4cam,ntotfiles,ACidata,
     &dataunit,spareunit,datapath,indexunit,ierr)
      implicit none
!--------------All inputs except for ierr. Outputs are written to files----------------
      integer ic3c4cam,ntotfiles,dataunit,spareunit,ierr(2),
     &indexunit(20)
!ierr(1)=0, ok, >=1 input data out of range
!ierr(2) specifies in which input file, the data is out of range
      character*100 datapath,ACidata(ntotfiles)
!-------------------------------------------------------------------------------
      integer ntotpoints,npoints(ntotfiles),i,j,k,n,curveno(ntotfiles),
     &iobs,maxobs,nmax,iwarning,warningunit,isitmassbased(ntotfiles),
     &iprintheader(ntotfiles),ivector(1000),startline,errorunit
      parameter(maxobs=2000,nmax=100)
      character*100 sample(ntotfiles)
      character*50 chartime,siteID(ntotfiles),species(ntotfiles),ftime,
     &longchar1*50000,longchar*5000,charvars(500),
     &woodporosity(ntotfiles)
      double precision esat,Latitude(ntotfiles),Longitude(ntotfiles),
     &Elevation(ntotfiles),yearsampled(ntotfiles),sampledoy(ntotfiles),
     &GrowingSeasonStart(ntotfiles),GrowingSeasonEnd(ntotfiles),
     &standage(ntotfiles),CanopyHeight(ntotfiles),
     &LeafAreaIndex(ntotfiles),MeanTimeBtwnSteadyReadings(ntotfiles),
     &SampleHeight(ntotfiles),Needleage(ntotfiles),
     &specificLAI(ntotfiles),nitrogencontent(ntotfiles),
     &carboncontent(ntotfiles),avetimeresolution(ntotfiles),
     &avetimesampled(ntotfiles),phoscontent(ntotfiles),
     &sapwooddensity(ntotfiles),leafratio(ntotfiles),
     &stom_COND_mol,CO2i_ppm,transp_mmol,vpdl_KPa,BLCond,Tair_oC,
     &Tleaf_oC,CO2chamber_ppm,H2OS_mmol,RH_S100,PARi_umol,Press_KPa,
     &oxygeni_KPa,PNcor_umol,uncorphoto,chamberarea,stmrad,tblk,co2r,
     &h2or,rh_r,flow,paro,csmch,hsmch,stablef,listatus,phips2,
     &ambientvaporpres,pari(ntotfiles,maxobs),
     &templeaf(ntotfiles,maxobs),pres_air(ntotfiles,maxobs),
     &yAnet(ntotfiles,maxobs),po2i(ntotfiles,maxobs),
     &trmmol(ntotfiles,maxobs),gswmeas(ntotfiles,maxobs),
     &vpdl(ntotfiles,maxobs),tempair(ntotfiles,maxobs),
     &eambient(ntotfiles,maxobs),xpco2i_ppm(ntotfiles,maxobs),
     &xpco2i(ntotfiles,maxobs),co2a_ppm(ntotfiles,maxobs),
     &pco2ambient(ntotfiles,maxobs),sampletime(ntotfiles,maxobs),
     &chlflphips2(ntotfiles,maxobs),CurveTypeID(ntotfiles,maxobs),
     &fo_pam(ntotfiles,maxobs),fm_pam(ntotfiles,maxobs),
     &fs_pam(ntotfiles,maxobs),pam_measlight(ntotfiles,maxobs),
     &vectorhorse(maxobs),stargamma25_usr(ntotfiles),
     &fkc25_usr(ntotfiles),fko25_usr(ntotfiles),tissuearea,tissuemass,
     &rdlight25_usr(ntotfiles),alpha25_usr(ntotfiles),datumlimit,
     &resistwp25_usr(ntotfiles),resistch25_usr(ntotfiles),gtc,gtw,
     &term,term1,H2OLeaf_mmol,fo_fluoresce,fm_fluoresce,fs_fluoresce,
     &f_measlight,stdpar,fmeanpar,xminpar,xmaxpar,
     &stdco2,fmeanco2,xminco2,xmaxco2
!
      warningunit=indexunit(10)
      errorunit=indexunit(11)
      ierr(1)=0
      if(ic3c4cam.ne.1.and.ic3c4cam.ne.2)then
        write(errorunit,*)'The analysis for CAM photosyntehsis is still
     &under development. Check out LeafWeb for this function later.'
        ierr(1)=1
        return
      endif
!      open(unit=121,file='sphagnumdata.csv')
!      write(121,'(200A)')'name,','hhmmss,','no,','time,','datumlimit,',
!     &'stom_COND_mol,','CO2chamber_ppm,','CO2i_ppm,','PARi_umol,',
!     &'Tleaf_oC,','Tair_oC,','transp_mmol,','PNcor_umol,','H2OS_mmol,',
!     &'RH_S100'

!We read all files at once
      do 10 i=1,ntotfiles
        isitmassbased(i)=0
        iwarning=0
        ierr(2)=i
        npoints(i)=0
        sample(i)=trim(ACidata(i))
!fill any blank spaces in sample(i) with '_'
1       j=index(trim(sample(i)),' ')
        if(j.gt.0)then
          sample(i)(j:j)='_'
          goto 1
        endif
        curveno(i)=i
!
!========================================================================================================================
!In early 2015, the following section of code is added to allow flexibity for the starting rows to be used for metadata.
!There is no need for a strict number of rows for metadata because the main data section is now determined automatically.
!Locate the rows for the actual data
        open(unit=spareunit,file=trim(datapath)//trim(ACidata(i)))
        read(spareunit,fmt=300,err=35,end=35)longchar1
        rewind(spareunit)
        open(unit=dataunit,file=
     &trim(datapath)//trim(ACidata(i))//'middle')
2       read(spareunit,fmt=300,err=35,end=5)longchar1
3       k=index(longchar1,char(13))
        if(k.gt.0)then
!DOS text format, convert it to unix format
          longchar1(k:k+len(char(10))-1)=char(10)
          goto 3
        endif
        write(dataunit,340)trim(longchar1)
        goto 2
5       close(spareunit)
        rewind(dataunit)

        open(unit=spareunit,file=
     &trim(datapath)//'clean'//trim(ACidata(i)))
7       read(dataunit,fmt=310,err=36,end=9)longchar
        if(longchar.eq.''.or.longchar.eq.' ')goto 7
        call charlineparser(longchar,nmax,charvars,n)
        if(n.eq.0)goto 7
        write(spareunit,340)trim(longchar)
        goto 7
9       rewind(spareunit)
        close(dataunit,status='delete')

        j=0
500     read(spareunit,fmt=310,err=40,end=600)longchar
        call charlineparser(longchar,nmax,charvars,n)
        j=j+1
        ivector(j)=n
        goto 500
600     rewind(spareunit)
        startline=0
610     startline=startline+1
        if(j.lt.12.or.startline.gt.j-11)then
          if(ierr(2).gt.0)then
            write(errorunit,*)'Input data error in ',trim(ACidata(i))
            write(errorunit,*)
     &'Please resubmit the data after correcting the following error:'
            ierr(2)=-ierr(2)
          endif
          write(errorunit,*)'This file has incorrect data format or does
     &not contain data'
          ierr(1)=1
          goto 630
        endif
        n=0
        if(ivector(startline).ne.ivector(startline+1))n=1
        if(ivector(startline).ne.ivector(startline+2))n=1
        if(ivector(startline+2).lt.15.or.ivector(startline+2).gt.25)n=1

        if(ivector(startline+3).ne.ivector(startline+4))n=1
        if(ivector(startline+3).ne.ivector(startline+5))n=1
        if(ivector(startline+5).lt.5.or.ivector(startline+5).gt.10)n=1

        if(ivector(startline+6).ne.ivector(startline+7))n=1
        if(ivector(startline+6).ne.ivector(startline+8))n=1
        if(ivector(startline+8).ne.ivector(startline+9))n=1
        if(ivector(startline+8).ne.ivector(startline+10))n=1
        if(ivector(startline+8).ne.ivector(startline+11))n=1
        if(ivector(startline+8).lt.25)n=1
        if(n.eq.1)goto 610

!startline is the line 'Elevation,SampleYear,SampleDayOfYear.....'
!In general
!Line 1-10 describe the general information about the data
!Line 11-12 are the header lines for line 13
!Line 13 gives the site information and the data about the leaf sampled
!Line 14-15 are the header lines for lines 16
!Line 16 user-supplied parameter values
!Line 17-18 are the header lines for lines 19 and higer
!Line 19 and higher: actual gas exchange data
        do j=1,startline+1
          read(spareunit,*)
        enddo
!=========================================================================================================================
        read(spareunit,fmt=310,err=40)longchar
        call charlineparser(longchar,nmax,charvars,n)
        do j=n+1,nmax
          charvars(j)='-9999'
        enddo
        siteID(i)=trim(charvars(1))
        species(i)=trim(charvars(12))
        woodporosity(i)=trim(charvars(20))
        n=len(trim(charvars(2)))
        call extCharToFloatNum(n,charvars(2),Latitude(i),j)
        n=len(trim(charvars(3)))
        call extCharToFloatNum(n,charvars(3),Longitude(i),j)
        n=len(trim(charvars(4)))
        call extCharToFloatNum(n,charvars(4),Elevation(i),j)
        n=len(trim(charvars(5)))
        call extCharToFloatNum(n,charvars(5),yearsampled(i),j)
        n=len(trim(charvars(6)))
        call extCharToFloatNum(n,charvars(6),sampledoy(i),j)
        n=len(trim(charvars(7)))
        call extCharToFloatNum(n,charvars(7),GrowingSeasonStart(i),j)
        n=len(trim(charvars(8)))
        call extCharToFloatNum(n,charvars(8),GrowingSeasonEnd(i),j)
        n=len(trim(charvars(9)))
        call extCharToFloatNum(n,charvars(9),standage(i),j)
        n=len(trim(charvars(10)))
        call extCharToFloatNum(n,charvars(10),CanopyHeight(i),j)
        n=len(trim(charvars(11)))
        call extCharToFloatNum(n,charvars(11),LeafAreaIndex(i),j)
        n=len(trim(charvars(13)))
        call extCharToFloatNum(n,charvars(13),
     &MeanTimeBtwnSteadyReadings(i),j)
        n=len(trim(charvars(14)))
        call extCharToFloatNum(n,charvars(14),SampleHeight(i),j)
        n=len(trim(charvars(15)))
        call extCharToFloatNum(n,charvars(15),Needleage(i),j)
        n=len(trim(charvars(16)))
        call extCharToFloatNum(n,charvars(16),specificLAI(i),j)
        n=len(trim(charvars(17)))
        call extCharToFloatNum(n,charvars(17),nitrogencontent(i),j)
        n=len(trim(charvars(18)))
        call extCharToFloatNum(n,charvars(18),carboncontent(i),j)
        n=len(trim(charvars(19)))
        call extCharToFloatNum(n,charvars(19),phoscontent(i),j)
        n=len(trim(charvars(21)))
        call extCharToFloatNum(n,charvars(21),sapwooddensity(i),j)
        n=len(trim(charvars(22)))
        call extCharToFloatNum(n,charvars(22),leafratio(i),j)
        do j=1,2
          read(spareunit,*)
        enddo
        read(spareunit,fmt=310,err=40)longchar
        call charlineparser(longchar,nmax,charvars,n)
        do j=n+1,nmax
          charvars(j)='-9999'
        enddo
        n=len(trim(charvars(1)))
        call extCharToFloatNum(n,charvars(1),stargamma25_usr(i),j)
        n=len(trim(charvars(2)))
        call extCharToFloatNum(n,charvars(2),fkc25_usr(i),j)
        n=len(trim(charvars(3)))
        call extCharToFloatNum(n,charvars(3),fko25_usr(i),j)
        n=len(trim(charvars(4)))
        call extCharToFloatNum(n,charvars(4),alpha25_usr(i),j)
        n=len(trim(charvars(5)))
        call extCharToFloatNum(n,charvars(5),rdlight25_usr(i),j)
        n=len(trim(charvars(6)))
        call extCharToFloatNum(n,charvars(6),resistwp25_usr(i),j)
        n=len(trim(charvars(7)))
        call extCharToFloatNum(n,charvars(7),resistch25_usr(i),j)
        if(stargamma25_usr(i).lt.0.0d0.or.
     &stargamma25_usr(i).gt.500.0d0)stargamma25_usr(i)=-9999.0d0
        if(fkc25_usr(i).lt.0.0d0.or.fkc25_usr(i).gt.5000.0d0)
     &fkc25_usr(i)=-9999.0d0
        if(fko25_usr(i).lt.0.0d0.or.fko25_usr(i).gt.90000.0d0)
     &fko25_usr(i)=-9999.0d0
        if(alpha25_usr(i).lt.0.0d0.or.alpha25_usr(i).gt.1.0d0)
     &alpha25_usr(i)=-9999.0d0
        if(rdlight25_usr(i).lt.0.0d0.or.rdlight25_usr(i).gt.100.0d0)
     &rdlight25_usr(i)=-9999.0d0
        if(resistwp25_usr(i).lt.0.0d0.or.resistwp25_usr(i).gt.10000.0d0)
     &resistwp25_usr(i)=-9999.0d0
        if(resistwp25_usr(i).lt.0.0d0.or.resistwp25_usr(i).gt.10000.0d0)
     &resistch25_usr(i)=-9999.0d0
        do j=1,2
          read(spareunit,*)
        enddo
20      read(spareunit,fmt=310,err=40,end=100)longchar
        call charlineparser(longchar,nmax,charvars,n)
        if(n.le.25)goto 20
        do j=n+1,nmax
          charvars(j)='-9999'
        enddo
        chartime=trim(charvars(2))
        ftime=trim(charvars(3))
        n=len(trim(charvars(1)))
        call extCharToFloatNum(n,charvars(1),term,j)
        iObs=idnint(term)
        n=len(trim(charvars(4)))
        call extCharToFloatNum(n,charvars(4),uncorphoto,j)
        n=len(trim(charvars(5)))
        call extCharToFloatNum(n,charvars(5),PNcor_umol,j)
        if(dabs(PNcor_umol+9999.0d0).lt.1.0d-4)PNcor_umol=uncorphoto
        n=len(trim(charvars(6)))
        call extCharToFloatNum(n,charvars(6),stom_COND_mol,j)
        n=len(trim(charvars(7)))
        call extCharToFloatNum(n,charvars(7),CO2i_ppm,j)
        n=len(trim(charvars(8)))
        call extCharToFloatNum(n,charvars(8),transp_mmol,j)
        n=len(trim(charvars(9)))
        call extCharToFloatNum(n,charvars(9),vpdl_KPa,j)
        n=len(trim(charvars(10)))
        call extCharToFloatNum(n,charvars(10),chamberarea,j)
        n=len(trim(charvars(11)))
        call extCharToFloatNum(n,charvars(11),stmrad,j)
        n=len(trim(charvars(12)))
        call extCharToFloatNum(n,charvars(12),BLCond,j)
        n=len(trim(charvars(13)))
        call extCharToFloatNum(n,charvars(13),Tair_oC,j)
        n=len(trim(charvars(14)))
        call extCharToFloatNum(n,charvars(14),Tleaf_oC,j)
        n=len(trim(charvars(15)))
        call extCharToFloatNum(n,charvars(15),tblk,j)
        n=len(trim(charvars(16)))
        call extCharToFloatNum(n,charvars(16),co2r,j)
        n=len(trim(charvars(17)))
        call extCharToFloatNum(n,charvars(17),CO2chamber_ppm,j)
        n=len(trim(charvars(18)))
        call extCharToFloatNum(n,charvars(18),h2or,j)
        n=len(trim(charvars(19)))
        call extCharToFloatNum(n,charvars(19),H2OS_mmol,j)
        n=len(trim(charvars(20)))
        call extCharToFloatNum(n,charvars(20),rh_r,j)
        n=len(trim(charvars(21)))
        call extCharToFloatNum(n,charvars(21),RH_S100,j)
        n=len(trim(charvars(22)))
        call extCharToFloatNum(n,charvars(22),flow,j)
        n=len(trim(charvars(23)))
        call extCharToFloatNum(n,charvars(23),PARi_umol,j)
        n=len(trim(charvars(24)))
        call extCharToFloatNum(n,charvars(24),paro,j)
        n=len(trim(charvars(25)))
        call extCharToFloatNum(n,charvars(25),Press_KPa,j)
        n=len(trim(charvars(26)))
        call extCharToFloatNum(n,charvars(26),csmch,j)
        n=len(trim(charvars(27)))
        call extCharToFloatNum(n,charvars(27),hsmch,j)
        n=len(trim(charvars(28)))
        call extCharToFloatNum(n,charvars(28),stablef,j)
        n=len(trim(charvars(29)))
        call extCharToFloatNum(n,charvars(29),listatus,j)
        n=len(trim(charvars(30)))
        call extCharToFloatNum(n,charvars(30),phips2,j)
        n=len(trim(charvars(31)))
        call extCharToFloatNum(n,charvars(31),oxygeni_KPa,j)
        n=len(trim(charvars(32)))
        call extCharToFloatNum(n,charvars(32),datumlimit,j)
        n=len(trim(charvars(33)))
        call extCharToFloatNum(n,charvars(33),tissuearea,j)
        n=len(trim(charvars(34)))
        call extCharToFloatNum(n,charvars(34),tissuemass,j)
!
        n=len(trim(charvars(35)))
        call extCharToFloatNum(n,charvars(35),fo_fluoresce,j)
        n=len(trim(charvars(36)))
        call extCharToFloatNum(n,charvars(36),fm_fluoresce,j)
        n=len(trim(charvars(37)))
        call extCharToFloatNum(n,charvars(37),fs_fluoresce,j)
        n=len(trim(charvars(38)))
        call extCharToFloatNum(n,charvars(38),f_measlight,j)

        if(tissuearea.gt.0.0d0.and.tissuemass.gt.0.0d0)then
!We assume the user requires mass-based calculations. We convert net photosynthesis,
!transpiration, conductance and PAR from area basis to mass basis. All fitted parameters
!are mass-based. However, mixing area- and mass- based calculations is not allowed.
          if(npoints(i).gt.0.and.isitmassbased(i).eq.0)then
            if(ierr(2).gt.0)then
              write(errorunit,*)'Input data error in ',trim(ACidata(i))
              write(errorunit,*)
     &'Please resubmit the data after correcting the following error:'
              ierr(2)=-ierr(2)
            endif
            write(errorunit,*)'Line starting with ',longchar(1:50)
            write(errorunit,*)'Check Column 33 or 34. Mixing area- and
     &mass-based measurements is not allowed'
            ierr(1)=1
          endif
          isitmassbased(i)=1
!Convert PAR from umol/m2/s to umol/kg/s. tissuearea is in cm2 and tissuemass in in g
          PARi_umol=PARi_umol*tissuearea/(tissuemass*10.0d0)
          term=(H2OS_mmol-h2or)/(1000.0d0-H2OS_mmol)
          transp_mmol=(flow/tissuemass)*term
          term=co2r-CO2chamber_ppm*(1000.0d0-h2or)/(1000.0d0-H2OS_mmol)
          PNcor_umol=(1.0d-3*flow/tissuemass)*term
          H2OLeaf_mmol=esat(Tleaf_oC+273.15d0,Press_KPa*1000.0d0)/
     &Press_KPa
!gtw is the conductance for water vapor between the water film and free air
          gtw=transp_mmol*1.0d-3*(1.0d+3-(H2OLeaf_mmol+H2OS_mmol)/2.0d0)
     &/(H2OLeaf_mmol-H2OS_mmol)
!we assume no stomatal conductance. We use the ratio of diffusivities of CO2 and water vapor in air (1.6),
!rather than the ratio of diffusivities of CO2 and water vapor in the boundary layer (1.37) as the latter applies
!to Pohlhausen analysis of mass transfer from a plate in laminar parallel flows which is probably not true
!for Sphagnum tissues.
          gtc=gtw/1.6d0
!we set treat gtw as if it is stomatal conductance.
          stom_COND_mol=gtw
          CO2i_ppm=((gtc-1.0d-3*transp_mmol/2.0d0)*CO2chamber_ppm-
     &PNcor_umol)/(gtc-1.0d-3*transp_mmol/2.0d0)
        else
          if(isitmassbased(i).ne.0)then
            if(ierr(2).gt.0)then
              write(errorunit,*)'Input data error in ',trim(ACidata(i))
              write(errorunit,*)
     &'Please resubmit the data after correcting the following error:'
              ierr(2)=-ierr(2)
            endif
            write(errorunit,*)'Line starting with ',longchar(1:50)
            write(errorunit,*)'Check Column 33 or 34. Mixing area- and
     &mass-based measurements is not allowed'
            ierr(1)=1
          endif
        endif
        if(isitmassbased(i).eq.0)then
          term=-100.0d0
          term1=200.0d0
        else
          term=-9998.0d0
          term1=1.0d+10
        endif
        if(PNcor_umol.lt.term.or.PNcor_umol.gt.term1)then
          if(fm_fluoresce.le.0.0d0)then
            if(ierr(2).gt.0)then
              write(errorunit,*)'Input data error in ',trim(ACidata(i))
              write(errorunit,*)
     &'Please resubmit the data after correcting the following error:'
              ierr(2)=-ierr(2)
            endif
            write(errorunit,*)'Line starting with ',longchar(1:50), '...
     &is within the main data body but has no valid photosynthesis data'
            if(dabs(PNcor_umol+9999.0d0).gt.1.d-6)then
              write(errorunit,*)'Photosynthesis out of range:'
              write(errorunit,*)PNcor_umol
            endif
            ierr(1)=1
          endif
        else
          if(transp_mmol.gt.0.0d0.and.stom_COND_mol.gt.0.0d0
     &.and.BLCond.gt.0.0d0)then
!use the corrected PN to calculate the Ci
!we assume BLCond already takes into account the stomatal ratio.
!for Missouri MOFLUX data, only 2004-2008 data need this correction
            gtc=1.0d0/(1.6d0/stom_COND_mol+1.37d0/BLCond)
            term=((gtc-transp_mmol*0.001d0/2.0d0)*CO2chamber_ppm
     &-PNcor_umol)/(gtc+transp_mmol*0.001d0/2.0d0)
            if(dabs(term-CO2i_ppm).gt.5.0d0)then
              if(iwarning.eq.0)then
      write(warningunit,*)'In file ',trim(sample(i))
      write(warningunit,*)'Provided CO2i values do not agree with other
     &input variables. Make sure input data are ok'
      write(warningunit,*)'Original CO2i',',','Calculated CO2i'
                iwarning=1
              endif
              write(warningunit,*)CO2i_ppm,',',term
            endif
!            CO2i_ppm=term
          endif
        endif
        if(CO2i_ppm.le.0.0d0.or.CO2i_ppm.gt.10000.0d0)then
!          if(ierr(2).gt.0)then
!            write(errorunit,*)'Input data error in ',trim(ACidata(i))
!            write(errorunit,*)
!     &'Please resubmit the data after correcting the following error:'
!            ierr(2)=-ierr(2)
!          endif
!          write(errorunit,*)'Intercellular CO2 (ppm) out of range'
!          ierr(1)=1
          if(fm_fluoresce.le.0.0d0)goto 20
        endif
        if(Tleaf_oC.lt.-50.0d0.or.Tleaf_oC.gt.100.0d0)then
          if(fm_fluoresce.le.0.0d0)then
            if(ierr(2).gt.0)then
              write(errorunit,*)'Input data error in ',trim(ACidata(i))
              write(errorunit,*)
     &'Please resubmit the data after correcting the following error:'
              ierr(2)=-ierr(2)
            endif
            write(errorunit,*)'Line starting with ',longchar(1:50), '...
     &is within the main data body but has no valid leaf temperature'
            write(errorunit,*)'Leaf temperature (oC) out of range'
            ierr(1)=1
          endif
        endif
        if(isitmassbased(i).eq.0)then
          term1=1.0d+5
        else
          term1=1.0d+10
        endif
        if(PARi_umol.lt.-10.01d0.or.PARi_umol.gt.term1)then
          if(ierr(2).gt.0)then
            write(errorunit,*)'Input data error in ',trim(ACidata(i))
            write(errorunit,*)
     &'Please resubmit the data after correcting the following error:'
            ierr(2)=-ierr(2)
          endif
          write(errorunit,*)'Line starting with ',longchar(1:50), '.....
     &is within the main data body but has no valid PAR data'
          write(errorunit,*)'Sample chamber PAR out of range'
          ierr(1)=1
        else
          PARi_umol=dmax1(0.0d0,PARi_umol)
        endif
        if(Press_KPa.lt.50.0d0.or.Press_KPa.gt.150.0d0)then
          Press_KPa=98.9d0
!          if(ierr(2).gt.0)then
!            write(errorunit,*)'Input data error in ',trim(ACidata(i))
!            write(errorunit,*)
!     &'Please resubmit the data after correcting the following error:'
!            ierr(2)=-ierr(2)
!          endif
!          write(errorunit,*)'Air pressure out of range'
!          ierr(1)=1
        endif
        if(Tair_oC.lt.-50.0d0.or.Tair_oC.gt.100.0d0)then
          Tair_oC=Tleaf_oC
        endif
        if(vpdl_KPa.lt.0.0d0.or.vpdl_KPa.gt.1000.0d0)then
          if(H2OS_mmol.gt.0.0d0)then
            term=H2OS_mmol*0.001d0/(1.0d0+H2OS_mmol*0.001d0)
            term=term*Press_KPa
            vpdl_KPa=esat((Tleaf_oC+273.15d0),(Press_KPa*1000.0d0))
            vpdl_KPa=vpdl_KPa*0.001d0-term
          else
            if(RH_S100.ge.0.0d0.and.RH_S100.le.100.0d0)then        
              term=0.01d0*RH_S100*
     &          esat((Tair_oC+273.15d0),(Press_KPa*1000.0d0))
              vpdl_KPa=0.001d0*(
     &    esat((Tleaf_oC+273.15d0),(Press_KPa*1000.0d0))-term)
            else
              vpdl_KPa=1.6d0
            endif
          endif
        endif
        if(H2OS_mmol.lt.0.0d0)then
          if(RH_S100.lt.0.0d0.or.RH_S100.gt.100.0d0)then
            ambientvaporpres=esat((Tair_oC+273.15d0),
     &           (Press_KPa*1000.0d0))-vpdl_KPa*1000.0d0 
            ambientvaporpres=dmax1(0.0d0,ambientvaporpres)
          else
            ambientvaporpres=0.01d0*RH_S100*esat((Tair_oC+273.15d0),
     &           (Press_KPa*1000.0d0))
          endif
        else
          ambientvaporpres=H2OS_mmol*0.001d0/(1.0d0+H2OS_mmol*0.001d0)
          ambientvaporpres=ambientvaporpres*Press_KPa*1000.0d0
        endif
        npoints(i)=npoints(i)+1
        pari(i,npoints(i))=PARi_umol
        if(Tleaf_oC.gt.-50.0d0.and.Tleaf_oC.lt.100.0d0)then
          templeaf(i,npoints(i))=Tleaf_oC+273.15d0
        else
          templeaf(i,npoints(i))=-9999.0d0
        endif
        pres_air(i,npoints(i))=Press_KPa*1000.0d0
        yAnet(i,npoints(i))=PNcor_umol
        if(oxygeni_KPa.le.0.0d0.or.oxygeni_KPa.ge.Press_KPa)then
          po2i(i,npoints(i))=0.2095d0*pres_air(i,npoints(i))
        else
          po2i(i,npoints(i))=oxygeni_KPa*1000.0d0
        endif
        trmmol(i,npoints(i))=transp_mmol
        gswmeas(i,npoints(i))=stom_COND_mol
        vpdl(i,npoints(i))=vpdl_KPa*1000.0d0
        if(Tair_oC.gt.-50.0d0.and.Tair_oC.lt.100.0d0)then
          tempair(i,npoints(i))=Tair_oC+273.15d0
        else
          tempair(i,npoints(i))=-9999.0d0
        endif
        eambient(i,npoints(i))=ambientvaporpres
        chlflphips2(i,npoints(i))=phips2
        fo_pam(i,npoints(i))=fo_fluoresce
        fm_pam(i,npoints(i))=fm_fluoresce
        fs_pam(i,npoints(i))=fs_fluoresce
        pam_measlight(i,npoints(i))=f_measlight
!the unit of CO2 is in umol/mol. We use both umol/mol and Pa. Li-Cor 6400
!measures CO2 on a moist air basis.
        xpco2i_ppm(i,npoints(i))=CO2i_ppm        
        xpco2i(i,npoints(i))=CO2i_ppm*
     &    pres_air(i,npoints(i))*1.0d-6
        if(CO2chamber_ppm.gt.0.0d0)then
          co2a_ppm(i,npoints(i))=CO2chamber_ppm
          pco2ambient(i,npoints(i))=CO2chamber_ppm*
     &     pres_air(i,npoints(i))*1.0d-6
        else
          pco2ambient(i,npoints(i))=-9999.0d0
          co2a_ppm(i,npoints(i))=-9999.0d0
        endif
        CurveTypeID(i,npoints(i))=datumlimit
        call CharToNumeric(chartime,term)
        sampletime(i,npoints(i))=term
        goto 20
100     do j=1,npoints(i)
          vectorhorse(j)=sampletime(i,j)
          call time_resolution(npoints(i),vectorhorse,
     &    avetimeresolution(i),avetimesampled(i))
        enddo
630     close(spareunit)
        goto 640
35      if(ierr(2).gt.0)then
          write(errorunit,*)'Input data error in ',trim(ACidata(i))
          write(errorunit,*)
     &'Please resubmit the data after correcting the following error:'
          ierr(2)=-ierr(2)
        endif
        write(errorunit,*)'This file has incorrect data format'
        ierr(1)=1
        close(spareunit)
        goto 640

36      if(ierr(2).gt.0)then
          write(errorunit,*)'Input data error in ',trim(ACidata(i))
          write(errorunit,*)
     &'Please resubmit the data after correcting the following error:'
          ierr(2)=-ierr(2)
        endif
        write(errorunit,*)'This file has incorrect data format'
        ierr(1)=1
        close(dataunit,status='delete')
        goto 640

40      if(ierr(2).gt.0)then
          write(errorunit,*)'Input data error in ',trim(ACidata(i))
          write(errorunit,*)
     &'Please resubmit the data after correcting the following error:'
          ierr(2)=-ierr(2)
        endif
        write(errorunit,*)'This file has incorrect data format'
        ierr(1)=1
        close(spareunit)
640     continue
10    enddo
      if(ierr(1).eq.1)return
      iprintheader(1)=1
      do i=2,ntotfiles
        if(isitmassbased(i).eq.isitmassbased(i-1))then
          iprintheader(i)=0
        else
          iprintheader(i)=1
        endif
      enddo
      k=1
      do i=1,ntotfiles
        if(k.eq.1.or.iprintheader(i).eq.1)then
          call LeafGasPrintToFiles(isitmassbased(i:i),indexunit,
     &ic3c4cam)
          k=0
        endif
        if(npoints(i).lt.3)goto 1112
!-----------------------------------------------------
!detect A/Ci or light response curves with many points but no curve types are given
        if(npoints(i).ge.7)then
          j=0
          do n=1,npoints(i)
            if(CurveTypeID(i,n).gt.0)j=1
          enddo
          if(j.eq.0)then
            call stdmaxmeanmin(npoints(i),pari(i:i,1:npoints(i)),
     &stdpar,fmeanpar,xminpar,xmaxpar)
            stdpar=100.0d0*(xmaxpar-xminpar)/fmeanpar
            call stdmaxmeanmin(npoints(i),pco2ambient(i:i,1:npoints(i)),
     &stdco2,fmeanco2,xminco2,xmaxco2)
            stdco2=100.0d0*(xmaxco2-xminco2)/fmeanco2
            if(stdpar.lt.5.0d0.and.stdco2.gt.5.0d0)then
!ACi curve
              do n=1,npoints(i)
                CurveTypeID(i,n)=11
              enddo
            else
              if(stdpar.gt.5.0d0.and.stdco2.lt.5.0d0)then
!light response curve
                do n=1,npoints(i)
                  CurveTypeID(i,n)=31
                enddo
              endif
            endif
          endif
        endif
!------------------------------------------------------
        if(ic3c4cam.eq.1)
     &call SetUpLeafGasFit(curveno(i:i),sample(i:i),npoints(i:i),
     &CurveTypeID(i:i,1:npoints(i)),yAnet(i:i,1:npoints(i)),
     &xpco2i(i:i,1:npoints(i)),templeaf(i:i,1:npoints(i)),
     &pari(i:i,1:npoints(i)),pres_air(i:i,1:npoints(i)),
     &po2i(i:i,1:npoints(i)),chlflphips2(i:i,1:npoints(i)),
     &pco2ambient(i:i,1:npoints(i)),trmmol(i:i,1:npoints(i)),
     &gswmeas(i:i,1:npoints(i)),vpdl(i:i,1:npoints(i)),
     &tempair(i:i,1:npoints(i)),eambient(i:i,1:npoints(i)),
     &fo_pam(i:i,1:npoints(i)),fm_pam(i:i,1:npoints(i)),
     &fs_pam(i:i,1:npoints(i)),pam_measlight(i:i,1:npoints(i)),
     &stargamma25_usr(i:i),fkc25_usr(i:i),fko25_usr(i:i),
     &rdlight25_usr(i:i),alpha25_usr(i:i),resistwp25_usr(i:i),
     &resistch25_usr(i:i),isitmassbased(i:i),indexunit,
     &siteID(i:i),Latitude(i:i),Longitude(i:i),Elevation(i:i),
     &yearsampled(i:i),sampledoy(i:i),GrowingSeasonStart(i:i),
     &GrowingSeasonEnd(i:i),standage(i:i),CanopyHeight(i:i),
     &LeafAreaIndex(i:i),species(i:i),avetimeresolution(i:i),
     &avetimesampled(i:i),SampleHeight(i:i),Needleage(i:i),
     &specificLAI(i:i),nitrogencontent(i:i),carboncontent(i:i),
     &phoscontent(i:i),woodporosity(i:i),sapwooddensity(i:i),
     &leafratio(i:i))
        if(ic3c4cam.eq.2)
     &call C4SetUpLeafGasFit(curveno(i:i),sample(i:i),npoints(i:i),
     &CurveTypeID(i:i,1:npoints(i)),yAnet(i:i,1:npoints(i)),
     &xpco2i(i:i,1:npoints(i)),templeaf(i:i,1:npoints(i)),
     &pari(i:i,1:npoints(i)),pres_air(i:i,1:npoints(i)),
     &po2i(i:i,1:npoints(i)),chlflphips2(i:i,1:npoints(i)),
     &pco2ambient(i:i,1:npoints(i)),trmmol(i:i,1:npoints(i)),
     &gswmeas(i:i,1:npoints(i)),vpdl(i:i,1:npoints(i)),
     &tempair(i:i,1:npoints(i)),eambient(i:i,1:npoints(i)),
     &fo_pam(i:i,1:npoints(i)),fm_pam(i:i,1:npoints(i)),
     &fs_pam(i:i,1:npoints(i)),pam_measlight(i:i,1:npoints(i)),
     &stargamma25_usr(i:i),fkc25_usr(i:i),fko25_usr(i:i),
     &rdlight25_usr(i:i),alpha25_usr(i:i),resistwp25_usr(i:i),
     &resistch25_usr(i:i),isitmassbased(i:i),indexunit,
     &siteID(i:i),Latitude(i:i),Longitude(i:i),Elevation(i:i),
     &yearsampled(i:i),sampledoy(i:i),GrowingSeasonStart(i:i),
     &GrowingSeasonEnd(i:i),standage(i:i),CanopyHeight(i:i),
     &LeafAreaIndex(i:i),species(i:i),avetimeresolution(i:i),
     &avetimesampled(i:i),SampleHeight(i:i),Needleage(i:i),
     &specificLAI(i:i),nitrogencontent(i:i),carboncontent(i:i),
     &phoscontent(i:i),woodporosity(i:i),sapwooddensity(i:i),
     &leafratio(i:i))
1112  continue
      enddo
      return
300   format(a50000)
310   format(a5000)
340   format(a)
      end subroutine ToLeafGasOptimization
!&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
