// Copyright (c) 2013-2018 - Samuel GOUGEON

function [r, err] = queryserial(h, command, nbytes, swait, errquery)
    // nbytes: maximal number of bytes to read. 0 means All bytes in buffer
    // swait: duration of the pause after the write command, before reading the buffer [s]
    // errquery (string): command to send in case of error status after the write command,
    //    in order to get from the device some information about the error that occurred.
    // r: result (string)
    // err: if errquery is provided: the result of error query command (string)
    //      else: output status as from writeserial (decimal)
    if argn(2)<3
        nbytes = 0
    end
    if argn(2)<4
        swait = 0.002
    else
        swait = min([abs(swait) .002])
    end
    if argn(2)<5
        errquery = ""
    end

    s = writeserial(h, command)
    if s==-1
        if errquery~=""
            [r, err] = queryserial(h, errquery, nbytes, swait) // no <errquery> => can't loop
        else
            r = ""
            err = -1
            return
        end
    end
    if swait
        sleep(swait*1000)
    end
    r = readserial(h, nbytes)
    err = 0
endfunction
