/*
DIRLIST
*/

#include <plib.h>
#include <prndir.g>

LOCAL_D VOID *dcb=NULL;
LOCAL_D VOID *hand;

LOCAL_C VOID error(TEXT *msg, INT errno)
    {
    TEXT bb[E_MAX_ERROR_TEXT_SIZE];

    p_close(dcb);
    dcb=NULL;
    p_errs(&bb[0],errno);
    p_printf("%s: %s",msg,&bb[0]);
    }

LOCAL_C VOID panic(TEXT *msg, INT errno)
    {
    error(msg,errno);
    p_leave(0);
    }

LOCAL_C VOID PrintDirLine(TEXT *name, P_INFO *pinfo)
    {
    P_DAYSEC ds;
    P_DATE dt;
    TEXT *p,b[40];

    p=&b[0];
    if (pinfo->status&P_FAVOLUME)
        p=p_scpy(p,"Vol,");
    if (pinfo->status&P_FADIR)
        p=p_scpy(p,"Dir,");
    if (pinfo->status&P_FAMOD)
        p=p_scpy(p,"Mod,");
    if (!(pinfo->status&P_FAWRITE))
        p=p_scpy(p,"Read,");
    if (pinfo->status&P_FASYSTEM)
        p=p_scpy(p,"Sys,");
    if (pinfo->status&P_FAHIDDEN)
        p=p_scpy(p,"Hid,");
    if (*(p-1)==',')
        *--p=0;
    p_sttods(&pinfo->modst,&ds);
    p_dstodt(&ds,&dt);
    p_printf("%- 12s %7lu %02u-%02u-%02u %02u:%02u %s",
        name,pinfo->size,dt.day+1,dt.month+1,dt.year,dt.hour,dt.minute,&b[0]);
    }

LOCAL_C VOID CDECL PrintDirList(TEXT *dir)
    {
    INT ret;
    UWORD i,count;
    DIRLIST_ITEM *pd,d;
    RC_VAXVAR rec;

    p_send2(hand,O_VA_RESET);
    if ((ret=p_open(&dcb,dir,P_FDIR))!=0)
        panic("Failed to open directory file",ret);
    while (!(ret=p_iow(dcb,P_FREAD,&d.name[0],&d.info)))
        {
        rec.buf=(UBYTE *)&d;
        rec.len=sizeof(d.info)+p_slen(&d.name[0])+1;
        p_send4(hand,O_VA_INSERTISQ,&rec,&i);
        }
    p_close(dcb);
    dcb=NULL;
    if (ret!=E_FILE_EOF)
        panic("Failed to read directory",ret);
    if (!(count=p_send2(hand,O_VA_COUNT)))
        p_printf("No files found");
    else
        {
        for (i=0;i<count;i++)
            {
            pd=(DIRLIST_ITEM *)p_send3(hand,O_VA_PBUF,i);
            PrintDirLine(&pd->name[0],&pd->info);
            }
        }
    }

GLDEF_C INT CDECL DoDirLists(VOID)
    {
    TEXT name[P_FNAMESIZE];

    hand=f_newsend(CAT_PRNDIR_PRNDIR,C_DIRLIST,O_VA_INIT,16);
    while (p_getl(">",&name[0],P_FNAMESIZE))
        PrintDirList(&name[0]);
    p_send2(hand,O_DESTROY);
    return(0);
    }

GLDEF_C INT main(VOID)
    {
    INT err;

    p_linklib(0);
    if ((err=p_enter((VOID *)DoDirLists))!=0)
        error("Called p_leave",err);
    return(0);
    }
