clean version barring the fact that there is a free() error on close, have to look into it