your solution to apply it is the same I wrote before with the difference that u not precompile a function from the script. your method compiles the script everytime before it runs on each unit. in my version its only compiled once.
the other difference is that u use forEach instead of count which is slightly faster.
and at last u use allUnits instead of allUnits-allPlayers which causes ur problem that the script is applied to players as well.
to get extra abilities to the medic u could rollback to the original version of the script and insert a check if unit is a medic like this:
if(_medic getUnitTrait "Medic") then
hint "its a medic";
hint "its not a medic";