I have the feeling that many of these variables don't need to be global. Could you please move all variables that can be local variables into the appropriate function?

Also, variable names such as "sq" are fine when inside a function or loop and when it's obvious what they're standing for. For global variables, these names are too cryptic. Also, I have no idea what "sq" and "sp" is standing for … *s*tats *p*ointer? What's the "g" prefix of "gsp" and "gsq"?