      program tsv_2_Dfile_batch

c  *************************************************************************
c     to compile: >gfortran tsv_2_Dfile_batch.f -o tsv_2_Dfile_batch.x 
c     to execute: >tsv_2_Dfile_batch.x 
c    
c     written: by Shao-Chin Huang,  Department of Atmospheric Sciences
c     Institute of Geography,  Chinese Culture University, Taipei, Taiwan
c     date: January 2011
c     modified by Paul Ciesielski (03/07/2011) to process several files contained in a list
c
c     This sample program used to reformat Vaisala tsv (tab separated value) 
c     file to D-file format, D-file format files can be easily processed through ASPEN.
c     Filename should be stnid-yyyymmddhh-vert.gls.
c     vert = '-al', '-up' or '-dn' (option for sondes run in research mode which have data
c     as sonde is ascending and descending 
c     if vert='-dn', it converts  data from  increase pressure to decrease pressure.
c  ***************************************************************************

      parameter (npt=99999)
      dimension p1(npt),z1(npt),t1(npt),td1(npt)
      dimension wd1(npt),ws1(npt),tim(npt),dz1(npt)
      dimension rh1(npt),rlon1(npt),rlat1(npt),isat1(npt)
      dimension ti(npt)
      character flist*30
      character tempfile*26,station*5,buf*100,vert*3
      character out*19,type*5,s_type*13,s_type1*14
      character input*24,buff*77,sonde*8
      character tmp(15)*133,fn(npt)*78
      parameter (spv=-32768.00)
      parameter (spv2=-999.)

c   *******************************************************************************

c   open file containing list of tsv file names to process ....

        print *, 'Specify file list name ...>'
        read (5,'(a)') flist
        open ( 9, file=flist, form='formatted', status='old') 
                      
        nf = 0

 22     nf = nf + 1

c-----------------------------------------------------------------------
c* To open souding data.
c-----------------------------------------------------------------------
        read(9,'(a)', end=99)tempfile
        read(tempfile,1)station,iy,im,id,ihr,vert
    1   format(a5,3x,4(i2),1x,a3)
        write(out,'("20",4i2.2,".",a5,a3)')iy,im,id,ihr,station,vert

        type = "Fixed"
        s_type = "Vaisala RS-92"

        open(10, file=tempfile, form='formatted', status='old')
        open(11,file='D'//out//'.gls',form='formatted'
     +         ,status='unknown')
c----------------------------------------------------------------------
c*  read souding data.
c----------------------------------------------------------------------
      do i=1,39
         read(10,'(a)')buf
         if(i.eq.7) read(buf(27:34),*)sonde
      enddo

      dz=spv2
      isa=4
      nn=0
   10 continue
      read(10,*,end=20)ttim,b,t,rh,v,u,ht,p,td,e,dir
     +                ,spd,az,ran,rlon,rlat
c     print *, nn, ttim, p
      if(p.gt.2000.)goto 10
      if(p.eq.spv)p=spv2
      if((ht.ge.90000.).or.(ht.lt.0).or.(ht.eq.spv))ht=spv2
      if((t.ge.900.).or.(t.lt.-100.).or.(t.eq.spv))t=spv2
      if((td.ge.900.).or.(td.lt.-100).or.(td.eq.spv))dp=spv2
      if((spd.ge.900.).or.(spd.lt.0).or.(spd.eq.spv))spd=spv2
      if((dir.ge.900.).or.(dir.lt.0).or.(dir.eq.spv))dir=spv2
      if(rh.eq.spv)rh=spv2
      if(rlon.eq.spv)rlon=spv2
      if(rlat.eq.spv)rlat=spv2
      nn=nn+1
      tim(nn)=ttim
      p1(nn)=p
      z1(nn)=ht
      if(t.eq.spv2)then
         t1(nn)=spv2
      else
         t1(nn)=t-273.15
      endif
      if(td.eq.spv2)then
         td1(nn)=spv2
      else
         td1(nn)=dp-273.15
      endif
      rh1(nn)=rh
      wd1(nn)=dir
      ws1(nn)=spd
      rlon1(nn)=rlon
      rlat1(nn)=rlat
      dz1(nn)=dz
      isat1(nn)=isa
c      print*,nn,ht,p,t,dp,dir,spd
      goto 10
   20 continue
c----------------------------------------------------------------------
c*  reformat
c----------------------------------------------------------------------
      write(11,'(a)')"Data Type:                         GLASS PROCESSED
     + DATA, FileFormat 1"
      write(11,'(a)')"Project ID:                        "
      write(11,'(a,a5,a,a5)')"Launch Site Type/Site ID:          ",type,
     +", ",station
      write(11,'(a)')"Launch Location (lon, lat alt):"
      write(11,'(4(a,i2.2),a)')"GMT Launch Time (y,m,d,h,m,s):     20"
     +,iy,", ",im,", ",id,", ",ihr,":00:00"
      write(11,'(a,a13,a,a8,a)')"Sonde Type/Id/Sensor ID/Tx Freq:   ",
     +s_type," ",sonde,", 999, 999"
      write(11,'(a)')"/"
      write(11,'(a)')"/"
      write(11,'(a)')"/"
      write(11,'(a)')"System Operator/Comments:          "
      write(11,'(a)')"/"
      write(11,'(a)')"CAUTION !!!  THIS DATA SET IS UNEDITED AND HAS NOT
     + BEEN REVIEWED FOR ACCURACY."
      write(11,'(a)')" Time  Press   Temp     RH    Wdir   Wspd     dz
     +  Lon     Lat    GPS Alt Sa"
      write(11,'(a)')"  sec    mb      C       %     deg    m/s    m/s
     +  deg     deg         m  #s" 
      write(11,'(a)')"------ ------ ------ ------ ------ ------- ------
     +-------- ------- ------- --"
      do i=1,nn
      write(11,21)tim(i),p1(i),t1(i),rh1(i),wd1(i),ws1(i),dz1(i)
     +            ,rlon1(i),rlat1(i),z1(i),isat1(i)
   21 format(5(f6.1,1x),f7.1,1x,f6.1,1x,f8.3,1x,f7.2,1x,f7.1,1x,i2.2)
      enddo

      print*,tempfile,' OK!'

      close(10)
      close(11)
c----------------------------------------------------------------------
c* if vert='-dn', convert gls format from 
c     increase pressure to decrease pressure.
c----------------------------------------------------------------------
      final_time=ttim

      if(vert.eq.'-dn')then
         input='D'//out//'.gls'
         open(12,file=input,form='formatted',status='unknown')
         open(21,file='new.'//input,form='formatted',status='unknown')
         do i=1,15
            read(12,'(a)')tmp(i)
            write(21,'(a)')tmp(i)
         enddo
         nn=0
   30    continue
            nn=nn+1
            read(12,'(f6.1,a)',err=30,end=40)time,buff
            time=time-final_time
            time=abs(time)

            ti(nn)=time
            fn(nn)=buff
         goto 30
   40    continue
         nn=nn-1
         do i=nn,1,-1
            write(21,'(f6.1,a)') ti(i),fn(i)
         enddo
         print*,'new.',input,' OK!'
      endif

      go to 22

   99 continue

      ntot = nf - 1

      print *, 'finished processing; read in ', ntot, ' files'

      stop
      end
