     tapp : tapp
   }
 
+#Give n position: [x,y,t] and delta: [dx,dy,dt],
+# Return position with biggest time <= t (inclusive).
+firstPositionBefore = (pos, delta, time) ->
+  # find integer i:
+  # t + i*dt < time
+  #
+  # i*dt < time - t
+  # i < (time-t)/dt
+  i0 = (time - pos[2]) / delta[2] #not integer.
+  #now find the nearest integer below
+  i = (Math.floor i0) |0
+  #and return the position
+  vecSum pos, vecScale delta, i
+  
+firstPositionAfter = (pos, delta, time) ->
+  i0 = (time - pos[2]) / delta[2] #not integer.
+  i = (Math.ceil i0) |0
+  vecSum pos, vecScale delta, i
+
+    
+#Normalize pattern and returns its rle.
 normalizedRle = (fld) ->
   ff = Cells.copy fld
   Cells.normalize ff

        #console.log "####      found! #{rle}"
        result.pos = [dx, dy, t]
        result.rle = rle
        result.found=true
        return false
      return (t-time) < period

    collided: false
  }

### Given the rule and the list of collition products (with their positions)
#   find a moment of time when they emerged.
###
findEmergeTime = (rule, products, minimalTime) ->
  invRule = rule.reverse()
  #Time position of the latest fragment
  maxTime = Math.max (p.pos[2] for p in products)...
  #Prepare all fragments, at time maxTime
  patterns = for product in products
    #console.log "#### Product: #{JSON.stringify product}"
    #first, calculate first space-time point before the maxTime
    initialPos = firstPositionBefore product.pos, product.delta, maxTime
    #Put the pattern at this point
    pattern = Cells.transform product.pattern, product.transform, false
    patternAtTime rule, pattern, initialPos, maxTime

  #console.log "#### Generated #{patterns.length} patterns at time #{maxTime}:"
  #console.log "#### #{normalizedRle [].concat(patterns...)}"
  
  #Now simulate it inverse in time
  invCollision = simulateUntilCollision invRule, patterns, -maxTime+1, -minimalTime
  if not invCollision.collided
    throw new Error "Something is wrong: patterns did not collided in inverse time"
  return -invCollision.time    
  
#simulate patern until it decomposes into several simple patterns
# Return list of collision products
finishCollision = (rule, field, time) ->
