Fixed endless loop when only resources with requirements are left.
Also fixed some border cases.