Got a general solution working for this problem.