/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <starlet.h>
#include <rms.h>

#include "high_res_timer.h"

static void test(const char *fnm, int expect, int blksiz)
{
    long stat;
    struct FAB fab;
    struct RAB rab;
    char *buf;
    TIMECOUNT_T t1, t2;
    int n, i;
    t1 = GET_TIMECOUNT;
    buf = malloc(blksiz);
    fab = cc$rms_fab;
    fab.fab$l_fna = (char *)fnm;
    fab.fab$b_fns = strlen(fnm);
    fab.fab$b_fac = FAB$M_BIO | FAB$M_GET;
    stat = sys$open(&fab, 0, 0);
    if(!(stat & 1))
    {
        printf("sys$open stat = %d\n", stat);
    }
    rab = cc$rms_rab;
    rab.rab$l_fab = &fab;
    rab.rab$b_rac = RAB$C_SEQ;
    rab.rab$l_rop = RAB$M_RAH;
    rab.rab$b_mbc = 127;
    rab.rab$b_mbf = 127;
    stat = sys$connect(&rab, 0 ,0);
    if(!(stat & 1))
    {
        printf("sys$connect stat = %d\n", stat);
    }
    n = 0;
    for(;;)
    {
        rab.rab$l_ubf = buf;
        rab.rab$w_usz = blksiz;
        stat = sys$read(&rab, 0, 0);
        if(stat == RMS$_EOF) break;
        if(!(stat & 1))
        {
            printf("sys$read stat = %d\n", stat);
        }
        for(i = 0; i < rab.rab$w_rsz; i++)
        {
            if(buf[i] == '\n') n++;
        }
    }
    if(n != expect)
    {
        printf("%d lines\n", n);
    }
    stat = sys$disconnect(&rab, 0, 0);
    if(!(stat & 1))
    {
       printf("sys$disconnect stat = %d\n", stat);
    }
    stat = sys$close(&fab, 0, 0);
    if(!(stat & 1))
    {
       printf("sys$close stat = %d\n", stat);
    }
    free(buf);
    t2 = GET_TIMECOUNT;
    printf("sys$read (rop=rah mbc=127 mbf=127) (block size %d) : %d ms\n", blksiz, (int)((t2 - t1) * 1000 / UNITS_PER_SECOND));
}

int main(int argc, char *argv[])
{
    int blksiz[] = { 512, 5120, 51200, 512000 };
    int i, j;
    for(j = 0; j < 4; j++)
    {
        for(i = 0; i < 10; i++)
        {
            test(argv[1], atoi(argv[2]), blksiz[j]);
        }
    }
    return 0;
}
