from math import asin, atan2,  sqrt, degrees


def normal2SD(x,y,z):
    """Converts a normal vector to a plane (given as x,y,z)
    to a strike and dip of the plane using the Right-Hand-Rule.
    Input:
        x: The x-component of the normal vector
        y: The y-component of the normal vector
        z: The z-component of the normal vector
    Output:
        strike: The strike of the plane, in degrees clockwise from north
        dip: The dip of the plane, in degrees downward from horizontal
    """

    # Due to geologic conventions, positive angles are downwards
    z = -z

    # First convert the normal vector to spherical coordinates
    #  (This is effectively a plunge/bearing of the normal vector)
    r = sqrt(x*x + y*y + z*z)
    plunge = degrees(asin(z/r))
    bearing = degrees(atan2(y, x))


    # Rotate bearing so that 0 is north instead of east
    bearing = 90-bearing
    if bearing<0: bearing += 360

    # If the plunge angle is upwards, get the opposite end of the line
    if plunge<0:
        plunge = -plunge
        bearing -= 180
        if bearing<0:
            bearing += 360

    # Now convert the plunge/bearing of the pole to the plane that it represents
    strike = bearing+90
    dip = 90-plunge
    if strike > 360: strike -= 360

    return strike, dip