Much more stable version, completely rewrote template functions, now properly handles defines