final working code with all changes