program Kennedy

!! Program is meant to read what files contain the Kennedy data !!
!! and then read those files to obtain water statistics data and!!
!! then output that data into IMEDS format.                     !!

      implicit none
      character(120)                :: filestations, junkC
      character(120), allocatable   :: stnid(:), filename(:)
      double precision, allocatable :: lat(:), lon(:)
      integer                       :: yy, mo, dd, hh, mi, ss
      integer                       :: nste, i, j, nsta
      real(8)                       :: junkR, hs, tp, wl

      write(6,*) "Enter the name of the station list."
      read(5,*) filestations
!       filestations = UNDKennedy_stations.txt

      open(unit=20,file=filestations,status='old',action='read')
      read(20,*) nsta
      read(20,*)
      allocate(stnid(1:nsta), lat(1:nsta), lon(1:nsta))
      allocate(filename(1:nsta))
      do i=1,nsta
        read(20,*) stnid(i), lat(i), lon(i), filename(i)
      enddo
      close(20)

! Read and write data to IMEDS format !

      open(unit=21,file="hs_UNDKennedy.IMEDS",status='replace',action='write')
      write(21,*) "% IMEDS generic format - Significant Wave Height"
      write(21,*) "% ", "year ","month ","day ","hour ","min ","sec ","hs (m)"
      write(21,*) "UNDKennedy ","UTC ","NAVD88"

      open(unit=22,file="tp_UNDKennedy.IMEDS",status='replace',action='write')
      write(22,*) "% IMEDS generic format - Peak Wave Period"
      write(22,*) "% ", "year ","month ","day ","hour ","min ","sec ","tp (s)"
      write(22,*) "UNDKennedy ","UTC ","NAVD88"

      open(unit=23,file="watlev_UNDKennedy.IMEDS",status='replace',action='write')
      write(23,*) "% IMEDS generic format - Water Level"
      write(23,*) "% ", "year ","month ","day ","hour ","min ","sec ","watlev (m)"
      write(23,*) "UNDKennedy ","UTC ","NAVD88"

      do i=1,nsta
        write(6,*) "Processing station ID: ", i, trim(stnid(i))
        write(21,*) trim(stnid(i)), lat(i), lon(i)
        write(22,*) trim(stnid(i)), lat(i), lon(i)            
        write(23,*) trim(stnid(i)), lat(i), lon(i)
        open(unit=11,file=trim(filename(i)),status='old',action='read')
          read(11,*) nste
          read(11,*)
          do j=1,nste
            read(11,*) junkC, yy, mo, dd, hh, mi, ss, hs, junkR, tp, wl
            write(21,210) yy, mo, dd, hh, mi, ss, hs
            write(22,220) yy, mo, dd, hh, mi, ss, tp
            write(23,230) yy, mo, dd, hh, mi, ss, wl
          enddo
      enddo
      close(11)
      close(21)
      close(22)
      close(23)
210   Format(6i6, f14.4)
220   Format(6i6, f14.4)
230   Format(6i6, f14.4)

end program
