Final working code