Refactor dependency resolution

At the same time, expand variables in manual order and groups
correctly. Dependencies can now be resolved in reverse order
all the time, and also in default order if a dependency outside
the target already exists.