Reworked code to avoid too much global variables