Some code replaced with std algorithms.
Unused global variables removed, moved some into the globals infrastructure.
Minor cleanup, more consistent formatting.