Mostly working now, but I'm concerned there's a fundamental flaw in the algorithm's implementation