REM -- create a table of base words and exceptions
  create or replace package genword
  as
    function get_word(n number) return varchar2;
    function cardinal(n number) return varchar2;
  end genword;
  /
  show errors;
  
  create or replace package body genword
  as
    function get_word(n number) return varchar2
    is
      l_wordnumwords.word%type;
    begin
      select word into l_word from numwords
       where lang = sys_context('userenv','lang') and num = n;
      return l_word;
    exception
      when no_data_found then
        return null;
    end;
    --
    function cardinal(n number) return varchar2
    is
      p number;    -- power
      t varchar2(30); -- template
      v number;    -- lower portion
      l_word   numwords.word%type;
    begin
      if n < 0 then
        l_word := get_word(-1);
        if l_word is null then
          return null;
        end if;
        return l_word||' '||cardinal(-n);
      end if;
      l_word := get_word(n);
      if l_word is not null then
        return l_word;
      end if;
      for row in
      (
        select * from numrules
         where lang = sys_context('userenv','lang')
         order by seq
      )
      loop
        if length(n) <= row.p1 + row.p2 then
          p := power(10,row.p2);
          v := mod(n,p);
          if row.seq = 0 then
            if n < 20 then
              return replace(row.temp0,'~2',cardinal(v));
            end if;
          else
            if v = 0 then
              return replace(row.temp0,'~1',cardinal(n/p));
            else
              return replace(replace(nvl(row.temp,'~1 ~2'),
                '~1',cardinal(n-v)),
                '~2',cardinal(v));
            end if;
          end if;
        end if;
      end loop;
      return 'NUMBER TOO LARGE';
    end cardinal;
  end genword;
  /
  show errors;