Return new file location
Write stream to file
Throw on invalid prefix
Create missing directories
remove some duplicate code