! scan_INIT_file.f90 — varre o INIT.file (gerado pelo const.f do initbc,
! lido pelo etafcst) procurando campos nao-fisicos que expliquem o
! SIGSEGV na 1a chamada da radiacao (E290/FST88: indice de tabela a
! partir de T e do caminho de vapor d'agua = f(Q, espessuras de PD)).
!
! Layout (const.f):
!   rec 1: run(l4), idat(3i4), ihrst(i4), ntsd(i4)
!   rec 2: pdt(im,jm)     rec 3: res(im,jm)=1/ref     rec 4: fist(im,jm)
!   lm recs de U, lm de V, lm de T, lm de Q (im,jm cada)
!   ... (si, sno, smc, cmc, stc, sh2o, albedo — nao lidos aqui)
!
! Compilar no mesmo ambiente Intel do initbc:
!   ifort -O0 -traceback scan_INIT_file.f90 -o scan_INIT_file
! Uso:
!   ./scan_INIT_file <rodada>/INIT.file IM JM LM
program scan_init_file
  implicit none
  integer :: im, jm, lm, ios, i, j, l, nrep, ntot
  character(len=512) :: fname, a1, a2, a3
  logical(4) :: run
  integer(4) :: idat(3), ihrst, ntsd
  real(4), allocatable :: pd(:,:), res(:,:), fist(:,:), f2(:,:)
  character(len=1) :: vn(4) = (/'U','V','T','Q'/)
  integer :: iv
  real(4) :: vmin, vmax

  call get_command_argument(1, fname)
  call get_command_argument(2, a1); read(a1,*) im
  call get_command_argument(3, a2); read(a2,*) jm
  call get_command_argument(4, a3); read(a3,*) lm

  allocate(pd(im,jm), res(im,jm), fist(im,jm), f2(im,jm))

  open(10, file=trim(fname), status='old', form='unformatted', iostat=ios)
  if (ios /= 0) stop 'erro abrindo INIT.file'
  read(10, iostat=ios) run, idat, ihrst, ntsd
  if (ios /= 0) stop 'erro no rec 1'
  read(10, iostat=ios) pd
  if (ios /= 0) stop 'erro lendo PD (conferir IM/JM)'
  read(10, iostat=ios) res
  read(10, iostat=ios) fist
  if (ios /= 0) stop 'erro lendo RES/FIST'

  write(*,'(a,3i5,a,i3)') 'idat=', idat, '  ihrst=', ihrst

  write(*,'(/a)') '=== PD (esperado ~20000..102000 Pa; radiacao quebra com <=0/NaN ou ~10x maior) ==='
  write(*,'(a,2es14.6,a,i10)') 'min/max:', minval(pd), maxval(pd), '   NaN:', count(pd /= pd)
  nrep = 0
  do j = 1, jm
    do i = 1, im
      if (pd(i,j) /= pd(i,j) .or. pd(i,j) <= 0. .or. pd(i,j) > 110000.) then
        nrep = nrep + 1
        if (nrep <= 20) write(*,'(a,2i6,es14.6,a,f10.1,a,f8.4)') &
          '  PD ruim (i,j)=', i, j, pd(i,j), '  fis/g=', fist(i,j)/9.8, &
          '  1/res=', 1./res(i,j)
      end if
    end do
  end do
  write(*,'(a,i10)') 'total PD fora de (0,110000]: ', nrep

  write(*,'(/a)') '=== RES (=1/ref, esperado [1, ~5]) ==='
  write(*,'(a,2es14.6,a,i10)') 'min/max:', minval(res), maxval(res), '   NaN:', count(res /= res)

  write(*,'(/a)') '=== FIST (geopot. sfc, esperado [0, ~65000]) ==='
  write(*,'(a,2es14.6,a,i10)') 'min/max:', minval(fist), maxval(fist), '   NaN:', count(fist /= fist)

  do iv = 1, 4
    write(*,'(/a)') '=== '//vn(iv)//' por nivel ==='
    ntot = 0
    do l = 1, lm
      read(10, iostat=ios) f2
      if (ios /= 0) then
        write(*,*) 'erro lendo '//vn(iv)//' nivel', l
        stop
      end if
      vmin = minval(f2); vmax = maxval(f2)
      nrep = count(f2 /= f2)
      select case (iv)
      case (1,2)   ! U,V
        nrep = nrep + count(abs(f2) > 150.)
      case (3)     ! T: radiacao exige [100,380)
        nrep = nrep + count(f2 < 100. .or. f2 >= 380.)
      case (4)     ! Q
        nrep = nrep + count(f2 < 0. .or. f2 > 0.05)
      end select
      if (nrep > 0 .or. l == 1 .or. l == lm) &
        write(*,'(a,i4,a,2es14.6,a,i8)') '  l=', l, '  min/max:', vmin, vmax, &
          '  suspeitos:', nrep
      if (nrep > 0 .and. ntot < 30) then
        do j = 1, jm
          do i = 1, im
            if (f2(i,j) /= f2(i,j) &
                .or. (iv == 3 .and. (f2(i,j) < 100. .or. f2(i,j) >= 380.)) &
                .or. (iv == 4 .and. (f2(i,j) < 0. .or. f2(i,j) > 0.05)) &
                .or. (iv <= 2 .and. abs(f2(i,j)) > 150.)) then
              ntot = ntot + 1
              if (ntot <= 30) write(*,'(a,3i6,es14.6)') &
                '    '//vn(iv)//' suspeito (i,j,l)=', i, j, l, f2(i,j)
            end if
          end do
        end do
      else
        ntot = ntot + nrep
      end if
    end do
    write(*,'(a,i10)') '  total suspeitos '//vn(iv)//': ', ntot
  end do
  close(10)
end program scan_init_file
