Refactor instances

This encapsulates the template instance lookup scheme, so that it can be later replaced with a more efficient one.