#include <exec/types.h>
#include <exec/memory.h>
#include <proto/dos.h>
#include <stdio.h>
#include <string.h>
#include <libraries/dos.h>
#include "zexport.h"
#include "/ross/protos.h"
#include <dos/dostags.h>

#include <proto/exec.h>
#include <proto/dos.h>

#include <link/io.h>

char *remember =  NULL;

/// PackMsgs
int PackMsgs(int from, int to)
{
   int msgnum;
   char string[100];
   char tstring[100];
   BPTR fh  =  NULL;
   struct FileInfoBlock *fib  =  NULL;

   AFPrintf(NULL,sout,"\n");

   if(!_LOG) strcpy(LOGHELPER,"[A");

   ASPrintf(NULL,logstring,"-> Exporting messages %d to %d",from,to);
   Log(logstring);

   fib=AllocDosObject(DOS_FIB,TAG_END);

   if(fib)
   {
      for(msgnum=from;msgnum<(to+1);msgnum++)
      {
         EX_THIS_AREA++;

         ASPrintf(NULL,string,"%s%d.msg",MSGAREAPATH,msgnum);

         strcpy(tstring,string);

         tstring[14]=NULL;

         AFPrintf(NULL,sout,"%s[0m[[33m%22.22s[0m] ",LOGHELPER,string);

         MyBorrowArea(MSGAREANUMBER);
         
         fh=Lock(string,ACCESS_READ);

         if(fh)
         {
            Examine(fh,fib);
            UnLock(fh); fh = NULL;

            if(*fib->fib_Comment)
            {
               handlemsg(string,MSGAREATAG);
            }
            else
            {
               AFPrintf(NULL,sout,"     exported at import  \n");
            }
         }

         UnBorrowArea(MSGAREANUMBER);
      }

      Log("<- Done");
      FreeDosObject(DOS_FIB,fib); fib = NULL;
      return(1);
   }

   return(0);
}
//-

/// handlemsg
int handlemsg(char *name, char *tagname)
{
   int okay;
   char *start;
   int length;
   int rc;

   okay=readinmsg(name,&start,&length);

   if(okay)
   {
      rc=handlemsg2(name,tagname,start,&length,get_area_from_tagname(a,tagname));

      writeoutmsg(name,start,length);

      free(remember); remember = NULL;
      return(rc);
   }
   return(0);
}
//-

/// readinmsg
int readinmsg(char *name,char **start,int *length)
{
   BPTR fh = NULL;

   fh=Open(name,MODE_OLDFILE);

   if(!fh)
   {
      AFPrintf(NULL,sout,"Message missing\n");
      return(0);
   }

   Seek(fh,0,OFFSET_END);
   *length=Seek(fh,0,OFFSET_BEGINNING);

   remember=(char *)calloc(*length+EXTRALENGTH,1);

   if(remember==NULL)
   {
      AFPrintf(NULL,sout,"ERROR: No mem for message\n");
      Log("*! ERROR: No mem for message");
      Close(fh); fh = NULL;
      return(0);
   }

   *start=remember;
   Read(fh,(void *)*start,*length);
   Close(fh); fh = NULL;
   return(1);
}
//-

/// writeoutmsg
int writeoutmsg(char *name,char *start,int length)
{
   BPTR fh;

   fh=Open(name,MODE_NEWFILE);

   if(!fh)
   {
      AFPrintf(NULL,sout,"ERROR: Can't open output file!\n");
      return(0);
   }

   Write(fh,(void *)start,length);
   Close(fh);
   return(1);
}
//-

