Some files has never closed leading to file descriptor leak

* Now all files open are also closed
* Make some refactorization in the code