Long before magic mushrooms became a way for hippies to turn on, tune in, and drop out, and well before ancient mesoamerican mystics employed them in religious ritual, they had their use as an insect repellant. Some 200 species of mushrooms naturally produce psilocybin, which, when imbibed by humans, can trigger “magic,” hallucinogenic effects. But obviously these mushrooms didn’t evolve to send humans on psychedelic trips.

Psilocybin also affects insects’ minds, making them less hungry. Given that most magic mushrooms grow in environments particularly welcoming to insects—the mushroom’s natural predator—it’s likely the psychedelic compound developed as a tool for evolutionary survival.

A study published Feb. 27 in Evolution Letters sets out the evidence for this reasoning. There’s no clear, distinct family of mushrooms that contain psilocybin. The dozens of different species are distantly related, suggesting the genes for psilocybin weren’t passed down through one biological lineage, but instead that the genetic material for psilocybin transferred across species (known as horizontal gene transfer.)

In their recent study, researchers led by Jason Slot, professor of fungal evolutionary genomics at Ohio State University, sequenced the genomes of three distantly related magic mushroom species and compared them with much more closely related non-psychedelic mushrooms. They identified a cluster of five genes responsible for psychedelic qualities, and found that the distantly related psilocybin mushrooms had more similar genomes than closely related mushrooms that lived in different environments.

This suggests that the genes were transferred (horizontal transferring is more common for genes within clusters) as a response to stresses within the environment. In this case, the environments in question are animal dung and rotting wood, where there are plenty of mushroom-eating insects.

Psilocybin’s ability to interfere with the mind has a clear evolutionary benefit for mushrooms growing amid animal dung. It interferes with neurotransmitters in insects’ minds to make them less hungry and so less likely to eat mushrooms. “The psilocybin probably doesn’t just poison predators or taste bad,” Slot said in a statement. “These mushrooms are altering the insects’ ‘mind’—if they have minds—to meet [the mushrooms’] own needs.”

Decoding the original purpose and genes behind magic mushrooms could help advance new uses for psilocybin. There’s currently fast-advancing research on psilocybin as a potential treatment for depression, addiction, and treating anxiety among patients with terminal cancer.