wrote a c version that actually works