Finding Z Order of Applications

I’m running a script that depends on the order of applications, which one was last accessed, and the one before that et. I’m writing a script to control multiple media programs, and if more than one is open I need to know which one was activated last. It isn’t as simple as finding the frontmost application, I need to find the order that they were accessed.