nit: It would be nice to use keyword arguments for all of these to make it easier for the reader to see which arguments are which parameters, especially since there are a lot of arguments to this function and some of them aren't obvious what they do (eg. `''`).