       'W' AS type,
       version,
       user_id,
-      t1 AS tstamp,
+      tstamp,
       changeset_id,
       visible,
       nodes

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;

    SELECT
      'N' AS type,
      NULL,--version,
      revs.user_id,
      revs.tstamp,
      revs.changeset_id,
      true,--visible,
      revs.nodes
    FROM revs) q
  WHERE last_rev_tstamp IS NULL OR q.tstamp > last_rev_tstamp
  ORDER BY q.tstamp, q.type DESC) LOOP
    IF row.type = 'W' THEN
      IF last_node.tstamp IS NOT NULL THEN
        rev := ($1,last_way.version,rev_count,last_way.visible,last_node.user_id,last_node.tstamp,last_node.changeset_id);
        rev_count := rev_count + 1;
        SELECT NULL::timestamp without time zone AS tstamp, NULL::int AS changeset_id INTO last_node;
        --raise notice 'AAAAAAAAAAAAAAAAa -- %', rev;
        RETURN NEXT rev;
      END IF;

      last_way := row;
      rev := ($1,row.version,rev_count,row.visible,row.user_id,row.tstamp,row.changeset_id);
      rev_count := rev_count + 1;
      --raise notice '-- %', rev;
      RETURN NEXT rev;
    END IF;

    IF row.type = 'N' AND last_way.nodes && row.nodes AND row.tstamp > last_way.tstamp THEN
      IF last_node.tstamp IS NOT NULL AND (row.tstamp - INTERVAL '5 seconds' > last_node.tstamp OR
          last_node.changeset_id != row.changeset_id) THEN
        rev := ($1,last_way.version,rev_count,last_way.visible,last_node.user_id,last_node.tstamp,last_node.changeset_id);
        rev_count := rev_count + 1;
        --raise notice 'BBBBBBBBBBBBBB -- %', rev;
        RETURN NEXT rev;
      END IF;
      last_node := row;
    END IF;
  END LOOP;

  IF last_node.tstamp IS NOT NULL THEN
    rev := ($1,last_way.version,rev_count,last_way.visible,last_node.user_id,last_node.tstamp,last_node.changeset_id);
    RETURN NEXT rev;
  END IF;

END;
$$ LANGUAGE plpgsql;

