--
-- dow_to_int/1
--
create or replace function dow_to_int(
  character varying
) returns int4 as $$

declare
       dow_to_int__weekday	alias for $1;
       v_dow			integer;
begin
       -- Brute force (what can I say?).
       select (case trim(upper(dow_to_int__weekday))
	             when 'SUNDAY'    then 1
	             when 'SUN'       then 1
		     when 'MONDAY'    then 2
		     when 'MON'	then 2
		     when 'TUESDAY'	then 3
		     when 'TUES'	then 3
		     when 'TUE'	then 3
		     when 'WEDNESDAY' then 4
		     when 'WED'	then 4
		     when 'WEDS'	then 4
		     when 'THURSDAY'  then 5
		     when 'THURS'	then 5
		     when 'THUR'	then 5
		     when 'THU'	then 5
		     when 'FRIDAY'	then 6
		     when 'FRI'	then 6
		     when 'SATURDAY'	then 7
		     when 'SAT'	then 7
		     else -1
		end) into v_dow
       from dual;
	
       if v_dow < 0 
       then 
	   raise exception 'Day of the week unknown';
       end if;

       return v_dow;

end;$$ language plpgsql;