Clean management of global variables. Added a bunch of tests