working version of BG minimization loop + rayleigh fit. Needs to clean up the code, and make the connections with the next routines.