Fix: Check output file isn't already a directory, handle errors, fix and add tests

Fixes #1034.
That's another option, but this way we're only running a single filesystem call instead of two.