def flatten_strokes(strokes):
    """
    Flatten a list of strokes. Add stroke state in the process.

    For each point j, the stroke state is a tuple (pj, qj, rj) where:
      * pj=1 indicates the point is not the end of a stroke.
      * qj=1 indicates the point is the end of a stroke (but not the end of the drawing).
      * rj=1 indicates the point is the end of the drawing.
    By construction, pj + qj + rj = 1

    Input:
        [
            ((x1, x2, ..., xi-1, xi), (y1, y2, ..., yi-1, yi)),
            ((xi+1, ...), (yi+1, ...)),
            ...,
            ((..., xn-1, xn), (..., yn-1, yn))
        ]

    Output:
        [
            [x1,   y1,   1, 0, 0],
            [x2,   y2,   1, 0, 0],
            ...,
            [xi-1, yi-1, 1, 0, 0],
            [xi,   yi,   0, 1, 0]
            [xi+1, yi+1, 1, 0, 0],
            ...,
            [xn-1, yn-1, 1, 0, 0]
            [xn,   yn,   0, 0, 1]
        ]
    """

    flat_strokes = []

    for xs, ys in strokes:

        for x, y in zip(xs, ys):
            # Mark stroke in progress by default
            flat_strokes.append([x, y, 1, 0, 0])

        # Mark end of stroke
        x, y, *_ = flat_strokes[-1]
        flat_strokes[-1] = [x, y, 0, 1, 0]

    # Mark end of drawing
    x, y, *_ = flat_strokes[-1]
    flat_strokes[-1] = [x, y, 0, 0, 1]

    return flat_strokes