/*
TXTREAD.C
*/

#include <p_std.h>
#include <p_file.h>
#include <wl$txt.g>
#include "wpfconv.h"

GLREF_D VOID *DatApp5;      /* used for file conversion DYLs... */
#define FileName DatApp5    /* ...to point to the source file's name */

LOCAL_C VOID InsertBuf(PR_TXTREAD *self, TEXT *buf, UINT len)
    {
    InsertText(self->txtread.pos,buf,len);
    self->txtread.pos+=len;
    }

LOCAL_C VOID ApplyPlainStyle(PR_TXTREAD *self)
    {
    PARA_STYLE *para;
    EMPH_STYLE *emph;
    TEXT paracode[2];
    TEXT emphcode[2];

    *(WORD *)&paracode[0]='B'+('T'<<8);
    para=SenseParaStyleBySC(&paracode[0]);
    DoApplyParaStyle(self->txtread.lastpos,self->txtread.pos,para);
    *(WORD *)&emphcode[0]='N'+('N'<<8);
    emph=(EMPH_STYLE *)SenseEmphStyleBySC(&emphcode[0]);
    DoApplyEmphasis(self->txtread.lastpos,self->txtread.pos,emph);
    }

#pragma METHOD_CALL

METHOD VOID txtread_ao_init(PR_TXTREAD *self)
/*
Keep the supplied filename extension.
*/
    {
    f_open((VOID **)&self->active.pcb,FileName,P_FOPEN|P_FTEXT);
    CloseCurrentFile();
    SetDefaultStyles(4,6);
    StartActive(self);
    }

METHOD VOID txtread_ao_queue(PR_TXTREAD *self)
    {
    self->active.isactive=TRUE;
    self->txtread.len=TXTREAD_BUFLEN;
    p_ioc5(self->active.pcb,P_FREAD,&self->active.stat,&self->txtread.buf[0],
        &self->txtread.len);
    }

METHOD INT txtread_ao_run(PR_TXTREAD *self)
    {
    if (self->active.stat==E_FILE_EOF)
        {
        ApplyPlainStyle(self); /* apply style to final paragraph */
        SwitchToNewFile(FileName);
        p_send2(self,O_DESTROY);
        return(RUN_ACTIVE_USED);
        }
    f_leave(self->active.stat);

    if (self->txtread.pos)
        {
        ApplyPlainStyle(self); /* range does not include the terminating NULL */
        InsertBuf(self,&self->txtread.eopara,1);
        self->txtread.lastpos=self->txtread.pos;
        }
    InsertBuf(self,&self->txtread.buf[0],self->txtread.len); /* add text of next paragraph */

    p_send2(self,O_AO_QUEUE);
    return(RUN_ACTIVE_USED);
    }

METHOD VOID txtread_ao_abrun(PR_TXTREAD *self)
/*
The application is shut down after reporting any error on loading.
No data is ever lost by doing this, since any previous file will
already have been saved.
*/
    {
    StopActive();
    p_supersend2(self,O_AO_ABRUN);
    p_exit(0);
    }

METHOD VOID txtread_destroy(PR_TXTREAD *self)
    {
    StopActive();
    p_supersend2(self,O_DESTROY);
    }
