Adding most of the logic