Refactored generate-function