fix nested ref bug and add unit test coverage