In testing out your script for the primary user, I found that if $PrimaryCount is set to 0.5 on line 169, because it's an Integer it rounds to 0. The script then errors when it tries to divide by 0.
I easily solved this by changing [int] to [decimal] in the 3 parts it's used in the script.
lines 133, 158, 169