   rev_count := 1;
 
   FOR row IN (WITH way_versions AS (
-    SELECT w.tstamp AS t1, next.tstamp AS t2, w.visible, w.version, w.changeset_id, w.user_id, w.nodes
+    SELECT w.tstamp, w.visible, w.version, w.changeset_id, w.user_id, w.nodes
     FROM ways w
     --LEFT JOIN ways next ON (next.id = w.id AND next.version = w.version + 1)
-    LEFT JOIN ways next ON (next.id = w.id AND next.version = (SELECT version FROM ways WHERE id = $1 AND version > w.version ORDER BY version LIMIT 1))
+    --LEFT JOIN ways next ON (next.id = w.id AND next.version = (SELECT version FROM ways WHERE id = $1 AND version > w.version ORDER BY version LIMIT 1))
     WHERE w.id = $1),
 
   revs AS (
-    SELECT MAX(n.tstamp) AS tstamp, n.changeset_id, n.user_id, array_agg(n.id) AS nodes--, wv.version, wv.visible, wv.nodes
+    SELECT n.tstamp, n.changeset_id, n.user_id, array_agg(n.id) AS nodes--, wv.version, wv.visible, wv.nodes
     FROM nodes n
     INNER JOIN nodes n2 ON (n2.id = n.id AND n2.version = n.version - 1)
     --INNER JOIN way_versions wv ON (n.tstamp > wv.t1 AND (t2 IS NULL OR n.tstamp < wv.t2) AND n.id IN (SELECT unnest(wv.nodes)))
     WHERE n.id IN (SELECT unnest(nodes) FROM way_versions) AND NOT n.geom = n2.geom AND n.visible
       AND (last_rev_tstamp IS NULL OR n.tstamp > last_rev_tstamp)
-      AND n.tstamp >= (SELECT MIN(t1) FROM way_versions)
-    GROUP BY n.changeset_id, n.user_id)--, wv.version, wv.visible, wv.nodes)
+      AND n.tstamp >= (SELECT MIN(tstamp) FROM way_versions)
+    GROUP BY n.tstamp, n.changeset_id, n.user_id, n.id)--, wv.version, wv.visible, wv.nodes)
 
   SELECT
     $1,

DECLARE
  last_rev_tstamp timestamp without time zone;
  row record;
  last_way record;
  rev way_revisions%rowtype;
  rev_count int;

BEGIN
  last_rev_tstamp := (SELECT MAX(tstamp) FROM way_revisions WHERE way_id = $1);

  RAISE NOTICE '% -- Generating revisions for way % [last = %]', clock_timestamp(), $1, last_rev_tstamp;

      'W' AS type,
      version,
      user_id,
      tstamp,
      changeset_id,
      visible,
      nodes
