import yaml
from typing import OrderedDict


def ordered_load_yaml(yaml_fn, Loader=yaml.Loader, **kwargs):
    """
    Ensure YAML entries are loaded in an ordered dict following the original file order
    """
    # Define custom loader
    class OrderedLoader(Loader):
        pass

    def construct_mapping(loader, node):
        loader.flatten_mapping(node)
        return OrderedDict(loader.construct_pairs(node))

    OrderedLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping)
    # Try to load file
    try:
        with open(yaml_fn, "r") as yaml_fp:
            d = yaml.load(stream=yaml_fp, Loader=OrderedLoader, **kwargs)
            return d
    except:
        return OrderedDict()