This function is really huge.  Can you simplify it, and calculate the major things (e.g., xPos, yPos, ...) in separate functions?