import yaml


def read_config(config, key=None):
    """Read a config file and return the right configuration."""
    print("INFO: Loading configuration from", config)
    config = yaml.load(open(config, 'r'), Loader=yaml.SafeLoader)
    if key is not None:
        if key in config:
            print("INFO: Using the '%s' configuration" % key)
            config = config[key]
        else:
            raise IOError("Configuration `%s` does not exist. Check your default file." % key)
    elif len(config) > 1:
        if 'default_config' in config:
            print("INFO: Using default configuration '%s'" % config['default_config'])
            config = config[config['default_config']]
        else:
            raise IOError("You must define a 'default_config' in you configuration file.")
    else:
        config = config[list(config)[0]]
    return config