New URL for NEMO forge!   http://forge.nemo-ocean.eu

Since March 2022 along with NEMO 4.2 release, the code development moved to a self-hosted GitLab.
This present forge is now archived and remained online for history.
fldread.F90 in NEMO/branches/2021/dev_r14116_HPC-10_mcastril_Mixed_Precision_implementation/src/OCE/SBC – NEMO

source: NEMO/branches/2021/dev_r14116_HPC-10_mcastril_Mixed_Precision_implementation/src/OCE/SBC/fldread.F90 @ 15540

Last change on this file since 15540 was 15540, checked in by sparonuz, 3 years ago

Mixed precision version, tested up to 30 years on ORCA2.

  • Property svn:keywords set to Id
File size: 88.3 KB
Line 
1MODULE fldread
2   !!======================================================================
3   !!                       ***  MODULE  fldread  ***
4   !! Ocean forcing:  read input field for surface boundary condition
5   !!=====================================================================
6   !! History :  2.0  !  2006-06  (S. Masson, G. Madec)  Original code
7   !!            3.0  !  2008-05  (S. Alderson)  Modified for Interpolation in memory from input grid to model grid
8   !!            3.4  !  2013-10  (D. Delrosso, P. Oddo)  suppression of land point prior to interpolation
9   !!                 !  12-2015  (J. Harle) Adding BDY on-the-fly interpolation
10   !!----------------------------------------------------------------------
11
12   !!----------------------------------------------------------------------
13   !!   fld_read      : read input fields used for the computation of the surface boundary condition
14   !!   fld_init      : initialization of field read
15   !!   fld_def       : define the record(s) of the file and its name
16   !!   fld_get       : read the data
17   !!   fld_map       : read global data from file and map onto local data using a general mapping (use for open boundaries)
18   !!   fld_rot       : rotate the vector fields onto the local grid direction
19   !!   fld_clopn     : close/open the files
20   !!   fld_fill      : fill the data structure with the associated information read in namelist
21   !!   wgt_list      : manage the weights used for interpolation
22   !!   wgt_print     : print the list of known weights
23   !!   fld_weight    : create a WGT structure and fill in data from file, restructuring as required
24   !!   apply_seaoverland : fill land with ocean values
25   !!   seaoverland   : create shifted matrices for seaoverland application
26   !!   fld_interp    : apply weights to input gridded data to create data on model grid
27   !!   fld_filename  : define the filename according to a given date
28   !!   ksec_week     : function returning seconds between 00h of the beginning of the week and half of the current time step
29   !!----------------------------------------------------------------------
30   USE oce            ! ocean dynamics and tracers
31   USE dom_oce        ! ocean space and time domain
32   USE phycst         ! physical constant
33   USE sbc_oce        ! surface boundary conditions : fields
34   USE geo2ocean      ! for vector rotation on to model grid
35   !
36   USE in_out_manager ! I/O manager
37   USE iom            ! I/O manager library
38   USE ioipsl  , ONLY : ymds2ju, ju2ymds   ! for calendar
39   USE lib_mpp        ! MPP library
40   USE lbclnk         ! ocean lateral boundary conditions (C1D case)
41   
42   IMPLICIT NONE
43   PRIVATE   
44 
45   PUBLIC   fld_map    ! routine called by tides_init
46   PUBLIC   fld_read, fld_fill   ! called by sbc... modules
47   PUBLIC   fld_def
48
49   TYPE, PUBLIC ::   FLD_N      !: Namelist field informations
50      CHARACTER(len = 256) ::   clname      ! generic name of the NetCDF flux file
51      REAL(dp)             ::   freqh       ! frequency of each flux file
52      CHARACTER(len = 34)  ::   clvar       ! generic name of the variable in the NetCDF flux file
53      LOGICAL              ::   ln_tint     ! time interpolation or not (T/F)
54      LOGICAL              ::   ln_clim     ! climatology or not (T/F)
55      CHARACTER(len = 8)   ::   clftyp      ! type of data file 'daily', 'monthly' or yearly'
56      CHARACTER(len = 256) ::   wname       ! generic name of a NetCDF weights file to be used, blank if not
57      CHARACTER(len = 34)  ::   vcomp       ! symbolic component name if a vector that needs rotation
58      !                                     ! a string starting with "U" or "V" for each component   
59      !                                     ! chars 2 onwards identify which components go together 
60      CHARACTER(len = 34)  ::   lname       ! generic name of a NetCDF land/sea mask file to be used, blank if not
61      !                                     ! 0=sea 1=land
62   END TYPE FLD_N
63
64   TYPE, PUBLIC ::   FLD        !: Input field related variables
65      CHARACTER(len = 256)            ::   clrootname   ! generic name of the NetCDF file
66      CHARACTER(len = 256)            ::   clname       ! current name of the NetCDF file
67      REAL(dp)                        ::   freqh        ! frequency of each flux file
68      CHARACTER(len = 34)             ::   clvar        ! generic name of the variable in the NetCDF flux file
69      LOGICAL                         ::   ln_tint      ! time interpolation or not (T/F)
70      LOGICAL                         ::   ln_clim      ! climatology or not (T/F)
71      CHARACTER(len = 8)              ::   clftyp       ! type of data file 'daily', 'monthly' or yearly'
72      CHARACTER(len = 1)              ::   cltype       ! nature of grid-points: T, U, V...
73      REAL(dp)                        ::   zsgn         ! -1. the sign change across the north fold, =  1. otherwise
74      INTEGER                         ::   num          ! iom id of the jpfld files to be read
75      INTEGER , DIMENSION(2,2)        ::   nrec         ! before/after record (1: index, 2: second since Jan. 1st 00h of yr nit000)
76      INTEGER                         ::   nbb          ! index of before values
77      INTEGER                         ::   naa          ! index of after  values
78      INTEGER , ALLOCATABLE, DIMENSION(:) ::   nrecsec   !
79      REAL(dp), POINTER, DIMENSION(:,:,:  ) ::   fnow   ! input fields interpolated to now time step
80      REAL(dp), POINTER, DIMENSION(:,:,:,:) ::   fdta   ! 2 consecutive record of input fields
81      CHARACTER(len = 256)            ::   wgtname      ! current name of the NetCDF weight file acting as a key
82      !                                                 ! into the WGTLIST structure
83      CHARACTER(len = 34)             ::   vcomp        ! symbolic name for a vector component that needs rotation
84      LOGICAL, DIMENSION(2)           ::   rotn         ! flag to indicate whether before/after field has been rotated
85      INTEGER                         ::   nreclast     ! last record to be read in the current file
86      CHARACTER(len = 256)            ::   lsmname      ! current name of the NetCDF mask file acting as a key
87      !                                                 !
88      !                                                 ! Variables related to BDY
89      INTEGER                         ::   igrd         !   grid type for bdy data
90      INTEGER                         ::   ibdy         !   bdy set id number
91      INTEGER, POINTER, DIMENSION(:)  ::   imap         !   Array of integer pointers to 1D arrays
92      LOGICAL                         ::   ltotvel      !   total velocity or not (T/F)
93      LOGICAL                         ::   lzint        !   T if it requires a vertical interpolation
94   END TYPE FLD
95
96!$AGRIF_DO_NOT_TREAT
97
98   !! keep list of all weights variables so they're only read in once
99   !! need to add AGRIF directives not to process this structure
100   !! also need to force wgtname to include AGRIF nest number
101   TYPE         ::   WGT        !: Input weights related variables
102      CHARACTER(len = 256)                    ::   wgtname      ! current name of the NetCDF weight file
103      INTEGER , DIMENSION(2)                  ::   ddims        ! shape of input grid
104      INTEGER , DIMENSION(2)                  ::   botleft      ! top left corner of box in input grid containing
105      !                                                         ! current processor grid
106      INTEGER , DIMENSION(2)                  ::   topright     ! top right corner of box
107      INTEGER                                 ::   jpiwgt       ! width of box on input grid
108      INTEGER                                 ::   jpjwgt       ! height of box on input grid
109      INTEGER                                 ::   numwgt       ! number of weights (4=bilinear, 16=bicubic)
110      INTEGER                                 ::   nestid       ! for agrif, keep track of nest we're in
111      INTEGER                                 ::   overlap      ! =0 when cyclic grid has no overlapping EW columns
112      !                                                         ! =>1 when they have one or more overlapping columns     
113      !                                                         ! =-1 not cyclic
114      LOGICAL                                 ::   cyclic       ! east-west cyclic or not
115      INTEGER,  DIMENSION(:,:,:), POINTER     ::   data_jpi     ! array of source integers
116      INTEGER,  DIMENSION(:,:,:), POINTER     ::   data_jpj     ! array of source integers
117      REAL(dp), DIMENSION(:,:,:), POINTER     ::   data_wgt     ! array of weights on model grid
118      REAL(dp), DIMENSION(:,:,:), POINTER     ::   fly_dta      ! array of values on input grid
119      REAL(dp), DIMENSION(:,:,:), POINTER     ::   col          ! temporary array for reading in columns
120   END TYPE WGT
121
122   INTEGER,     PARAMETER             ::   tot_wgts = 20
123   TYPE( WGT ), DIMENSION(tot_wgts)   ::   ref_wgts     ! array of wgts
124   INTEGER                            ::   nxt_wgt = 1  ! point to next available space in ref_wgts array
125   INTEGER                            ::   nflag = 0
126   REAL(dp), PARAMETER                ::   undeff_lsm = -999.00_wp
127
128!$AGRIF_END_DO_NOT_TREAT
129
130   !! * Substitutions
131#  include "do_loop_substitute.h90"
132#  include "single_precision_substitute.h90"
133#  include "domzgr_substitute.h90"
134   !!----------------------------------------------------------------------
135   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
136   !! $Id$
137   !! Software governed by the CeCILL license (see ./LICENSE)
138   !!----------------------------------------------------------------------
139CONTAINS
140
141   SUBROUTINE fld_read( kt, kn_fsbc, sd, kit, pt_offset, Kmm )
142      !!---------------------------------------------------------------------
143      !!                    ***  ROUTINE fld_read  ***
144      !!                   
145      !! ** Purpose :   provide at each time step the surface ocean fluxes
146      !!                (momentum, heat, freshwater and runoff)
147      !!
148      !! ** Method  :   READ each input fields in NetCDF files using IOM
149      !!      and intepolate it to the model time-step.
150      !!         Several assumptions are made on the input file:
151      !!      blahblahblah....
152      !!----------------------------------------------------------------------
153      INTEGER  , INTENT(in   )               ::   kt        ! ocean time step
154      INTEGER  , INTENT(in   )               ::   kn_fsbc   ! sbc computation period (in time step)
155      TYPE(FLD), INTENT(inout), DIMENSION(:) ::   sd        ! input field related variables
156      INTEGER  , INTENT(in   ), OPTIONAL     ::   kit       ! subcycle timestep for timesplitting option
157      REAL(wp) , INTENT(in   ), OPTIONAL     ::   pt_offset ! provide fields at time other than "now"
158      INTEGER  , INTENT(in   ), OPTIONAL     ::   Kmm       ! ocean time level index
159      !!
160      INTEGER  ::   imf          ! size of the structure sd
161      INTEGER  ::   jf           ! dummy indices
162      INTEGER  ::   isecsbc      ! number of seconds between Jan. 1st 00h of nit000 year and the middle of sbc time step
163      INTEGER  ::   ibb, iaa     ! shorter name for sd(jf)%nbb and sd(jf)%naa
164      LOGICAL  ::   ll_firstcall ! true if this is the first call to fld_read for this set of fields
165      REAL(wp) ::   zt_offset    ! local time offset variable
166      REAL(wp) ::   ztinta       ! ratio applied to after  records when doing time interpolation
167      REAL(wp) ::   ztintb       ! ratio applied to before records when doing time interpolation
168      CHARACTER(LEN=1000) ::   clfmt  ! write format
169      !!---------------------------------------------------------------------
170      ll_firstcall = kt == nit000
171      IF( PRESENT(kit) )   ll_firstcall = ll_firstcall .and. kit == 1
172
173      IF( nn_components == jp_iam_sas ) THEN   ;   zt_offset = REAL( nn_fsbc, wp )
174      ELSE                                     ;   zt_offset = 0.
175      ENDIF
176      IF( PRESENT(pt_offset) )   zt_offset = pt_offset
177
178      ! Note that all varibles starting by nsec_* are shifted time by +1/2 time step to be centrered
179      IF( PRESENT(kit) ) THEN   ! ignore kn_fsbc in this case
180         isecsbc = nsec_year + nsec1jan000 + NINT( (     REAL(      kit,wp) + zt_offset ) * rn_Dt / REAL(nn_e,wp) )
181      ELSE                      ! middle of sbc time step
182         ! note: we use kn_fsbc-1 because nsec_year is defined at the middle of the current time step
183         isecsbc = nsec_year + nsec1jan000 + NINT( ( 0.5*REAL(kn_fsbc-1,wp) + zt_offset ) * rn_Dt )
184      ENDIF
185      imf = SIZE( sd )
186      !
187      IF( ll_firstcall ) THEN                      ! initialization
188         DO jf = 1, imf 
189            IF( TRIM(sd(jf)%clrootname) == 'NOT USED' )   CYCLE
190            CALL fld_init( isecsbc, sd(jf) )       ! read each before field (put them in after as they will be swapped)
191         END DO
192         IF( lwp ) CALL wgt_print()                ! control print
193      ENDIF
194      !                                            ! ====================================== !
195      IF( MOD( kt-1, kn_fsbc ) == 0 ) THEN         ! update field at each kn_fsbc time-step !
196         !                                         ! ====================================== !
197         !
198         DO jf = 1, imf                            ! ---   loop over field   --- !
199            !
200            IF( TRIM(sd(jf)%clrootname) == 'NOT USED' )   CYCLE
201            CALL fld_update( isecsbc, sd(jf), Kmm )
202            !
203         END DO                                    ! --- end loop over field --- !
204
205         CALL fld_rot( kt, sd )                    ! rotate vector before/now/after fields if needed
206
207         DO jf = 1, imf                            ! ---   loop over field   --- !
208            !
209            IF( TRIM(sd(jf)%clrootname) == 'NOT USED' )   CYCLE
210            !
211            ibb = sd(jf)%nbb   ;   iaa = sd(jf)%naa
212            !
213            IF( sd(jf)%ln_tint ) THEN              ! temporal interpolation
214               IF(lwp .AND. ( kt - nit000 <= 20 .OR. nitend - kt <= 20 ) ) THEN
215                  clfmt = "('   fld_read: var ', a, ' kt = ', i8, ' (', f9.4,' days), Y/M/D = ', i4.4,'/', i2.2,'/', i2.2," //   &
216                     &    "', records b/a: ', i6.4, '/', i6.4, ' (days ', f9.4,'/', f9.4, ')')"
217                  WRITE(numout, clfmt)  TRIM( sd(jf)%clvar ), kt, REAL(isecsbc,wp)/rday, nyear, nmonth, nday,   &           
218                     & sd(jf)%nrec(1,ibb), sd(jf)%nrec(1,iaa), REAL(sd(jf)%nrec(2,ibb),wp)/rday, REAL(sd(jf)%nrec(2,iaa),wp)/rday
219                  IF( zt_offset /= 0._wp )   WRITE(numout, *) '      zt_offset is : ', zt_offset
220               ENDIF
221               ! temporal interpolation weights
222               ztinta =  REAL( isecsbc - sd(jf)%nrec(2,ibb), wp ) / REAL( sd(jf)%nrec(2,iaa) - sd(jf)%nrec(2,ibb), wp )
223               ztintb =  1. - ztinta
224               sd(jf)%fnow(:,:,:) = ztintb * sd(jf)%fdta(:,:,:,ibb) + ztinta * sd(jf)%fdta(:,:,:,iaa)
225            ELSE   ! nothing to do...
226               IF(lwp .AND. ( kt - nit000 <= 20 .OR. nitend - kt <= 20 ) ) THEN
227                  clfmt = "('   fld_read: var ', a, ' kt = ', i8,' (', f9.4,' days), Y/M/D = ', i4.4,'/', i2.2,'/', i2.2," //   &
228                     &    "', record: ', i6.4, ' (days ', f9.4, ' <-> ', f9.4, ')')"
229                  WRITE(numout, clfmt) TRIM(sd(jf)%clvar), kt, REAL(isecsbc,wp)/rday, nyear, nmonth, nday,    &
230                     &                 sd(jf)%nrec(1,iaa), REAL(sd(jf)%nrec(2,ibb),wp)/rday, REAL(sd(jf)%nrec(2,iaa),wp)/rday
231               ENDIF
232            ENDIF
233            !
234            IF( kt == nitend - kn_fsbc + 1 )   CALL iom_close( sd(jf)%num )   ! Close the input files
235
236         END DO                                    ! --- end loop over field --- !
237         !
238      ENDIF
239      !
240   END SUBROUTINE fld_read
241
242
243   SUBROUTINE fld_init( ksecsbc, sdjf )
244      !!---------------------------------------------------------------------
245      !!                    ***  ROUTINE fld_init  ***
246      !!
247      !! ** Purpose :  - first call(s) to fld_def to define before values
248      !!               - open file
249      !!----------------------------------------------------------------------
250      INTEGER  , INTENT(in   ) ::   ksecsbc   !
251      TYPE(FLD), INTENT(inout) ::   sdjf         ! input field related variables
252      !!---------------------------------------------------------------------
253      !
254      IF( nflag == 0 )   nflag = -HUGE(0)
255      !
256      CALL fld_def( sdjf )
257      IF( sdjf%ln_tint .AND. ksecsbc < sdjf%nrecsec(1) )   CALL fld_def( sdjf, ldprev = .TRUE. )
258      !
259      CALL fld_clopn( sdjf )
260      sdjf%nrec(:,sdjf%naa) = (/ 1, nflag /)  ! default definition to force flp_update to read the file.
261      !
262   END SUBROUTINE fld_init
263
264
265   SUBROUTINE fld_update( ksecsbc, sdjf, Kmm )
266      !!---------------------------------------------------------------------
267      !!                    ***  ROUTINE fld_update  ***
268      !!
269      !! ** Purpose : Compute
270      !!              if sdjf%ln_tint = .TRUE.
271      !!                  nrec(:,iaa): record number and its time (nrec(:,ibb) is obtained from nrec(:,iaa) when swapping)
272      !!              if sdjf%ln_tint = .FALSE.
273      !!                  nrec(1,iaa): record number
274      !!                  nrec(2,ibb) and nrec(2,iaa): time of the beginning and end of the record
275      !!----------------------------------------------------------------------
276      INTEGER  ,           INTENT(in   ) ::   ksecsbc   !
277      TYPE(FLD),           INTENT(inout) ::   sdjf      ! input field related variables
278      INTEGER  , OPTIONAL, INTENT(in   ) ::   Kmm    ! ocean time level index
279      !
280      INTEGER  ::   ja           ! end of this record (in seconds)
281      INTEGER  ::   ibb, iaa     ! shorter name for sdjf%nbb and sdjf%naa
282      !!----------------------------------------------------------------------
283      ibb = sdjf%nbb   ;   iaa = sdjf%naa
284      !
285      IF( ksecsbc > sdjf%nrec(2,iaa) ) THEN     ! --> we need to update after data
286       
287         ! find where is the new after record... (it is not necessary sdjf%nrec(1,iaa)+1 )
288         ja = sdjf%nrec(1,iaa)
289         DO WHILE ( ksecsbc >= sdjf%nrecsec(ja) .AND. ja < sdjf%nreclast )   ! Warning: make sure ja <= sdjf%nreclast in this test
290            ja = ja + 1
291         END DO
292         IF( ksecsbc > sdjf%nrecsec(ja) )   ja = ja + 1   ! in case ksecsbc > sdjf%nrecsec(sdjf%nreclast)
293
294         ! if ln_tint and if the new after is not ja+1, we need also to update after data before the swap
295         ! so, after the swap, sdjf%nrec(2,ibb) will still be the closest value located just before ksecsbc
296         IF( sdjf%ln_tint .AND. ( ja > sdjf%nrec(1,iaa) + 1 .OR. sdjf%nrec(2,iaa) == nflag ) ) THEN
297            sdjf%nrec(:,iaa) = (/ ja-1, sdjf%nrecsec(ja-1) /)   ! update nrec(:,iaa) with before information
298            CALL fld_get( sdjf, Kmm )                           ! read after data that will be used as before data
299         ENDIF
300           
301         ! if after is in the next file...
302         IF( ja > sdjf%nreclast ) THEN
303           
304            CALL fld_def( sdjf )
305            IF( ksecsbc > sdjf%nrecsec(sdjf%nreclast) )   CALL fld_def( sdjf, ldnext = .TRUE. )
306            CALL fld_clopn( sdjf )           ! open next file
307           
308            ! find where is after in this new file
309            ja = 1
310            DO WHILE ( ksecsbc > sdjf%nrecsec(ja) .AND. ja < sdjf%nreclast )
311               ja = ja + 1
312            END DO
313            IF( ksecsbc > sdjf%nrecsec(ja) )   ja = ja + 1   ! in case ksecsbc > sdjf%nrecsec(sdjf%nreclast)
314           
315            IF( ja > sdjf%nreclast ) THEN
316               CALL ctl_stop( "STOP", "fld_def: need next-next file? we should not be there... file: "//TRIM(sdjf%clrootname) )
317            ENDIF
318           
319            ! if ln_tint and if after is not the first record, we must (potentially again) update after data before the swap
320            IF( sdjf%ln_tint .AND. ja > 1 ) THEN
321               IF( sdjf%nrecsec(0) /= nflag ) THEN                    ! no trick used: after file is not the current file
322                  sdjf%nrec(:,iaa) = (/ ja-1, sdjf%nrecsec(ja-1) /)   ! update nrec(:,iaa) with before information
323                  CALL fld_get( sdjf, Kmm )                           ! read after data that will be used as before data
324               ENDIF
325            ENDIF
326           
327         ENDIF
328
329         IF( sdjf%ln_tint ) THEN                                ! Swap data
330            sdjf%nbb = sdjf%naa                                 !    swap indices
331            sdjf%naa = 3 - sdjf%naa                             !    = 2(1) if naa == 1(2)
332         ELSE                                                   ! No swap
333            sdjf%nrec(:,ibb) = (/ ja-1, sdjf%nrecsec(ja-1) /)   !    only for print
334         ENDIF
335           
336         ! read new after data
337         sdjf%nrec(:,sdjf%naa) = (/ ja, sdjf%nrecsec(ja) /)     ! update nrec(:,naa) as it is used by fld_get
338         CALL fld_get( sdjf, Kmm )                              ! read after data (with nrec(:,naa) informations)
339       
340      ENDIF
341      !
342   END SUBROUTINE fld_update
343
344
345   SUBROUTINE fld_get( sdjf, Kmm )
346      !!---------------------------------------------------------------------
347      !!                    ***  ROUTINE fld_get  ***
348      !!
349      !! ** Purpose :   read the data
350      !!----------------------------------------------------------------------
351      TYPE(FLD),           INTENT(inout) ::   sdjf   ! input field related variables
352      INTEGER  , OPTIONAL, INTENT(in   ) ::   Kmm    ! ocean time level index
353      !
354      INTEGER ::   ipk      ! number of vertical levels of sdjf%fdta ( 2D: ipk=1 ; 3D: ipk=jpk )
355      INTEGER ::   iaa      ! shorter name for sdjf%naa
356      INTEGER ::   iw       ! index into wgts array
357      INTEGER ::   idvar    ! variable ID
358      INTEGER ::   idmspc   ! number of spatial dimensions
359      LOGICAL ::   lmoor    ! C1D case: point data
360      REAL(dp), DIMENSION(:,:,:), POINTER ::   dta_alias   ! short cut
361      !!---------------------------------------------------------------------
362      iaa = sdjf%naa
363      !
364      IF( sdjf%ln_tint ) THEN   ;   dta_alias => sdjf%fdta(:,:,:,iaa)
365      ELSE                      ;   dta_alias => sdjf%fnow(:,:,:    )
366      ENDIF
367      ipk = SIZE( dta_alias, 3 )
368      !
369      IF( ASSOCIATED(sdjf%imap) ) THEN              ! BDY case
370         CALL fld_map( sdjf%num, sdjf%clvar, dta_alias(:,:,:), sdjf%nrec(1,iaa),   &
371            &          sdjf%imap, sdjf%igrd, sdjf%ibdy, sdjf%ltotvel, sdjf%lzint, Kmm )
372      ELSE IF( LEN(TRIM(sdjf%wgtname)) > 0 ) THEN   ! On-the-fly interpolation
373         CALL wgt_list( sdjf, iw )
374         CALL fld_interp( sdjf%num, sdjf%clvar, iw, ipk, dta_alias(:,:,:), sdjf%nrec(1,iaa), sdjf%lsmname )
375         CALL lbc_lnk( 'fldread', dta_alias(:,:,:), sdjf%cltype, CASTSP(sdjf%zsgn), kfillmode = jpfillcopy )
376      ELSE                                          ! default case
377         ! C1D case: If product of spatial dimensions == ipk, then x,y are of
378         ! size 1 (point/mooring data): this must be read onto the central grid point
379         idvar  = iom_varid( sdjf%num, sdjf%clvar )
380         idmspc = iom_file ( sdjf%num )%ndims( idvar )
381         IF( iom_file( sdjf%num )%luld( idvar ) )   idmspc = idmspc - 1   ! id of the last spatial dimension
382         lmoor  = (  idmspc == 0 .OR. PRODUCT( iom_file( sdjf%num )%dimsz( 1:MAX(idmspc,1) ,idvar ) ) == ipk  )   
383         !
384         IF( lk_c1d .AND. lmoor ) THEN
385            CALL iom_get( sdjf%num, jpdom_unknown, sdjf%clvar, dta_alias(2,2,:), sdjf%nrec(1,iaa) )   ! jpdom_unknown -> no lbc_lnk
386            CALL lbc_lnk( 'fldread', dta_alias(:,:,:), 'T', 1._wp, kfillmode = jpfillcopy )
387         ELSE
388            CALL iom_get( sdjf%num,  jpdom_global, sdjf%clvar, dta_alias(:,:,:), sdjf%nrec(1,iaa),   &
389               &          sdjf%cltype, CASTSP(sdjf%zsgn), kfill = jpfillcopy )
390         ENDIF
391      ENDIF
392      !
393      sdjf%rotn(iaa) = .false.   ! vector not yet rotated
394      !
395   END SUBROUTINE fld_get
396
397   
398   SUBROUTINE fld_map( knum, cdvar, pdta, krec, kmap, kgrd, kbdy, ldtotvel, ldzint, Kmm )
399      !!---------------------------------------------------------------------
400      !!                    ***  ROUTINE fld_map  ***
401      !!
402      !! ** Purpose :   read global data from file and map onto local data
403      !!                using a general mapping (for open boundaries)
404      !!----------------------------------------------------------------------
405      INTEGER                   , INTENT(in   ) ::   knum         ! stream number
406      CHARACTER(LEN=*)          , INTENT(in   ) ::   cdvar        ! variable name
407      REAL(dp), DIMENSION(:,:,:), INTENT(  out) ::   pdta         ! bdy output field on model grid
408      INTEGER                   , INTENT(in   ) ::   krec         ! record number to read (ie time slice)
409      INTEGER , DIMENSION(:)    , INTENT(in   ) ::   kmap         ! global-to-local bdy mapping indices
410      ! optional variables used for vertical interpolation:
411      INTEGER, OPTIONAL         , INTENT(in   ) ::   kgrd         ! grid type (t, u, v)
412      INTEGER, OPTIONAL         , INTENT(in   ) ::   kbdy         ! bdy number
413      LOGICAL, OPTIONAL         , INTENT(in   ) ::   ldtotvel     ! true if total ( = barotrop + barocline) velocity
414      LOGICAL, OPTIONAL         , INTENT(in   ) ::   ldzint       ! true if 3D variable requires a vertical interpolation
415      INTEGER, OPTIONAL         , INTENT(in   ) ::   Kmm          ! ocean time level index
416      !!
417      INTEGER                                   ::   ipi          ! length of boundary data on local process
418      INTEGER                                   ::   ipj          ! length of dummy dimension ( = 1 )
419      INTEGER                                   ::   ipk          ! number of vertical levels of pdta ( 2D: ipk=1 ; 3D: ipk=jpk )
420      INTEGER                                   ::   ipkb         ! number of vertical levels in boundary data file
421      INTEGER                                   ::   idvar        ! variable ID
422      INTEGER                                   ::   indims       ! number of dimensions of the variable
423      INTEGER, DIMENSION(4)                     ::   idimsz       ! size of variable dimensions
424      REAL(dp)                                  ::   zfv          ! fillvalue
425      REAL(dp), ALLOCATABLE, DIMENSION(:,:,:)   ::   zz_read      ! work space for global boundary data
426      REAL(dp), ALLOCATABLE, DIMENSION(:,:,:)   ::   zdta_read    ! work space local data requiring vertical interpolation
427      REAL(dp), ALLOCATABLE, DIMENSION(:,:,:)   ::   zdta_read_z  ! work space local data requiring vertical interpolation
428      REAL(dp), ALLOCATABLE, DIMENSION(:,:,:)   ::   zdta_read_dz ! work space local data requiring vertical interpolation
429      CHARACTER(LEN=1),DIMENSION(3)             ::   cltype
430      LOGICAL                                   ::   lluld        ! is the variable using the unlimited dimension
431      LOGICAL                                   ::   llzint       ! local value of ldzint
432      !!---------------------------------------------------------------------
433      !
434      cltype = (/'t','u','v'/)
435      !
436      ipi = SIZE( pdta, 1 )
437      ipj = SIZE( pdta, 2 )   ! must be equal to 1
438      ipk = SIZE( pdta, 3 )
439      !
440      llzint = .FALSE.
441      IF( PRESENT(ldzint) )   llzint = ldzint
442      !
443      idvar = iom_varid( knum, cdvar, kndims = indims, kdimsz = idimsz, lduld = lluld  )
444      IF( indims == 4 .OR. ( indims == 3 .AND. .NOT. lluld ) ) THEN   ;   ipkb = idimsz(3)   ! xy(zl)t or xy(zl)
445      ELSE                                                            ;   ipkb = 1           ! xy or xyt
446      ENDIF
447      !
448      ALLOCATE( zz_read( idimsz(1), idimsz(2), ipkb ) )  ! ++++++++ !!! this can be very big...         
449      !
450      IF( ipk == 1 ) THEN
451
452         IF( ipkb /= 1 ) CALL ctl_stop( 'fld_map : we must have ipkb = 1 to read surface data' )
453         CALL iom_get ( knum, jpdom_unknown, cdvar, zz_read(:,:,1), krec )   ! call iom_get with a 2D file
454         CALL fld_map_core( zz_read, kmap, pdta )
455
456      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
457      ! Do we include something here to adjust barotropic velocities !
458      ! in case of a depth difference between bdy files and          !
459      ! bathymetry in the case ln_totvel = .false. and ipkb>0?       !
460      ! [as the enveloping and parital cells could change H]         !
461      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
462
463      ELSE
464         !
465         CALL iom_get ( knum, jpdom_unknown, cdvar, zz_read(:,:,:), krec )   ! call iom_get with a 3D file
466         !
467         IF( ipkb /= ipk .OR. llzint ) THEN   ! boundary data not on model vertical grid : vertical interpolation
468            !
469            IF( ipk == jpk .AND. iom_varid(knum,'gdep'//cltype(kgrd)) /= -1 .AND. iom_varid(knum,'e3'//cltype(kgrd)) /= -1 ) THEN
470               
471               ALLOCATE( zdta_read(ipi,ipj,ipkb), zdta_read_z(ipi,ipj,ipkb), zdta_read_dz(ipi,ipj,ipkb) )
472               
473               CALL fld_map_core( zz_read, kmap, zdta_read )
474               CALL iom_get ( knum, jpdom_unknown, 'gdep'//cltype(kgrd), zz_read )   ! read only once? Potential temporal evolution?
475               CALL fld_map_core( zz_read, kmap, zdta_read_z )
476               CALL iom_get ( knum, jpdom_unknown,   'e3'//cltype(kgrd), zz_read )   ! read only once? Potential temporal evolution?
477               CALL fld_map_core( zz_read, kmap, zdta_read_dz )
478               
479               CALL iom_getatt(knum, '_FillValue', zfv, cdvar=cdvar )
480               CALL fld_bdy_interp(zdta_read, zdta_read_z, zdta_read_dz, pdta, kgrd, kbdy, zfv, ldtotvel, Kmm)
481               DEALLOCATE( zdta_read, zdta_read_z, zdta_read_dz )
482               
483            ELSE
484               IF( ipk /= jpk ) CALL ctl_stop( 'fld_map : this should be an impossible case...' )
485               WRITE(ctmp1,*) 'fld_map : vertical interpolation for bdy variable '//TRIM(cdvar)//' requires ' 
486               IF( iom_varid(knum, 'gdep'//cltype(kgrd)) == -1 ) CALL ctl_stop( ctmp1//'gdep'//cltype(kgrd)//' variable' )
487               IF( iom_varid(knum,   'e3'//cltype(kgrd)) == -1 ) CALL ctl_stop( ctmp1//  'e3'//cltype(kgrd)//' variable' )
488
489            ENDIF
490            !
491         ELSE                            ! bdy data assumed to be the same levels as bdy variables
492            !
493            CALL fld_map_core( zz_read, kmap, pdta )
494            !
495         ENDIF   ! ipkb /= ipk
496      ENDIF   ! ipk == 1
497     
498      DEALLOCATE( zz_read )
499
500   END SUBROUTINE fld_map
501
502     
503   SUBROUTINE fld_map_core( pdta_read, kmap, pdta_bdy )
504      !!---------------------------------------------------------------------
505      !!                    ***  ROUTINE fld_map_core  ***
506      !!
507      !! ** Purpose :  inner core of fld_map
508      !!----------------------------------------------------------------------
509      REAL(dp), DIMENSION(:,:,:), INTENT(in   ) ::   pdta_read    ! global boundary data
510      INTEGER,  DIMENSION(:    ), INTENT(in   ) ::   kmap         ! global-to-local bdy mapping indices
511      REAL(dp), DIMENSION(:,:,:), INTENT(  out) ::   pdta_bdy     ! bdy output field on model grid
512      !!
513      INTEGER,  DIMENSION(3) ::   idim_read,  idim_bdy            ! arrays dimensions
514      INTEGER                ::   ji, jj, jk, jb                  ! loop counters
515      INTEGER                ::   im1
516      !!---------------------------------------------------------------------
517      !
518      idim_read = SHAPE( pdta_read )
519      idim_bdy  = SHAPE( pdta_bdy  )
520      !
521      ! in all cases: idim_bdy(2) == 1 .AND. idim_read(1) * idim_read(2) == idim_bdy(1)
522      ! structured BDY with rimwidth > 1                     : idim_read(2) == rimwidth /= 1
523      ! structured BDY with rimwidth == 1 or unstructured BDY: idim_read(2) == 1
524      !
525      IF( idim_read(2) > 1 ) THEN    ! structured BDY with rimwidth > 1 
526         DO jk = 1, idim_bdy(3)
527            DO jb = 1, idim_bdy(1)
528               im1 = kmap(jb) - 1
529               jj = im1 / idim_read(1) + 1
530               ji = MOD( im1, idim_read(1) ) + 1
531               pdta_bdy(jb,1,jk) =  pdta_read(ji,jj,jk)
532            END DO
533         END DO
534      ELSE
535         DO jk = 1, idim_bdy(3)
536            DO jb = 1, idim_bdy(1)   ! horizontal remap of bdy data on the local bdy
537               pdta_bdy(jb,1,jk) = pdta_read(kmap(jb),1,jk)
538            END DO
539         END DO
540      ENDIF
541     
542   END SUBROUTINE fld_map_core
543   
544   SUBROUTINE fld_bdy_interp(pdta_read, pdta_read_z, pdta_read_dz, pdta, kgrd, kbdy, pfv, ldtotvel, Kmm )
545      !!---------------------------------------------------------------------
546      !!                    ***  ROUTINE fld_bdy_interp  ***
547      !!
548      !! ** Purpose :   on the fly vertical interpolation to allow the use of
549      !!                boundary data from non-native vertical grid
550      !!----------------------------------------------------------------------
551      USE bdy_oce, ONLY:  idx_bdy         ! indexing for map <-> ij transformation
552
553      REAL(dp), DIMENSION(:,:,:), INTENT(in   ) ::   pdta_read       ! data read in bdy file
554      REAL(dp), DIMENSION(:,:,:), INTENT(in   ) ::   pdta_read_z     ! depth of the data read in bdy file
555      REAL(dp), DIMENSION(:,:,:), INTENT(in   ) ::   pdta_read_dz    ! thickness of the levels in bdy file
556      REAL(dp), DIMENSION(:,:,:), INTENT(  out) ::   pdta            ! output field on model grid (2 dimensional)
557      REAL(dp)                  , INTENT(in   ) ::   pfv             ! fillvalue of the data read in bdy file
558      LOGICAL                   , INTENT(in   ) ::   ldtotvel        ! true if toal ( = barotrop + barocline) velocity
559      INTEGER                   , INTENT(in   ) ::   kgrd            ! grid type (t, u, v)
560      INTEGER                   , INTENT(in   ) ::   kbdy            ! bdy number
561      INTEGER, OPTIONAL         , INTENT(in   ) ::   Kmm             ! ocean time level index
562      !!
563      INTEGER                  ::   ipi                 ! length of boundary data on local process
564      INTEGER                  ::   ipkb                ! number of vertical levels in boundary data file
565      INTEGER                  ::   ipkmax              ! number of vertical levels in boundary data file where no mask
566      INTEGER                  ::   jb, ji, jj, jk, jkb ! loop counters
567      REAL(dp)                 ::   zcoef, zi           !
568      REAL(dp)                 ::   ztrans, ztrans_new  ! transports
569      REAL(dp), DIMENSION(jpk) ::   zdepth, zdhalf      ! level and half-level depth
570      !!---------------------------------------------------------------------
571     
572      ipi  = SIZE( pdta, 1 )
573      ipkb = SIZE( pdta_read, 3 )
574     
575      DO jb = 1, ipi
576         ji = idx_bdy(kbdy)%nbi(jb,kgrd)
577         jj = idx_bdy(kbdy)%nbj(jb,kgrd)
578         !
579         ! --- max jk where input data /= FillValue --- !
580         ipkmax = 1
581         DO jkb = 2, ipkb
582            IF( pdta_read(jb,1,jkb) /= pfv )   ipkmax = MAX( ipkmax, jkb )
583         END DO
584         !
585         ! --- calculate depth at t,u,v points --- !
586         SELECT CASE( kgrd )                         
587         CASE(1)            ! depth of T points:
588            zdepth(:) = gdept(ji,jj,:,Kmm)
589         CASE(2)            ! depth of U points: we must not use gdept_n as we don't want to do a communication
590            !                 --> copy what is done for gdept_n in domvvl...
591            zdhalf(1) = 0.0_wp
592            zdepth(1) = 0.5_wp * e3uw(ji,jj,1,Kmm)
593            DO jk = 2, jpk                               ! vertical sum
594               !    zcoef = umask - wumask    ! 0 everywhere tmask = wmask, ie everywhere expect at jk = mikt
595               !                              ! 1 everywhere from mbkt to mikt + 1 or 1 (if no isf)
596               !                              ! 0.5 where jk = mikt     
597               !!gm ???????   BUG ?  gdept_n as well as gde3w_n  does not include the thickness of ISF ??
598               zcoef = ( umask(ji,jj,jk) - wumask(ji,jj,jk) )
599               zdhalf(jk) = zdhalf(jk-1) + e3u(ji,jj,jk-1,Kmm)
600               zdepth(jk) =          zcoef  * ( zdhalf(jk  ) + 0.5_wp * e3uw(ji,jj,jk,Kmm))  &
601                  &         + (1._wp-zcoef) * ( zdepth(jk-1) +          e3uw(ji,jj,jk,Kmm))
602            END DO
603         CASE(3)            ! depth of V points: we must not use gdept_n as we don't want to do a communication
604            !                 --> copy what is done for gdept_n in domvvl...
605            zdhalf(1) = 0.0_wp
606            zdepth(1) = 0.5_wp * e3vw(ji,jj,1,Kmm)
607            DO jk = 2, jpk                               ! vertical sum
608               !    zcoef = vmask - wvmask    ! 0 everywhere tmask = wmask, ie everywhere expect at jk = mikt
609               !                              ! 1 everywhere from mbkt to mikt + 1 or 1 (if no isf)
610               !                              ! 0.5 where jk = mikt     
611               !!gm ???????   BUG ?  gdept_n as well as gde3w_n  does not include the thickness of ISF ??
612               zcoef = ( vmask(ji,jj,jk) - wvmask(ji,jj,jk) )
613               zdhalf(jk) = zdhalf(jk-1) + e3v(ji,jj,jk-1,Kmm)
614               zdepth(jk) =          zcoef  * ( zdhalf(jk  ) + 0.5_wp * e3vw(ji,jj,jk,Kmm))  &
615                     + (1._wp-zcoef) * ( zdepth(jk-1) +          e3vw(ji,jj,jk,Kmm))
616            END DO
617         END SELECT
618         !         
619         ! --- interpolate bdy data on the model grid --- !
620         DO jk = 1, jpk
621            IF(     zdepth(jk) <= pdta_read_z(jb,1,1)      ) THEN   ! above the first level of external data
622               pdta(jb,1,jk) = pdta_read(jb,1,1)
623            ELSEIF( zdepth(jk) >  pdta_read_z(jb,1,ipkmax) ) THEN   ! below the last level of external data /= FillValue
624               pdta(jb,1,jk) = pdta_read(jb,1,ipkmax)
625            ELSE                                                    ! inbetween: vertical interpolation between jkb & jkb+1
626               DO jkb = 1, ipkmax-1
627                  IF( ( ( zdepth(jk) - pdta_read_z(jb,1,jkb) ) * ( zdepth(jk) - pdta_read_z(jb,1,jkb+1) ) ) <= 0._wp ) THEN ! linear interpolation between 2 levels
628                     zi = ( zdepth(jk) - pdta_read_z(jb,1,jkb) ) / ( pdta_read_z(jb,1,jkb+1) - pdta_read_z(jb,1,jkb) )
629                     pdta(jb,1,jk) = pdta_read(jb,1,jkb) + zi * ( pdta_read(jb,1,jkb+1) - pdta_read(jb,1,jkb) )
630                  ENDIF
631               END DO
632            ENDIF
633         END DO   ! jpk
634         !
635      END DO   ! ipi
636
637      ! --- mask data and adjust transport --- !
638      SELECT CASE( kgrd )                         
639
640      CASE(1)                                 ! mask data (probably unecessary)
641         DO jb = 1, ipi
642            ji = idx_bdy(kbdy)%nbi(jb,kgrd)
643            jj = idx_bdy(kbdy)%nbj(jb,kgrd)
644            DO jk = 1, jpk                     
645               pdta(jb,1,jk) = pdta(jb,1,jk) * tmask(ji,jj,jk)
646            END DO
647         END DO
648         
649      CASE(2)                                 ! adjust the U-transport term
650         DO jb = 1, ipi
651            ji = idx_bdy(kbdy)%nbi(jb,kgrd)
652            jj = idx_bdy(kbdy)%nbj(jb,kgrd)
653            ztrans = 0._wp
654            DO jkb = 1, ipkb                              ! calculate transport on input grid
655               IF( pdta_read(jb,1,jkb) /= pfv )   ztrans = ztrans + pdta_read(jb,1,jkb) * pdta_read_dz(jb,1,jkb)
656            ENDDO
657            ztrans_new = 0._wp
658            DO jk = 1, jpk                                ! calculate transport on model grid
659               ztrans_new = ztrans_new +      pdta(jb,1,jk ) * e3u(ji,jj,jk,Kmm ) * umask(ji,jj,jk)
660            ENDDO
661            DO jk = 1, jpk                                ! make transport correction
662               IF(ldtotvel) THEN ! bdy data are total velocity so adjust bt transport term to match input data
663                  pdta(jb,1,jk) = ( pdta(jb,1,jk) + ( ztrans - ztrans_new ) * r1_hu(ji,jj,Kmm) ) * umask(ji,jj,jk)
664               ELSE              ! we're just dealing with bc velocity so bt transport term should sum to zero
665                  pdta(jb,1,jk) =   pdta(jb,1,jk) + (  0._wp - ztrans_new ) * r1_hu(ji,jj,Kmm)   * umask(ji,jj,jk)
666               ENDIF
667            ENDDO
668         ENDDO
669
670      CASE(3)                                 ! adjust the V-transport term
671         DO jb = 1, ipi
672            ji = idx_bdy(kbdy)%nbi(jb,kgrd)
673            jj = idx_bdy(kbdy)%nbj(jb,kgrd)
674            ztrans = 0._wp
675            DO jkb = 1, ipkb                              ! calculate transport on input grid
676               IF( pdta_read(jb,1,jkb) /= pfv )   ztrans = ztrans + pdta_read(jb,1,jkb) * pdta_read_dz(jb,1,jkb)
677            ENDDO
678            ztrans_new = 0._wp
679            DO jk = 1, jpk                                ! calculate transport on model grid
680               ztrans_new = ztrans_new +      pdta(jb,1,jk ) * e3v(ji,jj,jk,Kmm ) * vmask(ji,jj,jk)
681            ENDDO
682            DO jk = 1, jpk                                ! make transport correction
683               IF(ldtotvel) THEN ! bdy data are total velocity so adjust bt transport term to match input data
684                  pdta(jb,1,jk) = ( pdta(jb,1,jk) + ( ztrans - ztrans_new ) * r1_hv(ji,jj,Kmm) ) * vmask(ji,jj,jk)
685               ELSE              ! we're just dealing with bc velocity so bt transport term should sum to zero
686                  pdta(jb,1,jk) =   pdta(jb,1,jk) + (  0._wp - ztrans_new ) * r1_hv(ji,jj,Kmm)   * vmask(ji,jj,jk)
687               ENDIF
688            ENDDO
689         ENDDO
690      END SELECT
691     
692   END SUBROUTINE fld_bdy_interp
693
694
695   SUBROUTINE fld_rot( kt, sd )
696      !!---------------------------------------------------------------------
697      !!                    ***  ROUTINE fld_rot  ***
698      !!
699      !! ** Purpose :   Vector fields may need to be rotated onto the local grid direction
700      !!----------------------------------------------------------------------
701      INTEGER                , INTENT(in   ) ::   kt   ! ocean time step
702      TYPE(FLD), DIMENSION(:), INTENT(inout) ::   sd   ! input field related variables
703      !
704      INTEGER ::   ju, jv, jk, jn  ! loop indices
705      INTEGER ::   imf             ! size of the structure sd
706      INTEGER ::   ill             ! character length
707      INTEGER ::   iv              ! indice of V component
708      CHARACTER (LEN=100)          ::   clcomp       ! dummy weight name
709      REAL(dp), DIMENSION(jpi,jpj) ::   utmp, vtmp   ! temporary arrays for vector rotation
710      REAL(dp), DIMENSION(:,:,:), POINTER ::   dta_u, dta_v    ! short cut
711      !!---------------------------------------------------------------------
712      !
713      !! (sga: following code should be modified so that pairs arent searched for each time
714      !
715      imf = SIZE( sd )
716      DO ju = 1, imf
717         IF( TRIM(sd(ju)%clrootname) == 'NOT USED' )   CYCLE
718         ill = LEN_TRIM( sd(ju)%vcomp )
719         DO jn = 2-COUNT((/sd(ju)%ln_tint/)), 2
720            IF( ill > 0 .AND. .NOT. sd(ju)%rotn(jn) ) THEN   ! find vector rotations required             
721               IF( sd(ju)%vcomp(1:1) == 'U' ) THEN      ! east-west component has symbolic name starting with 'U'
722                  ! look for the north-south component which has same symbolic name but with 'U' replaced with 'V'
723                  clcomp = 'V' // sd(ju)%vcomp(2:ill)   ! works even if ill == 1
724                  iv = -1
725                  DO jv = 1, imf
726                     IF( TRIM(sd(jv)%clrootname) == 'NOT USED' )   CYCLE
727                     IF( TRIM(sd(jv)%vcomp) == TRIM(clcomp) )   iv = jv
728                  END DO
729                  IF( iv > 0 ) THEN   ! fields ju and iv are two components which need to be rotated together
730                     IF( sd(ju)%ln_tint ) THEN   ;   dta_u => sd(ju)%fdta(:,:,:,jn)   ;   dta_v => sd(iv)%fdta(:,:,:,jn) 
731                     ELSE                        ;   dta_u => sd(ju)%fnow(:,:,:   )   ;   dta_v => sd(iv)%fnow(:,:,:   )
732                     ENDIF
733                     DO jk = 1, SIZE( sd(ju)%fnow, 3 )
734                        CALL rot_rep( dta_u(:,:,jk), dta_v(:,:,jk), 'T', 'en->i', utmp(:,:) )
735                        CALL rot_rep( dta_u(:,:,jk), dta_v(:,:,jk), 'T', 'en->j', vtmp(:,:) )
736                        dta_u(:,:,jk) = utmp(:,:)   ;   dta_v(:,:,jk) = vtmp(:,:)
737                     END DO
738                     sd(ju)%rotn(jn) = .TRUE.               ! vector was rotated
739                     IF( lwp .AND. kt == nit000 )   WRITE(numout,*)   &
740                        &   'fld_read: vector pair ('//TRIM(sd(ju)%clvar)//', '//TRIM(sd(iv)%clvar)//') rotated on to model grid'
741                  ENDIF
742               ENDIF
743            ENDIF
744         END DO
745       END DO
746      !
747   END SUBROUTINE fld_rot
748
749
750   SUBROUTINE fld_def( sdjf, ldprev, ldnext )
751      !!---------------------------------------------------------------------
752      !!                    ***  ROUTINE fld_def  ***
753      !!
754      !! ** Purpose :   define the record(s) of the file and its name
755      !!----------------------------------------------------------------------
756      TYPE(FLD)        , INTENT(inout) ::   sdjf       ! input field related variables
757      LOGICAL, OPTIONAL, INTENT(in   ) ::   ldprev     !
758      LOGICAL, OPTIONAL, INTENT(in   ) ::   ldnext     !
759      !
760      INTEGER  :: jt
761      INTEGER  :: idaysec               ! number of seconds in 1 day = NINT(rday)
762      INTEGER  :: iyr, imt, idy, isecwk
763      INTEGER  :: indexyr, indexmt
764      INTEGER  :: ireclast
765      INTEGER  :: ishift, istart
766      INTEGER, DIMENSION(2)  :: isave
767      REAL(wp) :: zfreqs
768      LOGICAL  :: llprev, llnext, llstop
769      LOGICAL  :: llprevmt, llprevyr
770      LOGICAL  :: llnextmt, llnextyr
771      !!----------------------------------------------------------------------
772      idaysec = NINT(rday)
773      !
774      IF( PRESENT(ldprev) ) THEN   ;   llprev = ldprev
775      ELSE                         ;   llprev = .FALSE.
776      ENDIF
777      IF( PRESENT(ldnext) ) THEN   ;   llnext = ldnext
778      ELSE                         ;   llnext = .FALSE.
779      ENDIF
780
781      ! current file parameters
782      IF( sdjf%clftyp(1:4) == 'week' ) THEN         ! find the day of the beginning of the current week
783         isecwk = ksec_week( sdjf%clftyp(6:8) )     ! seconds between the beginning of the week and half of current time step
784         llprevmt = isecwk > nsec_month             ! longer time since beginning of the current week than the current month
785         llprevyr = llprevmt .AND. nmonth == 1
786         iyr = nyear  - COUNT((/llprevyr/))
787         imt = nmonth - COUNT((/llprevmt/)) + 12 * COUNT((/llprevyr/))
788         idy = nday + nmonth_len(nmonth-1) * COUNT((/llprevmt/)) - isecwk / idaysec
789         isecwk = nsec_year - isecwk                ! seconds between 00h jan 1st of current year and current week beginning
790      ELSE
791         iyr = nyear
792         imt = nmonth
793         idy = nday
794         isecwk  = 0
795      ENDIF
796
797      ! previous file parameters
798      IF( llprev ) THEN
799         IF( sdjf%clftyp(1:4) == 'week'    ) THEN   ! find the day of the beginning of previous week
800            isecwk = isecwk + 7 * idaysec           ! seconds between the beginning of previous week and half of the time step
801            llprevmt = isecwk > nsec_month          ! longer time since beginning of the previous week than the current month
802            llprevyr = llprevmt .AND. nmonth == 1
803            iyr = nyear  - COUNT((/llprevyr/))
804            imt = nmonth - COUNT((/llprevmt/)) + 12 * COUNT((/llprevyr/))
805            idy = nday + nmonth_len(nmonth-1) * COUNT((/llprevmt/)) - isecwk / idaysec
806            isecwk = nsec_year - isecwk             ! seconds between 00h jan 1st of current year and previous week beginning
807         ELSE
808            idy = nday   - COUNT((/ sdjf%clftyp == 'daily'                 /))
809            imt = nmonth - COUNT((/ sdjf%clftyp == 'monthly' .OR. idy == 0 /))
810            iyr = nyear  - COUNT((/ sdjf%clftyp == 'yearly'  .OR. imt == 0 /))
811            IF( idy == 0 ) idy = nmonth_len(imt)
812            IF( imt == 0 ) imt = 12
813            isecwk = 0
814         ENDIF
815      ENDIF
816
817      ! next file parameters
818      IF( llnext ) THEN
819         IF( sdjf%clftyp(1:4) == 'week'    ) THEN   ! find the day of the beginning of next week
820            isecwk = 7 * idaysec - isecwk           ! seconds between half of the time step and the beginning of next week
821            llnextmt = isecwk > ( nmonth_len(nmonth)*idaysec - nsec_month )   ! larger than the seconds to the end of the month
822            llnextyr = llnextmt .AND. nmonth == 12
823            iyr = nyear  + COUNT((/llnextyr/))
824            imt = nmonth + COUNT((/llnextmt/)) - 12 * COUNT((/llnextyr/))
825            idy = nday - nmonth_len(nmonth) * COUNT((/llnextmt/)) + isecwk / idaysec + 1
826            isecwk = nsec_year + isecwk             ! seconds between 00h jan 1st of current year and next week beginning
827         ELSE
828            idy = nday   + COUNT((/ sdjf%clftyp == 'daily'                                 /))
829            imt = nmonth + COUNT((/ sdjf%clftyp == 'monthly' .OR. idy > nmonth_len(nmonth) /))
830            iyr = nyear  + COUNT((/ sdjf%clftyp == 'yearly'  .OR. imt == 13                /))
831            IF( idy > nmonth_len(nmonth) )   idy = 1
832            IF( imt == 13                )   imt = 1
833            isecwk = 0
834         ENDIF
835      ENDIF
836      !
837      ! find the last record to be read -> update sdjf%nreclast
838      indexyr = iyr - nyear + 1                 ! which  year are we looking for? previous(0), current(1) or next(2)?
839      indexmt = imt + 12 * ( indexyr - 1 )      ! which month are we looking for (relatively to current year)?
840      !
841      ! Last record to be read in the current file
842      ! Predefine the number of record in the file according of its type.
843      ! We could compare this number with the number of records in the file and make a stop if the 2 numbers do not match...
844      ! However this would be much less fexible (e.g. for tests) and will force to rewite input files according to nleapy...
845      IF    ( NINT(sdjf%freqh) == -12 ) THEN            ;   ireclast = 1    ! yearly mean: consider only 1 record
846      ELSEIF( NINT(sdjf%freqh) ==  -1 ) THEN                                ! monthly mean:
847         IF(     sdjf%clftyp      == 'monthly' ) THEN   ;   ireclast = 1    !  consider that the file has  1 record
848         ELSE                                           ;   ireclast = 12   !  consider that the file has 12 record
849         ENDIF
850      ELSE                                                                  ! higher frequency mean (in hours)
851         IF(     sdjf%clftyp      == 'monthly' ) THEN   ;   ireclast = NINT( 24. * REAL(nmonth_len(indexmt), wp) / sdjf%freqh )
852         ELSEIF( sdjf%clftyp(1:4) == 'week'    ) THEN   ;   ireclast = NINT( 24. * 7.                            / sdjf%freqh )
853         ELSEIF( sdjf%clftyp      == 'daily'   ) THEN   ;   ireclast = NINT( 24.                                 / sdjf%freqh )
854         ELSE                                           ;   ireclast = NINT( 24. * REAL( nyear_len(indexyr), wp) / sdjf%freqh )
855         ENDIF
856      ENDIF
857
858      sdjf%nreclast = ireclast
859      ! Allocate arrays for beginning/middle/end of each record (seconds since Jan. 1st 00h of nit000 year)
860      IF( ALLOCATED(sdjf%nrecsec) )   DEALLOCATE( sdjf%nrecsec )
861      ALLOCATE( sdjf%nrecsec( 0:ireclast ) )
862      !
863      IF    ( NINT(sdjf%freqh) == -12 ) THEN                                     ! yearly mean and yearly file
864         SELECT CASE( indexyr )
865         CASE(0)   ;   sdjf%nrecsec(0) = nsec1jan000 - nyear_len( 0 ) * idaysec
866         CASE(1)   ;   sdjf%nrecsec(0) = nsec1jan000
867         CASE(2)   ;   sdjf%nrecsec(0) = nsec1jan000 + nyear_len( 1 ) * idaysec
868         ENDSELECT
869         sdjf%nrecsec(1) = sdjf%nrecsec(0) + nyear_len( indexyr ) * idaysec
870      ELSEIF( NINT(sdjf%freqh) ==  -1 ) THEN                                     ! monthly mean:
871         IF(     sdjf%clftyp      == 'monthly' ) THEN                            !    monthly file
872            sdjf%nrecsec(0   ) = nsec1jan000 + nmonth_beg(indexmt  )
873            sdjf%nrecsec(1   ) = nsec1jan000 + nmonth_beg(indexmt+1)
874         ELSE                                                                    !    yearly  file
875            ishift = 12 * ( indexyr - 1 )
876            sdjf%nrecsec(0:12) = nsec1jan000 + nmonth_beg(1+ishift:13+ishift)
877         ENDIF
878      ELSE                                                                       ! higher frequency mean (in hours)
879         IF(     sdjf%clftyp      == 'monthly' ) THEN   ;   istart = nsec1jan000 + nmonth_beg(indexmt)
880         ELSEIF( sdjf%clftyp(1:4) == 'week'    ) THEN   ;   istart = nsec1jan000 + isecwk
881         ELSEIF( sdjf%clftyp      == 'daily'   ) THEN   ;   istart = nsec1jan000 + nmonth_beg(indexmt) + ( idy - 1 ) * idaysec
882         ELSEIF( indexyr          == 0         ) THEN   ;   istart = nsec1jan000 - nyear_len( 0 ) * idaysec
883         ELSEIF( indexyr          == 2         ) THEN   ;   istart = nsec1jan000 + nyear_len( 1 ) * idaysec
884         ELSE                                           ;   istart = nsec1jan000
885         ENDIF
886         zfreqs = sdjf%freqh * rhhmm * rmmss
887         DO jt = 0, sdjf%nreclast
888            sdjf%nrecsec(jt) = istart + NINT( zfreqs * REAL(jt,wp) )
889         END DO
890      ENDIF
891      !
892      IF( sdjf%ln_tint ) THEN   ! record time defined in the middle of the record, computed using an implementation
893                                ! of the rounded average that is valid over the full integer range
894         sdjf%nrecsec(1:sdjf%nreclast) = sdjf%nrecsec(0:sdjf%nreclast-1) / 2 + sdjf%nrecsec(1:sdjf%nreclast) / 2 + &
895            & MAX( MOD( sdjf%nrecsec(0:sdjf%nreclast-1), 2 ), MOD( sdjf%nrecsec(1:sdjf%nreclast), 2 ) )
896      END IF
897      !
898      sdjf%clname = fld_filename( sdjf, idy, imt, iyr )
899      !
900   END SUBROUTINE fld_def
901
902   
903   SUBROUTINE fld_clopn( sdjf )
904      !!---------------------------------------------------------------------
905      !!                    ***  ROUTINE fld_clopn  ***
906      !!
907      !! ** Purpose :   close/open the files
908      !!----------------------------------------------------------------------
909      TYPE(FLD)        , INTENT(inout) ::   sdjf       ! input field related variables
910      !
911      INTEGER  :: isave
912      LOGICAL  :: llprev, llnext, llstop
913      !!----------------------------------------------------------------------
914      !
915      llprev = sdjf%nrecsec(sdjf%nreclast) < nsec000_1jan000   ! file ends before the beginning of the job -> file may not exist
916      llnext = sdjf%nrecsec(      1      ) > nsecend_1jan000   ! file begins after the end of the job -> file may not exist
917
918      llstop = sdjf%ln_clim .OR. .NOT. ( llprev .OR. llnext )
919
920      IF( sdjf%num <= 0 .OR. .NOT. sdjf%ln_clim  ) THEN
921         IF( sdjf%num > 0 )   CALL iom_close( sdjf%num )   ! close file if already open
922         CALL iom_open( sdjf%clname, sdjf%num, ldstop = llstop, ldiof = LEN_TRIM(sdjf%wgtname) > 0 )
923      ENDIF
924      !
925      IF( sdjf%num <= 0 .AND. .NOT. llstop ) THEN   ! file not found but we do accept this...
926         !
927         IF( llprev ) THEN   ! previous file does not exist : go back to current and accept to read only the first record
928            CALL ctl_warn('previous file: '//TRIM(sdjf%clname)//' not found -> go back to current year/month/week/day file')
929            isave = sdjf%nrecsec(sdjf%nreclast)   ! save previous file info
930            CALL fld_def( sdjf )                  ! go back to current file
931            sdjf%nreclast = 1                     ! force to use only the first record (do as if other were not existing...)
932         ENDIF
933         !
934         IF( llnext ) THEN   ! next     file does not exist : go back to current and accept to read only the last  record
935            CALL ctl_warn('next file: '//TRIM(sdjf%clname)//' not found -> go back to current year/month/week/day file')
936            isave = sdjf%nrecsec(1)               ! save next file info
937            CALL fld_def( sdjf )                  ! go back to current file
938         ENDIF
939         ! -> read "last" record but keep record info from the first record of next file
940         sdjf%nrecsec(  sdjf%nreclast  ) = isave
941         sdjf%nrecsec(0:sdjf%nreclast-1) = nflag
942         !
943         CALL iom_open( sdjf%clname, sdjf%num, ldiof = LEN_TRIM(sdjf%wgtname) > 0 )   
944         !
945      ENDIF
946      !
947   END SUBROUTINE fld_clopn
948
949
950   SUBROUTINE fld_fill( sdf, sdf_n, cdir, cdcaller, cdtitle, cdnam, knoprint )
951      !!---------------------------------------------------------------------
952      !!                    ***  ROUTINE fld_fill  ***
953      !!
954      !! ** Purpose :   fill the data structure (sdf) with the associated information
955      !!              read in namelist (sdf_n) and control print
956      !!----------------------------------------------------------------------
957      TYPE(FLD)  , DIMENSION(:)          , INTENT(inout) ::   sdf        ! structure of input fields (file informations, fields read)
958      TYPE(FLD_N), DIMENSION(:)          , INTENT(in   ) ::   sdf_n      ! array of namelist information structures
959      CHARACTER(len=*)                   , INTENT(in   ) ::   cdir       ! Root directory for location of flx files
960      CHARACTER(len=*)                   , INTENT(in   ) ::   cdcaller   ! name of the calling routine
961      CHARACTER(len=*)                   , INTENT(in   ) ::   cdtitle    ! description of the calling routine
962      CHARACTER(len=*)                   , INTENT(in   ) ::   cdnam      ! name of the namelist from which sdf_n comes
963      INTEGER                  , OPTIONAL, INTENT(in   ) ::   knoprint   ! no calling routine information printed
964      !
965      INTEGER  ::   jf   ! dummy indices
966      !!---------------------------------------------------------------------
967      !
968      DO jf = 1, SIZE(sdf)
969         sdf(jf)%clrootname = sdf_n(jf)%clname
970         IF( TRIM(sdf_n(jf)%clname) /= 'NOT USED' )   sdf(jf)%clrootname = TRIM( cdir )//sdf(jf)%clrootname
971         sdf(jf)%clname     = "not yet defined"
972         sdf(jf)%freqh      = sdf_n(jf)%freqh
973         sdf(jf)%clvar      = sdf_n(jf)%clvar
974         sdf(jf)%ln_tint    = sdf_n(jf)%ln_tint
975         sdf(jf)%ln_clim    = sdf_n(jf)%ln_clim
976         sdf(jf)%clftyp     = sdf_n(jf)%clftyp
977         sdf(jf)%cltype     = 'T'   ! by default don't do any call to lbc_lnk in iom_get
978         sdf(jf)%zsgn       = 1.    ! by default don't do change signe across the north fold
979         sdf(jf)%num        = -1
980         sdf(jf)%nbb        = 1  ! start with before data in 1
981         sdf(jf)%naa        = 2  ! start with after  data in 2
982         sdf(jf)%wgtname    = " "
983         IF( LEN( TRIM(sdf_n(jf)%wname) ) > 0 )   sdf(jf)%wgtname = TRIM( cdir )//sdf_n(jf)%wname
984         sdf(jf)%lsmname = " "
985         IF( LEN( TRIM(sdf_n(jf)%lname) ) > 0 )   sdf(jf)%lsmname = TRIM( cdir )//sdf_n(jf)%lname
986         sdf(jf)%vcomp      = sdf_n(jf)%vcomp
987         sdf(jf)%rotn(:)    = .TRUE.   ! pretend to be rotated -> won't try to rotate data before the first call to fld_get
988         IF( sdf(jf)%clftyp(1:4) == 'week' .AND. nn_leapy == 0  )   &
989            &   CALL ctl_stop('fld_clopn: weekly file ('//TRIM(sdf(jf)%clrootname)//') needs nn_leapy = 1')
990         IF( sdf(jf)%clftyp(1:4) == 'week' .AND. sdf(jf)%ln_clim )   &
991            &   CALL ctl_stop('fld_clopn: weekly file ('//TRIM(sdf(jf)%clrootname)//') needs ln_clim = .FALSE.')
992         sdf(jf)%nreclast   = -1 ! Set to non zero default value to avoid errors, is updated to meaningful value during fld_clopn
993         sdf(jf)%igrd       = 0
994         sdf(jf)%ibdy       = 0
995         sdf(jf)%imap       => NULL()
996         sdf(jf)%ltotvel    = .FALSE.
997         sdf(jf)%lzint      = .FALSE.
998      END DO
999      !
1000      IF(lwp) THEN      ! control print
1001         WRITE(numout,*)
1002         IF( .NOT.PRESENT( knoprint) ) THEN
1003            WRITE(numout,*) TRIM( cdcaller )//' : '//TRIM( cdtitle )
1004            WRITE(numout,*) (/ ('~', jf = 1, LEN_TRIM( cdcaller ) ) /)
1005         ENDIF
1006         WRITE(numout,*) '   fld_fill : fill data structure with information from namelist '//TRIM( cdnam )
1007         WRITE(numout,*) '   ~~~~~~~~'
1008         WRITE(numout,*) '      list of files and frequency (>0: in hours ; <0 in months)'
1009         DO jf = 1, SIZE(sdf)
1010            WRITE(numout,*) '      root filename: '  , TRIM( sdf(jf)%clrootname ), '   variable name: ', TRIM( sdf(jf)%clvar )
1011            WRITE(numout,*) '         frequency: '      ,       sdf(jf)%freqh       ,   &
1012               &                  '   time interp: '    ,       sdf(jf)%ln_tint     ,   &
1013               &                  '   climatology: '    ,       sdf(jf)%ln_clim
1014            WRITE(numout,*) '         weights: '        , TRIM( sdf(jf)%wgtname    ),   &
1015               &                  '   pairing: '        , TRIM( sdf(jf)%vcomp      ),   &
1016               &                  '   data type: '      ,       sdf(jf)%clftyp      ,   &
1017               &                  '   land/sea mask:'   , TRIM( sdf(jf)%lsmname    )
1018            call flush(numout)
1019         END DO
1020      ENDIF
1021      !
1022   END SUBROUTINE fld_fill
1023
1024
1025   SUBROUTINE wgt_list( sd, kwgt )
1026      !!---------------------------------------------------------------------
1027      !!                    ***  ROUTINE wgt_list  ***
1028      !!
1029      !! ** Purpose :   search array of WGTs and find a weights file entry,
1030      !!                or return a new one adding it to the end if new entry.
1031      !!                the weights data is read in and restructured (fld_weight)
1032      !!----------------------------------------------------------------------
1033      TYPE( FLD ), INTENT(in   ) ::   sd        ! field with name of weights file
1034      INTEGER    , INTENT(  out) ::   kwgt      ! index of weights
1035      !
1036      INTEGER ::   kw, nestid   ! local integer
1037      !!----------------------------------------------------------------------
1038      !
1039      !! search down linked list
1040      !! weights filename is either present or we hit the end of the list
1041      !
1042      !! because agrif nest part of filenames are now added in iom_open
1043      !! to distinguish between weights files on the different grids, need to track
1044      !! nest number explicitly
1045      nestid = 0
1046#if defined key_agrif
1047      nestid = Agrif_Fixed()
1048#endif
1049      DO kw = 1, nxt_wgt-1
1050         IF( ref_wgts(kw)%wgtname == sd%wgtname .AND. &
1051             ref_wgts(kw)%nestid  == nestid) THEN
1052            kwgt = kw
1053            RETURN
1054         ENDIF
1055      END DO
1056      kwgt = nxt_wgt
1057      CALL fld_weight( sd )
1058      !
1059   END SUBROUTINE wgt_list
1060
1061
1062   SUBROUTINE wgt_print( )
1063      !!---------------------------------------------------------------------
1064      !!                    ***  ROUTINE wgt_print  ***
1065      !!
1066      !! ** Purpose :   print the list of known weights
1067      !!----------------------------------------------------------------------
1068      INTEGER ::   kw   !
1069      !!----------------------------------------------------------------------
1070      !
1071      DO kw = 1, nxt_wgt-1
1072         WRITE(numout,*) 'weight file:  ',TRIM(ref_wgts(kw)%wgtname)
1073         WRITE(numout,*) '      ddims:  ',ref_wgts(kw)%ddims(1),ref_wgts(kw)%ddims(2)
1074         WRITE(numout,*) '     numwgt:  ',ref_wgts(kw)%numwgt
1075         WRITE(numout,*) '     jpiwgt:  ',ref_wgts(kw)%jpiwgt
1076         WRITE(numout,*) '     jpjwgt:  ',ref_wgts(kw)%jpjwgt
1077         WRITE(numout,*) '    botleft:  ',ref_wgts(kw)%botleft
1078         WRITE(numout,*) '   topright:  ',ref_wgts(kw)%topright
1079         IF( ref_wgts(kw)%cyclic ) THEN
1080            WRITE(numout,*) '       cyclical'
1081            IF( ref_wgts(kw)%overlap > 0 ) WRITE(numout,*) '              with overlap of ', ref_wgts(kw)%overlap
1082         ELSE
1083            WRITE(numout,*) '       not cyclical'
1084         ENDIF
1085         IF( ASSOCIATED(ref_wgts(kw)%data_wgt) )  WRITE(numout,*) '       allocated'
1086      END DO
1087      !
1088   END SUBROUTINE wgt_print
1089
1090
1091   SUBROUTINE fld_weight( sd )
1092      !!---------------------------------------------------------------------
1093      !!                    ***  ROUTINE fld_weight  ***
1094      !!
1095      !! ** Purpose :   create a new WGT structure and fill in data from file,
1096      !!              restructuring as required
1097      !!----------------------------------------------------------------------
1098      TYPE( FLD ), INTENT(in) ::   sd   ! field with name of weights file
1099      !!
1100      INTEGER ::   ji,jj,jn   ! dummy loop indices
1101      INTEGER ::   inum       ! local logical unit
1102      INTEGER ::   id         ! local variable id
1103      INTEGER ::   ipk        ! local vertical dimension
1104      INTEGER ::   zwrap      ! local integer
1105      LOGICAL ::   cyclical   !
1106      CHARACTER (len=5) ::   clname   !
1107      INTEGER , DIMENSION(4) ::   ddims
1108      INTEGER                ::   isrc
1109      REAL(dp), DIMENSION(jpi,jpj) ::   data_tmp
1110      !!----------------------------------------------------------------------
1111      !
1112      IF( nxt_wgt > tot_wgts ) THEN
1113        CALL ctl_stop("fld_weight: weights array size exceeded, increase tot_wgts")
1114      ENDIF
1115      !
1116      !! new weights file entry, add in extra information
1117      !! a weights file represents a 2D grid of a certain shape, so we assume that the current
1118      !! input data file is representative of all other files to be opened and processed with the
1119      !! current weights file
1120
1121      !! get data grid dimensions
1122      id = iom_varid( sd%num, sd%clvar, ddims )
1123
1124      !! now open the weights file
1125      CALL iom_open ( sd%wgtname, inum )   ! interpolation weights
1126      IF( inum > 0 ) THEN
1127
1128         !! determine whether we have an east-west cyclic grid
1129         !! from global attribute called "ew_wrap" in the weights file
1130         !! note that if not found, iom_getatt returns -999 and cyclic with no overlap is assumed
1131         !! since this is the most common forcing configuration
1132
1133         CALL iom_getatt(inum, 'ew_wrap', zwrap)
1134         IF( zwrap >= 0 ) THEN
1135            cyclical = .TRUE.
1136         ELSE IF( zwrap == -999 ) THEN
1137            cyclical = .TRUE.
1138            zwrap = 0
1139         ELSE
1140            cyclical = .FALSE.
1141         ENDIF
1142
1143         ref_wgts(nxt_wgt)%ddims(1) = ddims(1)
1144         ref_wgts(nxt_wgt)%ddims(2) = ddims(2)
1145         ref_wgts(nxt_wgt)%wgtname = sd%wgtname
1146         ref_wgts(nxt_wgt)%overlap = zwrap
1147         ref_wgts(nxt_wgt)%cyclic = cyclical
1148         ref_wgts(nxt_wgt)%nestid = 0
1149#if defined key_agrif
1150         ref_wgts(nxt_wgt)%nestid = Agrif_Fixed()
1151#endif
1152         !! weights file is stored as a set of weights (wgt01->wgt04 or wgt01->wgt16)
1153         !! for each weight wgtNN there is an integer array srcNN which gives the point in
1154         !! the input data grid which is to be multiplied by the weight
1155         !! they are both arrays on the model grid so the result of the multiplication is
1156         !! added into an output array on the model grid as a running sum
1157
1158         !! two possible cases: bilinear (4 weights) or bicubic (16 weights)
1159         id = iom_varid(inum, 'src05', ldstop=.FALSE.)
1160         IF( id <= 0 ) THEN   ;   ref_wgts(nxt_wgt)%numwgt = 4
1161         ELSE                 ;   ref_wgts(nxt_wgt)%numwgt = 16
1162         ENDIF
1163
1164         ALLOCATE( ref_wgts(nxt_wgt)%data_jpi(Nis0:Nie0,Njs0:Nje0,4) )
1165         ALLOCATE( ref_wgts(nxt_wgt)%data_jpj(Nis0:Nie0,Njs0:Nje0,4) )
1166         ALLOCATE( ref_wgts(nxt_wgt)%data_wgt(Nis0:Nie0,Njs0:Nje0,ref_wgts(nxt_wgt)%numwgt) )
1167
1168         DO jn = 1,4
1169            WRITE(clname,'(a3,i2.2)') 'src',jn
1170            CALL iom_get ( inum, jpdom_global, clname, data_tmp(:,:), cd_type = 'Z' )   !  no call to lbc_lnk
1171            DO_2D( 0, 0, 0, 0 )
1172               isrc = NINT(data_tmp(ji,jj)) - 1
1173               ref_wgts(nxt_wgt)%data_jpi(ji,jj,jn) = 1 + MOD(isrc,  ref_wgts(nxt_wgt)%ddims(1))
1174               ref_wgts(nxt_wgt)%data_jpj(ji,jj,jn) = 1 +     isrc / ref_wgts(nxt_wgt)%ddims(1)
1175            END_2D
1176         END DO
1177
1178         DO jn = 1, ref_wgts(nxt_wgt)%numwgt
1179            WRITE(clname,'(a3,i2.2)') 'wgt',jn
1180            CALL iom_get ( inum, jpdom_global, clname, data_tmp(:,:), cd_type = 'Z' )   !  no call to lbc_lnk
1181            DO_2D( 0, 0, 0, 0 )
1182               ref_wgts(nxt_wgt)%data_wgt(ji,jj,jn) = data_tmp(ji,jj)
1183            END_2D
1184         END DO
1185         CALL iom_close (inum)
1186 
1187         ! find min and max indices in grid
1188         ref_wgts(nxt_wgt)%botleft( 1) = MINVAL(ref_wgts(nxt_wgt)%data_jpi(:,:,:))
1189         ref_wgts(nxt_wgt)%botleft( 2) = MINVAL(ref_wgts(nxt_wgt)%data_jpj(:,:,:))
1190         ref_wgts(nxt_wgt)%topright(1) = MAXVAL(ref_wgts(nxt_wgt)%data_jpi(:,:,:))
1191         ref_wgts(nxt_wgt)%topright(2) = MAXVAL(ref_wgts(nxt_wgt)%data_jpj(:,:,:))
1192
1193         ! and therefore dimensions of the input box
1194         ref_wgts(nxt_wgt)%jpiwgt = ref_wgts(nxt_wgt)%topright(1) - ref_wgts(nxt_wgt)%botleft(1) + 1
1195         ref_wgts(nxt_wgt)%jpjwgt = ref_wgts(nxt_wgt)%topright(2) - ref_wgts(nxt_wgt)%botleft(2) + 1
1196
1197         ! shift indexing of source grid
1198         ref_wgts(nxt_wgt)%data_jpi(:,:,:) = ref_wgts(nxt_wgt)%data_jpi(:,:,:) - ref_wgts(nxt_wgt)%botleft(1) + 1
1199         ref_wgts(nxt_wgt)%data_jpj(:,:,:) = ref_wgts(nxt_wgt)%data_jpj(:,:,:) - ref_wgts(nxt_wgt)%botleft(2) + 1
1200
1201         ! create input grid, give it a halo to allow gradient calculations
1202         ! SA: +3 stencil is a patch to avoid out-of-bound computation in some configuration.
1203         ! a more robust solution will be given in next release
1204         ipk =  SIZE(sd%fnow, 3)
1205         ALLOCATE( ref_wgts(nxt_wgt)%fly_dta(ref_wgts(nxt_wgt)%jpiwgt+3, ref_wgts(nxt_wgt)%jpjwgt+3 ,ipk) )
1206         IF( ref_wgts(nxt_wgt)%cyclic ) ALLOCATE( ref_wgts(nxt_wgt)%col(1,ref_wgts(nxt_wgt)%jpjwgt+3,ipk) )
1207         !
1208         nxt_wgt = nxt_wgt + 1
1209         !
1210      ELSE
1211         CALL ctl_stop( '    fld_weight : unable to read the file ' )
1212      ENDIF
1213      !
1214   END SUBROUTINE fld_weight
1215
1216
1217   SUBROUTINE apply_seaoverland( clmaskfile, zfieldo, jpi1_lsm, jpi2_lsm, jpj1_lsm,   &
1218      &                          jpj2_lsm, itmpi, itmpj, itmpz, rec1_lsm, recn_lsm )
1219      !!---------------------------------------------------------------------
1220      !!                    ***  ROUTINE apply_seaoverland  ***
1221      !!
1222      !! ** Purpose :   avoid spurious fluxes in coastal or near-coastal areas
1223      !!                due to the wrong usage of "land" values from the coarse
1224      !!                atmospheric model when spatial interpolation is required
1225      !!      D. Delrosso INGV         
1226      !!----------------------------------------------------------------------
1227      INTEGER,                   INTENT(in   ) :: itmpi,itmpj,itmpz                    ! lengths
1228      INTEGER,                   INTENT(in   ) :: jpi1_lsm,jpi2_lsm,jpj1_lsm,jpj2_lsm  ! temporary indices
1229      INTEGER, DIMENSION(3),     INTENT(in   ) :: rec1_lsm,recn_lsm                    ! temporary arrays for start and length
1230      REAL(dp),DIMENSION (:,:,:),INTENT(inout) :: zfieldo                              ! input/output array for seaoverland application
1231      CHARACTER (len=100),       INTENT(in   ) :: clmaskfile                           ! land/sea mask file name
1232      !
1233      INTEGER :: inum,jni,jnj,jnz,jc   ! local indices
1234      REAL(dp),DIMENSION (:,:,:),ALLOCATABLE :: zslmec1             ! local array for land point detection
1235      REAL(dp),DIMENSION (:,:),  ALLOCATABLE :: zfieldn   ! array of forcing field with undeff for land points
1236      REAL(dp),DIMENSION (:,:),  ALLOCATABLE :: zfield    ! array of forcing field
1237      !!---------------------------------------------------------------------
1238      !
1239      ALLOCATE ( zslmec1(itmpi,itmpj,itmpz), zfieldn(itmpi,itmpj), zfield(itmpi,itmpj) )
1240      !
1241      ! Retrieve the land sea mask data
1242      CALL iom_open( clmaskfile, inum )
1243      SELECT CASE( SIZE(zfieldo(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:),3) )
1244      CASE(1)
1245         CALL iom_get( inum, jpdom_unknown, 'LSM', zslmec1(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,1),   &
1246            &          1, kstart = rec1_lsm, kcount = recn_lsm)
1247      CASE DEFAULT
1248         CALL iom_get( inum, jpdom_unknown, 'LSM', zslmec1(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:),   &
1249            &          1, kstart = rec1_lsm, kcount = recn_lsm)
1250      END SELECT
1251      CALL iom_close( inum )
1252      !
1253      DO jnz=1,rec1_lsm(3)             !! Loop over k dimension
1254         !
1255         DO jni = 1, itmpi                               !! copy the original field into a tmp array
1256            DO jnj = 1, itmpj                            !! substituting undeff over land points
1257               zfieldn(jni,jnj) = zfieldo(jni,jnj,jnz)
1258               IF( zslmec1(jni,jnj,jnz) == 1. )   zfieldn(jni,jnj) = undeff_lsm
1259            END DO
1260         END DO
1261         !
1262         CALL seaoverland( zfieldn, itmpi, itmpj, zfield )
1263         DO jc = 1, nn_lsm
1264            CALL seaoverland( zfield, itmpi, itmpj, zfield )
1265         END DO
1266         !
1267         !   Check for Undeff and substitute original values
1268         IF( ANY(zfield==undeff_lsm) ) THEN
1269            DO jni = 1, itmpi
1270               DO jnj = 1, itmpj
1271                  IF( zfield(jni,jnj)==undeff_lsm )   zfield(jni,jnj) = zfieldo(jni,jnj,jnz)
1272               END DO
1273            END DO
1274         ENDIF
1275         !
1276         zfieldo(:,:,jnz) = zfield(:,:)
1277         !
1278      END DO                           !! End Loop over k dimension
1279      !
1280      DEALLOCATE ( zslmec1, zfieldn, zfield )
1281      !
1282   END SUBROUTINE apply_seaoverland 
1283
1284
1285   SUBROUTINE seaoverland( zfieldn, ileni, ilenj, zfield )
1286      !!---------------------------------------------------------------------
1287      !!                    ***  ROUTINE seaoverland  ***
1288      !!
1289      !! ** Purpose :   create shifted matrices for seaoverland application 
1290      !!      D. Delrosso INGV
1291      !!----------------------------------------------------------------------
1292      INTEGER                          , INTENT(in   ) :: ileni,ilenj   ! lengths
1293      REAL(dp), DIMENSION (ileni,ilenj), INTENT(in   ) :: zfieldn       ! array of forcing field with undeff for land points
1294      REAL(dp), DIMENSION (ileni,ilenj), INTENT(  out) :: zfield        ! array of forcing field
1295      !
1296      REAL(dp) , DIMENSION (ileni,ilenj)   :: zmat1, zmat2, zmat3, zmat4  ! local arrays
1297      REAL(dp) , DIMENSION (ileni,ilenj)   :: zmat5, zmat6, zmat7, zmat8  !   -     -
1298      REAL(dp) , DIMENSION (ileni,ilenj)   :: zlsm2d                      !   -     -
1299      REAL(dp) , DIMENSION (ileni,ilenj,8) :: zlsm3d                      !   -     -
1300      LOGICAL  , DIMENSION (ileni,ilenj,8) :: ll_msknan3d                 ! logical mask for undeff detection
1301      LOGICAL  , DIMENSION (ileni,ilenj)   :: ll_msknan2d                 ! logical mask for undeff detection
1302      !!----------------------------------------------------------------------
1303      zmat8 = eoshift( zfieldn , SHIFT=-1 , BOUNDARY = (/zfieldn(:,1)/)     , DIM=2 )
1304      zmat1 = eoshift( zmat8   , SHIFT=-1 , BOUNDARY = (/zmat8(1,:)/)       , DIM=1 )
1305      zmat2 = eoshift( zfieldn , SHIFT=-1 , BOUNDARY = (/zfieldn(1,:)/)     , DIM=1 )
1306      zmat4 = eoshift( zfieldn , SHIFT= 1 , BOUNDARY = (/zfieldn(:,ilenj)/) , DIM=2 )
1307      zmat3 = eoshift( zmat4   , SHIFT=-1 , BOUNDARY = (/zmat4(1,:)/)       , DIM=1 )
1308      zmat5 = eoshift( zmat4   , SHIFT= 1 , BOUNDARY = (/zmat4(ileni,:)/)   , DIM=1 )
1309      zmat6 = eoshift( zfieldn , SHIFT= 1 , BOUNDARY = (/zfieldn(ileni,:)/) , DIM=1 )
1310      zmat7 = eoshift( zmat8   , SHIFT= 1 , BOUNDARY = (/zmat8(ileni,:)/)   , DIM=1 )
1311      !
1312      zlsm3d  = RESHAPE( (/ zmat1, zmat2, zmat3, zmat4, zmat5, zmat6, zmat7, zmat8 /), (/ ileni, ilenj, 8 /))
1313      ll_msknan3d = .NOT.( zlsm3d  == undeff_lsm )
1314      ll_msknan2d = .NOT.( zfieldn == undeff_lsm )  ! FALSE where is Undeff (land)
1315      zlsm2d = SUM( zlsm3d, 3 , ll_msknan3d ) / MAX( 1 , COUNT( ll_msknan3d , 3 ) )
1316      WHERE( COUNT( ll_msknan3d , 3 ) == 0._wp )   zlsm2d = undeff_lsm
1317      zfield = MERGE( zfieldn, zlsm2d, ll_msknan2d )
1318      !
1319   END SUBROUTINE seaoverland
1320
1321
1322   SUBROUTINE fld_interp( num, clvar, kw, kk, dta, nrec, lsmfile)     
1323      !!---------------------------------------------------------------------
1324      !!                    ***  ROUTINE fld_interp  ***
1325      !!
1326      !! ** Purpose :   apply weights to input gridded data to create data
1327      !!                on model grid
1328      !!----------------------------------------------------------------------
1329      INTEGER                   , INTENT(in   ) ::   num     ! stream number
1330      CHARACTER(LEN=*)          , INTENT(in   ) ::   clvar   ! variable name
1331      INTEGER                   , INTENT(in   ) ::   kw      ! weights number
1332      INTEGER                   , INTENT(in   ) ::   kk      ! vertical dimension of kk
1333      REAL(dp), DIMENSION(:,:,:), INTENT(inout) ::   dta     ! output field on model grid
1334      INTEGER                   , INTENT(in   ) ::   nrec    ! record number to read (ie time slice)
1335      CHARACTER(LEN=*)          , INTENT(in   ) ::   lsmfile ! land sea mask file name
1336      !
1337      INTEGER, DIMENSION(3) ::   rec1, recn           ! temporary arrays for start and length
1338      INTEGER, DIMENSION(3) ::   rec1_lsm, recn_lsm   ! temporary arrays for start and length in case of seaoverland
1339      INTEGER ::   ii_lsm1,ii_lsm2,ij_lsm1,ij_lsm2    ! temporary indices
1340      INTEGER ::   ji, jj, jk, jn, jir, jjr           ! loop counters
1341      INTEGER ::   ipk
1342      INTEGER ::   ni, nj                             ! lengths
1343      INTEGER ::   jpimin,jpiwid                      ! temporary indices
1344      INTEGER ::   jpimin_lsm,jpiwid_lsm              ! temporary indices
1345      INTEGER ::   jpjmin,jpjwid                      ! temporary indices
1346      INTEGER ::   jpjmin_lsm,jpjwid_lsm              ! temporary indices
1347      INTEGER ::   jpi1,jpi2,jpj1,jpj2                ! temporary indices
1348      INTEGER ::   jpi1_lsm,jpi2_lsm,jpj1_lsm,jpj2_lsm   ! temporary indices
1349      INTEGER ::   itmpi,itmpj,itmpz                     ! lengths
1350      REAL(dp),DIMENSION(:,:,:), ALLOCATABLE ::   ztmp_fly_dta                 ! local array of values on input grid     
1351      !!----------------------------------------------------------------------
1352      ipk = SIZE(dta, 3)
1353      !
1354      !! for weighted interpolation we have weights at four corners of a box surrounding
1355      !! a model grid point, each weight is multiplied by a grid value (bilinear case)
1356      !! or by a grid value and gradients at the corner point (bicubic case)
1357      !! so we need to have a 4 by 4 subgrid surrounding each model point to cover both cases
1358
1359      !! sub grid from non-model input grid which encloses all grid points in this nemo process
1360      jpimin = ref_wgts(kw)%botleft(1)
1361      jpjmin = ref_wgts(kw)%botleft(2)
1362      jpiwid = ref_wgts(kw)%jpiwgt
1363      jpjwid = ref_wgts(kw)%jpjwgt
1364
1365      !! when reading in, expand this sub-grid by one halo point all the way round for calculating gradients
1366      rec1(1) = MAX( jpimin-1, 1 )
1367      rec1(2) = MAX( jpjmin-1, 1 )
1368      rec1(3) = 1
1369      recn(1) = MIN( jpiwid+2, ref_wgts(kw)%ddims(1)-rec1(1)+1 )
1370      recn(2) = MIN( jpjwid+2, ref_wgts(kw)%ddims(2)-rec1(2)+1 )
1371      recn(3) = kk
1372
1373      !! where we need to put it in the non-nemo grid fly_dta
1374      !! note that jpi1 and jpj1 only differ from 1 when jpimin and jpjmin are 1
1375      !! (ie at the extreme west or south of the whole input grid) and similarly for jpi2 and jpj2
1376      jpi1 = 2 + rec1(1) - jpimin
1377      jpj1 = 2 + rec1(2) - jpjmin
1378      jpi2 = jpi1 + recn(1) - 1
1379      jpj2 = jpj1 + recn(2) - 1
1380
1381
1382      IF( LEN_TRIM(lsmfile) > 0 ) THEN
1383      !! indeces for ztmp_fly_dta
1384      ! --------------------------
1385         rec1_lsm(1)=MAX(rec1(1)-nn_lsm,1)  ! starting index for enlarged external data, x direction
1386         rec1_lsm(2)=MAX(rec1(2)-nn_lsm,1)  ! starting index for enlarged external data, y direction
1387         rec1_lsm(3) = 1                    ! vertical dimension
1388         recn_lsm(1)=MIN(rec1(1)-rec1_lsm(1)+recn(1)+nn_lsm,ref_wgts(kw)%ddims(1)-rec1_lsm(1)) ! n points in x direction
1389         recn_lsm(2)=MIN(rec1(2)-rec1_lsm(2)+recn(2)+nn_lsm,ref_wgts(kw)%ddims(2)-rec1_lsm(2)) ! n points in y direction
1390         recn_lsm(3) = kk                   ! number of vertical levels in the input file
1391
1392      !  Avoid out of bound
1393         jpimin_lsm = MAX( rec1_lsm(1)+1, 1 )
1394         jpjmin_lsm = MAX( rec1_lsm(2)+1, 1 )
1395         jpiwid_lsm = MIN( recn_lsm(1)-2,ref_wgts(kw)%ddims(1)-rec1(1)+1)
1396         jpjwid_lsm = MIN( recn_lsm(2)-2,ref_wgts(kw)%ddims(2)-rec1(2)+1)
1397
1398         jpi1_lsm = 2+rec1_lsm(1)-jpimin_lsm
1399         jpj1_lsm = 2+rec1_lsm(2)-jpjmin_lsm
1400         jpi2_lsm = jpi1_lsm + recn_lsm(1) - 1
1401         jpj2_lsm = jpj1_lsm + recn_lsm(2) - 1
1402
1403
1404         itmpi=jpi2_lsm-jpi1_lsm+1
1405         itmpj=jpj2_lsm-jpj1_lsm+1
1406         itmpz=kk
1407         ALLOCATE(ztmp_fly_dta(itmpi,itmpj,itmpz))
1408         ztmp_fly_dta(:,:,:) = 0.0
1409         SELECT CASE( SIZE(ztmp_fly_dta(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:),3) )
1410         CASE(1)
1411              CALL iom_get( num, jpdom_unknown, clvar, ztmp_fly_dta(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,1),   &
1412                 &          nrec, kstart = rec1_lsm, kcount = recn_lsm)
1413         CASE DEFAULT
1414              CALL iom_get( num, jpdom_unknown, clvar, ztmp_fly_dta(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:),   &
1415                 &          nrec, kstart = rec1_lsm, kcount = recn_lsm)
1416         END SELECT
1417         CALL apply_seaoverland(lsmfile,ztmp_fly_dta(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:),                  &
1418                 &                                      jpi1_lsm,jpi2_lsm,jpj1_lsm,jpj2_lsm,                  &
1419                 &                                      itmpi,itmpj,itmpz,rec1_lsm,recn_lsm)
1420
1421
1422         ! Relative indeces for remapping
1423         ii_lsm1 = (rec1(1)-rec1_lsm(1))+1
1424         ii_lsm2 = (ii_lsm1+recn(1))-1
1425         ij_lsm1 = (rec1(2)-rec1_lsm(2))+1
1426         ij_lsm2 = (ij_lsm1+recn(2))-1
1427
1428         ref_wgts(kw)%fly_dta(:,:,:) = 0.0
1429         ref_wgts(kw)%fly_dta(jpi1:jpi2,jpj1:jpj2,:) = ztmp_fly_dta(ii_lsm1:ii_lsm2,ij_lsm1:ij_lsm2,:)
1430         DEALLOCATE(ztmp_fly_dta)
1431
1432      ELSE
1433         
1434         ref_wgts(kw)%fly_dta(:,:,:) = 0.0
1435         CALL iom_get( num, jpdom_unknown, clvar, ref_wgts(kw)%fly_dta(jpi1:jpi2,jpj1:jpj2,:), nrec, kstart = rec1, kcount = recn)
1436      ENDIF
1437     
1438
1439      !! first four weights common to both bilinear and bicubic
1440      !! data_jpi, data_jpj have already been shifted to (1,1) corresponding to botleft
1441      !! note that we have to offset by 1 into fly_dta array because of halo added to fly_dta (rec1 definition)
1442      dta(:,:,:) = 0._wp
1443      DO jn = 1,4
1444         DO_3D( 0, 0, 0, 0, 1,ipk )
1445            ni = ref_wgts(kw)%data_jpi(ji,jj,jn) + 1
1446            nj = ref_wgts(kw)%data_jpj(ji,jj,jn) + 1
1447            dta(ji,jj,jk) = dta(ji,jj,jk) + ref_wgts(kw)%data_wgt(ji,jj,jn) * ref_wgts(kw)%fly_dta(ni,nj,jk)
1448         END_3D
1449      END DO
1450
1451      IF(ref_wgts(kw)%numwgt .EQ. 16) THEN
1452
1453         !! fix up halo points that we couldnt read from file
1454         IF( jpi1 == 2 ) THEN
1455            ref_wgts(kw)%fly_dta(jpi1-1,:,:) = ref_wgts(kw)%fly_dta(jpi1,:,:)
1456         ENDIF
1457         IF( jpi2 + jpimin - 1 == ref_wgts(kw)%ddims(1)+1 ) THEN
1458            ref_wgts(kw)%fly_dta(jpi2+1,:,:) = ref_wgts(kw)%fly_dta(jpi2,:,:)
1459         ENDIF
1460         IF( jpj1 == 2 ) THEN
1461            ref_wgts(kw)%fly_dta(:,jpj1-1,:) = ref_wgts(kw)%fly_dta(:,jpj1,:)
1462         ENDIF
1463         IF( jpj2 + jpjmin - 1 == ref_wgts(kw)%ddims(2)+1 .AND. jpj2 .LT. jpjwid+2 ) THEN
1464            ref_wgts(kw)%fly_dta(:,jpj2+1,:) = 2.0*ref_wgts(kw)%fly_dta(:,jpj2,:) - ref_wgts(kw)%fly_dta(:,jpj2-1,:)
1465         ENDIF
1466         
1467         !! if data grid is cyclic we can do better on east-west edges
1468         !! but have to allow for whether first and last columns are coincident
1469         IF( ref_wgts(kw)%cyclic ) THEN
1470            rec1(2) = MAX( jpjmin-1, 1 )
1471            recn(1) = 1
1472            recn(2) = MIN( jpjwid+2, ref_wgts(kw)%ddims(2)-rec1(2)+1 )
1473            jpj1 = 2 + rec1(2) - jpjmin
1474            jpj2 = jpj1 + recn(2) - 1
1475            IF( jpi1 == 2 ) THEN
1476               rec1(1) = ref_wgts(kw)%ddims(1) - ref_wgts(kw)%overlap
1477               CALL iom_get( num, jpdom_unknown, clvar, ref_wgts(kw)%col(:,jpj1:jpj2,:), nrec, kstart = rec1, kcount = recn)
1478               ref_wgts(kw)%fly_dta(jpi1-1,jpj1:jpj2,:) = ref_wgts(kw)%col(1,jpj1:jpj2,:)
1479            ENDIF
1480            IF( jpi2 + jpimin - 1 == ref_wgts(kw)%ddims(1)+1 ) THEN
1481               rec1(1) = 1 + ref_wgts(kw)%overlap
1482               CALL iom_get( num, jpdom_unknown, clvar, ref_wgts(kw)%col(:,jpj1:jpj2,:), nrec, kstart = rec1, kcount = recn)
1483               ref_wgts(kw)%fly_dta(jpi2+1,jpj1:jpj2,:) = ref_wgts(kw)%col(1,jpj1:jpj2,:)
1484            ENDIF
1485         ENDIF
1486         !
1487!!$         DO jn = 1,4
1488!!$            DO_3D( 0, 0, 0, 0, 1,ipk )
1489!!$               ni = ref_wgts(kw)%data_jpi(ji,jj,jn) + 1
1490!!$               nj = ref_wgts(kw)%data_jpj(ji,jj,jn) + 1
1491!!$               dta(ji,jj,jk) = dta(ji,jj,jk)   &
1492!!$                  ! gradient in the i direction
1493!!$                  &            + ref_wgts(kw)%data_wgt(ji,jj,jn+4) * 0.5_wp *                                    &
1494!!$                  &                (ref_wgts(kw)%fly_dta(ni+1,nj  ,jk) - ref_wgts(kw)%fly_dta(ni-1,nj  ,jk))     &
1495!!$                  ! gradient in the j direction
1496!!$                  &            + ref_wgts(kw)%data_wgt(ji,jj,jn+8) * 0.5_wp *                                    &
1497!!$                  &                (ref_wgts(kw)%fly_dta(ni  ,nj+1,jk) - ref_wgts(kw)%fly_dta(ni  ,nj-1,jk))     &
1498!!$                  ! gradient in the ij direction
1499!!$                  &            + ref_wgts(kw)%data_wgt(ji,jj,jn+12) * 0.25_wp *                                  &
1500!!$                  &               ((ref_wgts(kw)%fly_dta(ni+1,nj+1,jk) - ref_wgts(kw)%fly_dta(ni-1,nj+1,jk)) -   &
1501!!$                  &                (ref_wgts(kw)%fly_dta(ni+1,nj-1,jk) - ref_wgts(kw)%fly_dta(ni-1,nj-1,jk)))
1502!!$            END_3D
1503!!$         END DO
1504         !
1505         DO jn = 1,4
1506            DO_3D( 0, 0, 0, 0, 1,ipk )
1507               ni = ref_wgts(kw)%data_jpi(ji,jj,jn)
1508               nj = ref_wgts(kw)%data_jpj(ji,jj,jn)
1509               ! gradient in the i direction
1510               dta(ji,jj,jk) = dta(ji,jj,jk) + ref_wgts(kw)%data_wgt(ji,jj,jn+4) * 0.5_wp *         &
1511                  &                (ref_wgts(kw)%fly_dta(ni+2,nj+1,jk) - ref_wgts(kw)%fly_dta(ni  ,nj+1,jk))
1512            END_3D
1513         END DO
1514         DO jn = 1,4
1515            DO_3D( 0, 0, 0, 0, 1,ipk )
1516               ni = ref_wgts(kw)%data_jpi(ji,jj,jn)
1517               nj = ref_wgts(kw)%data_jpj(ji,jj,jn)
1518               ! gradient in the j direction
1519               dta(ji,jj,jk) = dta(ji,jj,jk) + ref_wgts(kw)%data_wgt(ji,jj,jn+8) * 0.5_wp *         &
1520                  &                (ref_wgts(kw)%fly_dta(ni+1,nj+2,jk) - ref_wgts(kw)%fly_dta(ni+1,nj  ,jk))
1521            END_3D
1522         END DO
1523         DO jn = 1,4
1524            DO_3D( 0, 0, 0, 0, 1,ipk )
1525               ni = ref_wgts(kw)%data_jpi(ji,jj,jn)
1526               nj = ref_wgts(kw)%data_jpj(ji,jj,jn)
1527               ! gradient in the ij direction
1528               dta(ji,jj,jk) = dta(ji,jj,jk) + ref_wgts(kw)%data_wgt(ji,jj,jn+12) * 0.25_wp * (     &
1529                  &                (ref_wgts(kw)%fly_dta(ni+2,nj+2,jk) - ref_wgts(kw)%fly_dta(ni  ,nj+2,jk)) -   &
1530                  &                (ref_wgts(kw)%fly_dta(ni+2,nj  ,jk) - ref_wgts(kw)%fly_dta(ni  ,nj  ,jk)))
1531            END_3D
1532         END DO
1533         !
1534      ENDIF
1535      !
1536   END SUBROUTINE fld_interp
1537
1538
1539   FUNCTION fld_filename( sdjf, kday, kmonth, kyear )
1540      !!---------------------------------------------------------------------
1541      !!                    ***  FUNCTION fld_filename ***
1542      !!
1543      !! ** Purpose :   define the filename according to a given date
1544      !!---------------------------------------------------------------------
1545      TYPE(FLD), INTENT(in) ::   sdjf         ! input field related variables
1546      INTEGER  , INTENT(in) ::   kday, kmonth, kyear
1547      !
1548      CHARACTER(len = 256) ::   clname, fld_filename
1549      !!---------------------------------------------------------------------
1550
1551     
1552      ! build the new filename if not climatological data
1553      clname=TRIM(sdjf%clrootname)
1554      !
1555      ! note that sdjf%ln_clim is is only acting on the presence of the year in the file name
1556      IF( .NOT. sdjf%ln_clim ) THEN   
1557                                         WRITE(clname, '(a,"_y",i4.4)' ) TRIM( sdjf%clrootname ), kyear    ! add year
1558         IF( sdjf%clftyp /= 'yearly' )   WRITE(clname, '(a, "m",i2.2)' ) TRIM( clname          ), kmonth   ! add month
1559      ELSE
1560         ! build the new filename if climatological data
1561         IF( sdjf%clftyp /= 'yearly' )   WRITE(clname, '(a,"_m",i2.2)' ) TRIM( sdjf%clrootname ), kmonth   ! add month
1562      ENDIF
1563      IF(    sdjf%clftyp == 'daily' .OR. sdjf%clftyp(1:4) == 'week' ) &
1564         &                               WRITE(clname, '(a,"d" ,i2.2)' ) TRIM( clname          ), kday     ! add day
1565
1566      fld_filename = clname
1567     
1568   END FUNCTION fld_filename
1569
1570
1571   FUNCTION ksec_week( cdday )
1572      !!---------------------------------------------------------------------
1573      !!                    ***  FUNCTION ksec_week ***
1574      !!
1575      !! ** Purpose :   seconds between 00h of the beginning of the week and half of the current time step
1576      !!---------------------------------------------------------------------
1577      CHARACTER(len=*), INTENT(in)   ::   cdday   ! first 3 letters of the first day of the weekly file
1578      !!
1579      INTEGER                        ::   ksec_week      ! output variable
1580      INTEGER                        ::   ijul, ishift   ! local integer
1581      CHARACTER(len=3),DIMENSION(7)  ::   cl_week 
1582      !!----------------------------------------------------------------------
1583      cl_week = (/"sun","sat","fri","thu","wed","tue","mon"/)
1584      DO ijul = 1, 7
1585         IF( cl_week(ijul) == TRIM(cdday) ) EXIT
1586      END DO
1587      IF( ijul .GT. 7 )   CALL ctl_stop( 'ksec_week: wrong day for sdjf%clftyp(6:8): '//TRIM(cdday) )
1588      !
1589      ishift = ijul * NINT(rday)
1590      !
1591      ksec_week = nsec_monday + ishift
1592      ksec_week = MOD( ksec_week, 7*NINT(rday) )
1593      !
1594   END FUNCTION ksec_week
1595
1596   !!======================================================================
1597END MODULE fldread
Note: See TracBrowser for help on using the repository browser.