Generalized to include ternary structures. Cleaned up. Looks like it works, but more thorough testing required.