-- Function: public.geometry_filter(geometry, text)

-- DROP FUNCTION public.geometry_filter(geometry, text);

CREATE OR REPLACE FUNCTION public.geometry_filer(geometry, text)
  RETURNS geometry AS
'DECLARE

  shp ALIAS for $1;

  gtype ALIAS for $2;

  gshp GEOMETRY;

  i integer;

  j integer;



  ishp GEOMETRY;

  exshp GEOMETRY;  

  c_shp  GEOMETRY;

  m_shp GEOMETRY;

BEGIN



   IF ( geometrytype(shp) = gtype) THEN

     return shp;

   END IF;

   

   IF ( geometrytype(shp) = \'POLYGON\' ) THEN

     ishp = replace(astext(shp),\'POLYGON(\',\'MULTIPOLYGON((\') || \')\';     

   ELSE

     IF ( geometrytype(shp) = \'LINESTRING\' ) THEN

       ishp = replace(astext(shp),\'LINESTRING(\',\'MULTILINESTRING((\') || \')\';   

     ELSE

       ishp = shp;

     END IF;

   END IF; 



   IF ( (numgeometries(ishp) is NULL) ) THEN

       return NULL;

   END IF;



  

   c_shp = NULL;

-- non compound objects (non Multi) drop through here

   FOR j IN 1..(numgeometries(ishp)) LOOP



     gshp = geometryn(ishp,j); 

     IF ( geometrytype(gshp) = \'POLYGON\' ) THEN

       gshp = replace(astext(gshp),\'POLYGON(\',\'MULTIPOLYGON((\') || \')\';

     END IF;

     IF ( (geometrytype(shp) = \'LINESTRING\') and (startpoint(shp) = endpoint(shp)) ) THEN

       ishp = replace(astext(shp),\'LINESTRING(\',\'MULTIPOLYGON(((\') || \'))\';   

     END;

 

     IF ( (geometrytype(gshp) = gtype ) ) THEN

       IF ( c_shp is not NULL ) THEN

          c_shp = geometry_union(c_shp,gshp);

       ELSE

          c_shp = gshp;

       END IF;

     END IF;

   END LOOP;

  

  -- hard coded for MultiPolygons 

  IF ( geometrytype(c_shp) = \'POLYGON\' ) THEN

     c_shp = replace(astext(c_shp),\'POLYGON(\',\'MULTIPOLYGON((\') || \')\';

   END IF;

 

   RETURN c_shp;



END;'
  LANGUAGE 'plpgsql' IMMUTABLE STRICT;
