Needs more testing, but I think it works now.