Here's a sketch of how it's done. Does this help?

https://github.com/Pash-Project/Pash/commit/d3f5bc5106c66bd7305cb9b0c0d9a7d72c592d92