improved ref derivation, still some bugs