Custom query result formatting

This adds interfaces for query output formatting. And provides implementations for writing into files, with custom format specified. 
Good catch. Will fix