Inefficient code for most of the calcs. The Z and betas might be wrong.