I’ve debugged your code and it seems to do exactly what you wish to achieve.
I have to say I don’t really like the usage of .data in general, but this might be a valid use case. 
At least I’m not sure how to make it better without manipulating the linear implementation.
Maybe someone else will have a good idea.