Updated logic for choosing proper template