Generate legends conditionally.
Miscellaneous refactoring.