/******************************************************************************
 * program:     wp2latex                                                      *
 * function:    convert WordPerfect 6.x, 7.x, 8.x files into LaTeX	      *
 * modul:       pass1_6.cc                                                    *
 * description: This modul contains functions for first pass. In the first    *
 *              pass information of the WP binary file will splitted in two   *
 *              parts:                                                        *
 *              1) A text file containing the whole text. The special WP      *
 *                 characters are translated.                                 *
 *              2) A binary file which contains information about             *
 *                 environments, tabbings, line endings                       *
 * licency:     GPL		                                              *
 ******************************************************************************/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>

#include <sets.h>
#include <strings.h>
#include <lists.h>
#include <stacks.h>
#include "wp2latex.h"
#include "cp_lib/cptran.h"


extern set filter[4];

int set0_60[]={0 ___ 0xFF};		//Everything
int set1_60[]={0 ___ 0xBF,0xC0,0xD2,0xD4 ___ 0xFF}; //Header, Footer, Minipage Text
int set2_60[]={0x1 ___ 0x81,0xA9,0xC0,0xF0,0xF1};  //Characters Only
int set3_60[]={0xF1};  		//Nothing


extern BYTE ObjWP6SizesF0[0x10]; /*(4,5,3,3,3,3,4,4,4,5,5,6,6,8,8,0);*/

static const unsigned char CharsWP6_1_32[0x21] = { //Default extended international characters (from 0)
0,  35, 34, 37, 36, 31, 30, 27, 33, 29,
77, 76, 39, 38, 45, 41, 40, 47, 43, 49,
57, 56, 81, 80, 83, 82, 63, 62, 71, 70,
67, 73, 23 };


typedef struct
	{
	BYTE	Flags;
	BYTE	PacketType;
	WORD	UseCount;
	WORD	HiddenCount;
	DWORD	PacketSize;
	DWORD	ResourceFilePos;
	} Resource;


class TconvertedPass1_WP6: public TconvertedPass1
     {
public:
     WORD ResourceStart;
     stack UndoRedo;

     virtual int Dispatch(int FuncNo, ...);
     virtual int Convert_first_pass(void);
     };


static void ProcessKey60(TconvertedPass1_WP6 *cq);

/*Register translators here*/
TconvertedPass1 *Factory_WP6(void) {return new TconvertedPass1_WP6;}
FFormatTranslator FormatWP6("WP6.x",&Factory_WP6);



static const char *RefTypes[10] = {
  "Page", "Counter", "CapNum", "SecPage", "Chapter", "Volume", "Paragraph",
  "Footnote", "Endnote", "?"};



static boolean LoadResource(TconvertedPass1_WP6 *cq, WORD ResourceNo, Resource & Res)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#LoadResource(%u) ",(unsigned)ResourceNo);fflush(cq->log);
#endif
 boolean Corrupt=false;

 if(cq->ResourceStart==0) return true; /* Resources are not available */
 fseek(cq->wpd, (long)ResourceNo*14 + cq->ResourceStart, SEEK_SET);

 Res.Flags = fgetc(cq->wpd);
 Res.PacketType = fgetc(cq->wpd);
 Rd_word(cq->wpd, &Res.UseCount );
 Rd_word(cq->wpd, &Res.HiddenCount );
 Rd_dword(cq->wpd, &Res.PacketSize );
 Rd_dword(cq->wpd, &Res.ResourceFilePos );

 if(feof(cq->wpd))
 	{
        Res.ResourceFilePos=0;
	fseek(cq->wpd, 0l, SEEK_SET);
	Corrupt=true;
	}

 if(ResourceNo==0) return true; // First packet is a header only

 if(Res.ResourceFilePos>cq->DocumentStart) Corrupt=true; /* Fast check of resource data */
 if(Res.ResourceFilePos<=0x10) Corrupt=true;
 if(Res.ResourceFilePos+Res.PacketSize>cq->DocumentStart) Corrupt=true;

 if(Corrupt)
     {
     if (cq->err != NULL)
	{
	cq->perc.Hide();
	fprintf(cq->err, _("\nWarning: Resource #%d seems to be corrupted, its contents will be ignored!"),(int)ResourceNo);
	}
     return true;
     }
 return false;
}


#ifndef FINAL
void CrackObject(TconvertedPass1 *cq, DWORD end_of_code);

/** Dump all resources into a log file. */
static void CrackResources(TconvertedPass1_WP6 *cq)
{
WORD ResourceNo, Resources;
Resource Res;
long pos;

 if(cq->log==NULL) return;
 pos = ftell(cq->wpd);

 LoadResource(cq,0,Res); // the 0th resource is the header
 Resources=Res.UseCount;
 ResourceNo=1;
 fprintf(cq->log, _("\nResource array, # of resources:%u\n"),(unsigned)(Resources));

 while(ResourceNo<Resources)
   {
   if(LoadResource(cq,ResourceNo,Res)) fprintf(cq->log, "!");
				  else fprintf(cq->log, " ");

   fprintf(cq->log, _("%2d: Start:%4lx, Len:%4lx, Type:%d, Flags:%d, Use:%d, Hidden:%d \n"),
	(int)ResourceNo, (long)Res.ResourceFilePos, (long)Res.PacketSize,
	(int)Res.PacketType, (int)Res.Flags, (int)Res.UseCount, (int)Res.HiddenCount );

   ResourceNo++;
   }

 fseek(cq->wpd, pos, 0);
}


/**This procedure isn't normally called. It can be used for exploration of new packets*/
static void CrackResource(TconvertedPass1_WP6 *cq, int ResourceNo)
{
  FILE *txt;
  long pos;
  DWORD i;
  static char ss[13] = "00_RHack.txt";
  unsigned char c;
  Resource Res;

  c=LoadResource(cq,ResourceNo,Res);

  pos = ftell(cq->wpd);

  if (ss[1] > '9')
     {
     ss[1] = '0';
     ss[0]++;
     }

  txt=fopen(ss,"w");
  if (txt == NULL) return;

  fprintf(txt, "Resource #%d:\n Start:%4lXh, Length:%4lXh, Type:%Xh, Flags:%Xh, Use:%d, Hidden:%d \n"
	       "\nResource data:\n",
	(int)ResourceNo, (long)Res.ResourceFilePos, (long)Res.PacketSize,
	(int)Res.PacketType, (int)Res.Flags, (int)Res.UseCount, (int)Res.HiddenCount );

  if(!c) {
	 fseek(cq->wpd, Res.ResourceFilePos, 0);

	 for (i=0; i<Res.PacketSize; i++)
		{
		c=fgetc(cq->wpd);
		fprintf(txt," %4lu: %u",(long)i,(unsigned)c);
		if (c >= ' ' && c <= 'z')
			  fprintf(txt, " %c", c);
		putc('\n', txt);
		}
	 }

  if (txt != NULL) fclose(txt);
  txt = NULL;
  ss[1]++;   /**/

  fseek(cq->wpd, pos, 0);
  if (txt != NULL) fclose(txt);
}
#endif


static void BadResource(TconvertedPass1 *cq, int ResourceNo)
{
if(cq->err!=NULL)
  fprintf(cq->err, _("\nWarning: Strange content of the resource #%d, it will be ignored!"),(int)ResourceNo);
}


static void DoCaption6(TconvertedPass1 *_cq,unsigned short CaptionSize)
{
#ifdef DEBUG
  fprintf(_cq->log,"\n#DoCaption6() ");fflush(_cq->log);
#endif
 TconvertedPass1_WP6 *cq;
 DWORD end_of_code;
 unsigned char OldFlag;
 char OldEnvir;
 attribute OldAttr;
 int CaptionChars;

  if (CaptionSize == 0)
    return;

  cq = (TconvertedPass1_WP6 *)_cq;
  cq->ActualPos = ftell(cq->wpd);
  end_of_code = cq->ActualPos + CaptionSize;
  OldFlag = cq->flag;
  OldEnvir = cq->envir;
  cq->recursion++;

  OldAttr = cq->attr;
  InitAttr(cq->attr);

  cq->flag = HeaderText;
  CaptionChars=0;

  fprintf(cq->strip, "\\caption{");
  while (cq->ActualPos < end_of_code)
  	{
	if(fread(&cq->by, 1, 1, cq->wpd) !=1 ) break; /*Error during read*/

        if(CaptionChars==0)
          {			// Rule out return before any character
	  if((cq->by==0xB9)||(cq->by==0xCC)||(cq->by==0xCF)) cq->by=0x80; //WP6 space
          }
	if(cq->by==0xCC) cq->by=0xCF; // Replace [HRt] by [SRt]

        if(isalnum(cq->by)) CaptionChars++;

	ProcessKey60(cq);
	}
  Close_All_Attr(cq->attr,cq->strip);
  fprintf(cq->strip, "}\n");

  cq->line_term = 's';   /* Soft return */
  Make_tableentry_envir_extra_end(cq);

  cq->recursion--;
  cq->flag = OldFlag;
  cq->envir = OldEnvir;
  cq->attr = OldAttr;
  cq->char_on_line = false;
  cq->nomore_valid_tabs = false;
  cq->rownum++;
  Make_tableentry_attr(cq);
  cq->latex_tabpos = 0;
}


/**This function fixes user Counter name string to be readable from LaTeX*/
static void FixCounterName(string & counter)
{
  counter=replacesubstring(counter,"0","zero");
  counter=replacesubstring(counter,"1","one");
  counter=replacesubstring(counter,"2","two");
  counter=replacesubstring(counter,"3","three");
  counter=replacesubstring(counter,"4","four");
  counter=replacesubstring(counter,"5","five");
  counter=replacesubstring(counter,"6","six");
  counter=replacesubstring(counter,"7","sewen");
  counter=replacesubstring(counter,"8","eight");
  counter=replacesubstring(counter,"9","nine");

  counter=replacesubstring(counter,"\\","backslash");
  counter=replacesubstring(counter,"{","bracketon");
  counter=replacesubstring(counter,"}","bracketoff");
  counter=replacesubstring(counter,"%","percent");
  counter=replacesubstring(counter,",","comma");
  counter=replacesubstring(counter," ","space");
}


static void ExtractCaptionLabel6(TconvertedPass1 *_cq,const TBox & Box)
{
#ifdef DEBUG
  fprintf(_cq->log,"\n#ExtractCaptionLabel6() ");fflush(_cq->log);
#endif
TconvertedPass1_WP6 *cq;
DWORD end_of_code;
unsigned char OldFlag;
//boolean FoundLabel=false;

  if (Box.CaptionSize == 0) return;

  cq = (TconvertedPass1_WP6 *)_cq;
  fseek(cq->wpd, Box.CaptionPos, SEEK_SET);
  cq->ActualPos = Box.CaptionPos;
  end_of_code = cq->ActualPos + Box.CaptionSize;
  OldFlag = cq->flag;
  cq->recursion++;

  cq->flag = Nothing;
  InitAttr(cq->attr);

  while (cq->ActualPos < end_of_code)
	{
	if(fread(&cq->by, 1, 1, cq->wpd) !=1 ) break; /*Error during read*/

	if(cq->by==0xD4)
		{
		if(fread(&cq->subby, 1, 1, cq->wpd)!=1) break;
		fseek(cq->wpd,-1,SEEK_CUR);
		if(cq->subby==8)	//convert \label{} only
			{
			cq->flag = HeaderText;
			ProcessKey60(cq);
			NewLine(cq);
//			FoundLabel=true;
			break;
			}
		}
	ProcessKey60(cq);
	}

  cq->recursion--;
  cq->flag = OldFlag;
}


static void SkipNumber6(TconvertedPass1 *cq, DWORD & NewPos)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#SkipNumber6() ");fflush(cq->log);
#endif
int i;
unsigned char by;
unsigned char OldFlag;

  OldFlag = cq->flag;
  cq->flag = Nothing;
  fseek(cq->wpd, NewPos, 0);

  i=0;
  while(i<20)		// Read the page number text
	{
	fread(&by, 1, 1, cq->wpd);
	if(!isalnum(by)) break;
        // ProcessKey60(cq);
	i++;
	}

  if(by==0xDA && i<20)	// Skip the page number text after object
	{
	NewPos+=i;
	}

  cq->flag = OldFlag;
}

//---------WP6.x feature conversion procedures----------

static void BackTab(TconvertedPass1 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#BackTab() ");fflush(cq->log);
#endif
int wpu;

if (!Tabs || Columns>=2)
       {
NoTab: putc(' ', cq->strip);
       strcpy(cq->ObjType, "!Back Tab");
       return;
       }

wpu = cq->tabpos[0] - cq->WP_sidemargin;  /* Correctie ivm WP kantlijn */
wpu = abs(wpu);

if(cq->envir == 'B') goto NoTab;
if(cq->envir == 'T')
	{
	fprintf(cq->strip, "\\< ");
	}
else	{
	fprintf(cq->strip, "\\kern-%2.2fcm ",wpu / 470.0);
	}

strcpy(cq->ObjType, "Back Tab");
}


/**This procedure converts Boxes (char, paragraph or page anchored) from WP6.x*/
static void Box6(TconvertedPass1_WP6 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#Box6() ");fflush(cq->log);
#endif
 BYTE PIDs;
 WORD PPIDs,TextBlocks,SizeOfArea;
 WORD ResourceNo,DataResNo,CaptionResNo,IDFlags;
 Resource Res;
 SWORD NameLen;
 TBox Box;
 DWORD OleSize=0,OlePos;
 char OldEnvir;
 unsigned char OldFlag;
 attribute OldAttr;
 string StrBeg,StrEnd,ImageName;
 DWORD end_of_code,pos,subpos;
 DWORD BlockOffset,BlockSize;
 WORD Wchar;
 int i;
 const char *BoxDescription;
 WORD wpu;

// CrackObject(cq, NewPos);
  BoxDescription="!Box";
  fseek(cq->wpd, 1L, SEEK_CUR);
  if( (PIDs = fgetc(cq->wpd)) == 0)
    {				//Box has no resource available
	if(cq->err!=NULL)
       fprintf(cq->err, _("\nWarning: Box contains unexpected amount of resources %d!"),(int)PIDs);
	goto BadResource;
    }

  initBox(Box);
  switch(cq->subby)
	{
	case 0:Box.AnchorType=2; break; //character
	case 1:Box.AnchorType=0; break; //paragraph
	case 2:Box.AnchorType=1; break; //page
	default:Box.AnchorType=0;	//not detected
	}  

  DataResNo=CaptionResNo=0;
  pos = ftell(cq->wpd);
  while(PIDs>0)
	{
	fseek(cq->wpd, pos, SEEK_SET);
	pos+=2;
	Rd_word(cq->wpd, &ResourceNo);

	PIDs--;

	if(ResourceNo==0)
	   {
	   if(cq->err != NULL)
		{
		cq->perc.Hide();
		fprintf(cq->err, _("\nWarning: Resource #0 should not be referred from data!"));
		}
	   continue;
	   }
	if(LoadResource(cq, ResourceNo, Res)) goto BadResource;

	switch(Res.PacketType)
		{
		case 0x08:if(DataResNo==0) DataResNo=ResourceNo; //BoxCaption
				      else CaptionResNo=ResourceNo;
			  if(Box.Contents==0)	//no box contents defined
				{
				if(Box.Type==4) Box.Contents=4;
                                           else Box.Contents=1;
				}
			  break;
                case 0x40:                      //Graphics FileName
                          fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
			  if(Res.Flags & 1 != 0)  //are there childrens?
			    {
			    Rd_word(cq->wpd, &PPIDs);

			    subpos = ftell(cq->wpd);
			    for(i=0;i<PPIDs;i++)
				{
				Rd_word(cq->wpd, &ResourceNo);
				subpos+=2;
				if(!LoadResource(cq, ResourceNo, Res))
				   {
				   if(Res.PacketType==0x6F) //WPG graphics
					{
					Box.Image_type=2;
					Box.Image_offset=Res.ResourceFilePos;
					Box.Image_size=Res.PacketSize;
					}
                                   if(Res.PacketType==0x70) //OLE archive
				     {
				     if(Box.Type==5)
					{
					OleSize=Res.PacketSize;
					OlePos=Res.ResourceFilePos;
					}
				     }
				   }
				fseek(cq->wpd, subpos, SEEK_SET);
				}
			    fseek(cq->wpd, PPIDs * 2l, SEEK_CUR);
                            }

                          Rd_word(cq->wpd, &PPIDs);
			  while(PPIDs!=0 && PPIDs!=0xFFFF)
			       {   //?? Nonsense characters inside filename ??
                               if(PPIDs<0xEFF && PPIDs!=26)
                                 {
				 switch(PPIDs)
				   {
				   case '\\':
				   case '$':
				   case '_':
					ImageName+=(char)PPIDs;
					break;
                                   default:
			             {
				     const char *Ch=Ext_chr_str(PPIDs, cq, cq->ConvertCpg);
				     while(*Ch)
                                       {
				       if(*Ch==' ' && Ch[1]==0) break;

				       switch(*Ch)
				         {
					 case '{': if(Ch[1]=='}') 
							{Ch++; break;}   //ignore
						   ImageName+="_opb";
						   break;
					 case '}': ImageName+="_clb";
						   break;
					 case '~': ImageName+="_tld";
					 case '\\': break;
					
					 default: ImageName+=*Ch;
					 }
				       Ch++;
				       }
                                     }
				   }   
				 }
			       if(feof(cq->wpd)) break;
			       Rd_word(cq->wpd, &PPIDs);
			       }

			  if(DataResNo==0) DataResNo=ResourceNo;
                                      else CaptionResNo=DataResNo;
			  Box.Contents=3;
			  break;
		case 0x41:			//Box template
			  fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
			  Rd_word(cq->wpd, &PPIDs);       //Number of prefix packet IDs
			  fseek(cq->wpd, 2L*PPIDs         //skip nested resource indices
				         +2, SEEK_CUR);   //Skip size of box name/library data

			  Rd_word(cq->wpd, &SizeOfArea);  //Read size of box name/library data area
			  BlockOffset = 2L * PPIDs + 2 + 2 + 2 + SizeOfArea;
			  fseek(cq->wpd, 2L, SEEK_CUR);
			  Rd_word(cq->wpd, (WORD *)&NameLen); //box namelength
			  switch(NameLen)
				{
				case  0:Box.Type=0;BoxDescription="Fig Box"; break;  //figure box
				case -1:Box.Type=1;BoxDescription="Table Box"; break;//table box
				case -2:Box.Type=3;BoxDescription="Text Box"; break; //text box
				case -3:Box.Type=2;BoxDescription="User Box"; break; //user box
				case -4:Box.Type=4;BoxDescription="Equ Box"; break;  //equation box
				case -5:Box.Type=2;BoxDescription="Button"; break;   //button box as user box

				case -7:Box.Type=5;BoxDescription="OLE Equ Box"; break;//new shape equation box
				}

			  fseek(cq->wpd, Res.ResourceFilePos+BlockOffset, SEEK_SET);
			  Rd_word(cq->wpd, &SizeOfArea);  //Read size of box counter data
			  BlockOffset += 2 + SizeOfArea;
					  //skip Box counter Area
			  fseek(cq->wpd, Res.ResourceFilePos+BlockOffset, SEEK_SET);
			  Rd_word(cq->wpd, &SizeOfArea);  //Read size of box positioning data
			  BlockOffset += 2 + SizeOfArea;

			  fseek(cq->wpd, 1L, SEEK_CUR);
			  fread(&Box.AnchorType, 1, 1, cq->wpd);
			  Box.AnchorType &= 0x3;   /*0-Paragraph, 1-Page, 2-Character*/
			  switch(Box.AnchorType)
				{
				case 0:Box.AnchorType=1;break;	//paragraph
				case 1:Box.AnchorType=0;break;  //page
				case 2:break;			//character
				}
			  fread(&Box.HorizontalPos, 1, 1, cq->wpd);
			  Box.HorizontalPos = (Box.HorizontalPos>>2)& 3;	/*0-Left, 1-Right, 2-Center, 3-Full */

			  fseek(cq->wpd, 11L, SEEK_CUR);

			  Rd_word(cq->wpd, &wpu); Box.Width=wpu/47.0;

			  fseek(cq->wpd, Res.ResourceFilePos+BlockOffset, SEEK_SET);
			  Rd_word(cq->wpd, &SizeOfArea);  //Read size of box contents data
			  BlockOffset += 2 + SizeOfArea;
			  if(SizeOfArea<5) break;
			  BYTE BoxContentType;
			  fseek(cq->wpd, 1L, SEEK_CUR);
			  BoxContentType=fgetc(cq->wpd);
			  fseek(cq->wpd, 1L, SEEK_CUR);
			  Rd_word(cq->wpd, &SizeOfArea);  //Total size of content rendering data
			  if(SizeOfArea>0)
			    {
			    switch(BoxContentType)  //This is not finished yet.
				{
				case 3:break;	//image content rendering flags
				}
			    }

			  break;
		case 0x64:Box.Contents=4;	//Box Equation Content
			  break;
		}

	}


  pos+=20;			  //Process override build in data
  fseek(cq->wpd, pos, SEEK_SET);
  Rd_word(cq->wpd, &PPIDs);	  //BoxOverrideFlags
  pos+=2;

  if(PPIDs & 0x8000)			//box counter data
	{
	Rd_word(cq->wpd, &SizeOfArea);  //Read size of box counter data
	pos += SizeOfArea+2;
	fseek(cq->wpd, pos, SEEK_SET);
	}
  if(PPIDs & 0x4000)			//box positioning data
	{
	Rd_word(cq->wpd, &SizeOfArea);  //Read size of box positioning data
		// Position Preffix ID Flags 1B
		// General Position Flags 1D
		// Horizontal Position Flags 1B
		// Horizontal Offset 2B
		// LeftColumn 1B
		// RightColumn 1B
		// Vertical Position Flags 1B
		// Vertical Offset 2B
		// Width Flags 1B
		// Width 2B
		// Height flags 1B
		// Height 2B
	pos += SizeOfArea+2;
	fseek(cq->wpd, pos, SEEK_SET);
	}
  if(PPIDs & 0x2000)			//box contents data
	{
	BYTE ContentType=0;
	Rd_word(cq->wpd, &SizeOfArea);  //Read size of box positioning data
	Rd_word(cq->wpd, &IDFlags);
	BlockOffset=4;

	if(IDFlags & 0x8000) BlockOffset+=2;
	if(IDFlags & 0x4000)
		{
		BlockOffset+=1;
		ContentType=fgetc(cq->wpd);
		}
	if(IDFlags & 0x2000)
	       {
	       WORD TotSize;
	       fseek(cq->wpd, pos+BlockOffset, SEEK_SET);
	       Rd_word(cq->wpd, &TotSize);  //Total size of image content override data
	       if(ContentType==3)	//content of box is image
		   {
		   WORD ContentsOverrideFlags;
		   Rd_word(cq->wpd, &ContentsOverrideFlags);
		   if(ContentsOverrideFlags & 0x8000) fseek(cq->wpd, 2L, SEEK_CUR);
		   if(ContentsOverrideFlags & 0x4000) fseek(cq->wpd, 4L, SEEK_CUR);
		   if(ContentsOverrideFlags & 0x2000)
			   {
			   BYTE b;
			   fseek(cq->wpd, 1L, SEEK_CUR);	//skip mask
			   b=fgetc(cq->wpd);
			   if(b & 0x80) Box.HScale=-Box.HScale;
			   if(b & 0x40) Box.VScale=-Box.VScale;
			   }
		   if(ContentsOverrideFlags & 0x1000)  //bit 12 - scalling factor
			   fseek(cq->wpd, 8L, SEEK_CUR);
		   if(ContentsOverrideFlags & 0x0800)  //bit 11 - translation factor
			   fseek(cq->wpd, 8L, SEEK_CUR);
		   if(ContentsOverrideFlags & 0x0400)  //bit 10 - rotation
			   {
			   fseek(cq->wpd, 2L, SEEK_CUR);	//skip lo WORD from DWORD
			   Rd_word(cq->wpd, &Box.RotAngle);
			   }
		   }
	       BlockOffset+=TotSize+2;
	       }
	if(IDFlags & 0x1000) BlockOffset+=3;
	if(IDFlags & 0x0800)
		{
		fseek(cq->wpd, BlockOffset, SEEK_CUR); //1+???
		Rd_word(cq->wpd, &wpu);Box.Width=wpu/47.0;
		}

	pos+=SizeOfArea+2;
	fseek(cq->wpd, pos, SEEK_SET);
	}
  if(PPIDs & 0x2000)			//box contents data

				/* Any of section's attr cannot be opened */
  for(i=First_com_section;i<=Last_com_section;i++)
		     AttrOff(cq,i);

  OldEnvir = cq->envir;
  OldFlag = cq->flag;
  OldAttr = cq->attr;

  if(Box.Contents==1 && DataResNo>0)	//text
	{
	if(LoadResource(cq, DataResNo, Res)) goto BadResource;
	if(Res.PacketType!=8) {BadResource(cq,ResourceNo);goto BadResource;}

	fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
	Rd_word(cq->wpd, &TextBlocks);	// Load # of text blocks
	if(TextBlocks<1) {BadResource(cq,ResourceNo);goto BadResource;}

	Rd_dword(cq->wpd, &BlockOffset);
	Rd_dword(cq->wpd, &BlockSize);
	if(BlockOffset + BlockSize > Res.PacketSize) {BadResource(cq,ResourceNo);goto BadResource;}

	fseek(cq->wpd, Res.ResourceFilePos+BlockOffset, SEEK_SET);
	end_of_code = Res.ResourceFilePos+BlockOffset+BlockSize;


	if(cq->char_on_line == -20)    /* Left one enpty line for new enviroment */
	       {
	       fputc('%', cq->table);
	       fputc('%', cq->strip);
	       NewLine(cq);
	       cq->char_on_line = true;
	       }
	if(cq->char_on_line==true)     /* make new line for leader of minipage */
	       {
	       NewLine(cq);
	       }

	if(!BoxTexHeader(cq,Box)) CaptionResNo=0; //caption is disabled
	cq->envir='!';			//Ignore enviroments Before
	NewLine(cq);

	cq->char_on_line = -10;
	cq->envir=' ';
	cq->ActualPos=ftell(cq->wpd);
	cq->recursion++;
	while (cq->ActualPos < end_of_code)
		 {
		 fread(&cq->by, 1, 1, cq->wpd);

		 ProcessKey60(cq);
		 }
	cq->recursion--;

	Close_All_Attr(cq->attr,cq->strip);

	cq->envir=' ';
	if (cq->char_on_line==true)
	     {
	     NewLine(cq);
	     }
	if(CaptionResNo>0) //process caption
		{
		if(LoadResource(cq, CaptionResNo, Res)) goto NoCaption;
		if(Res.PacketType!=8) {BadResource(cq,CaptionResNo);goto NoCaption;}

		fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
		Rd_word(cq->wpd, &TextBlocks);	// Load # of text blocks
		if(TextBlocks<1) {BadResource(cq,CaptionResNo);goto NoCaption;}

		Rd_dword(cq->wpd, &BlockOffset);
		Rd_dword(cq->wpd, &BlockSize);
		if(BlockOffset + BlockSize > Res.PacketSize) {BadResource(cq,CaptionResNo);goto NoCaption;}

		Box.CaptionPos=Res.ResourceFilePos+BlockOffset;
		fseek(cq->wpd, Box.CaptionPos, SEEK_SET);
		DoCaption6(cq, BlockSize);
		}
NoCaption:
	BoxTexFoot(cq, Box);

	cq->envir='^';		//Ignore enviroments after minipage
	NewLine(cq);
	}


  if(Box.Contents==3 && Box.Type==5 && DataResNo>0 && OleSize>0) //new WP12 OLE equation
    {
    string temp_filename;
    TconvertedPass1 *cq1_new;
    FILE *SrcOLE;

    temp_filename = OutputDir+GetSomeImgName(".OLE");
    if( (SrcOLE=fopen(temp_filename(),"wb")) != NULL )
	{
	fseek(cq->wpd,OlePos,SEEK_SET);

	i=44+4+2+2+2+2+4+4;
	fseek(cq->wpd,i,SEEK_CUR);
	OleSize-=i;

		//OLE stream is starting here
	fseek(cq->wpd,39,SEEK_CUR); //Why 39??? Don't know.
	OleSize-=39;

        i=fgetc(cq->wpd);
        if(i!=0xD0)
          {
          if(cq->err != NULL)
	    {
	    cq->perc.Hide();
	    fprintf(cq->err, _("\nWarning: Incorrect guess of OLE offset. Please send me this file for analysis."));
	    }
          }
	fputc(i,SrcOLE); OleSize--;

	while (OleSize-->0)
	  fputc(fgetc(cq->wpd), SrcOLE); /*Copy all OLE contents*/
	fclose(SrcOLE);

	SrcOLE=fopen(temp_filename(),"rb");
        if(SrcOLE)
          {
	  CheckFileFormat(SrcOLE,FilForD);
	  cq1_new=GetConvertor(FilForD.Convertor);
          if(cq1_new!=NULL)
	    {
	    //cq.perc.Hide();
	    if(Verbosing >= 1) printf(_("[nested \"%s\" %s] "), temp_filename(),FilForD.Convertor);
	    cq1_new->InitMe(SrcOLE,cq->table,cq->strip,cq->log,cq->err);
	    cq1_new->Convert_first_pass(); //>=1) RetVal=1;
	    if(Verbosing >= 1) printf(_("\n[continuing] "));
	    if(cq->log!=NULL) fputs(_("\n--End or nested file.--\n"),cq->log);
	    //cq.perc.Show();
	    delete cq1_new;
	    }
          }
	fclose(SrcOLE);
	}
    }

  if(Box.Contents==3)           	//graphics
	{
	Box.CaptionSize=0;
	if(CaptionResNo>0) //process caption
		{
		if(LoadResource(cq, CaptionResNo, Res)) goto NoCaptionG;
		if(Res.PacketType!=8) goto NoCaptionG;

		fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
		Rd_word(cq->wpd, &TextBlocks);	// Load # of text blocks
		if(TextBlocks<1) goto NoCaptionG;

		Rd_dword(cq->wpd, &BlockOffset);
		Rd_dword(cq->wpd, &BlockSize);
		if(BlockOffset + BlockSize > Res.PacketSize) goto NoCaptionG;

		Box.CaptionPos=Res.ResourceFilePos+BlockOffset;
		Box.CaptionSize=BlockSize;
		}
NoCaptionG:
        cq->recursion++;
	ImageWP(cq,ImageName,Box,DoCaption6);
	cq->recursion--;
	}

  if(Box.Contents==4 && DataResNo>0)	//equation
	{
	FormulaNo++;
	Box.CaptionSize=0;
	if(CaptionResNo>0) //process caption
		{
		if(LoadResource(cq, CaptionResNo, Res)) goto NoCaptionEq;
		if(Res.PacketType!=8) goto NoCaptionEq;

		fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
		Rd_word(cq->wpd, &TextBlocks);	// Load # of text blocks
		if(TextBlocks<1) goto NoCaptionEq;

		Rd_dword(cq->wpd, &BlockOffset);
		Rd_dword(cq->wpd, &BlockSize);
		if(BlockOffset + BlockSize > Res.PacketSize) goto NoCaptionEq;

		Box.CaptionPos=Res.ResourceFilePos+BlockOffset;
		Box.CaptionSize=BlockSize;
		}
NoCaptionEq:
	if(LoadResource(cq, DataResNo, Res)) goto BadResource;
	if(Res.PacketType!=8) {BadResource(cq,ResourceNo);goto BadResource;}

	fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
	Rd_word(cq->wpd, &TextBlocks);	// Load # of text blocks
	if(TextBlocks<1) {BadResource(cq,ResourceNo);goto BadResource;}

	Rd_dword(cq->wpd, &BlockOffset);
	Rd_dword(cq->wpd, &BlockSize);
	if(BlockOffset + BlockSize > Res.PacketSize) {BadResource(cq,ResourceNo);goto BadResource;}

	fseek(cq->wpd, Res.ResourceFilePos+BlockOffset, SEEK_SET);

	end_of_code = Res.ResourceFilePos+BlockOffset+BlockSize;
	StrBeg = "";
	StrEnd = "";

	cq->flag = Nothing;
	InitAttr(cq->attr);
	cq->recursion++;

	cq->ActualPos = ftell(cq->wpd);
	while (cq->ActualPos < end_of_code)
	     {
	     fread(&cq->by, 1, 1, cq->wpd);
	     if(cq->by<=0) break;
	     if(cq->by>=0x01 && cq->by<=0x20)
		      {
		      StrEnd=Ext_chr_str(0x100 | CharsWP6_1_32[cq->by],cq,cq->ConvertCpg);
		      StrBeg+=FixFormulaStrFromTeX(StrEnd);  //wong accents must be fixed here.
		      }
	     if(cq->by == '$')
		      {
		      StrBeg += "\\$ ";
		      cq->ActualPos++;
		      continue;
		      }
	     if(cq->by == '\\')
		      {
		      StrBeg += (char)1;
		      cq->ActualPos++;
		      continue;
		      }
	     if(cq->by > ' ' && cq->by < 0x80)
		      {
		      StrBeg += (char)cq->by;
		      cq->ActualPos++;
		      continue;
		      }
	     if(cq->by==0xCC || cq->by==0xCF || cq->by==0xD0)   //New line
		      {
		      StrBeg += ' ';
		      }
	     if(cq->by==0x80) StrBeg += ' ';
	     if(cq->by==0x81) StrBeg += '~';
	     if(cq->by==0x82 || cq->by==0x83 || cq->by==0x85)
			      StrBeg += "\\-";
	     if(cq->by==0x84) StrBeg += '-';
	     if(cq->by==0x86) StrBeg += "{\\penalty0}";
	     if(cq->by==0x87) StrBeg += ' '; 	//!!! Terminate Line

	     if(cq->by == 0xF0)       /*extended character*/
		  {			/*why special wp characters are in equations?*/
		  Rd_word(cq->wpd, &Wchar);
		  StrEnd = Ext_chr_str(Wchar, cq, cq->ConvertCpg);
		  StrBeg+=FixFormulaStrFromTeX(StrEnd,Wchar>>8);
		  StrEnd="";
		  }

	     ProcessKey60(cq);
	     }
	cq->recursion--;

	i=OptimizeFormulaStr(cq,StrBeg);
	if(StrBeg=="") goto LEqEmpty;
	if(i!=0 && Box.AnchorType==2) StrBeg+='\n';

	while(cq->attr.Opened_Depth>0)  //discard temporarily created attributes
		{
		_AttrOff(cq->attr, cq->attr.stack[cq->attr.Opened_Depth],StrEnd);
		StrBeg+=StrEnd;
		}

	cq->attr = OldAttr;	//Return saved attributes before placing a formula

	if(cq->char_on_line == -20)    /* Left one enpty line for new enviroment */
		 {
		 fputc('%', cq->table);
		 fputc('%', cq->strip);
		 NewLine(cq);
		 cq->char_on_line = true;
		 }
	if(cq->char_on_line==true)     /* make new line for leader of minipage */
		   {
		   NewLine(cq);
		   }

	PutFormula(cq,StrBeg(),Box,DoCaption6,ExtractCaptionLabel6);

      /*     if(CaptionLen>0) then   // captions are currently loosed
		begin
		seek(cq.wpd^,CaptionPos);
		DoCaption(cq,CaptionLen);
		end;*/
	goto AttrsRestored;
	}

LEqEmpty:
  cq->attr = OldAttr;
AttrsRestored:
  if(cq->envir=='^') cq->char_on_line = -10;		// stronger false;
  cq->flag = OldFlag;
  cq->envir = OldEnvir;

BadResource:
  strcpy(cq->ObjType, BoxDescription);
}


static void Column6(TconvertedPass1 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#Column6() ");fflush(cq->log);
#endif
BYTE ColType, NoColumns;

if(Columns<false)
	{
	strcpy(cq->ObjType, "!Col");
	return;
	}

fseek(cq->wpd, 3L, SEEK_CUR);	//skip <flags>,[non del size]
ColType=getc(cq->wpd);ColType=ColType;
fseek(cq->wpd, 4L, SEEK_CUR);	//skip {spacing}
NoColumns=getc(cq->wpd);

Column(cq,NoColumns);

sprintf(cq->ObjType, "Col Def:%d",(int)NoColumns);
}


static void Comment6(TconvertedPass1_WP6 *cq, int CommentLevel=1)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#Comment6() ");fflush(cq->log);
#endif
  unsigned char OldFlag;
  signed char OldCharOnLine;
  attribute OldAttr;
  DWORD end_of_code,SavedPos;
  WORD ResourceNo;
  Resource Res;

  OldFlag = cq->flag;
  OldAttr = cq->attr;
  OldCharOnLine = cq->char_on_line;

//CrackObject(cq, NewPos);

  fseek(cq->wpd, 2L, SEEK_CUR);
  Rd_word(cq->wpd, &ResourceNo);


  if(LoadResource(cq, ResourceNo, Res)) goto BadResource;
  fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
  fread(&cq->by, 1, 1, cq->wpd);
  if(cq->by!=1) {BadResource(cq,ResourceNo);goto BadResource;}
  fseek(cq->wpd, 1L, SEEK_CUR);
  Rd_word(cq->wpd, &ResourceNo);	// Load 2nd indexed resource


  if(LoadResource(cq, ResourceNo, Res)) goto BadResource;
  fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
  fread(&cq->by, 1, 1, cq->wpd);
  if(cq->by!=1) {BadResource(cq,ResourceNo);goto BadResource;}
  fseek(cq->wpd, 9, SEEK_CUR);


  cq->flag = CharsOnly;
  cq->recursion++;
  InitAttr(cq->attr);		//Turn all attributes in the comment off
  end_of_code = Res.ResourceFilePos+Res.PacketSize;

  fprintf(cq->strip,"%.*s",CommentLevel,"%%%%%%%%%%");
  cq->ActualPos = ftell(cq->wpd);
  while (cq->ActualPos < end_of_code)
	{
	SavedPos=cq->ActualPos;
	fread(&cq->by, 1, 1, cq->wpd);
	if(cq->by<=0x01) break;
	ProcessKey60(cq);


	if(cq->by==0xD4 && cq->subby==0x1D)   //Nested Comments
		{
		fseek(cq->wpd,SavedPos+4,SEEK_SET);
		SavedPos=cq->ActualPos;

		Comment6(cq,CommentLevel+1);
		fprintf(cq->strip,"%.*s",CommentLevel,"%%%%%%%%%%");

		cq->ActualPos=SavedPos;
		fseek(cq->wpd,SavedPos,SEEK_SET);
		continue;
		}

	if(cq->by==0xCC || cq->by==0xCF || cq->by==0xD0)   //New comment line
       		{
                cq->line_term = 's';    	//Soft return
		Make_tableentry_envir_extra_end(cq);
		fprintf(cq->strip, "\n");
		cq->rownum++;
		Make_tableentry_attr(cq);

		fprintf(cq->strip,"%.*s",CommentLevel,"%%%%%%%%%%");
		}
       }

  cq->line_term = 's';    	//Soft return
  Make_tableentry_envir_extra_end(cq);
  fprintf(cq->strip, "\n");
  cq->rownum++;
  Make_tableentry_attr(cq);

  cq->recursion--;
  cq->attr = OldAttr;
  cq->flag = OldFlag;
  if(OldCharOnLine==true || OldCharOnLine==-1) cq->char_on_line = -1;
	else cq->char_on_line = false;
BadResource:
  strcpy(cq->ObjType, "Comment");
}


static void Endnote6(TconvertedPass1_WP6 *cq, DWORD & NewPos)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#Endnote6() ");fflush(cq->log);
#endif
  unsigned char OldFlag;
  attribute OldAttr;
  DWORD end_of_code,BlockOffset,BlockSize;
  WORD ResourceNo,TextBlocks;
  Resource Res;
  int ignored;

  OldFlag = cq->flag;

//CrackObject(cq, NewPos);

  fseek(cq->wpd, 2L, SEEK_CUR);
  Rd_word(cq->wpd, &ResourceNo);


  if(LoadResource(cq, ResourceNo, Res)) goto BadResource;
  if(Res.PacketType!=8) {BadResource(cq,ResourceNo);goto BadResource;}

  fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
  Rd_word(cq->wpd, &TextBlocks);	// Load # of text blocks
  if(TextBlocks<1) {BadResource(cq,ResourceNo);goto BadResource;}

  Rd_dword(cq->wpd, &BlockOffset);
  Rd_dword(cq->wpd, &BlockSize);

  fseek(cq->wpd, Res.ResourceFilePos+BlockOffset, SEEK_SET);

  end_of_code = Res.ResourceFilePos+BlockOffset+BlockSize;
  if(BlockOffset + BlockSize > Res.PacketSize)
		end_of_code = Res.ResourceFilePos+Res.PacketSize; //resource seems to be bad - try anyway


  cq->flag = CharsOnly;
  cq->recursion++;

  Close_All_Attr(cq->attr,cq->strip);
  OldAttr=cq->attr;
  InitAttr(cq->attr);		//Turn all attributes in the endnote off

  if(!EndNotes) EndNotes=true;		/* set up endnotes */
  if(EndNotes==-1) EndNotes=-2;
  fprintf(cq->strip, "\\endnote{");

  cq->ActualPos = ftell(cq->wpd);
  while (cq->ActualPos < end_of_code)
	{
	fread(&cq->by, 1, 1, cq->wpd);

	switch (cq->by)
	     {
	     case 0xC7:
	     case 0xCC:fprintf(cq->strip, " \\\\ ");
		       cq->ActualPos++;
		       break;
	     case 0xCF:putc(' ', cq->strip);
		       cq->ActualPos++;
		       break;
	     case 0xD0:cq->flag = CharsOnly;
		       ProcessKey60(cq);
		       cq->flag = HeaderText;
		       switch (cq->subby)
			  {
			  case 4:                               //HRt
			  case 6:			        //Spg-HRt
			  case 9:fprintf(cq->strip, " \\\\ ");  //Hpg
				 break;
			  case 1:                               //SRt
			  case 3:putc(' ', cq->strip);          //SRt-Spg
				 break;
			  }
		       break;
	     case 0xDD:ProcessKey60(cq);
		       switch (cq->subby)
			  {
			  case 0xA:cq->flag = Nothing;    break; //Global On
			  case 0xB:cq->flag = HeaderText; break; //Global Off
			  }
		       break;


	     default: ProcessKey60(cq);
		      break;
	     }
	}

  Close_All_Attr(cq->attr,cq->strip);   /* Echt nodig ? */
  putc('}', cq->strip);

  cq->recursion--;

// Cut Useless Bookmarks and endnote index from main document
  ignored=0;
  cq->flag = Nothing;

  fseek(cq->wpd, NewPos, SEEK_SET);
  cq->ActualPos=NewPos;

  while(!feof(cq->wpd) && ignored<20)
	{
	fread(&cq->by, 1, 1, cq->wpd);

	if(cq->by==0xD7)
		{
		NewPos=cq->ActualPos;
		break;			//Everything is OK, useless section successfully ignored.
		}

	ProcessKey60(cq);
	ignored++;
	}

  if(ignored>=20)
     if (cq->err != NULL)
	{
	cq->perc.Hide();
	fprintf(cq->err, _("\nWarning: Cannot remove strange Endnote index!"));
	}

  cq->attr = OldAttr;
  cq->flag = OldFlag;
BadResource:
  strcpy(cq->ObjType, "Endnote");
}


static void Filename(TconvertedPass1 *cq, DWORD & NewPos)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#Filename() ");fflush(cq->log);
#endif
int i;
unsigned char by;

  fprintf(cq->strip, "\\jobname.tex"); /*the full filename is not distinguished now*/
  fseek(cq->wpd, NewPos, SEEK_SET);

  i=0;                  // maximal allowed filename length is 80 characters
  while(i<80)		// Read the page number text
	{
	fread(&by, 1, 1, cq->wpd);
	if(by==0) break;
	if(by>0x80) break;
	i++;
	}

  if(by==0xD4 && i<80)	// Skip the page number text after object
	{
	NewPos+=i;
	}

  strcpy(cq->ObjType, "Filename");
  cq->char_on_line = true;
}


static void Footnote6(TconvertedPass1_WP6 *cq, DWORD & NewPos)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#Footnote6() ");fflush(cq->log);
#endif
  unsigned char OldFlag;
  attribute OldAttr;
  DWORD end_of_code,BlockOffset,BlockSize;
  WORD ResourceNo,TextBlocks;
  Resource Res;
  int ignored;

  OldFlag = cq->flag;

//CrackObject(cq, NewPos);

  fseek(cq->wpd, 2L, SEEK_CUR);
  Rd_word(cq->wpd, &ResourceNo);


  if(LoadResource(cq, ResourceNo, Res)) goto BadResource;
  if(Res.PacketType!=8) {BadResource(cq,ResourceNo);goto BadResource;}

  fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
  Rd_word(cq->wpd, &TextBlocks);	// Load # of text blocks
  if(TextBlocks<1) {BadResource(cq,ResourceNo);goto BadResource;}

  Rd_dword(cq->wpd, &BlockOffset);
  Rd_dword(cq->wpd, &BlockSize);

  fseek(cq->wpd, Res.ResourceFilePos+BlockOffset, SEEK_SET);

  end_of_code = Res.ResourceFilePos+BlockOffset+BlockSize;
  if(BlockOffset + BlockSize > Res.PacketSize)
		end_of_code = Res.ResourceFilePos+Res.PacketSize; //resource seems to be bad - try anyway


  cq->flag = HeaderText;
  cq->recursion++;

  Close_All_Attr(cq->attr,cq->strip);
  OldAttr=cq->attr;
  InitAttr(cq->attr);		//Turn all attributes in the footnotet off


  fprintf(cq->strip, "\\footnote{");

  cq->ActualPos = ftell(cq->wpd);
  while (cq->ActualPos < end_of_code)
	{
	fread(&cq->by, 1, 1, cq->wpd);

	switch (cq->by)
	     {
	     case 0xC7:
	     case 0xCC:fprintf(cq->strip, " \\\\ ");
		       cq->ActualPos++;
		       break;
	     case 0xCF:putc(' ', cq->strip);
		       cq->ActualPos++;
		       break;
	     case 0xD0:cq->flag = CharsOnly;
		       ProcessKey60(cq);
		       cq->flag = HeaderText;
		       switch (cq->subby)
			  {
			  case 4:                               //HRt
			  case 6:			        //Spg-HRt
			  case 9:fprintf(cq->strip, " \\\\ ");  //Hpg
				 break;
			  case 1:                               //SRt
			  case 3:putc(' ', cq->strip);          //SRt-Spg
				 break;
			  }
		       break;
	     case 0xDD:ProcessKey60(cq);
		       switch (cq->subby)
			  {
			  case 0xA:cq->flag = Nothing;    break; //Global On
			  case 0xB:cq->flag = HeaderText; break; //Global Off
			  }
		       break;


	     default: ProcessKey60(cq);
		      break;
	     }
	}

  Close_All_Attr(cq->attr,cq->strip);   /* Echt nodig ? */
  putc('}', cq->strip);

  cq->recursion--;

// Cut Useless Bookmarks and endnote index from main document
  ignored=0;
  cq->flag = Nothing;

  fseek(cq->wpd, NewPos, SEEK_SET);
  cq->ActualPos=NewPos;

  while(!feof(cq->wpd) && ignored<20)
	{
	fread(&cq->by, 1, 1, cq->wpd);

	if(cq->by==0xD7)
		{
		NewPos=cq->ActualPos;
		break;			//Everything is OK, useless section successfully ignored.
		}

	ProcessKey60(cq);
	ignored++;
	}

  if(ignored>=20)
     if (cq->err != NULL)
	{
	cq->perc.Hide();
	fprintf(cq->err, _("\nWarning: Cannot remove strange Endnote index!"));
	}

  cq->attr = OldAttr;
  cq->flag = OldFlag;
BadResource:
  strcpy(cq->ObjType, "Footnote");
}


/**This function prints the current number of the footnote*/
static void FootnoteNumber6(TconvertedPass1 *cq, DWORD & NewPos)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#FootnoteNumber6() ");fflush(cq->log);
#endif

  fprintf(cq->strip, "\\thefootnote ");

  SkipNumber6(cq,NewPos);

  strcpy(cq->ObjType, "Formatted Footnote Num");
  cq->char_on_line = true;
}


static void Header_Footer6(TconvertedPass1_WP6 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#Header_Footer6() ");fflush(cq->log);
#endif
 BYTE occurance,flags,PIDS;
 attribute OldAttr;
 unsigned char OldFlag,OldEnvir;
 DWORD BlockOffset,BlockSize,end_of_code;
 WORD ResourceNo,TextBlocks;
 Resource Res;
 const char *ObjectName;
 static const char Occurance6to5[4] = {0,2,4,1};


  switch (cq->subby)
	{
	case 0:ObjectName="Header A";	 break;
	case 1:ObjectName="Header B";	 break;
	case 2:ObjectName="Footer A";	 break;
	case 3:ObjectName="Footer B";	 break;
	case 4:ObjectName="!Watermark A";goto BadResource;
	case 5:ObjectName="!Watermark B";goto BadResource;
	default:ObjectName="!Unknown";	 goto BadResource;
	}

  flags=getc(cq->wpd);flags=flags;
  PIDS=getc(cq->wpd);
  if(PIDS<=0) goto BadResource;

  Rd_word(cq->wpd, &ResourceNo);
  fseek(cq->wpd, 2L*(PIDS-1) + 2L, SEEK_CUR);  //skip other resources + size of non del data
  occurance=getc(cq->wpd);


  if(LoadResource(cq, ResourceNo, Res)) goto BadResource;
  if(Res.PacketType!=8) {BadResource(cq,ResourceNo);goto BadResource;}

  fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
  Rd_word(cq->wpd, &TextBlocks);	// Load # of text blocks
  if(TextBlocks<1) {BadResource(cq,ResourceNo);goto BadResource;}

  Rd_dword(cq->wpd, &BlockOffset);
  Rd_dword(cq->wpd, &BlockSize);

  fseek(cq->wpd, Res.ResourceFilePos+BlockOffset, SEEK_SET); // seek to the beginning of the text

  end_of_code = Res.ResourceFilePos+BlockOffset+BlockSize;
  if(BlockOffset + BlockSize > Res.PacketSize)
		end_of_code = Res.ResourceFilePos+Res.PacketSize; //resource seems to be bad - try anyway


  OldFlag = cq->flag;
  OldEnvir= cq->envir;

  Close_All_Attr(cq->attr,cq->strip);
  OldAttr=cq->attr;			/* Backup all attributes */
  if(cq->Font==FONT_HEBREW || cq->Font==FONT_CYRILLIC)
      {
      cq->Font = FONT_NORMAL;
      }

  cq->line_term = 's';    	//Soft return
  if(cq->char_on_line == -20)    /* Left one enpty line for new enviroment */
      {
      fputc('%', cq->table);
      fputc('%', cq->strip);
      NewLine(cq);
      }
  if(cq->char_on_line==true)
      {
      NewLine(cq);
      }

  cq->recursion++;
  InitAttr(cq->attr);
			// bit 0 - occurance on odd pages
			// bit 1 - occurance on even pages
  InitHeaderFooter(cq, cq->subby, Occurance6to5[occurance & 3]);

  cq->envir='!';		//Ignore enviroments after header/footer
  NewLine(cq);

  InitAttr(cq->attr);		//Turn all attributes in the header/footer off

  cq->flag = HeaderText;
  cq->envir = ' ';
  cq->ActualPos = ftell(cq->wpd);
  cq->char_on_line = -10;
  while (cq->ActualPos < end_of_code)
        {
        fread(&cq->by, 1, 1, cq->wpd);

	ProcessKey60(cq);
        }

  Close_All_Attr(cq->attr,cq->strip);
  if(cq->char_on_line==true)
     {
     cq->line_term = 's';    	//Soft return
     NewLine(cq);
     }
  putc('}', cq->strip);

  cq->line_term = 's';    	//Soft return
  cq->envir='^';		//Ignore enviroments after header/footer
  NewLine(cq);

  cq->attr=OldAttr;			/* Restore backuped attributes */
  cq->flag = OldFlag;
  cq->envir = OldEnvir;
  cq->char_on_line = -10;		// stronger false;
  cq->recursion--;

BadResource:
  strcpy(cq->ObjType,ObjectName);
}


static void Hyphenation6(TconvertedPass1 *cq)
{
BYTE b;

 fseek(cq->wpd, 3L, SEEK_CUR);
 fread(&b, 1, 1, cq->wpd);    /*0- hyphenation off; 1- hyphenation on*/

 Hyphenation(cq,b);
}


static void Label16Inside(TconvertedPass1_WP6 *cq, DWORD end_of_code, WORD Wchar = 0)
{
const char *CharStr;

  if(Wchar==0) Rd_word(cq->wpd, &Wchar);
  cq->ActualPos=ftell(cq->wpd)-2;
  while(Wchar!=0 && cq->ActualPos<=end_of_code)
	{
	CharStr = Ext_chr_str(Wchar, cq, cq->ConvertCpg);
	FixLabelText(CharStr,cq->strip);

	Rd_word(cq->wpd, &Wchar);
        cq->ActualPos+=2;

        if(feof(cq->wpd)) break;
        }

if(feof(cq->wpd)) fseek(cq->wpd, cq->DocumentStart, SEEK_SET);
}


static void LineSpacing6(TconvertedPass1 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#LineSpacing6() ");fflush(cq->log);
#endif
DWORD CurrentSpacing;
WORD  WordSpacing;
char b;

  fseek(cq->wpd, 3l, SEEK_CUR);
  Rd_dword(cq->wpd,&CurrentSpacing);

  WordSpacing=(WORD)(CurrentSpacing*128l / 0x10000);

  b = 'l';
  fwrite(&b, 1, 1, cq->table);
  Wr_word(cq->table,WordSpacing);

  sprintf(cq->ObjType, "Line Spacing %2.2f",float(CurrentSpacing)/0x10000);
}


/*This procedure converts a sequence of overstriked characters*/
static void Overstrike6(TconvertedPass1_WP6 *cq, DWORD end_of_code)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#Ovestrike6() ");fflush(cq->log);
#endif
int CharCount=0;
WORD Wchar;
attribute OldAttr;
string s;

  fseek(cq->wpd, 3L, SEEK_CUR);
  Rd_word(cq->wpd, &Wchar);
  cq->ActualPos=ftell(cq->wpd)-2;

  cq->recursion++;
  end_of_code-=4;
  OldAttr = cq->attr;
  *cq->ObjType=0;
  while(Wchar!=0 && cq->ActualPos<=end_of_code)
	{
	switch(Wchar)
	  {
	  case 0xFC66:Attr_ON(cq,0);	break;
	  case 0xFC67:Attr_ON(cq,1);	break;
	  case 0xFC68:Attr_ON(cq,2);	break;
	  case 0xFC69:Attr_ON(cq,3);	break;
	  case 0xFC6A:Attr_ON(cq,4);	break;
	  case 0xFC6B:Attr_ON(cq,5);	break;
	  case 0xFC6C:Attr_ON(cq,6);	break;
	  case 0xFC6D:Attr_ON(cq,7);	break;
	  case 0xFC6E:Attr_ON(cq,8);	break;
	  case 0xFC6F:Attr_ON(cq,9);	break;
	  case 0xFC70:Attr_ON(cq,10);	break;
	  case 0xFC71:Attr_ON(cq,11);	break;
	  case 0xFC72:Attr_ON(cq,12);	break;
	  case 0xFC73:Attr_ON(cq,13);	break;
	  case 0xFC74:Attr_ON(cq,14);	break;
	  case 0xFC75:Attr_ON(cq,15);	break;

	  case 0xFC76:Attr_OFF(cq,0);	break;
	  case 0xFC77:Attr_OFF(cq,1);	break;
	  case 0xFC78:Attr_OFF(cq,2);	break;
	  case 0xFC79:Attr_OFF(cq,3);	break;
	  case 0xFC7A:Attr_OFF(cq,4);	break;
	  case 0xFC7B:Attr_OFF(cq,5);	break;
	  case 0xFC7C:Attr_OFF(cq,6);	break;
	  case 0xFC7D:Attr_OFF(cq,7);	break;
	  case 0xFC7E:Attr_OFF(cq,8);	break;
	  case 0xFC7F:Attr_OFF(cq,9);	break;
	  case 0xFC80:Attr_OFF(cq,10);	break;
	  case 0xFC81:Attr_OFF(cq,11);	break;
	  case 0xFC82:Attr_OFF(cq,12);	break;
	  case 0xFC83:Attr_OFF(cq,13);	break;
	  case 0xFC84:Attr_OFF(cq,14);	break;
	  case 0xFC85:Attr_OFF(cq,15);	break;

	  default:Open_All_Attr(cq->attr, cq->strip);
		  if(CharCount>0)
		    {
		    if(cq->attr.Math_Depth>0) cq->attr.Math_Depth=0;//Math might be nested inside \llap
		    fputs("\\llap{",cq->strip);
		    }
		  CharacterStr(cq,Ext_chr_str(Wchar, cq, cq->ConvertCpg));
		  if(CharCount>0)  fputs("}",cq->strip);
		  CharCount++;
	  }

	if (cq->log != NULL)
	     {   /**/
	     if (*cq->ObjType != '\0')
		  {
		  fprintf(cq->log, "\n%*s [%s] ",cq->recursion * 2,"",
			 cq->ObjType);
		  *cq->ObjType=0;
		  }
	     else fprintf(cq->log, " [%u] ", Wchar);
	     }


	Rd_word(cq->wpd, &Wchar);
	cq->ActualPos+=2;
	}

  AttrFit(cq->attr,OldAttr,s);
  if(s!="") fputs(s(),cq->strip);

  cq->recursion--;
  if(CharCount>0) cq->char_on_line = true;

  strcpy(cq->ObjType, "Overstrike");
}


static void SetFontShape(TconvertedPass1_WP6 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#SetFontShape() ");fflush(cq->log);
#endif
WORD  ResourceNo,FontNameSize,Wchar;
string FontName;
const char *ig="!";
Resource Res;

  fseek(cq->wpd, 2L, SEEK_CUR);
  Rd_word(cq->wpd, &ResourceNo);
  if(LoadResource(cq, ResourceNo, Res)) goto BadResource;
  if(Res.PacketType!=0x55) goto BadResource;

  fseek(cq->wpd, Res.ResourceFilePos+22, SEEK_SET);
  Rd_word(cq->wpd, &FontNameSize);
  while(FontNameSize>0)
	{
	Rd_word(cq->wpd, &Wchar);
	if(Wchar==0) break;
	FontName+=Ext_chr_str(Wchar, cq, cq->ConvertCpg);
	FontNameSize--;
	}

  SetFont(cq,0,FontName());
  if(NFSS && FontName!="") ig="";

BadResource:
  if(length(FontName)>(int)sizeof(cq->ObjType)-7)
	FontName=copy(FontName,0,sizeof(cq->ObjType)-7);
  sprintf(cq->ObjType, "%sFont %s", ig, chk(FontName()));
}




//---------------------------

/*This procedure increments the number of current endnote*/
static void IncCounterNum(TconvertedPass1 *cq,const char *CounterName)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#IncCounterNum() ");fflush(cq->log);
#endif

  fprintf(cq->strip, "\\stepcounter{%s}",CounterName);
  sprintf(cq->ObjType, "Inc %s Num",CounterName);
}


/**This procedure increments the number of the user counter*/
static void IncUserCounter(TconvertedPass1_WP6 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#IncUserCounter() ");fflush(cq->log);
#endif
  BYTE Flag,NumID;
  WORD ResourceNo,Wchr;
  Resource Res;
  string CounterName;

  Flag = getc(cq->wpd);
  if(!(Flag & 0x80)) goto BadResource;
  NumID = getc(cq->wpd);

  while(NumID>0)
	{
	Rd_word(cq->wpd,&ResourceNo);
	if(LoadResource(cq, ResourceNo, Res)) goto BadResource;
	if(Res.PacketType==0x11)
		{
		fseek(cq->wpd,Res.ResourceFilePos,SEEK_SET);

		Rd_word(cq->wpd,&Wchr);
		while(Wchr!=0)
		  {
		  CounterName+=Ext_chr_str(Wchr, cq, cq->ConvertCpg);
		  Rd_word(cq->wpd,&Wchr);
		  }

		break;
		}

	NumID--;
	}
  if(CounterName=="") goto BadResource;

  FixCounterName(CounterName);
  Counters|=CounterName;
  fprintf(cq->strip, "\\stepcounter{%s}",CounterName());

BadResource:
  if(length(CounterName)>(int)sizeof(cq->ObjType)-13)
	{
	CounterName[sizeof(cq->ObjType)-13]=0;
	}
  sprintf(cq->ObjType, "Inc %s Counter",chk(CounterName()));
}


/*This procedure decrements the number of the user counter*/
static void DecUserCounter(TconvertedPass1_WP6 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#DecUserCounter() ");fflush(cq->log);
#endif
  BYTE Flag,NumID;
  WORD ResourceNo,Wchr;
  Resource Res;
  string CounterName;

  Flag=getc(cq->wpd);
  if(!(Flag & 0x80)) goto BadResource;
  NumID=getc(cq->wpd);

  while(NumID>0)
	{
	Rd_word(cq->wpd,&ResourceNo);
	if(LoadResource(cq, ResourceNo, Res)) goto BadResource;
	if(Res.PacketType==0x11)
		{
		fseek(cq->wpd,Res.ResourceFilePos,SEEK_SET);

		Rd_word(cq->wpd,&Wchr);
		while(Wchr!=0)
		  {
		  CounterName+=Ext_chr_str(Wchr, cq, cq->ConvertCpg);
		  Rd_word(cq->wpd,&Wchr);
		  }

		break;
		}

	NumID--;
	}
  if(CounterName=="") goto BadResource;

  FixCounterName(CounterName);
  Counters|=CounterName;
  fprintf(cq->strip, "\\addtocounter{%s}{-1}",CounterName());

BadResource:
  if(length(CounterName)>(int)sizeof(cq->ObjType)-13)
	{
	CounterName[sizeof(cq->ObjType)-13]=0;
	}
  sprintf(cq->ObjType, "Dec %s Counter",chk(CounterName()));
}


static void UserCounter(TconvertedPass1_WP6 *cq, DWORD & NewPos)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#PageNumber6() ");fflush(cq->log);
#endif
  int i;
  unsigned char by;
  BYTE Flag,NumID;
  WORD ResourceNo,Wchr;
  Resource Res;
  string CounterName;

  Flag=getc(cq->wpd);
  if(!(Flag & 0x80)) goto BadResource;
  NumID=getc(cq->wpd);

  while(NumID>0)
	{
	Rd_word(cq->wpd,&ResourceNo);
	if(LoadResource(cq, ResourceNo, Res)) goto BadResource;
	if(Res.PacketType==0x11)
		{
		fseek(cq->wpd,Res.ResourceFilePos,SEEK_SET);

		Rd_word(cq->wpd,&Wchr);
		while(Wchr!=0)
		  {
		  CounterName+=Ext_chr_str(Wchr, cq, cq->ConvertCpg);
		  Rd_word(cq->wpd,&Wchr);
		  }

		break;
		}

	NumID--;
	}
  if(CounterName=="") goto BadResource;


  FixCounterName(CounterName);
  Counters|=CounterName;
  fprintf(cq->strip, "\\the%s ",CounterName());

  fseek(cq->wpd, NewPos, 0);
  i=0;
  while(i<20)		// Read the page number text
	{
	fread(&by, 1, 1, cq->wpd);
	if(!isalnum(by)) break;
	i++;
	}

  if(by==0xDA && i<20)	// Skip the page number text after object
	{
	NewPos+=i;
	}


  cq->char_on_line = true;
BadResource:
  if(length(CounterName)>(int)sizeof(cq->ObjType)-9)
	{
	CounterName[sizeof(cq->ObjType)-9]=0;
	}
  sprintf(cq->ObjType, "Counter %s",chk(CounterName()));
}


/*This procedure increments the number of current endnote*/
static void DecCounterNum(TconvertedPass1 *cq,const char *CounterName)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#DecCounterNum() ");fflush(cq->log);
#endif

  fprintf(cq->strip, "\\addtocounter{%s}{-1}",CounterName);
  sprintf(cq->ObjType, "Inc %s Num",CounterName);
}


static void EndnoteNumber6(TconvertedPass1 *cq, DWORD & NewPos)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#EndnoteNumber6() ");fflush(cq->log);
#endif

  if(!EndNotes) EndNotes=true;		/* set up endnotes */
  if(EndNotes<0)
	{
	strcpy(cq->ObjType, "!Endnote Num");
	return;
	}

  fprintf(cq->strip, "\\theendnote ");

  SkipNumber6(cq,NewPos);

  strcpy(cq->ObjType, "Formatted Endnote Num");
  cq->char_on_line = true;
}


/**This procedure converts WP6.x Line numbering*/
static void LineNumbering6(TconvertedPass1_WP6 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#LineNumbering6() ");fflush(cq->log);
#endif
 BYTE PIDs, LineNumFlag;

  fseek(cq->wpd, 1L, SEEK_CUR);		// skip Flag
  PIDs = fgetc(cq->wpd);
  fseek(cq->wpd, 2*PIDs+2+2+1+2+2, SEEK_CUR);
  LineNumFlag = fgetc(cq->wpd);

  LineNumbering(cq, LineNumFlag&1);
}


static void MakeIndex60(TconvertedPass1_WP6 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#MakeIndex60() ");fflush(cq->log);
#endif
  unsigned char OldFlag;
  WORD ResourceNo,Wchar;
  Resource Res;

  OldFlag = cq->flag;

  fseek(cq->wpd, 2L, SEEK_CUR);
  Rd_word(cq->wpd, &ResourceNo);
  if(LoadResource(cq, ResourceNo, Res)) goto BadResource;


  fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
  Rd_word(cq->wpd, &Wchar);	// Load first resource char
  if(feof(cq->wpd)) {fseek(cq->wpd, 0l, SEEK_CUR);{BadResource(cq,ResourceNo);goto BadResource;}};
  if(Wchar!=0) {BadResource(cq,ResourceNo);goto BadResource;}


  fprintf(cq->strip, " \\index{");

  cq->flag = HeaderText;
  Label16Inside(cq, cq->DocumentStart, Wchar);

  putc('}', cq->strip);
  Index=true;

  cq->flag = OldFlag;
  cq->char_on_line = true;

BadResource:
  strcpy(cq->ObjType, "Index");
}


static void MakeLabel6(TconvertedPass1_WP6 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#MakeLabel6() ");fflush(cq->log);
#endif
  unsigned char OldFlag;
  WORD Wchar, ResourceNo;
  Resource Res;
  BYTE PIDs;

  OldFlag = cq->flag;

  fseek(cq->wpd, 1L, SEEK_CUR);
  PIDs=fgetc(cq->wpd);
  if(PIDs!=1)
    {
    if(cq->err!=NULL)
       fprintf(cq->err, _("\nWarning: Label contains unexpected amount of resources %d!"),(int)PIDs);
	goto BadResource;
    }
  Rd_word(cq->wpd, &ResourceNo);
  if(LoadResource(cq, ResourceNo, Res)) goto BadResource;


  if(Res.PacketType!=0xF) {BadResource(cq,ResourceNo);goto BadResource;}
  fseek(cq->wpd, Res.ResourceFilePos, SEEK_SET);
  Rd_word(cq->wpd, &Wchar);	// Load first resource char
  if(feof(cq->wpd)) {fseek(cq->wpd, 0l, SEEK_SET);{BadResource(cq,ResourceNo);goto BadResource;}};
  if(Wchar==0) {BadResource(cq,ResourceNo);goto BadResource;}


  fprintf(cq->strip, "%s\\label{",cq->char_on_line>0?" ":"");

  cq->flag = HeaderText;
  Label16Inside(cq, cq->DocumentStart, Wchar);

  putc('}', cq->strip);

  cq->flag = OldFlag;
  if(cq->char_on_line == false)
  	cq->char_on_line = -1;
BadResource:
  strcpy(cq->ObjType, "Label");
}


static void MakeRef6(TconvertedPass1_WP6 *cq, DWORD & NewPos, char TypeRef)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#MakeRef6() ");fflush(cq->log);
#endif
  unsigned char OldFlag;
  DWORD end_of_code;
  int i;
  unsigned char ch,SubRefType;


  end_of_code=NewPos;
  OldFlag = cq->flag;
  end_of_code -= 4;

  fread(&SubRefType, 1, 1, cq->wpd);
  fseek(cq->wpd,SubRefType<0x80? 2l : 7l , SEEK_CUR);
  cq->ActualPos = ftell(cq->wpd);

  if(TypeRef>9) TypeRef=9;
  if(TypeRef==0) fprintf(cq->strip, " \\pageref{");
  	    else fprintf(cq->strip, " \\ref{");

  cq->flag = HeaderText;
  Label16Inside(cq, end_of_code);

  putc('}', cq->strip);

//The referred number must be removed
  if(SubRefType>=0x80)
    {
    fseek(cq->wpd, NewPos, 0);
    i=0;
    while(i<20)		// Read the page number text
  	  {
          fread(&ch, 1, 1, cq->wpd);
          if(!isalnum(ch)) break;
          i++;
	  }

    if(ch==0xD5 && i<20)	// Skip the page number text after object
  	  {
          NewPos+=i;
          }
    }

  cq->flag = OldFlag;
  cq->char_on_line = true;
  sprintf(cq->ObjType, "Ref:%s",RefTypes[TypeRef]);
}


static void PageNumber6(TconvertedPass1 *cq, DWORD & NewPos)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#PageNumber6() ");fflush(cq->log);
#endif
int i;
unsigned char by;

  fprintf(cq->strip, "\\thepage ");
  fseek(cq->wpd, NewPos, 0);

  i=0;
  while(i<20)		// Read the page number text
	{
	fread(&by, 1, 1, cq->wpd);
	if(!isalnum(by)) break;
	i++;
	}

  if(by==0xDA && i<20)	// Skip the page number text after object
	{
	NewPos+=i;
	}

  strcpy(cq->ObjType, "Formatted Pg Num");
  cq->char_on_line = true;
}


/*This procedure sets the user counter to a given number*/
static void SetUserCounter(TconvertedPass1_WP6 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#SetUserCounter() ");fflush(cq->log);
#endif
  BYTE Flag,NumID;
  WORD ResourceNo,Wchr;
  Resource Res;
  string CounterName;
  DWORD SavePos;

  Flag=getc(cq->wpd);
  if(!(Flag & 0x80)) goto BadResource;
  NumID=getc(cq->wpd);

  while(NumID>0)
	{
	Rd_word(cq->wpd,&ResourceNo);
	SavePos= ftell(cq->wpd);
	if(LoadResource(cq, ResourceNo, Res)) goto BadResource;
	if(Res.PacketType==0x11)
		{
		fseek(cq->wpd,Res.ResourceFilePos,SEEK_SET);

		Rd_word(cq->wpd,&Wchr);
		while(Wchr!=0)
		  {
		  CounterName+=Ext_chr_str(Wchr, cq, cq->ConvertCpg);
		  Rd_word(cq->wpd,&Wchr);
		  }
		}

	fseek(cq->wpd,SavePos,SEEK_SET);
	NumID--;
	}
  if(CounterName=="") goto BadResource;

  fseek(cq->wpd,4l,SEEK_CUR);
  Rd_word(cq->wpd, &Wchr);

  FixCounterName(CounterName);
  Counters|=CounterName;
  fprintf(cq->strip, "\\setcounter{%s}{%u}",CounterName(),(unsigned int)Wchr);

BadResource:
  if(length(CounterName)>(int)sizeof(cq->ObjType)-13)
	{
	CounterName[sizeof(cq->ObjType)-13]=0;
	}
  sprintf(cq->ObjType, "Set Counter %s=%u",chk(CounterName()),(unsigned int)Wchr);
}


static void TableOfContents6(TconvertedPass1 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#TableOfContents6() ");fflush(cq->log);
#endif
  char ListType;

  if ((cq->char_on_line==true)||(cq->attr.Opened_Depth>0))
    {
    Close_All_Attr(cq->attr,cq->strip);

    NewLine(cq);
    }

  fseek(cq->wpd, 6L, SEEK_CUR);
  fread(&ListType, 1, 1, cq->wpd);

  switch(ListType)
  	{
	case  0:fprintf(cq->strip, "\\tableofcontents");
		cq->line_term = 's';   /* Soft return */
		NewLine(cq);
        	strcpy(cq->ObjType, "Def Mark:ToC");
                break;
	case  1:sprintf(cq->ObjType, "!Def Mark:List");
// !!!!!!!!! The lists are not converted yet
		break;
	case  2:PlaceIndex(cq);
		strcpy(cq->ObjType, "Def Mark:Index");
		break;
	case  3:sprintf(cq->ObjType, "!Def Mark:ToA");
// !!!!!!!!! The tables of autorities are not converted yet
	        break;

	default: strcpy(cq->ObjType, "!Def Mark:?Unknown");
	}
}


static void TabSet6(TconvertedPass1 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#TabSet6() ");fflush(cq->log);
#endif
 int j,SideMargin;
 WORD oldw,w,difw,Adjust;
 BYTE Definition,TabsNum,TabType,TabRepeater;

  fseek(cq->wpd, 3L, SEEK_CUR);

  Definition = fgetc(cq->wpd);
  Rd_word(cq->wpd, &Adjust);
  TabsNum = fgetc(cq->wpd);

  if(Definition & 1 == 1)
	{
	SideMargin=Adjust+cq->WP_sidemargin-cq->Lmar;//Relative Tab
	}
	else SideMargin=cq->WP_sidemargin;	//Absolute Tab

  cq->num_of_tabs = 0;
  oldw=0;
  TabRepeater=TabType=0;
  for (j = 1; j <= TabsNum; j++)
      {
      if(TabRepeater<1)
	 {
	 TabRepeater = fgetc(cq->wpd);
	 if(TabRepeater>=0x80)
		     {
		     TabRepeater &= 0x7F;
		     j-= TabRepeater-1;
		     Rd_word(cq->wpd, &difw);
		     }
		else {
		     TabType=TabRepeater;
		     TabRepeater=0;
		     Rd_word(cq->wpd, &w);
		     }
	 }

      if(TabRepeater>0)
	   {
	   TabRepeater--;
	   w=oldw+difw;
	   }

      if (w > cq->WP_sidemargin && w != 0xffffL)
	    {
	    cq->num_of_tabs++;
	    cq->tabpos[cq->num_of_tabs - 1] = w - SideMargin;
	    }
      oldw=w;
      }

  Make_tableentry_tabset(cq);
  sprintf(cq->ObjType, "TabSet:%s",Definition & 1?"Rel":"Abs");
}


/**This procedure converts beginning of the table and reads alignment of columns.*/
static void TableStart6(TconvertedPass1_WP6 *cq, DWORD & NewPos)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#TableStart6() ");fflush(cq->log);
#endif
int columns;
WORD w;
DWORD attributes;
unsigned char by,subby,align;
string TexAttrib;
boolean bookmark=false;
unsigned char OldFlag;
char OldEnvir;
BYTE Flag, NumID;

  Flag = getc(cq->wpd);
  if(!(Flag & 0x80)) {Flag=0;goto BadResource;}
  NumID = getc(cq->wpd);
  fseek(cq->wpd, 2*NumID + 2 + 1, SEEK_CUR);

  Flag = getc(cq->wpd);		//table flags

BadResource:
  fseek(cq->wpd, NewPos, SEEK_SET);
  OldFlag = cq->flag;
  OldEnvir= cq->envir;

  columns=0;            // a counter of columns
  while(columns<80)		// Read next text
	{
	fread(&by, 1, 1, cq->wpd);
	fread(&subby, 1, 1, cq->wpd);
	if(!bookmark)
		{
		if(by==0xF1 && subby==0x0)  //remove useless bookmark
			{
			bookmark=true;
			NewPos+=5;
			fseek(cq->wpd, NewPos, SEEK_SET);
			continue;
			}
		}

	if(subby!=0x2C) break;
	if(by!=0xD4) break;
	Rd_word(cq->wpd, &w);

	fseek(cq->wpd, 10l, SEEK_CUR);
	Rd_dword(cq->wpd, &attributes);
	fread(&align, 1, 1, cq->wpd);

	if(columns==0)
		{
		cq->line_term = 's';   /* Soft return */
		cq->recursion++;

		if(cq->char_on_line == -20)    /* Left one enpty line for new enviroment */
		    {
		    fputc('%', cq->table);fputc('%', cq->strip);
		    NewLine(cq);
		    }
		if(cq->char_on_line>=true) //  if(cq->char_on_line>=-1)
		    {
		    NewLine(cq);
		    }		
			
		switch(Flag & 3)	// Apply table position flag
		{
		  case 1:if(OldEnvir!='R')
		 	   {fprintf(cq->strip, "\\begin{flushright}"); NewLine(cq);}
			 break;
		  case 2:if(OldEnvir!='C')
		 	   {fprintf(cq->strip, "\\begin{center}"); NewLine(cq);}
			 break;
		}

		cq->envir='!';
		fputc('%', cq->table);fputc('%', cq->strip);
		NewLine(cq);

		cq->envir = 'B';
		fprintf(cq->strip, "{|");
		}

	TexAttrib=Attributes2String(attributes); //Solve attributes for columns
	if(TexAttrib != "")
	  {
	  fprintf(cq->strip,"@{%s}",TexAttrib());
	  }
	switch(align & 0x7) /* bits 0-2 align; bit 3 - absolute position; 4-7 num of chars */
		{
		case 0x0:fprintf(cq->strip, "l|"); break;  //left
		case 0x1:fprintf(cq->strip, "c|"); break;  //full
		case 0x2:fprintf(cq->strip, "c|"); break;  //center
		case 0x3:fprintf(cq->strip, "r|"); break;  //right
		case 0x4:		//full all lines
		case 0x5:		//decimal align
		default:fprintf(cq->strip, "c|");
		}

	NewPos+=w;
//	CrackObject(cq, NewPos);
	fseek(cq->wpd, NewPos, SEEK_SET);
	columns++;
	}

  if(columns>0) putc('}', cq->strip);
  cq->char_on_line = false;
  cq->nomore_valid_tabs = false;
  cq->rownum++;
  Make_tableentry_attr(cq);
  cq->latex_tabpos = 0;
  if(columns<=0) goto NoTable;

	/*Process all content of the table */
  fseek(cq->wpd,cq->ActualPos=NewPos,SEEK_SET);
  cq->by=fgetc(cq->wpd);
  while(!feof(cq->wpd))
	{
	if(cq->by==0xD4 && cq->envir!='B')
		{
		cq->envir='B';
		}
	ProcessKey60(cq);
	NewPos=cq->ActualPos;
	if(cq->by==0xD0 && cq->subby>=17 && cq->subby<=19) break; /*End of table*/
	if(cq->by>=0xBD && cq->by<=0xBF) break;

	cq->by=fgetc(cq->wpd);
	}
  if(cq->char_on_line <= -10)    /* Left one empty line for ending enviroment */
	{
	fputc('%', cq->table);fputc('%', cq->strip);
	NewLine(cq);
	}

  switch(Flag & 3)
  {
    case 1:if(OldEnvir!='R')
	     {fprintf(cq->strip, "\\end{flushright}"); NewLine(cq);}
	   break;
    case 2:if(OldEnvir!='C')
	     {fprintf(cq->strip, "\\end{center}"); NewLine(cq);}
	   break;
  }

  cq->envir='^';		//Ignore enviroments after table
  fputc('%', cq->table);
  NewLine(cq);
  cq->char_on_line = -10;		// stronger false;

  cq->recursion--;

NoTable:
  cq->flag=OldFlag;
  cq->envir=OldEnvir;
  strcpy(cq->ObjType, "!Table Start"+((columns!=0)?1:0));
}


static void Undo(TconvertedPass1_WP6 *cq, DWORD & NewPos)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#Undo() ");fflush(cq->log);
#endif
unsigned char OldFlag;
attribute OldAttr;
BYTE Type;
WORD Level;
SWORD SubLevel;
const char *UndoType;

  Type=fgetc(cq->wpd);
  Rd_word(cq->wpd, &Level);
  if(!UndoRedo) goto SkipUndoStuff;

  fseek(cq->wpd, NewPos, SEEK_SET);

  if(Type==0 && EmptyCheck(cq->UndoRedo))
    {
    cq->UndoRedo.push(-(int)Level);
    if(cq->log)
      fprintf(cq->log,_("\n%*sIgnored from undo %d:"), cq->recursion*2, "", Level);

    OldFlag = cq->flag;
    OldAttr = cq->attr;

    cq->flag = Nothing;

    fseek(cq->wpd, NewPos, SEEK_SET);
    cq->ActualPos=NewPos;

    cq->recursion++;
    while(!feof(cq->wpd))
	{
	if(fread(&cq->by, 1, 1, cq->wpd)<1) break;

	if(cq->by==0xF1) //next Undo command
		{
		NewPos=cq->ActualPos; //Everything is OK
		Type=fgetc(cq->wpd);
		Rd_word(cq->wpd, (WORD *)&SubLevel);
		fseek(cq->wpd,cq->ActualPos+1,SEEK_SET);

		switch(Type)
                  {
		  case 0:cq->UndoRedo.push(-(int)SubLevel); break;
		  case 2:cq->UndoRedo.push((int)SubLevel);  break;

		  case 1:SubLevel=-SubLevel;  	//continuing on label 3:
                  case 3:while(cq->UndoRedo.pop()!=(int)SubLevel && !EmptyCheck(cq->UndoRedo))
			   {
			   if(cq->err!=NULL)
	 		     {
	 		     cq->perc.Hide();
	 		     fprintf(cq->err,
			       _("\nError: Undo/Redo stack is corrupted, Type=%d!"),Type);
	 		     }
                           }
                  }
		if(EmptyCheck(cq->UndoRedo))
                  {
                  ProcessKey60(cq);
		  NewPos=cq->ActualPos; //Everything is OK
                  break;}
		}
	ProcessKey60(cq);
	}

     cq->recursion--;
     cq->attr = OldAttr;
     cq->flag = OldFlag;

     Type=0;
     }

SkipUndoStuff:
 switch(Type)
   {
   case 0:UndoType="Invalid Start";	break;
   case 1:UndoType="Invalid End";	break;
   case 2:UndoType="Valid Start";	break;
   case 3:UndoType="Valid End";		break;
   default:if (cq->err != NULL)
		{
		cq->perc.Hide();
		fprintf(cq->err, _("\nWarning: Strange Undo type:%d !"),(int)Type);
		}
	   sprintf(cq->ObjType, "!Undo (?%d:%d)"+(UndoRedo?1:0),Type,(int)Level);
	   return;
   }

  sprintf(cq->ObjType, "!Undo (%s:%d)"+(UndoRedo?1:0), UndoType, (int)Level);
}

//-------------------------------------------------


static boolean CheckConzistency60(TconvertedPass1 *cq, long NewPos)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#CheckConzistency60() ");fflush(cq->log);
#endif

  boolean Result = true;
  unsigned char TestedBy;
  long Pos;

  Pos = ftell(cq->wpd);

  fseek(cq->wpd, NewPos-1 , 0);
  fread(&TestedBy, 1, 1, cq->wpd);

  if (TestedBy != cq->by)
  	{
	if (cq->err != NULL)
	 {
	 cq->perc.Hide();
	 fprintf(cq->err,
	      _("\nError: Object %lX:%X consistency check failed. Trying to ignore."),Pos,(int)cq->by);
	 }
        CorruptedObjects++;
        Result = false;
	/* asm int 3; end;*/
	}

  fseek(cq->wpd, Pos, 0);
  return Result;
}


/**This is main procedure for processing one key. It is recursivelly called.*/
static void ProcessKey60(TconvertedPass1_WP6 *cq)
{
#ifdef DEBUG
  fprintf(cq->log,"\n#ProcessKey60() ");fflush(cq->log);
#endif
WORD w;
DWORD NewPos = 0;
unsigned char by, subby;
WORD Wchar;

  if(cq->by == 0)
    fread(&cq->by, 1, 1, cq->wpd);

#ifdef DEBUG
  if(cq->ActualPos+1 != ftell(cq->wpd))
	fprintf(cq->err,
	      _("\nInternal Error: Position skew was detected at 0x%lX != 0x%X!"),cq->ActualPos,ftell(cq->wpd)-1);
#endif //DEBUG

  *cq->ObjType = '\0';
  w=1;
  cq->subby=0;

  /*Computing end position of the object*/
  if (cq->by >= 0x7F)
    {
    if ( (cq->by & 0xF0) == 0xF0 )
	{
	w = ObjWP6SizesF0[cq->by - 0xF0];
	if (w > 0) NewPos = cq->ActualPos + w;
	cq->subby = 0xFF;   /*ignored subcommand*/
	}
    else if (cq->by >= 0xD0 && cq->by <= 0xEF)
		    {
		    fread(&cq->subby, 1, 1, cq->wpd);
		    Rd_word(cq->wpd, &w);
		    cq->Linebegin = false;
		    NewPos = cq->ActualPos + w;
		    }
    }

  by = cq->by;
  subby = cq->subby;

  if (ExtendedCheck && NewPos != 0)
    if (!CheckConzistency60(cq, NewPos))
      {
      NewPos = cq->ActualPos+1;
      strcpy(cq->ObjType, "Corrupted!!");
      goto _LObjectError;
      }


  if( filter[cq->flag][by] )
     {
     switch (by)
	{
	case 0x01:	//Default extended international characters
	case 0x02:
	case 0x03:
	case 0x04:
	case 0x05:
	case 0x06:
	case 0x07:
	case 0x08:
	case 0x09:
	case 0x0A:
	case 0x0B:
	case 0x0C:
	case 0x0D:
	case 0x0E:
	case 0x0F:
	case 0x10:
	case 0x11:
	case 0x12:
	case 0x13:
	case 0x14:
	case 0x15:
	case 0x16:
	case 0x17:
	case 0x18:
	case 0x19:
	case 0x1A:
	case 0x1B:
	case 0x1C:
	case 0x1D:
	case 0x1E:
	case 0x1F:
	case 0x20:CharacterStr(cq,Ext_chr_str(0x100 | CharsWP6_1_32[by],cq,cq->ConvertCpg));
		  break;

	case 0x80:putc(' ', cq->strip);   /*soft space*/
		  break;
	case 0x81:fputc('~', cq->strip);strcpy(cq->ObjType, " ");
		  break;
	case 0x82:
	case 0x83:SoftHyphen(cq); break;
	case 0x84:HardHyphen(cq); break;		/*Hyphen*/
	case 0x85:fputs("\\-", cq->strip);strcpy(cq->ObjType, "- Auto Hyphen");
		  break;
	case 0x86:InvisibleSoftReturn(cq);		break;
	case 0x87:Terminate_Line(cq, 'h');	/* Dormant Hard Return */
		  strcpy(cq->ObjType, "Dorm HRt");
		  break;

	case 0x90:CancelHyph(cq);			break;

	case 0xB8:if(cq->char_on_line>false)	    /*Deleteble Hard EOC/EOP*/
			Terminate_Line(cq, 'h'); /*[THRt]  Hard return */
		  cq->char_on_line = -1;
		  strcpy(cq->ObjType, "TH_EOC/EOP");
		  break;
	case 0xB9:if(cq->char_on_line>false)
			Terminate_Line(cq, 'h'); /*[THRt]  Hard return */
		  cq->char_on_line = -1;
		  strcpy(cq->ObjType, "THRt");
		  break;

	case 0xBD:				/*Table Off/EOC/EOP*/
	case 0xBE:				/*Table Off/EOC*/
	case 0xBF:EndTable(cq);  break;		/*Table Off*/
	case 0xC0:				/*Table Row/Hard EOP*/
	case 0xC1:				/*Table Row/Hard EOC/EOP*/
	case 0xC2:				/*Table Row/Hard EOC*/
	case 0xC3:				/*Table Row/EOC/EOP*/
	case 0xC4:				/*Table Row/EOC*/
	case 0xC5:RowTable(cq);  break;		/*Table Row*/
	case 0xC6:if(cq->char_on_line==0) cq->char_on_line=-1;
		  CellTable(cq); break;		/*Table Cell*/
	case 0xC7:HardPage(cq);  break;		/* Hard page */

	case 0xCC:HardReturn(cq);break;		/*[HRt]  Hard return */

	case 0xCF:SoftReturn(cq);	break;		/* soft return */
	case 0xD0:switch (subby)
		    {
		    case  1:SoftReturn(cq); break;      /* Soft Return */
		    case  3:SoftReturn(cq); strcpy(cq->ObjType, "SRt-SPg");
			    break;      		/* Soft Return - Soft Page */
		    case  4:HardReturn(cq); break;	/* Hard Return (within TAB) */
		    case  6:Terminate_Line(cq, 'h');	/* Prefer Hard return - Soft page */
			    strcpy(cq->ObjType, "HRt-SPg");
			    break;
		    case  9:HardPage(cq);   break;	 /* Hard page */
		    case 10:if(cq->char_on_line==0) cq->char_on_line=-1;
			    CellTable(cq);  break;
		    case 11:RowTable(cq);   break;
		    case 13:RowTable(cq);   break;	/* in the case of page break */
		    case 17:			/*Table Off*/
		    case 18:                    /*     at EOC*/
		    case 19:EndTable(cq);break; /*     at EOC/EOP*/
		    case 0x1A:if(cq->char_on_line) Terminate_Line(cq, 's');
			   strcpy(cq->ObjType, "THCol");
			   break;
		    }
		  break;
	case 0xD1:switch (subby)
		    {
		    case    0:strcpy(cq->ObjType,"!Top Margin");break;
		    case    1:strcpy(cq->ObjType,"!Bottom Margin");break;
		    case    2:Suppress(cq,6);			break;
		    case    3:Page_number_position(cq,6);	break;
		    case    4:CenterPage(cq);			break;
		    case    5:strcpy(cq->ObjType,"!Center Page Top Bottom"); break;
		    case    6:WidowOrphan(cq,6);		break;
		    case    7:strcpy(cq->ObjType,"!Set Footnote spaces");break;
		    case    8:strcpy(cq->ObjType,"!Set Endnote spaces");break;

                    case 0x11:strcpy(cq->ObjType,"!Form");	break;
		    case 0x12:strcpy(cq->ObjType,"!Form Labels");break;
		    case 0x13:strcpy(cq->ObjType,"!Double Sided Printing");break;
		    case 0x14:strcpy(cq->ObjType,"!Logical Pages");break;
		    case 0x15:strcpy(cq->ObjType,"!Delayed Codes");break;
		    case 0x16:strcpy(cq->ObjType,"!Delay on");	break;
		    case 0x17:strcpy(cq->ObjType,"!~Delay on");	break;
		    }
		  break;
	case 0xD2:switch (subby)
		    {
		    case 0: strcpy(cq->ObjType,"!Left Margin");break;
		    case 1: strcpy(cq->ObjType,"!Right Margin");break;
		    case 2: Column6(cq);		break;
		    }
		  break;
	case 0xD3:switch (subby)
		    {
		    case  1:LineSpacing6(cq);		break;
		    case  4:TabSet6(cq);		break;
		    case  5:Justification(cq,6); 	break;
		    case  6:Hyphenation6(cq); 		break;
		    case  8:strcpy(cq->ObjType,"!Begin Generated Text");break;
		    case  9:strcpy(cq->ObjType,"!End Generated Text");break;
                    case 0xC:strcpy(cq->ObjType,"!Left Margin Adjust");break; 
		    case 0xD:strcpy(cq->ObjType,"!Right Margin Adjust");break;
		    case 0xE:strcpy(cq->ObjType,"!Outline Define");break;
                    case 0x12:LineNumbering6(cq);	break; 
		    case 0x14:PlaceEndnotes(cq);	break;
		    case 0x16:TableOfContents6(cq);	break;
		    }
		  break;
	case 0xD4:switch (subby)
		    {
		    case 0x06:MakeIndex60(cq);		break;
		    case 0x08:MakeLabel6(cq);		break;
		    case 0x0A:StartSection(cq,6);	break;
		    case 0x0B:EndSection(cq,6);		break;
		    case 0x18:Color(cq,6);		break;
		    case 0x1C:if(w>=0xE)
				{
				char flags=getc(cq->wpd);
				WORD NdelData;
				Rd_word(cq->wpd, &NdelData);
				Language(cq, 6);
				}
			      break;
		    case 0x1A:SetFontShape(cq);		break;
		    case 0x1B:SetFontSize(cq,6);	break;

		    case 0x1D:Comment6(cq);		break;

		    case 0x25:strcpy(cq->ObjType,"!Bookmark");break;

		    case 0x29:Overstrike6(cq,NewPos);	break;
		    case 0x2A:TableStart6(cq,NewPos);	break;

		    case 0x2C:strcpy(cq->ObjType,"!Table Hdr");break;

                    case 0x2E:Filename(cq,NewPos);	break;
                    case 0x2F:strcpy(cq->ObjType,"~Filename"); break;

		    case 0x32:strcpy(cq->ObjType,"!Par Num On"); break;
		    case 0x33:strcpy(cq->ObjType,"!Par Num Off"); break;
                    }
        	  break;
        case 0xD5:switch (subby)
                    {
                    case  0:MakeRef6(cq, NewPos, 1);	break;
                    case  2:MakeRef6(cq, NewPos, 2);	break;
		    case  4:MakeRef6(cq, NewPos, 0);	break;
                    case  6:MakeRef6(cq, NewPos, 3);	break;
                    case  8:MakeRef6(cq, NewPos, 4);	break;
                    case 10:MakeRef6(cq, NewPos, 5);	break;
                    case 12:MakeRef6(cq, NewPos, 6);	break;
                    case 14:MakeRef6(cq, NewPos, 7);	break;
                    case 16:MakeRef6(cq, NewPos, 8);	break;
                    case  1:
                    case  3:
                    case  5:
                    case  7:
		    case  9:
                    case 11:
                    case 13:
                    case 15:
		    case 17:strcpy(cq->ObjType,"~Ref"); break;
		    }
		  break;
	case 0xD6:if(subby<=5) Header_Footer6(cq);
		  break;
	case 0xD7:switch (subby)
		    {
		    case 0: Footnote6(cq, NewPos);		break;
		    case 1: strcpy(cq->ObjType,"~Footnote");	break;
		    case 2: Endnote6(cq, NewPos);		break;
		    case 3: strcpy(cq->ObjType,"~EndNote");	break;
		    }
		  break;
	case 0xD8:switch (subby)
		    {
		    case  0:SetUserCounter(cq);			break;
		    case  2:SetPgNum(cq,6);			break;
		    case  7:SetFootnoteNum(cq,6);		break;
		    case  8:SetEndnoteNum(cq,6);		break;
		    }
		  break;

	case 0xDA:switch (subby)
		    {
		    case    0:UserCounter(cq, NewPos);		  break;
		    case    1:strcpy(cq->ObjType,"~User Counter");break;

		    case    4:PageNumber6(cq, NewPos);		  break;
		    case    5:strcpy(cq->ObjType, "~Pg Num");	  break;

		    case  0xC:SkipNumber6(cq,NewPos);
			      strcpy(cq->ObjType,"!Par Num Disp");break;
		    case  0xD:strcpy(cq->ObjType,"!~Par Num Disp");break;
		    case  0xE:FootnoteNumber6(cq, NewPos);	  break;
		    case  0xF:strcpy(cq->ObjType,"~Footnote Num");break;
		    case 0x10:EndnoteNumber6(cq, NewPos);	  break;
		    case 0x11:strcpy(cq->ObjType,"~Endnote Num"); break;
		    }
		  break;
	case 0xDB:switch (subby)
		    {
		    case  0:IncUserCounter(cq);			break;

		    case  2:IncCounterNum(cq,"page");		break;
		    case  7:IncCounterNum(cq,"footnote");	break;
		    case  8:IncCounterNum(cq,"endnote");
			    if(!EndNotes) EndNotes=true; 	break;
		    }
		  break;
	case 0xDC:switch (subby)
		    {
		    case  0:DecUserCounter(cq);			break;

		    case  2:DecCounterNum(cq,"page");		break;
		    case  7:DecCounterNum(cq,"footnote");	break;
		    case  8:DecCounterNum(cq,"endnote");
			    if(!EndNotes) EndNotes=true;	break;
		    }
		  break;
	case 0xDD:switch (subby)
		    {
		    case 0x0:strcpy(cq->ObjType,"!Style Begin On"); break;
		    case 0x1:strcpy(cq->ObjType,"!Style Begin Off"); break;
	            case 0x2:strcpy(cq->ObjType,"!Style End On"); break;
		    case 0x3:strcpy(cq->ObjType,"!Style End Off"); break;
		    case 0x4:strcpy(cq->ObjType,"!Par Style 1 Beg On"); break;
		    case 0x5:strcpy(cq->ObjType,"!Par Style 1 Beg Off"); break;
		    case 0x6:strcpy(cq->ObjType,"!Par Style 2 Beg On"); break;
		    case 0x7:strcpy(cq->ObjType,"!Par Style 2 Beg Off"); break;
		    case 0x8:strcpy(cq->ObjType,"!Par Style End On"); break;
		    case 0x9:strcpy(cq->ObjType,"!Par Style End Off"); break;
		    case 0xA:strcpy(cq->ObjType,"!Global on"); break;
		    case 0xB:strcpy(cq->ObjType,"!Global off");break;
                    }
		  break;
	case 0xDF:if (subby<=2) Box6(cq);
		  if (subby==0x3) HLine(cq,6);
		  break;
	case 0xE0:switch (subby)
		    {
		    case 0x00:BackTab(cq);		break;
		    case 0x11:Tab(cq,6);		break;
		    case 0x30:Indent(cq,6);		break;
		    case 0x40:Center(cq);		break;
		    case 0x80:Flush_right(cq,0);	break;
		    case 0x82:Flush_right(cq,1);	break;
		    case 0xD1:strcpy(cq->ObjType, "!Dec Tab");
			      putc(' ', cq->strip);	break;
		    default:sprintf(cq->ObjType,"!TAB %Xh",subby);
			    putc(' ', cq->strip);
			    break;
		    }
		  break;
        case 0xE1:if(subby==0xC)
			{
			fseek(cq->wpd,3,SEEK_CUR); //<flags>[NDelSize]
			Color(cq,7);		break;
			}
		  break;
	case 0xF0:cq->char_on_line = true;   /*Some character is placed on line */
		  if(cq->attr.Closed_Depth!=cq->attr.Opened_Depth)
			{
		        Open_All_Attr(cq->attr,cq->strip);
		        }

		  Rd_word(cq->wpd, &Wchar);
		  sprintf(cq->ObjType,"%u,%u",Wchar>>8,Wchar & 0xFF);

		  CharacterStr(cq,Ext_chr_str(Wchar, cq, cq->ConvertCpg));

		  subby=fgetc(cq->wpd);		// charset again
		  break;
	case 0xF1:Undo(cq, NewPos);	break;
	case 0xF2:Attr_ON(cq);         	break;
	case 0xF3:Attr_OFF(cq);		break;


	default:if(cq->by>0x20 && cq->by<=0x7f)
		 {
                   if(cq->RequiredFont==FONT_HEBREW)
                   {
		   if(by=='.')
                       {CharacterStr(cq,"\\textrm{.}");break;}
                   if(by==',')
                       {CharacterStr(cq,"\\textrm{,}");break;}
		   if(by==':')
                       {CharacterStr(cq,"\\textrm{:}");break;}
                   if(by==';')
                       {CharacterStr(cq,"\\textrm{;}");break;}
                   }
		 cq->RequiredFont = FONT_NORMAL;
		 CharacterStr(cq,Ext_chr_str(cq->by,cq,cq->ConvertCpg));   /* Normal_char */
    		 break;
	         }
        }
     }

_LObjectError:
  if (cq->log != NULL)
    {   /**/
    if (by==0xF0) fprintf(cq->log, " [ExtChr %s] ", cq->ObjType);
    else if (by >= ' ' && by <= 'z')
	         putc(by, cq->log);
    else if (by==0x80) putc(' ', cq->log);
    else if ((by > 0xc0)||(*cq->ObjType != '\0'))
	{
	fprintf(cq->log,_("\n%*sObject type:%3Xh subtype:%3Xh length:%4u"),
		  cq->recursion * 2,"", by, subby, w);
	if (*cq->ObjType != '\0')
		  fprintf(cq->log, " [%s] ", cq->ObjType);
	     else fprintf(cq->log, "    ");
	if(*cq->ObjType==0) UnknownObjects++;
	}
    }


  if (NewPos == 0)
	{
	if(by<0xD0) cq->ActualPos++;	//Only one byte read - simple guess of new position
	       else cq->ActualPos = ftell(cq->wpd);
	return;
	}
  cq->ActualPos = ftell(cq->wpd);
  if (NewPos == cq->ActualPos) return;
  fseek(cq->wpd, NewPos, SEEK_SET);
  cq->ActualPos = NewPos;
  NewPos = 0;
  /*these functions have fixed size - see table SizesC0*/
}


static void InitFilter60(void)
{
 filter[0]=set(set0_60,sizeof(set0_60)/sizeof(int));
 filter[1]=set(set1_60,sizeof(set1_60)/sizeof(int));
 filter[2]=set(set2_60,sizeof(set2_60)/sizeof(int));
 filter[3]=set(set3_60,sizeof(set3_60)/sizeof(int));
}


int TconvertedPass1_WP6::Dispatch(int FuncNo, ...)
{
#ifdef DEBUG
  fprintf(log,"\n#TconvertedPass1_WP6::Dispatch(%d) ",FuncNo);fflush(log);
#endif
va_list ap;

 va_start(ap, FuncNo);
 switch(FuncNo)
   {
   case DISP_PROCESSKEY:
	 ProcessKey60(this);
	 return 0;
   case DISP_WRAPPER:		// Notification from OLE wrapper is discarded for now.
         return 0;
   }

 if(err != NULL)
   {
   perc.Hide();
   fprintf(err, _("\nInternal Error: Unknown dispatch %d."),FuncNo);
   }
return(-1);
}


/***************************************/
/* This procedure provides all needed processing for the first pass*/
int TconvertedPass1_WP6::Convert_first_pass(void)
{
#ifdef DEBUG
  fprintf(log,"\n#TconvertedPass1_WP6::Convert_first_pass() ");fflush(log);
#endif
DWORD fsize;

  InitFilter60();

  ConvertCpg = GetTranslator("wp6TOinternal");

  DocumentStart=ftell(wpd);
  fsize=filesize(wpd);

  ResourceStart=0;
  if(DocumentStart>0x10)
    {
    fseek(wpd,14,SEEK_SET);
    Rd_word(wpd,&ResourceStart);
    if(ResourceStart==0) ResourceStart=0x10;
    if(ResourceStart<0x10) ResourceStart=0;
    fseek(wpd,DocumentStart,SEEK_SET);
    }

  perc.Init(ftell(wpd),fsize,_("First pass WP 6.x:"));

#ifndef FINAL
  CrackResources(this);
#endif

  ActualPos = ftell(wpd);
  while (ActualPos < fsize)
      {
      if(Verbosing >= 1)		//actualise a procentage counter
	      perc.Actualise(ActualPos);

      by = 0;
      ProcessKey60(this);
      }

  Finalise_Conversion(this);
  return(1);
}


#if 0
void Convert_pass1_WP6_encrypted(FILE *FileIn,FILE  *table, FILE *StripOut,FILE *LogFile,FILE *ErrorFile,void *Wrapper);
FFormatTranslator FormatWP6encrypted("WP6.x encrypted",Convert_pass1_WP6_encrypted);

void Convert_pass1_WP6_encrypted(FILE *FileIn,FILE  *table, FILE *StripOut,FILE *LogFile,FILE *ErrorFile,void *Wrapper)
{
 FileIn=FileIn;
 table=table;
 StripOut=StripOut;
 ErrorFile=ErrorFile;
 LogFile=LogFile;

//
// Sorry, I have no Idea how to decrypt WP6.x files!");
//     please help ............
//
RunError(0x203);
}
#endif


/*--------------------End of PASS1_6----------------------*/
