Start with the oldest layer of the story. Tradition holds that before the capital moved to Heian-kyo in 794, a small shrine on this ground already honored a deity of epidemics, the storm god Susanoo. That little shrine survives today as an auxiliary shrine within Imamiya Shrine, called Yakujinja, the Epidemic Deity Shrine. Then came the year 994. A great plague swept the capital, and Kyoto answered the way it often did, with a goryoe, a ritual meant to soothe angry spirits blamed for disease. The court built two portable shrines and moved the epidemic deity into them. They were carried to the hill called Funaokayama and left there, music was offered, and the calamity was then drawn into offerings and sent floating away toward the inlet of Naniwa. This ritual, the Murasakino Goryoe, is regarded as the beginning of the Imamiya Festival. It happened again in 1001, when plague returned. This time the court moved the deity down from Funaokayama and built a proper sanctuary, sacred fence and portable shrine on the old site, and named it Imamiya-sha. That is the moment the shrine as an institution is said to begin. Three deities are enshrined here: Onamuchi no Mikoto, Kotoshironushi no Mikoto and Kushinadahime no Mikoto.