I think this code is mostly working now