Refactoring of gen.py