#Metview Macro

#  **************************** LICENSE START ***********************************
# 
#  Copyright 2018 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 ************************************
# 

# **************************************************************************
# Function      : geostrophic_wind_pl
#
# Syntax        : fieldset geostrophic_wind_pl(fs_x:fieldset,fs_y:fieldset)
#                                          
# Category      : DERIVATIVES
#
# OneLineDesc   : Computes geostrophic wind on pressure levels
#
# Description   : Compute the geostrophic wind from geopotentials fields defined on 
#                 pressure levels and regular lat-lon grid. The computation uses a 
#                 second order accuracy
#                 finite difference scheme.
#
# Parameters    : 
#                 
# Return Value  : resulting fieldset
#
# Dependencies  : none
#
# Example Usage : 
#                 
#
# **************************************************************************
function geostrophic_wind_pl(z: fieldset)

	fn_name = "geostrophic_wind_pl"

    # some constants
	omega = 7.292115E-5 # angular velocity of Earth
    coriolis_limit = 1E-7
       
	if count(z) = 0 then
		fail(fn_name & ": no valid input fieldset is specifed")
	end if
  
    # extract metadata keys
    keys = grib_get(z,["gridType","typeOfLevel"])
    
    res = nil
    
    for i=1 to count(z) do

    	# get metadata keys
        grid_type = keys[i][1]
        level_type = keys[i][2]
        
        # check if level is pressure 
        if level_type <> "isobaricInhPa" then
            fail(fn_name & ": [z field=",i,"] - unsupported level type(=",level_type,"), must be \"isobaricInhPa\" ")
        end if
        
        # check if grid is regular latlon 
        if grid_type <> "regular_ll" then
            fail(fn_name & ": [z field=",i,"] - unsupported grid (=",grid_type,"), implemented only for regular lat-lon grid")
        end if
        
        # compute the Coriolis parameter
        f=2*omega*sinlat(z[i])

        # mask the tropics
        f = bitmap(f,bitmap(abs(f) > coriolis_limit,0))

        # compute the geopotential gradient
        grad_z = gradient(z[i])

        # compute the geostrophic wind
        u_g = -grad_z[2]/f
        v_g = grad_z[1]/f

		# set param ids as U/V according to level    
        u_g = grib_set_long(u_g,["paramId",131])
        v_g = grib_set_long(v_g,["paramId",132])
       
        res = res & u_g & v_g
		
	end for
	
    return res
    
end geostrophic_wind_pl
