--
-- define_function_args/2
--
create or replace function define_function_args(
  character varying,
  character varying
) returns int4 as $$

declare
  p_function            alias for $1;
  p_arg_list            alias for $2;

  v_arg_seq             integer default 1;
  v_arg_name            varchar;
  v_arg_default         varchar;
  v_elem                varchar;
  v_pos                 integer;
begin
  delete from acs_function_args where function = upper(trim(p_function));

  v_elem = split(p_arg_list, ',', v_arg_seq);
  while v_elem is not null loop
    
    v_pos = instr(v_elem, ';', 1, 1);
    if v_pos > 0 then
      v_arg_name := substr(v_elem, 1, v_pos-1);
      v_arg_default := substr(v_elem, v_pos+1, length(v_elem) - v_pos);
    else
      v_arg_name := v_elem;
      v_arg_default := NULL;
    end if;

    insert into acs_function_args (function, arg_seq, arg_name, arg_default)
	   values (upper(trim(p_function)), v_arg_seq, upper(trim(v_arg_name)), v_arg_default);

    v_arg_seq := v_arg_seq + 1;
    v_elem = split(p_arg_list, ',', v_arg_seq);
  end loop;
    
  return 1;
end;$$ language plpgsql;