Removes duplicate code and flattens the structure