import vector, config

Vector *def readvalues_v(char const *filename):
    FILE *f = fopen(filename, "rb")
    if not f: return None
    Vector *v = vector_new(sizeof(V))
    V x
    while fscanf(f, "%fl", &x) > 0:
        vector_add(v, &x)
    fclose(f)

    return v

def writevalues_v(char const *filename, Vector *v):
    FILE *f = fopen(filename, "wb")
    if not f: return
    for int i = 0; i < v->count; i++:
        V *xp = vector_get(v, i)
        fprintf(f, "%fl ", *xp)
    fclose(f)

Vector *def readfile_datasize(char const *filename, int datasize):
    FILE *f = fopen(filename, "rb")
    if not f: return None
    Vector *v = vector_new(datasize)
    size_t K = 1024
    char buf[K * datasize]
    while 1:
        size_t s = fread(buf, datasize, K, f)
        vector_cat(v, buf, s)
        if s < K:
            break
    fclose(f)
    return v

Vector *def readfile(char const *filename):
    return readfile_datasize(filename, 1)

def writefile(char const *filename, Vector *v):
    FILE *f = fopen(filename, "wb")
    fwrite(v->data, v->count, v->element_size, f)
    fclose(f)

int def hasword(char const *list, char const *word):
    int i = 0
    while 1:
        char const *pos = strstr(list + i, word)
        if not pos: return False
        # Do not consider beginning in the middle of a word.
        if pos > list:
            if *(pos - 1) != ' ':
                i = pos - list + 1
                continue
        # Do not consider ending in the middle of a word.
        if pos + strlen(word) < list + strlen(list):
            if *(pos + strlen(word)) != ' ':
                i = pos - list + 1
                continue
        return True

double def util_time():
    struct timeval tv
    gettimeofday(&tv, None)
    return tv.tv_sec + tv.tv_usec / 1000000.0