def build_kd_tree(catalog, depth=0):
    """
    Recursive algorithm to build a k-d tree from catalog
    K-d tree is stored in a nested dictionary.

    Parameters
    ----------
    catalog: 2D numpy array. Ex: catalog[i] = [RA, DEC, ID]. See cross_matching_tools.load_bss, load_cosmos
    depth:   int, for recursion.
    """
    n = len(catalog)

    if n <= 0:
        return None

    coord = depth % 2

    sorted_data = catalog[catalog[:,coord].argsort()] # will sort numpy array by column instead of by axis

    return {
        'star': sorted_data[n // 2],
        'left': build_kd_tree(sorted_data[:n // 2], depth + 1),
        'right': build_kd_tree(sorted_data[n // 2 + 1:], depth + 1)
    }