Close all writers before returning error. Also fixed bug in last commit