some memory leaks fixed, but some left, and attempt for writefile