Restructed working code