#include "all.h"
#include "mygraph.h"
#include "justify.h"
int g_get_font(int *f);

#define true (!false)
#define false 0
#define dbg if ((gle_debug & 32)>0)
extern int gle_debug;

extern int32 *(*gpcode)[];   /* gpcode is a polonger to an array of poiter to int32 */
extern int32 (*gplen)[];   /* gpcode is a pointer to an array of int32 */
extern int ngpcode;

static double base_owidth;
int g_textfindend(char *s, double *x, double *y);
int tab_line(char *ss,char *outbuff);
begin_tab(int *pln,int32 *pcode, int *cp)
{
	int sl,i,bl,cjust;
	char *tabbuff;
 	char tbuff[200];
 	double zzz;
	int save_fnt;
	double save_hei;
	g_get_font(&save_fnt);
	g_get_hei(&save_hei);

	tabbuff = myalloc(5000);
    bl = 0;
    g_get_just(&cjust);
	g_textfindend("o",&base_owidth,&zzz);
    tabbuff[0] = 0;
    for (i=0;;i++) {
	dbg showpcode(pcode);
	if (*(pcode+*cp-1)==0) { /* END XXX */
		break;
	}
	sl = strlen((char *) (pcode+*cp));
	strcpy(tbuff,(char *) (pcode+*cp));
	if (i>1) {
		tab_line(tbuff,tabbuff);
	}
	pcode = (*gpcode)[(*pln)++];
	*cp = 2;
    }
	dbg printf("+_+_+_+_+_ %d {%s} \n",strlen(tabbuff),tabbuff);
	g_set_font(save_fnt);
	g_set_hei(save_hei);
	(*pln)--;

       text_block(UC tabbuff,0.0,cjust);
     myfree(tabbuff);
}
#define aspace(c) (c == ' ')
tab_line(char *ss,char *tabbuff)
{
	double bl,br,bu,bd,swid;
	char wbuff[100],str2[30];
	char *s,*wb;
	int i,c=0,cjust,savec,old_len;
	swid = base_owidth;
	old_len = strlen(tabbuff);
	for (s=ss;*s!=0;) {
		if (*s==9) {
			c = (c/8)*8+8; s++;
		} else {
		  if (aspace(*s))  {
			c++; s++;
		  } else {
			wb = wbuff;
			savec = c;
			for (;*s!=0  && !(*s==9)
				&& !(isspace(*s) && isspace(*(s+1))) ;) {
				if (*s == '\\') if (*(s+1) != '\\') c -= 2;
				if (strchr("{}_^",*s)!=NULL) {
					*wb++ = '\\';
				}
				*wb++ = *s++; c++;
			}
			*wb++ = 0;
			g_textfindend(wbuff,&br,&bd);
			wb--;
			sprintf(wb,"\\movexy{%g}{0}",-br-swid*savec);
			sprintf(str2,"\\movexy{%g}{0}",swid*savec);
			if (strlen(tabbuff)>3000) {
				gprint("Too much tabbing text in one section.\n");
				return;
			}
			strcat(tabbuff,str2);
			strcat(tabbuff,wbuff);
		  }
		}
	}
	if (strlen(tabbuff)==old_len)  strcat(tabbuff,"\\movexy{0}{0}");
	strcat(tabbuff,"\n");
}











