Thousands of prosecutions brought by two rail firms have been declared "null and void" by a court