refactored beta reduction code