Refactored, cleaned-up and commented; Fixed a few efficiency/leaks, possibly.