huge clean up, replace for loops with *apply, added many more detailed comments