Improved 'index' counter to prevent using global variables and therefore also reseting those variables.