#Metview Macro

#  **************************** LICENSE START ***********************************
# 
#  Copyright 2021 ECMWF. This software is distributed under the terms
#  of the Apache License version 2.0. In applying this license, ECMWF does not
#  waive the privileges and immunities granted to it by virtue of its status as
#  an Intergovernmental Organization or submit itself to any jurisdiction.
# 
#  ***************************** LICENSE END ************************************
# 

# **************************************************************************
# OneLineDesc   : Compute shear deformation of vector fields   
# **************************************************************************

function shear_deformation
    _fn_name = "shear_deformation"
    
    _args = arguments()
    _v = __prepare_gradient_arg(_fn_name, 2, _args)
    if count(_v) <> 5 then
        fail(_fn_name & ": invalid arguments=" & _args)
    end if
    _fs_x = _v[1]
    _fs_y = _v[2]
    _mode = _v[3]
    _pole_missing = _v[4]
    _vector_mode = _v[5]

    if count(_fs_x) <> count(_fs_y) then
        fail(_fn_name & ": different number of fields in fieldsets [fieldset1=",count(_fs_x),", fieldset2=",count(_fs_y),"]")
    end if          
  
    _res = nil
    
    # finite difference
    if _mode = "fdiff" then

        #radius of Earth
        _R = 6371200.0
      
        # extract metadata keys
        _keys_x = grib_get(_fs_x,["gridType","paramId"])
        _keys_y = grib_get(_fs_y,["gridType","paramId"])
        
        for _i=1 to count(_fs_x) do
            # get metadata keys
            _grid_type_x = _keys_x[_i][1]
            _grid_type_y = _keys_y[_i][1]
           
            # check if grid is regular latlon 
            if _grid_type_x <> "regular_ll" then
                fail(_fn_name & ": [fieldset_x, field=",_i,"] - unsupported grid (=",_grid_type_x,"), implemented only for regular lat-lon grid")
            end if
            
            if _grid_type_y <> "regular_ll" then
                fail(_fn_name & ": [fieldset_y, field=",_i,"] - unsupported grid (=",_grid_type_y,"), implemented only for regular lat-lon grid")
            end if
        end for    
            
        # compute shear_deformation
        _dfxdy = first_derivative_y(_fs_x)
        _dfydx = first_derivative_x(_fs_y)
        _res = _dfydx + _dfxdy + _fs_x*tanlat(_fs_x)/_R
       
    # finite element
    else if _mode = "felem" then
        _res = nil
        fail(_fn_name & ": finite element menthod is not available")
    end if    
    
    return _res
    
end shear_deformation    
