-- Function: rasters.makegrid(geometry, double precision, double precision)

-- DROP FUNCTION rasters.makegrid(geometry, double precision, double precision);

CREATE OR REPLACE FUNCTION rasters.makegrid(IN geometry, IN double precision, IN double precision)
  RETURNS TABLE(gid integer, the_geom geometry) AS
$BODY$
DECLARE
	geom ALIAS FOR $1;  -- bounding box
	xstep ALIAS for $2; -- x grid step
	ystep ALIAS for $3; -- y grid step
	x float8;
	y float8;
	xmax float8;
	ymax float8;

		
BEGIN

x := st_xmin(geom);
y := st_ymin(geom);
xmax := st_xmax(geom);
ymax := st_ymax(geom);

create unlogged table tmp_makegrid (gid serial, the_geom geometry);

LOOP --xloop
	
	LOOP --yloop

	insert into tmp_makegrid(the_geom)
	select st_geomfromtext('POLYGON((
	'||x||' '||y||',
	'||x+xstep||' '||y||',
	'||x+xstep||' '||y+ystep||',
	'||x||' '||y+ystep||',
	'||x||' '||y||'))',
	st_srid(geom)
	);

	y := y+ystep;

	EXIT WHEN y > ymax;
	END LOOP;
	
x := x+xstep;
y := st_ymin(geom);

EXIT WHEN x > xmax;
END LOOP;
	
return query

select * from tmp_makegrid;
	
RETURN ;

drop table tmp_makegrid;

END;

$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;
ALTER FUNCTION rasters.makegrid(geometry, double precision, double precision)
  OWNER TO hug;
