added calls to free to prevent memory leaks