#Metview Macro

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

#=================================================================================
# Computes the x and y components from polar components
#
# OneLineDesc   : Computes the x and y components from polar components
#
# Input: 
#       
# Return:
#            
#==============================================================================


function xy_from_polar(sp, d)
    fn_name = "xy_from_polar"
    
    DEG_TO_RAD = pi/180.
    a = (270.0 - d) * DEG_TO_RAD
   
    if type(sp) = "fieldset" then
        if count(sp) <> count(d) then
            fail(fn & ": sp and d must have the number of fields! " &
                 count(sp) & "!=" & count(d) & "!")
        end if
        
        meta = grib_get_long(sp, "paramId")  
       
        r = nil
        for i=1 to count(sp) do
            u = sp[i]* cos(a[i])
            v = sp[i]* sin(a[i]) 
            
            # 10 m wind        
            if meta[i] = 207 then
                u = grib_set_long(u, ["paramId", 165])
                v = grib_set_long(v, ["paramId", 166])
            # wind 
            else if meta[i] = 10 then
                u = grib_set_long(u, ["paramId", 131])
                v = grib_set_long(v, ["paramId", 132])
            end if
            
            r = r & u & v
        end for 
        
        return r    
    
    else        
        return [sp * cos(a), sp * sin(a)]
    end if
    
end xy_from_polar