Opening and closing socket on each query
Some bugs corrected on free functions