Stefan,
The code above errors for me at (distance m v) because 'v' returns nil.
Curve fit polylines are nothing more than a bunch of arcs.
It might happen to get an arc of 180deg or it might be replaced by a line, but i guess only after editing or stretching the polyline.
These are the only cases when v is nil and both can be solved.
For the first case you need to divide the arc in 2 segments. You need to do so for arcs larger than 180deg also.
For the second, v=m and w=1.0.