Modularized this a bit to make it easier to read. Will modularie it further.
Finished cleaning up the script. Much more modularized now.