Sped things up a bit by optimizing cost function