finalized working code