Moved all repeated code to the begining of generation