complete overhaul, inspired by work on the C++ version