/*
P_COMP.C
*/

#include <plib.h>

typedef struct
    {
    INT ret;
    VOID *chan;
    LONG len;
    TEXT name[P_FNAMESIZE];
    UBYTE buf[P_FBLKSIZE];
    } FILE_DATA;
    
LOCAL_D FILE_DATA f1={0,NULL};
LOCAL_D FILE_DATA f2={0,NULL};
    
LOCAL_C VOID CleanUp(TEXT *msg, FILE_DATA *pf)
    {
    TEXT bb[E_MAX_ERROR_TEXT_SIZE];

    p_close(pf->chan);
    pf->chan=NULL;
    if (pf->ret<0)
        {
        p_errs(&bb[0],pf->ret);
        p_printf("Failed to %s %s\n\r%s)",msg,&pf->name[0],&bb[0]);
        pf->ret=0;
        }
    }

LOCAL_C VOID Exit(TEXT *msg)
    {
    if (f1.ret>=0 && f2.ret>=0)
        p_printf(msg);
    CleanUp(msg,&f1);
    CleanUp(msg,&f2);
    p_leave(0);
    }

LOCAL_C VOID OpenFile(FILE_DATA *pf, TEXT *name, TEXT *related)
    {
    LONG pos;

    if ((pf->ret=p_fparse(name,related,&pf->name[0],NULL))<0)
        Exit("parse");
    if ((pf->ret=p_open(&pf->chan,&pf->name[0],P_FSTREAM|P_FSHARE|P_FRANDOM))<0)
        Exit("open");
    pf->len=0L; p_seek(pf->chan,P_FEND,&pf->len);
    pos=0; p_seek(pf->chan,P_FABS,&pos);
    }

LOCAL_C VOID ReadFile(FILE_DATA *pf)
    {
    pf->ret=p_read(pf->chan,&pf->buf[0],sizeof(pf->buf));
    if (pf->ret!=E_FILE_EOF && pf->ret<0)
        Exit("read");
    }

LOCAL_C VOID CDECL CompareFiles(TEXT *file1, TEXT *file2)
    {
    OpenFile(&f1,file1,NULL);
    OpenFile(&f2,file2,&f1.name[0]);
    p_printf("Compare %s (%ld)",&f1.name[0],f1.len);
    p_printf("   with %s (%ld)",&f2.name[0],f2.len);
    if (f1.len!=f2.len)
        Exit("Files are of different length");
    FOREVER
        {
        ReadFile(&f1);
        ReadFile(&f2);
        if (f1.ret==E_FILE_EOF && f2.ret==E_FILE_EOF)
            {
            f1.ret=f2.ret=0;
            Exit("Files are identical");
            }
        if (p_bcmp(&f1.buf[0],f1.ret,&f2.buf[0],f2.ret))
            Exit("Files are different");
        }
    }

GLDEF_C INT main(VOID)
    {
    TEXT *p;
    TEXT bb[P_FNAMESIZE];

    while (p_getl("Enter <file1> <file2>?\r\n",&bb[0],P_FNAMESIZE))
        {
        p=p_skipch(&bb[0]);
        if (*p)
            *p++=0;
        p_enter((VOID *)CompareFiles,&bb[0],p_skipwh(p));
        }
    return(0);
    }
