--
-- next_day/2
--
create or replace function next_day(
  timestamp with time zone,
  character varying
) returns timestamptz as $$

declare
       next_day__somedate	alias for $1;
       next_day__weekday	alias for $2;
       v_dow			integer;
       v_ref_dow		integer;
       v_add_days		integer;
begin
	-- I cant find a function that converts days of the week to
	-- the corresponding integer value, so I roll my own (above)
	-- We avoid extract(dow from timestamp) because of incompatible output with to_char.
	v_ref_dow := dow_to_int(next_day__weekday);
	v_dow := to_number(to_char(next_day__somedate,'D'),'9');
	
	-- If next_day___weekday is the same day of the week as
	-- next_day__somedate, we add a full week.
	if v_dow < v_ref_dow
	then
	     v_add_days := v_ref_dow - v_dow;
        else
	     v_add_days := v_ref_dow - v_dow + 7;
	end if;

	-- Do date math
	return next_day__somedate + to_interval(v_add_days,'days');

end;$$ language plpgsql;