Anyone able to recommend a possible soultion to this problem?

(If it's not clear, how the script is supposed to work ask & i will explain the unclear parts in details)