finished code to optimize first threshold WRT wa