/* 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 <string.h>
#include <stdlib.h>

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

#include "high_res_timer.h"

static void test(const char *fnm, int expect)
{
    long stat;
    struct FAB fab;
    struct RAB rab;
    char buf[1000];
    TIMECOUNT_T t1, t2;
    int n;
    t1 = GET_TIMECOUNT;
    fab = cc$rms_fab;
    fab.fab$l_fna = (char *)fnm;
    fab.fab$b_fns = strlen(fnm);
    fab.fab$b_fac = 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;
    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 = sizeof(buf);
        stat = sys$get(&rab, 0, 0);
        if(stat == RMS$_EOF) break;
        if(!(stat & 1))
        {
            printf("sys$get stat = %d\n", stat);
        }
        buf[rab.rab$w_rsz] = 0;
        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);
    }
    t2 = GET_TIMECOUNT;
    printf("sys$get : %d ms\n", (int)((t2 - t1) * 1000 / UNITS_PER_SECOND));
}

int main(int argc, char *argv[])
{
    int i;
    for(i = 0; i < 10; i++)
    {
        test(argv[1], atoi(argv[2]));
    }
    return 0;
}
