--SELECT gid, id, prec_plani, nom, code_insee, statut, canton, arrondisst, depart, region, popul, multican, geometrie FROM ign_bd_topo.commune;
 
--SELECT ceiling (( ST_xmax ( ST_Extent (geometrie)) - ST_xmin ( ST_Extent (geometrie))) / 533 ) as width, ceiling (( ST_ymax ( ST_Extent (geometrie)) - ST_ymin ( ST_Extent (geometrie))) / 600 ) as height, ST_Extent (geometrie) as thee FROM ign_bd_topo.commune 
 
 TRUNCATE export.grille_500m;
 --CREATE TABLE export.grille_500m(gid SERIAL PRIMARY KEY);
 --SELECT AddGeometryColumn('export', 'grille_500m', 'geometrie', 310024140, 'POLYGON', 2);
 
 INSERT INTO export.grille_500m(geometrie)
 SELECT DISTINCT slice FROM (SELECT ST_translate(ref.boxrep, hor.n*width, ver.n*height) AS slice
 FROM
 (SELECT ST_xmin(ST_Extent(geometrie)) AS xstart, ST_xmin(ST_Extent(geometrie)) AS ystart, ST_SetSRID(CAST('BOX(588681.1 6137110.7,589181.1 6137610.7)' AS box2d), 310024140) AS boxrep,
 ceiling((ST_xmax(ST_Extent(geometrie)) - ST_xmin(ST_Extent(geometrie)))/533) AS width, 
     ceiling((ST_ymax(ST_Extent(geometrie)) - ST_ymin(ST_Extent(geometrie)))/600) AS height
 FROM ign_bd_topo.commune) AS ref, generate_series(1,533) AS hor(n), generate_series(1,600) AS ver(n)) foo INNER JOIN ign_bd_topo.commune
 ON st_intersects(foo.slice, commune.geometrie)-- WHERE commune.code_insee LIKE '34%'
 ;
 
 --CREATE INDEX geom_index_grille_500m ON export.grille_500m USING gist(geometrie);
 
-- SELECT sum(area2d(geometrie))/(500*500) FROM ign_bd_topo.commune;