Cleanly define maximum lengths and add more checks for them
The new tests also found a few bugs that were fixed in commits just before this one.