/*->c.ident */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <signal.h>
#include <ctype.h>
#include <time.h>

#include "h.os"
#include "h.wimp"
#include "h.bbc"
#include "h.flex"
#include "h.swis"

#include "h.Drawlevel0"

#include "h.def"
#include "h.wos"
#include "h.timex"
#include "h.xext"
#include "h.main"
#include "h.mym"
#include "h.strdef"
#include "h.fax"
#include "h.serial"
#include "h.ram"
#include "h.file"
#include "h.pr"
#include "h.key"
#include "h.script"
#include "h.dir"
#include "h.view"
#include "h.batch"
#include "h.fo"
#include "h.pic"
#include "h.vx"
#include "h.sched"
#include "h.config"

#include "h.ident"


/*****************************************************************************/

static char * raster;    /* 1728bits*8 */
static int    rwidth;

int identshift;

static char   identformat[128];


static int expand[16]=
{
 0x0,
 0x3,
 0xC,
 0xF,

 0x30,
 0x33,
 0x3C,
 0x3F,

 0xC0,
 0xC3,
 0xCC,
 0xCF,

 0xF0,
 0xF3,
 0xFC,
 0xFF
};


/* From ident date time page 1 of 1 */

os_error * identopen(int width,int totpage,int page)
{
 os_error * err;
 char       temp[64];
 char       identlinex[128];
 char       pblock[9];
 int        len;
 char     * write;
 int        i;
 int        j;
 int        byte;
 os_regset  rx;

 if(!doidentline) return(NULL);


 rwidth=(width/8+1);    /* in bytes */
 err=flex_alloce((flex_ptr)&raster,rwidth*8);
 if(!err)
 {
  memset(raster,0,rwidth*8);

  writesysst(temp,1,1);

  sprintf(identlinex,identformat,identline,temp,page,totpage);

  len=strlen(identlinex);

  write=raster;
  write+=(rwidth-2*len)/2;

  for(i=0;i<len;i++)
  {
   rx.r[0]=10;
   rx.r[1]=(int)pblock;
   pblock[0]=identlinex[i];
   os_swix(OS_Word,&rx);

   for(j=0;j<8;j++)
   {
    byte=bitrev[pblock[j+1]];

    *(write+j*rwidth)=expand[byte & 0xF];
    *(write+j*rwidth+1)=expand[byte >> 4];
   }
   write+=2;
  }
 }
 return(err);
}


void writeident(int row,int * runs,unsigned short int * run)
{
 int    i;
 int    j;
 int    runn;
 int    posn;
 int    colour;
 char * write;

 if(!doidentline) return;

 runn=*runs;
 colour=1;

 /* or runs to raster      */
 /* first run is white     */

 write=raster+row*rwidth;
 posn=0;

 for(i=0;i<runn;i++)
 {
  if(colour) posn+=run[i];
  else
  {
   for(j=0;j<run[i];j++)
   {
    *(write+posn/8)|=(1<<(posn & 0x7));
    posn++;
   }
  }
  colour^=1;
 }

 /* re-code raster to runs */

 colour=1;
 runn=0;
 for(i=0,j=0;i<posn;i++)
 {
  if((*(write+i/8)) & (1<<(i & 0x7)))
  {
   if(colour)
   {
    run[j++]=runn;
    runn=1;
    colour=0;
   }
   else
   {
    runn++;
   }
  }
  else
  {
   if(colour)
   {
    runn++;
   }
   else
   {
    run[j++]=runn;
    runn=1;
    colour=1;
   }
  }
 }

 if(runn) run[j++]=runn;
 *runs=j;
}


void identclose(void)
{
 if(!doidentline) return;
 if(raster) flex_free((flex_ptr)&raster);
}


void configurefaxheader(int fp)
{
 identshift=stack[fp];
 strcpy(identformat,stringptr(stack[fp+1]));
}

