SUBROUTINE READ_PROF(inputdir,ierr,prestr,extstr,runid,label,fac,var_min,var_max, &
                     nt_out,t_out,nr_out,r_out,var_out,idev)
!
! History:
! 03/01/10 CLF: added inputdir
!               double -> REAL(KIND=rspec)
!               allocate arrays

use swim_global_data_mod, only: rspec

implicit none

character*(*) :: inputdir
integer :: nx1,nx2,nt_out,nr_out,ierr,it,jx
character(*)  :: prestr,extstr
character(2)  :: label
character*(*) :: runid
character*(*) :: idev
character(len=30) :: xlab,ylab,dlab          ! Ufile labels

real   :: t_out(nt_out)
real   :: var_min,var_max

real,   dimension(:),     allocatable :: time_u, rho_tor_u
real,   dimension(:),     allocatable :: d1d
real,   dimension(:,:),   allocatable :: d2d
REAL(KIND=rspec), dimension(:,:),   allocatable :: d2d_dbl
REAL(KIND=rspec) :: fac,max_var
REAL(KIND=rspec) :: r_out(nr_out),var_out(nt_out,nr_out)

integer :: nx3, nscal
integer :: iochan
integer :: l

WRITE(6,*) 'Reading ' // label // '(time,rho_tor) from UFile'
call managerd_u(inputdir,runid,prestr,extstr,iochan,nx1,nx2,nx3,nscal,ierr)
allocate(d2d(nx1,nx2),time_u(nx1),rho_tor_u(nx2), STAT=iErr)
allocate(d2d_dbl(nt_out,nx2), d1d(nx2), STAT=iErr)
CALL read_u2d(iochan,idev,time_u,nx1,rho_tor_u,nx2,d2d,nscal,iErr)
if (iErr .ne. 0) then
  WRITE(6,*) ' Error reading '//label//'(time,rho_tor) from UFile'
  STOP
endif

if (iErr .ne. 0) then ! array could not be allocated
  WRITE(6,*) " Could not allocate array '"//label//"(nt_out,nrho)'"
  STOP
endif
CALL INTERP2D(nx2,nx1,time_u,d2d(1:nx1,1:nx2),nt_out,t_out,d2d_dbl(1:nt_out,1:nx2))
DO it=1,nt_out
   DO jx=1,nx2
      d1d(jx)=real(d2d_dbl(it,jx))
   ENDDO
  CALL INTERP1D(nx2,rho_tor_u(1:nx2),d1d(1:nx2),nr_out,r_out,var_out(it,1:nr_out))
ENDDO

deallocate(d1d, d2d, time_u, rho_tor_u, d2d_dbl)

var_out=fac*var_out
max_var=maxval(var_out)
IF ( ( max_var .LE. var_min) .OR. (max_var .GE. var_max) ) THEN
  write(6,*) 'Maximum value of '//label //' is ',max_var
  if (len_trim(runid) .eq. 8) then
     l=5
  else
     l=6
  endif
  write(6,'(2A,i5,2A)') 'Please check units in ', prestr, runid(1:l), '.', extstr
  STOP
endif

RETURN

END SUBROUTINE READ_PROF
