#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 ************************************
# 

#=============================================================================
# Function      : xs_build_curve
#
# Syntax        : 
#                                          
# Category      : 
#
# OneLineDesc   : returns a curve for the given cross section data
#
# Description   : Returns a curve for the given cross section data
#
# Parameters    : 
# 
# Return Value  : 
#
# Dependencies  : none
#
#==============================================================================

function xs_build_curve(xs_d, fs, colour: string, style: string, thickness: number)

    __DEBUG_BUILD_CURVE=0

    # read cross section line points from the
    # cross section dataobject
    setcurrent(xs_d, "lat")
    lats = values(xs_d)
    setcurrent(xs_d, "lon")
    lons = values(xs_d)

    if __DEBUG_BUILD_CURVE then
        # print("lats=", lats)
        # print("lons=", lons)
    end if

    # figure out the horizontal interpolation method used
    # to generate the cross section data
    attr = global_attributes(xs_d)
    hm = "interpolate"
    if attr.xsHorizontalMethod <> nil then
        hm = attr.xsHorizontalMethod
    end if
    
    if __DEBUG_BUILD_CURVE then
        print("hm=", hm)
    end if

    # sample field along the line with the right method
    if hm = "nearest" then
        vals = nearest_gridpoint(fs, lats, lons)
    else
        vals = vector(count(lats))
        for i=1 to count(lats) do
            v = interpolate(fs, lats[i], lons[i])
            if v =  nil then
                v = vector_missing_value
            end if
            vals[i] = v
       end for        
    end if

    if __DEBUG_BUILD_CURVE then
        print(" lons=", lons)
        print(" vals=", vals)
    end if

    # the x variable selection has to match the xs view algorythm, 
    # otherwise the curve is not plotted! 
    # See CrossS.cc CreateOuputRequest()    
    d_lons = abs(lons[1] - lons[count(lons)])
    eps = 1E-6
    if d_lons < eps then
        # NETCDF_X_GEOLINE_CONVENTION=lonlat
        xp = lats
    else
        # NETCDF_X_GEOLINE_CONVENTION=latlon
        xp = lons
    end if
    
    
    return xy_curve(xp, vals, colour, style, thickness)
    
end xs_build_curve