add little optimisation + remove some global variables, need code review