rewrote in C with some crazy optimization