Refactor to reduce number of loops

Only build the missing_keys array once we have detected that there
actually are missing keys by moving the check to be part of the block
that performs the path substitution.