More correct function with check if file already exists