      
declare
bid     alias for $1;
eid     alias for $2;
topn    alias for $3;
textstr text;
rec RECORD;
begin
-- Confirm snap IDs
PERFORM 1 from edb$snap where edb_id = bid;
if not found then
     raise exception 'Begin snapshot identifier % does not exist', bid::text;
END IF;
PERFORM 1 from edb$snap where edb_id = eid;
if not found then
     raise exception 'End snapshot identifier % does not exist', eid::text;
END IF;
textstr := rpad('WAIT NAME',40,' ')||' '||rpad('COUNT',10,' ')||' '||rpad('WAIT TIME',15,' ')||
' '||'% WAIT';
return next textstr;
textstr := '---------------------------------------------------------------------------';
return next textstr;
for rec in (
select e.wait_name,
        abs(e.wait_count - b.wait_count)  as wait_count,   -- sum of all session wait counts
        abs(e.totalwait - b.totalwait)  as totalwait,      -- sum of all session wait times
        round(100* (sumwait/twaits),2) as pctwait     -- divides total waits per event/total of all waits 
                 from  edb$system_waits as b
                    ,  edb$system_waits  as e
    , (select b.wait_name ,sum(abs(e.totalwait - b.totalwait)) as sumwait 
		from edb$system_waits b,
		edb$system_waits e
	where b.edb_id = bid
	and e.edb_id = eid
	and b.wait_name = e.wait_name 
        group by b.wait_name
        ) as sw,           			-- this gets total waits per event for snap period
        (select sum(abs(e.totalwait - b.totalwait)) as twaits 
     		from edb$system_waits b,
			edb$system_waits e
		where b.edb_id = bid
		and e.edb_id = eid
		and b.wait_name = e.wait_name) as tw  -- this gets sum of all waits per snap period
where b.edb_id              = bid
and e.edb_id              = eid
and b.dbname              = e.dbname
and b.wait_name           = e.wait_name
and e.wait_name          = sw.wait_name
and twaits               > 0              -- avoids divide by zero error
    order by pctwait desc, totalwait desc 
    limit topn)  LOOP                               
textstr := rpad(rec.wait_name,40,' ')||' '||rpad(rec.wait_count::text,10,' ')||' '||rpad(rec.totalwait::text,15,' ')||
' '||rec.pctwait;
return next textstr;
end loop;
return;
end;
    