Semi-working one-threaded version with debug prints