I am a step further.. it seems to have something to do with the Shapefiles I am using. There are some types of Shapefiles where the code works, for some other ones, it doesn't. Here are two example shapefiles (130kb):
ShapeA_B.zip
ShapeA_B.zip