Massive cleanup and refactor, now using macros to eliminate duplicate code