Rewrote in C++