Move awful, awful magic into separate file + fix off by one