Fixed and improved filewriting