def convert(kml_path, output_dir, separate_folders=False,
  style_type=None, style_filename='style.json'):
    """
    Given a path to a KML file, convert it to one or several GeoJSON FeatureCollection files and save the result(s) to the given output directory.

    If not ``separate_folders`` (the default), then create one GeoJSON file.
    Otherwise, create several GeoJSON files, one for each folder in the KML file that contains geodata or that has a descendant node that contains geodata.
    Warning: this can produce GeoJSON files with the same geodata in case the KML file has nested folders with geodata.

    If a ``style_type`` is given, then also build a JSON style file of the given style type and save it to the output directory under the name given by ``style_filename``.
    """
    # Create absolute paths
    kml_path = Path(kml_path).resolve()
    output_dir = Path(output_dir)
    if not output_dir.exists():
        output_dir.mkdir()
    output_dir = output_dir.resolve()

    # Parse KML
    with kml_path.open(encoding='utf-8', errors='ignore') as src:
        kml_str = src.read()
    root = md.parseString(kml_str)

    # Build GeoJSON layers
    if separate_folders:
        layers = build_layers(root)
    else:
        layers = [build_feature_collection(root, name=kml_path.stem)]

    # Create filenames for layers
    filenames = disambiguate(
      [to_filename(layer['name'])
      for layer in layers])
    filenames = [name + '.geojson' for name in filenames]

    # Write layers to files
    for i in range(len(layers)):
        path = output_dir/filenames[i]
        with path.open('w') as tgt:
            json.dump(layers[i], tgt)

    # Build and export style file if desired
    if style_type is not None:
        if style_type not in STYLE_TYPES:
            raise ValueError('style type must be one of {!s}'.format(
              STYLE_TYPES))
        builder_name = 'build_{!s}_style'.format(style_type)
        style_dict = globals()[builder_name](root)
        path = output_dir/style_filename
        with path.open('w') as tgt:
            json.dump(style_dict, tgt)