Refactored to reduce code size; now down from 1304 to 1105 bytes.