CREATE OR REPLACE FUNCTION to_legal_tsvector(doctext text)
  RETURNS tsvector
  LANGUAGE plpgsql
  IMMUTABLE
  RETURNS NULL ON NULL INPUT
  COST 1000
AS $to_legal_tsvector$
DECLARE
  cite text;
  wrk text = '';
  wordcount int = 0;
  matchlevel char;
BEGIN
  FOR cite IN
    SELECT regexp_matches(doctext, '(?:[A-Z]+\-?)?[0-9]+[A-Za-z0-9]*(?:\([A-Za-z0-9]+\)|[\.\-][A-Za-z0-9]+)+(?:\([A-Za-z0-9]+\)[A-Za-z0-9]+)?', 'g')
  LOOP
    cite = substring(cite from 2 for char_length(cite) - 2);
    matchlevel = 'A';
    LOOP
      wordcount = wordcount + 1;
      wrk = wrk || cite || ':' || wordcount::text || matchlevel || ' ';
      cite = regexp_replace(cite, '\.?\(?[^\(\.\-\)]+\)?$', '');
      EXIT WHEN cite = '';
      matchlevel = CASE matchlevel WHEN 'A' THEN 'B' ELSE 'C' END;
    END LOOP;
  END LOOP;
  RETURN rtrim(wrk)::tsvector || to_tsvector(doctext);
END;
$to_legal_tsvector$;
