/*
TXTWRITE.C
*/

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

GLREF_D VOID *DatApp5;

LOCAL_C INT OpenFile(PR_TXTSAVE *self)
/* forces .TXT extension */
    {
    TEXT extension[6];
    P_INFO info;
    TEXT name[P_FNAMESIZE];

    *((UWORD *)&extension[0])='.'+('T'<<8);
    *((UWORD *)&extension[2])='X'+('T'<<8);
    extension[4]=0;
    f_fparse(&extension[0],DatApp5,&name[0],NULL);
    if (!p_finfo(&name[0],&info))
        {
        if (!DoConfirmOverwrite())
            return(FALSE);
        }
    f_open(&self->active.pcb,&name[0],P_FUPDATE|P_FREPLACE|P_FSTREAM_TEXT);
    return(TRUE);
    }

LOCAL_C VOID ReplaceNulls(TEXT *p,UINT len)
    {
    TEXT *pe;

    for (pe=p+len;p<pe;p++)
        {
        if (!*p)
            *p=CHAR_CR;
        }
    }

#pragma METHOD_CALL

METHOD VOID txtsave_ao_init(PR_TXTSAVE *self)
    {
    OpenFile(self);
    self->txtsave.ntags=CountTags();
    StartActive(self);
    }
METHOD VOID txtsave_ao_queue(PR_TXTSAVE *self)
    {
    self->active.isactive=TRUE;
    p_iosignal();
    }
METHOD INT txtsave_ao_run(PR_TXTSAVE *self)
    {
    PARA_STYLE style;
    EMPH_STYLE emphasis;
    UINT taglen,txtlen;

    taglen=SenseTagItem(self->txtsave.curtag++,&style,&emphasis);
    while (taglen)
        {
        txtlen=taglen>TXTSAVE_BUFFER_LEN ? TXTSAVE_BUFFER_LEN : taglen;
        ExtractText(self->txtsave.pos,&self->txtsave.buf[0],txtlen);
        ReplaceNulls(&self->txtsave.buf[0],txtlen);
        f_write(self->active.pcb,&self->txtsave.buf[0],txtlen);
        self->txtsave.pos+=txtlen;
        taglen-=txtlen;
        }
    if (self->txtsave.curtag<self->txtsave.ntags)
        p_send2(self,O_AO_QUEUE);
    else
        p_send2(self,O_DESTROY);
    return(RUN_ACTIVE_USED);
    }
METHOD VOID txtsave_ao_abrun(PR_TXTSAVE *self)
    {
    p_close(self->active.pcb);
    StopActive();
    p_supersend2(self,O_AO_ABRUN);
    p_supersend2(self,O_DESTROY);
    }
METHOD VOID txtsave_destroy(PR_TXTSAVE *self)
    {
    StopActive();
    p_supersend2(self,O_DESTROY);
    }
