How to interpret dihedraltypes

I have a code that reads GROMACS top files. I’m having trouble figuring out how to interpret dihedraltypes directives correctly. It allows each line to list either all four atoms, or just the two central ones. How do I determine how many atoms are in a given line? If I know the function type, that tells me the expected number of parameters on the line, from which I can determine how many fields must contain atom types. But until I know how many atoms are listed, I don’t know which field contains the function type, so I don’t know how many fields to expect.

I’ve come up with various hacks, but I’m not confident that any of them will be robust. What is the correct way of doing it?

Thanks!