-- Prefix UNACCENT with "public"

CREATE OR REPLACE FUNCTION public.getsafexmlpath(val character varying, with_root integer DEFAULT 0)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  IF with_root = 1 THEN
    val = regexp_replace(val, '^\w+', 'root');
  ELSIF with_root = 2 THEN
    val = regexp_replace(val, '^\w+/', '');
  END IF;

  val = public.UNACCENT(val);
  val = REGEXP_REPLACE(val, '[\., _]', '-', 'g');
  val = REPLACE(val, '&', '-'); /* ampersand should always be blank but it gets fixed in below */
  val = lower(val);
  val = REGEXP_REPLACE(val, '-+', '-', 'g');
  val = REGEXP_REPLACE(val, '[^\/\w\-]', '', 'g');

  RETURN val;

END;
$function$
;
