moved some functions out of loops and fixed vars conflict