Final working... unoptimised though