Major refactoring. Cleaned up variable names. Removed duplication. Still needs work, but no longer so ugly and confusing.