Some refactoring to simplify the generate() method.