Rewrote inline function, now 100% more robust