Fixed memory leak in generator, minor refactoring.