   private var g : G
   
   mutating public func next() -> T? {
-    return g.next().flatMap { transform($0) ?? next() }
+    
+    while let next = g.next() {
+      if let ret = transform(next) {
+        return ret
+      }
+    }
+    return nil
+    
+//    Recursive version:
+//
+//    return g.next().flatMap { transform($0) ?? next() }
   }
 }
 

  private var innerGen : S.Generator?
  
  public mutating func next() -> S.Generator.Element? {
    return innerGen?.next() ?? {
      g.next().flatMap {
        innerGen = transform($0).generate()
        return next()
      }
    }()
  }
}

public struct FlatMapSeq<S0 : SequenceType, S1 : SequenceType> : LazySequenceType {

  private let transform: S0.Generator.Element -> S1
  
  public func generate() -> FlatMapGen<S0.Generator, S1> {
    return FlatMapGen(transform: transform, g: seq.generate())
  }
  
}
