Does the following meet your requirements? (Requirements were hard to understand. I assume there is more simple and faster XSLT code to accomplish this task ...)
It evaluates for the given input to the expected output https://xsltfiddle.liberty-development.net/pNmC4J7