Added some stuff not used before, fixed a few bugs, restructured for code clarity.