/*
P_PRNDIR.C
*/

#include <plib.h>

LOCAL_D VOID *dcb=NULL;

LOCAL_C VOID panic(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]);
    p_leave(errno);
    }

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 %8lu  %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 INT CDECL PrintDirList(TEXT *dir)
    {
    INT ret,NoFiles;
    P_INFO info;
    TEXT name[P_FNAMESIZE];

    if ((ret=p_open(&dcb,dir,P_FDIR))!=0)
        panic("Failed to open directory file",ret);
    NoFiles=TRUE;
    while (!(ret=p_iow(dcb,P_FREAD,&name[0],&info)))
        {
        NoFiles=FALSE;
        PrintDirLine(&name[0],&info);
        }
    p_close(dcb); dcb=NULL;
    if (ret!=E_FILE_EOF)
        panic("Failed to read directory",ret);
    if (NoFiles)
        p_printf("No files found");
    return(0);
    }

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

    while (p_getl(">",&name[0],P_FNAMESIZE))
        p_enter((VOID *)PrintDirList,&name[0]);
    return(0);
    }
