Context Free – Create a grammar that generates the language a ^ n. b ^ m. c ^ q. d ^ p such that n + p = q + m


I'm stuck with this question. I'm having trouble keeping track of the number of a and d generated.

The professor did not give the correction.

I have seen similar questions, but the condition is different, I can not find the grammar. Can you prove that it is not context-free?

EDIT: Inspiration from other, slightly similar questions, here is my solution, but I think it could be factored / improved

S -> S1 | S2
// S1 is the case in which I want to try to couple a to c (that is, if more c than d); S2 is the case where I want to couple d to b (ie, if there are more b than a).
S1 -> XY
X -> aXc | Z // for each a generate a c
Z -> aZb | epsilon // for each a generate a b
Y -> cYd | Epsilon // for each d generate c
// Since all the bs were created together with a's, I have not found a way to pair it with bs
S2 -> UV
U -> aUb | epsilon
V -> bVd | W
W -> cWd | episode