Integrated David's code