gave credit to fabien for his explanation of this code