It seems to be working now

But I'm still unsure that it's returning the right quantities and need
to figure that out. Also, I'm pretty sure the calculations for level 0
are meaningless. I'll worry more about it later.