function [rwspd,rwdir,Urel,Vrel] = sd_true_to_uv_rel(spd,dir,hed,cog,sog)
%{
    Computes relative wind speed and direction from true spd/dir and
    ship cog/sog/heading.  U is defined as positive for wind blowing
    toward the bow and V is positive for wind blowing toward port.
    This is a right-handed convention and is the normal format for sonic
    anemometer wind components in all NOAA/PSD flux scripts.

    rwdir format is the direction wind is coming FROM, 0-360 deg.

    Relative wind components are in the ship frame (Urel/Vrel), as
    for raw sonic anemometer wind speeds.

    Jan 2016, BWB
%}

[Un,Uw] = sd_to_uv(spd,dir);  % compute true wind N/W components

% pol2cart follows left-handed convention so components are N/E!
[hed_n, hed_e] = pol2cart(-hed*pi/180, 1);	% negate hed angle for CW rotation!
[sog_n, sog_e] = pol2cart(cog*pi/180, sog); % N/E ship speed components

% compute rel wind comps in earth frame
Un_rel = Un - sog_n;
Uw_rel = Uw + sog_e;

% rotate components CW into ship frame
Urel = Un_rel.*hed_n + Uw_rel.*hed_e;     
Vrel = -Un_rel.*hed_e + Uw_rel.*hed_n;

% compute relative winds
rwdir = atan2(-Vrel, Urel)*180/pi + 180;
rwspd = sqrt(Urel.^2 + Vrel.^2);
end