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

Fixes #1034.