I'll be the first to admit I hate all this logic in the template, but the whole template is like this. Definitely the whole file could use a refactoring but at the moment this is the best I can do.