WP_Scripts::print_scripts() calls two recursive functions.
- WP_Scripts::all_deps() builds a hierarchical array of dependencies.
- WP_Scripts::_print_scripts() reads that hierarchical array and echoes out a correctly ordered list of script tags.
The function should instead call one recursive function that builds a correctly ordered array of scripts. That simple array can then be processed non-recursively.
The attached also adds a new filter, print_scripts_array that could be used to do final post-processing of the scripts to deal with things WP_Script's naive dependency system can't do. Example: if prototype and jQuery are loaded on the same page, prototype should come first.
It could use some testing.