code: def template_to_filepath(template, metadata, template_patterns=None):
  	path = Path(template)
  	if template_patterns is None:
  		template_patterns = TEMPLATE_PATTERNS
  	suggested_filename = suggest_filename(metadata)
  	if (
  		path == Path.cwd()
  		or path == Path('%suggested%')
  	):
  		filepath = Path(suggested_filename)
  	elif any(template_pattern in path.parts for template_pattern in template_patterns):
  		if template.endswith(('/', '\\')):
  			template += suggested_filename
  		path = Path(template.replace('%suggested%', suggested_filename))
  		parts = []
  		for part in path.parts:
  			if part == path.anchor:
  				parts.append(part)
  			else:
  				for key in template_patterns:
  					if (
  						key in part
  						and any(field in metadata for field in template_patterns[key])
  					):
  						field = more_itertools.first_true(
  							template_patterns[key],
  							pred=lambda k: k in metadata
  						)
  						if key.startswith(('%disc', '%track')):
  							number = _split_number_field(
  								str(
  									list_to_single_value(
  										metadata[field]
  									)
  								)
  							)
  							if key.endswith('2%'):
  								metadata[field] = number.zfill(2)
  							else:
  								metadata[field] = number
  						part = part.replace(
  							key,
  							list_to_single_value(
  								metadata[field]
  							)
  						)
  				parts.append(_replace_invalid_characters(part))
  		filepath = Path(*parts)
  	elif '%suggested%' in template:
  		filepath = Path(template.replace('%suggested%', suggested_filename))
  	elif template.endswith(('/', '\\')):
  		filepath = path / suggested_filename
  	else:
  		filepath = path
  	return filepath