A backwards relationship Write a program or function that, given two ASCII strings A and B, will produce strings A' and B' where the common substrings are reversed in their place. The process for finding A' is as follows:


A' is initially empty.
If the first character of A is in B, find the longest prefix of A which is a substring of B. Remove this prefix from A and add its reversal to A'.
Otherwise, remove this first character from A and add it to A'.
Repeat steps 2-3 until A is empty.


Finding B' is done similarly.

Example

Let's consider the strings A = "abc bab" and B = "abdabc". For A', this is what happens:


A = "abc bab": The first character "a" is in B and the longest prefix of A found in B is "abc". We remove this prefix from A and add its reversal "cba" to A'.
A = " bab": The first character " " is not in B, so we remove this character from A and add it to A'.
A = "bab": The first character "b" is in B and the longest prefix of A found in B is "b". We remove this prefix from A and add its reversal (which is still "b") to A'.
A = "ab": The first character "a" is in B and the longest prefix of A found in B is "ab". We remove this prefix from A and add its reversal "ba" to A'.
A = "": A is empty, so we stop.


Thus we get A' = "cba" + " " + "b" + "ba" = "cba bba". For B', the process is similar:

B = "abdabc"  -&gt;  "a" in A, remove prefix "ab"
B = "dabc"    -&gt;  "d" not in A, remove "d"
B = "abc"     -&gt;  "a" in A, remove prefix "abc"


Thus we get B' = "ba" + "d" + "cba" = "badcba".

Finally, we return the two strings, i.e.

(A', B') = ("cba bba", "badcba")


Test cases

"abc bab", "abdabc" -&gt; "cba bba", "badcba"
"abcde", "abcd bcde" -&gt; "dcbae", "dcba edcb"
"hello test", "test banana" -&gt; "hello tset", "tset banana"
"birds flying high", "whistling high nerds" -&gt; "bisdr flyhgih gni", "wihstlhgih gni nesdr"




Shortest code in bytes wins.
Haskell, 120 111 bytes

import Data.List
a&amp;b=(a#b,b#a)
[]#_=[]
(a:y)#b=[a]%y where p%(i:w)|reverse(i:p)`isInfixOf`b=(i:p)%w;p%x=p++x#b


Test runs:

λ: "abc bab"&amp;"abdabc"
("cba bba","badcba")

λ: "abcde"&amp;"abcd bcde"
("dcbae","dcba edcb")

λ: "hello test"&amp;"test banana"
("hello tset","tset banana")

λ: "birds flying high"&amp;"whistling high nerds"
("bisdr flyhgih gni","wihstlhgih gni nesdr")