
create or replace function wcost_average_sf (numeric[],  numeric, numeric)
returns numeric[] as 
$Body$
	declare 
		_state numeric[];
	begin 
		_state := $1;
		_state := array_append(_state, $2);
		_state := array_append(_state, $3);
		return _state;
	end;
$Body$
LANGUAGE 'plpgsql' VOLATILE;

create or replace function wcost_average_ff (numeric[] )
returns numeric as 
$Body$
	declare 
		iState       alias for $1 ;
		_sumedWeight numeric ;
		_sumedWxV    numeric ;
		_elmentCount integer ;
		_icounter    integer ;
	begin 
		_elmentCount := array_upper(iState,1) ;
		_sumedWeight := 0 ;
		_sumedWxV    := 0 ;
		_icounter    := 0 ;
			
		loop
			_sumedWeight := _sumedWeight + iState[_icounter + 1] ;
			_icounter := _icounter + 2 ;
			
			if ( _icounter = _elmentCount ) then
				exit; 
			end if ;
		end loop ; 

		_icounter := 0;
		loop 
			_sumedWxV := _sumedWxV + ( (iState[_icounter + 1]/_sumedWeight) * iState[_icounter+2]) ;
			_icounter := _icounter + 2 ;
			
			if ( _icounter = _elmentCount ) then
				exit; 
			end if ;
		end loop ;
		return _sumedWxV;
	end;
$Body$
LANGUAGE 'plpgsql' VOLATILE;


create aggregate wcost_average (numeric, numeric)(
sfunc = wcost_average_sf, 
stype = numeric[],
initcond = '{0,0}',
finalfunc = wcost_average_ff
);