! From http://tama.green.gifu-u.ac.jp/~tama/soft/sample_prog/csv2/
! Data file (csv) are read from stdin
! small change 2014.6.11

implicit none

integer, parameter  :: maxch=200
integer, parameter  :: maxn = 10000
character(len=1024) :: buf, eachcol(maxch), title(maxch)
integer :: i, j, ch, num, err_read, j1
real,parameter :: MISS=-9999
integer :: year(maxn), month(maxn), day(maxn)
integer :: doy(maxn), hour(maxn), minute(maxn)
integer :: tmin(maxn)
character(len=80) :: cdate(maxn)
real :: data(maxn, maxch)

i=0 ; err_read = 0
do while( (i < maxn).and.(err_read == 0) )
 read(*, '(A)', err=999, end=999) buf
 i= i+1
 call devidecsv( buf, eachcol, maxch, ch )

 if(i==1) then
  do j=1, ch
   title(j) = eachcol(j)
  end do
 else


 j= 1
   if( eachcol(j) /= '' ) then
      read(eachcol(j), *) year(i-1)

 j= 2
   if( eachcol(j) /= '' ) then
      read(eachcol(j), *) doy(i-1)
       call doy2monthday( year(i-1), doy(i-1), month(i-1), day(i-1))


 j= 3
   if( eachcol(j) /= '' ) then
     do j1=1, len_trim(eachcol(j))
       if( eachcol(j)(j1:j1) == ':' ) then
             eachcol(j)(j1:j1) = ' '
       end if
     end do
      read(eachcol(j), *) hour(i-1), minute(i-1)

! Just monitor
  write(0,*) year(i-1), month(i-1), day(i-1), hour(i-1), minute(i-1)


 j= 4
   if( eachcol(j) /= '' ) then
      read(eachcol(j), *) tmin(i-1)
 j= 5
   if( eachcol(j) /= '' ) then
      cdate(i-1) = eachcol(j)


  do j=6, ch
   if( eachcol(j) /= '' ) then
      read(eachcol(j), *) data(i-1, j-5)
   else
      data(i-1, j-5) = MISS
   end if
 end do

else
  i = i-1
end if
end if
end if
end if
end if
end if

end do

999  num = i-1
  write(0,*) 'read finished'


! From here, Data processing

do i=1, num
 write(*,'(I4,4I0.2,5F8.2)')  year(i), month(i), day(i), hour(i), minute(i), &
     data(i,44) - data(i,45) +  data(i,48) - data(i,49), &
     data(i,44), data(i,45), data(i,48), data(i,49)
end do

end


subroutine devidecsv( buf, eachcol, maxch, num )
implicit none
integer   :: maxch, num
character(len=*) :: buf, eachcol(maxch)
integer :: i, j, prev, now, now1, ll
logical :: quote

quote = .FALSE.

ll = len_trim(buf)
prev=0; now=1; i=1
do j=1, ll
 if( buf(j:j) == '"' ) then
   quote = .NOT. quote
 end if
 if( quote .eqv. .FALSE. ) then
  if(buf(j:j) == ',') then
   now = j
   now1 = now -1
   if( now1 <prev+1 ) then
    eachcol(i) = ''
   else
    eachcol(i) = buf(prev+1:now1)
   end if
   i=i+1
   if( i > maxch ) then
     write(0,*) 'maxch is too small'
     stop
   end if
  prev=now
  end if
 end if
end do

if( prev < ll ) then
 eachcol(i) =  buf(prev+1:ll)
 num = i
else
 num=i-1
end if

end
