static void SFDSizeMap(EncMap *map,int glyphcnt,int enccnt) {
    if ( glyphcnt>map->backmax ) {
	map->backmap = realloc(map->backmap,glyphcnt*sizeof(int));
	memset(map->backmap+map->backmax,-1,(glyphcnt-map->backmax)*sizeof(int));
	map->backmax = glyphcnt;
    }
    if ( enccnt>map->encmax ) {
	map->map = realloc(map->map,enccnt*sizeof(int));
	memset(map->map+map->backmax,-1,(enccnt-map->encmax)*sizeof(int));
	map->encmax = map->enccount = enccnt;
    }
}


static void SFGuessScriptList(SplineFont1 *sf) {
    uint32 scripts[32], script;
    int i, scnt=0, j;

    for ( i=0; i<sf->sf.glyphcnt; ++i ) if ( sf->sf.glyphs[i]!=NULL ) {
	script = SCScriptFromUnicode(sf->sf.glyphs[i]);
	if ( script!=0 && script!=DEFAULT_SCRIPT ) {
	    for ( j=scnt-1; j>=0 ; --j )
		if ( scripts[j]==script )
	    break;
	    if ( j<0 ) {
		scripts[scnt++] = script;
		if ( scnt>=32 )
    break;
	    }
	}
    }
    if ( scnt==0 )
	scripts[scnt++] = CHR('l','a','t','n');

    /* order scripts */
    for ( i=0; i<scnt-1; ++i ) for ( j=i+1; j<scnt; ++j ) {
	if ( scripts[i]>scripts[j] ) {
	    script = scripts[i];
	    scripts[i] = scripts[j];
	    scripts[j] = script;
	}
    }

    if ( sf->sf.cidmaster ) sf = (SplineFont1 *) sf->sf.cidmaster;
    else if ( sf->sf.mm!=NULL ) sf=(SplineFont1 *) sf->sf.mm->normal;
    if ( sf->script_lang!=NULL )
return;
    sf->script_lang = calloc(2,sizeof(struct script_record *));
    sf->script_lang[0] = calloc(scnt+1,sizeof(struct script_record));
    sf->sli_cnt = 1;
    for ( j=0; j<scnt; ++j ) {
	sf->script_lang[0][j].script = scripts[j];
	sf->script_lang[0][j].langs = malloc(2*sizeof(uint32));
	sf->script_lang[0][j].langs[0] = DEFAULT_LANG;
	sf->script_lang[0][j].langs[1] = 0;
    }
    sf->script_lang[1] = NULL;
}

Fix for #4084 Use-after-free (heap) in the SFD_GetFontMetaData() function
Fix for #4086 NULL pointer dereference in the SFDGetSpiros() function
Fix for #4088 NULL pointer dereference in the SFD_AssignLookups() function
Add empty sf->fontname string if it isn't set, fixing #4089 #4090 and many
  other potential issues (many downstream calls to strlen() on the value).

/* No explicit global definitions found. */


static GuidelineSet *SFDReadGuideline(FILE *sfd, GuidelineSet **gll, GuidelineSet *lastgl)
{
    GuidelineSet *gl = chunkalloc(sizeof(GuidelineSet));
    gl->name = SFDReadUTF7Str(sfd);
    gl->identifier = SFDReadUTF7Str(sfd);
    getreal(sfd,&gl->point.x);
    getreal(sfd,&gl->point.y);
    getreal(sfd,&gl->angle);
    getint(sfd,&gl->color);
    getint(sfd,&gl->flags);
    if ( lastgl!=NULL )
	lastgl->next = gl;
    else if (gll)
        *gll = gl;
    return( gl );
}

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };

static char base64[64] = {
 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};

static const char *end_tt_instrs = "EndTTInstrs";

static void SFDConsumeUntil( FILE *sfd, const char** terminators );

static void SFDDumpRefs(FILE *sfd,RefChar *refs, int *newgids);

static void SFDDumpGuidelines(FILE *sfd,GuidelineSet *gl);

static RefChar *SFDGetRef(FILE *sfd, int was_enc);

static void SFDDumpImage(FILE *sfd,ImageList *img);

static void SFDDumpImagePNG(FILE *sfd,ImageList *img);

static AnchorPoint *SFDReadAnchorPoints(FILE *sfd,SplineChar *sc,AnchorPoint** alist, AnchorPoint *lastap);

static GuidelineSet *SFDReadGuideline(FILE *sfd, GuidelineSet **gll, GuidelineSet *lastgl);

static void SFDDumpTtfInstrs(FILE *sfd,SplineChar *sc);


static int SLCount(struct script_record *sr) {
    int sl_cnt = 0;
    int i,j;

    for ( i=0; sr[i].script!=0; ++i ) {
	for ( j=0; sr[i].langs[j]!=0; ++j )
	    ++sl_cnt;
    }
return( sl_cnt );
}


static void FPSTReplaceTagsWithLookups(FPST *fpst,SplineFont1 *sf) {
    int i,j,k;

    if ( fpst->type == pst_reversesub )
return;
    for ( i=0; i<fpst->rule_cnt; ++i ) {
	for ( j=0; j<fpst->rules[i].lookup_cnt; ++j ) {
	    OTLookup *otl = FindNestedLookupByTag(sf,(uint32) (intpt) (fpst->rules[i].lookups[j].lookup) );
	    if ( otl!=NULL )
		fpst->rules[i].lookups[j].lookup = otl;
	    else {
		for ( k=j+1; k<fpst->rules[i].lookup_cnt; ++k )
		    fpst->rules[i].lookups[k-1] = fpst->rules[i].lookups[k];
		--fpst->rules[i].lookup_cnt;
	    }
	}
    }
}


static struct ttf_table *SFDGetShortTable(FILE *sfd, SplineFont *sf,struct ttf_table *lasttab[2]) {
    /* We've read the ShortTable token, it is followed by a tag and a word count */
    /* and then the (text) values of the words that make up the cvt table */
    int i,len, ch;
    uint8 *pt;
    int which, iscvt, started;
    struct ttf_table *tab = chunkalloc(sizeof(struct ttf_table));

    tab->tag = gettag(sfd);

    if ( tab->tag==CHR('f','p','g','m') || tab->tag==CHR('p','r','e','p') ||
	    tab->tag==CHR('c','v','t',' ') || tab->tag==CHR('m','a','x','p'))
	which = 0;
    else
	which = 1;
    iscvt = tab->tag==CHR('c','v','t',' ');

    getint(sfd,&len);
    pt = tab->data = malloc(2*len);
    tab->len = 2*len;
    started = false;
    for ( i=0; i<len; ++i ) {
	int num;
	getint(sfd,&num);
	*pt++ = num>>8;
	*pt++ = num&0xff;
	if ( iscvt ) {
	    ch = nlgetc(sfd);
	    if ( ch==' ' ) {
		if ( !started ) {
		    sf->cvt_names = calloc(len+1,sizeof(char *));
		    sf->cvt_names[len] = END_CVT_NAMES;
		    started = true;
		}
		sf->cvt_names[i] = SFDReadUTF7Str(sfd);
	    } else
		ungetc(ch,sfd);
	}
    }

    if ( lasttab[which]!=NULL )
	lasttab[which]->next = tab;
    else if ( which==0 )
	sf->ttf_tables = tab;
    else
	sf->ttf_tab_saved = tab;
    lasttab[which] = tab;
return( tab );
}

int UndoRedoLimitToSave = 0;

int UndoRedoLimitToLoad = 0;

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

int prefRevisionsToRetain = 32;

int WritePNGInSFD = true;

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };


void SFD_DumpKerns( FILE *sfd, SplineChar *sc, int *newgids ) {
    KernPair *kp;
    int v;

    for ( v=0; v<2; ++v ) {
	kp = v ? sc->vkerns : sc->kerns;
	if ( kp!=NULL ) {
	    fprintf( sfd, v ? "VKerns2:" : "Kerns2:" );
	    for ( ; kp!=NULL; kp=kp->next )
		if ( !SFDOmit(kp->sc)) {
		    fprintf( sfd, " %d %d ",
			    newgids!=NULL?newgids[kp->sc->orig_pos]:kp->sc->orig_pos,
			    kp->off );
		    SFDDumpUTF7Str(sfd,kp->subtable->subtable_name);
		    if ( kp->adjust!=NULL ) putc(' ',sfd);
		    SFDDumpDeviceTable(sfd,kp->adjust);
		}
	    fprintf(sfd, "\n" );
	}
    }
}

int UndoRedoLimitToSave = 0;

int UndoRedoLimitToLoad = 0;

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

int prefRevisionsToRetain = 32;

int WritePNGInSFD = true;

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };

static void SFDConsumeUntil( FILE *sfd, const char** terminators );

static void SFDDumpRefs(FILE *sfd,RefChar *refs, int *newgids);

static void SFDDumpGuidelines(FILE *sfd,GuidelineSet *gl);

static RefChar *SFDGetRef(FILE *sfd, int was_enc);

static void SFDDumpImage(FILE *sfd,ImageList *img);

static void SFDDumpImagePNG(FILE *sfd,ImageList *img);

static AnchorPoint *SFDReadAnchorPoints(FILE *sfd,SplineChar *sc,AnchorPoint** alist, AnchorPoint *lastap);

static GuidelineSet *SFDReadGuideline(FILE *sfd, GuidelineSet **gll, GuidelineSet *lastgl);

static void SFDDumpTtfInstrs(FILE *sfd,SplineChar *sc);

static void SFDDumpTtfInstrsExplicit(FILE *sfd,uint8 *ttf_instrs, int16 ttf_instrs_len );

static void SFDDumpHintList(FILE *sfd,const char *key, StemInfo *h);

static void SFDDumpDHintList( FILE *sfd,const char *key, DStemInfo *d );

static StemInfo *SFDReadHints(FILE *sfd);

static DStemInfo *SFDReadDHints( SplineFont *sf,FILE *sfd,int old );

struct enc85 {
    FILE *sfd;
    unsigned char sofar[4];
    int pos;
    int ccnt;
}


void SFDDumpMacFeat(FILE *sfd,MacFeat *mf) {
    struct macsetting *ms;

    if ( mf==NULL )
return;

    while ( mf!=NULL ) {
	if ( mf->featname!=NULL ) {
	    fprintf( sfd, "MacFeat: %d %d %d\n", mf->feature, mf->ismutex, mf->default_setting );
	    SFDDumpMacName(sfd,mf->featname);
	    for ( ms=mf->settings; ms!=NULL; ms=ms->next ) {
		if ( ms->setname!=NULL ) {
		    fprintf( sfd, "MacSetting: %d\n", ms->setting );
		    SFDDumpMacName(sfd,ms->setname);
		}
	    }
	}
	mf = mf->next;
    }
    fprintf( sfd,"EndMacFeatures\n" );
}

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };

static void SFDConsumeUntil( FILE *sfd, const char** terminators );

static void SFDDumpRefs(FILE *sfd,RefChar *refs, int *newgids);

static void SFDDumpGuidelines(FILE *sfd,GuidelineSet *gl);

static RefChar *SFDGetRef(FILE *sfd, int was_enc);

static void SFDDumpImage(FILE *sfd,ImageList *img);

static void SFDDumpImagePNG(FILE *sfd,ImageList *img);

static AnchorPoint *SFDReadAnchorPoints(FILE *sfd,SplineChar *sc,AnchorPoint** alist, AnchorPoint *lastap);

static GuidelineSet *SFDReadGuideline(FILE *sfd, GuidelineSet **gll, GuidelineSet *lastgl);

static void SFDDumpTtfInstrs(FILE *sfd,SplineChar *sc);

static void SFDDumpTtfInstrsExplicit(FILE *sfd,uint8 *ttf_instrs, int16 ttf_instrs_len );

static void SFDDumpHintList(FILE *sfd,const char *key, StemInfo *h);

static void SFDDumpDHintList( FILE *sfd,const char *key, DStemInfo *d );

static StemInfo *SFDReadHints(FILE *sfd);

static DStemInfo *SFDReadDHints( SplineFont *sf,FILE *sfd,int old );

struct enc85 {
    FILE *sfd;
    unsigned char sofar[4];
    int pos;
    int ccnt;
}


int SFDWriteBak(char *filename,SplineFont *sf,EncMap *map,EncMap *normal) {
    char *buf=0, *buf2=NULL;
    int ret;

    if ( sf->save_to_dir )
    {
	ret = SFDWrite(filename,sf,map,normal,true);
	return(ret);
    }

    if ( sf->cidmaster!=NULL )
	sf=sf->cidmaster;
    buf = malloc(strlen(filename)+10);
    if ( sf->compression!=0 )
    {
	buf2 = malloc(strlen(filename)+10);
	strcpy(buf2,filename);
	strcat(buf2,compressors[sf->compression-1].ext);
	strcpy(buf,buf2);
	strcat(buf,"~");
	if ( rename(buf2,buf)==0 )
	    sf->backedup = bs_backedup;
    }
    else
    {
	sf->backedup = bs_dontknow;

	if( prefRevisionsToRetain )
	{
	    char path[PATH_MAX];
	    char pathnew[PATH_MAX];
	    int idx = 0;

	    snprintf( path,    PATH_MAX, "%s", filename );
	    snprintf( pathnew, PATH_MAX, "%s-%02d", filename, idx );
	    (void)rename( path, pathnew );

	    for( idx=prefRevisionsToRetain; idx > 0; idx-- )
	    {
		snprintf( path, PATH_MAX, "%s-%02d", filename, idx-1 );
		snprintf( pathnew, PATH_MAX, "%s-%02d", filename, idx );

		int rc = rename( path, pathnew );
		if( !idx && !rc )
		    sf->backedup = bs_backedup;
	    }
	    idx = prefRevisionsToRetain+1;
	    snprintf( path, PATH_MAX, "%s-%02d", filename, idx );
	    unlink(path);
	}

    }
    free(buf);

    ret = SFDWrite(filename,sf,map,normal,false);
    if ( ret && sf->compression!=0 ) {
	unlink(buf2);
	buf = malloc(strlen(filename)+40);
	sprintf( buf, "%s %s", compressors[sf->compression-1].recomp, filename );
	if ( system( buf )!=0 )
	    sf->compression = 0;
	free(buf);
    }
    free(buf2);
    return( ret );
}


void SFDDumpUndo(FILE *sfd,SplineChar *sc,Undoes *u, const char* keyPrefix, int idx ) {
    fprintf(sfd, "%sOperation\n",      keyPrefix );
    fprintf(sfd, "Index: %d\n",        idx );
    fprintf(sfd, "Type: %d\n",         u->undotype );
    fprintf(sfd, "WasModified: %d\n",  u->was_modified );
    fprintf(sfd, "WasOrder2: %d\n",    u->was_order2 );
    if( u->layer != UNDO_LAYER_UNKNOWN )
    {
	fprintf(sfd, "Layer: %d\n",    u->layer );
    }

    switch( u->undotype )
    {
        case ut_tstate:
        case ut_state:
            fprintf(sfd, "Width: %d\n",           u->u.state.width );
            fprintf(sfd, "VWidth: %d\n",          u->u.state.vwidth );
            fprintf(sfd, "LBearingChange: %d\n",  u->u.state.lbearingchange );
            fprintf(sfd, "UnicodeEnc: %d\n",      u->u.state.unicodeenc );
            if( u->u.state.charname )
                fprintf(sfd, "Charname: \"%s\"\n", u->u.state.charname );
            if( u->u.state.comment )
                fprintf(sfd, "Comment: \"%s\"\n", u->u.state.comment );
            if( u->u.state.refs ) {
                SFDDumpRefs( sfd, u->u.state.refs, 0 );
            }
	    if( u->u.state.images ) {
#ifndef _NO_LIBPNG
                if (WritePNGInSFD)
                    SFDDumpImagePNG( sfd, u->u.state.images );
                else
#endif
                    SFDDumpImage( sfd, u->u.state.images );
            }
            fprintf(sfd, "InstructionsLength: %d\n", u->u.state.instrs_len );
            if( u->u.state.anchor ) {
                SFDDumpAnchorPoints( sfd, u->u.state.anchor );
            }
	    if( u->u.state.splines ) {
                fprintf(sfd, "SplineSet\n" );
                SFDDumpSplineSet( sfd, u->u.state.splines, u->was_order2 );
            }
            break;

        case ut_statehint:
        {
            SplineChar* tsc = 0;
            tsc = SplineCharCopy( sc, 0, 0 );
            ExtractHints( tsc, u->u.state.hints, 1 );
            SFDDumpHintList(  sfd, "HStem: ",  tsc->hstem);
            SFDDumpHintList(  sfd, "VStem: ",  tsc->vstem);
            SFDDumpDHintList( sfd, "DStem2: ", tsc->dstem);
            SplineCharFree( tsc );

	    if( u->u.state.instrs_len )
                SFDDumpTtfInstrsExplicit( sfd, u->u.state.instrs, u->u.state.instrs_len );
            break;
        }

        case ut_hints:
        {
            SplineChar* tsc = 0;
            tsc = SplineCharCopy( sc, 0, 0 );
            tsc->ttf_instrs = 0;
            ExtractHints( tsc, u->u.state.hints, 1 );
            SFDDumpHintList(  sfd, "HStem: ",  tsc->hstem);
            SFDDumpHintList(  sfd, "VStem: ",  tsc->vstem);
            SFDDumpDHintList( sfd, "DStem2: ", tsc->dstem);
            SplineCharFree( tsc );

            if( u->u.state.instrs_len )
                SFDDumpTtfInstrsExplicit( sfd, u->u.state.instrs, u->u.state.instrs_len );
            if( u->copied_from && u->copied_from->fullname )
                fprintf(sfd, "CopiedFrom: %s\n", u->copied_from->fullname );
            break;
        }

        case ut_width:
        case ut_vwidth:
        {
            fprintf(sfd, "Width: %d\n", u->u.width );
            break;
        }

        default:
        break;
    }

    fprintf(sfd, "End%sOperation\n", keyPrefix );
}


static int getlonglong(FILE *sfd, long long *val) {
    char tokbuf[100]; int ch;
    char *pt=tokbuf, *end = tokbuf+100-2;

    while ( isspace(ch = nlgetc(sfd)));
    if ( ch=='-' || ch=='+' ) {
	*pt++ = ch;
	ch = nlgetc(sfd);
    }
    while ( isdigit(ch)) {
	if ( pt<end ) *pt++ = ch;
	ch = nlgetc(sfd);
    }
    *pt='\0';
    ungetc(ch,sfd);
    *val = strtoll(tokbuf,NULL,10);
return( pt!=tokbuf?1:ch==EOF?-1: 0 );
}


static void SFDEnc85EndEnc(struct enc85 *enc) {
    int i;
    int ch2, ch3, ch4, ch5;
    unsigned val;
    if ( enc->pos==0 )
return;
    for ( i=enc->pos; i<4; ++i )
	enc->sofar[i] = 0;
    val = (enc->sofar[0]<<24)|(enc->sofar[1]<<16)|(enc->sofar[2]<<8)|enc->sofar[3];
    if ( val==0 ) {
	fputc('z',enc->sfd);
    } else {
	ch5 = val%85;
	val /= 85;
	ch4 = val%85;
	val /= 85;
	ch3 = val%85;
	val /= 85;
	ch2 = val%85;
	val /= 85;
	fputc('!'+val,enc->sfd);
	fputc('!'+ch2,enc->sfd);
	fputc('!'+ch3,enc->sfd);
	fputc('!'+ch4,enc->sfd);
	fputc('!'+ch5,enc->sfd);
    }
    enc->pos = 0;
}

int UndoRedoLimitToSave = 0;

int UndoRedoLimitToLoad = 0;

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

int prefRevisionsToRetain = 32;

int WritePNGInSFD = true;

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };

static char base64[64] = {
 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};

static const char *end_tt_instrs = "EndTTInstrs";

static void SFDConsumeUntil( FILE *sfd, const char** terminators );

static void SFDDumpRefs(FILE *sfd,RefChar *refs, int *newgids);

static void SFDDumpGuidelines(FILE *sfd,GuidelineSet *gl);

static RefChar *SFDGetRef(FILE *sfd, int was_enc);

static void SFDDumpImage(FILE *sfd,ImageList *img);

static void SFDDumpImagePNG(FILE *sfd,ImageList *img);

static AnchorPoint *SFDReadAnchorPoints(FILE *sfd,SplineChar *sc,AnchorPoint** alist, AnchorPoint *lastap);


static int SFDOmit(SplineChar *sc) {
    int layer;
    BDFFont *bdf;

    if ( sc==NULL )
return( true );
    if ( sc->comment!=NULL || sc->color!=COLOR_DEFAULT )
return( false );
    for ( layer = ly_back; layer<sc->layer_cnt; ++layer ) {
	if ( sc->layers[layer].splines!=NULL ||
		sc->layers[layer].refs!=NULL ||
		sc->layers[layer].images!=NULL )
return( false );
    }
    if ( sc->parent->onlybitmaps ) {
	for ( bdf = sc->parent->bitmaps; bdf!=NULL; bdf=bdf->next ) {
	    if ( sc->orig_pos<bdf->glyphcnt && bdf->glyphs[sc->orig_pos]!=NULL )
return( false );
	}
    }
    if ( !sc->widthset )
return(true);

return( false );
}


static SplineFont *SFD_FigureDirType(SplineFont *sf,char *tok, char *dirname,
	Encoding *enc, struct remap *remap,int had_layer_cnt) {
    /* In a sfdir a directory will either contain glyph files */
    /*                                            subfont dirs */
    /*                                            instance dirs */
    /* (or bitmap files, but we don't care about them here */
    /* It will not contain some glyph and some subfont nor instance files */
    int gc=0, sc=0, ic=0, bc=0;
    DIR *dir;
    struct dirent *ent;
    char *name, *props, *pt;

    dir = opendir(dirname);
    if ( dir==NULL )
return( sf );
    sf->save_to_dir = true;
    while ( (ent=readdir(dir))!=NULL ) {
	pt = strrchr(ent->d_name,EXT_CHAR);
	if ( pt==NULL )
	    /* Nothing interesting */;
	else if ( strcmp(pt,GLYPH_EXT)==0 )
	    ++gc;
	else if ( strcmp(pt,SUBFONT_EXT)==0 )
	    ++sc;
	else if ( strcmp(pt,INSTANCE_EXT)==0 )
	    ++ic;
	else if ( strcmp(pt,STRIKE_EXT)==0 )
	    ++bc;
    }
    rewinddir(dir);
    name = malloc(strlen(dirname)+NAME_MAX+3);
    props = malloc(strlen(dirname)+2*NAME_MAX+4);
    if ( gc!=0 ) {
	sf->glyphcnt = 0;
	sf->glyphmax = gc;
	sf->glyphs = calloc(gc,sizeof(SplineChar *));
	ff_progress_change_total(gc);
	if ( sf->cidmaster!=NULL ) {
	    sf->map = sf->cidmaster->map;
	} else {
	    sf->map = EncMapNew(enc->char_cnt>gc?enc->char_cnt:gc,gc,enc);
	    sf->map->remap = remap;
	}
	SFDSizeMap(sf->map,sf->glyphcnt,enc->char_cnt>gc?enc->char_cnt:gc);

	while ( (ent=readdir(dir))!=NULL ) {
	    pt = strrchr(ent->d_name,EXT_CHAR);
	    if ( pt==NULL )
		/* Nothing interesting */;
	    else if ( strcmp(pt,GLYPH_EXT)==0 ) {
		FILE *gsfd;
		sprintf(name,"%s/%s", dirname, ent->d_name);
		gsfd = fopen(name,"r");
		if ( gsfd!=NULL ) {
		    SFDGetChar(gsfd,sf,had_layer_cnt);
		    ff_progress_next();
		    fclose(gsfd);
		}
	    }
	}
	ff_progress_next_stage();
    } else if ( sc!=0 ) {
	int i=0;
	sf->subfontcnt = sc;
	sf->subfonts = calloc(sf->subfontcnt,sizeof(SplineFont *));
	sf->map = EncMap1to1(1000);
	ff_progress_change_stages(2*sc);

	while ( (ent=readdir(dir))!=NULL ) {
	    pt = strrchr(ent->d_name,EXT_CHAR);
	    if ( pt==NULL )
		/* Nothing interesting */;
	    else if ( strcmp(pt,SUBFONT_EXT)==0 && i<sc ) {
		FILE *ssfd;
		sprintf(name,"%s/%s", dirname, ent->d_name);
		sprintf(props,"%s/" FONT_PROPS, name);
		ssfd = fopen(props,"r");
		if ( ssfd!=NULL ) {
		    if ( i!=0 )
			ff_progress_next_stage();
		    sf->subfonts[i++] = SFD_GetFont(ssfd,sf,tok,true,name,sf->sfd_version);
		    fclose(ssfd);
		}
	    }
	}
    } else if ( ic!=0 ) {
	MMSet *mm = sf->mm;
	int ipos, i=0;

	MMInferStuff(sf->mm);
	ff_progress_change_stages(2*(mm->instance_count+1));
	while ( (ent=readdir(dir))!=NULL ) {
	    pt = strrchr(ent->d_name,EXT_CHAR);
	    if ( pt==NULL )
		/* Nothing interesting */;
	    else if ( strcmp(pt,INSTANCE_EXT)==0 && sscanf( ent->d_name, "mm%d", &ipos)==1 ) {
		FILE *ssfd;
		if ( i!=0 )
		    ff_progress_next_stage();
		sprintf(name,"%s/%s", dirname, ent->d_name);
		sprintf(props,"%s/" FONT_PROPS, name);
		ssfd = fopen(props,"r");
		if ( ssfd!=NULL ) {
		    SplineFont *mmsf;
		    mmsf = SFD_GetFont(ssfd,NULL,tok,true,name,sf->sfd_version);
		    if ( ipos!=0 ) {
			EncMapFree(mmsf->map);
			mmsf->map=NULL;
		    }
		    mmsf->mm = mm;
		    if ( ipos == 0 )
			mm->normal = mmsf;
		    else
			mm->instances[ipos-1] = mmsf;
		    fclose(ssfd);
		}
	    }
	}
	ff_progress_next_stage();
	sf->mm = NULL;
	SplineFontFree(sf);
	sf = mm->normal;
	if ( sf->map->enc!=&custom ) {
	    EncMap *map;
	    MMMatchGlyphs(mm);		/* sfd files from before the encoding change can have mismatched orig pos */
	    map = EncMapFromEncoding(sf,sf->map->enc);
	    EncMapFree(sf->map);
	    sf->map = map;
	}
    }

    if ( bc!=0 ) {
	rewinddir(dir);
	while ( (ent=readdir(dir))!=NULL ) {
	    pt = strrchr(ent->d_name,EXT_CHAR);
	    if ( pt==NULL )
		/* Nothing interesting */;
	    else if ( strcmp(pt,STRIKE_EXT)==0 ) {
		FILE *ssfd;
		sprintf(name,"%s/%s", dirname, ent->d_name);
		sprintf(props,"%s/" STRIKE_PROPS, name);
		ssfd = fopen(props,"r");
		if ( ssfd!=NULL ) {
		    if ( getname(ssfd,tok)==1 && strcmp(tok,"BitmapFont:")==0 )
			SFDGetBitmapFont(ssfd,sf,true,name);
		    fclose(ssfd);
		}
	    }
	}
	SFOrderBitmapList(sf);
    }
    closedir(dir);
    free(name);
    free(props);
return( sf );
}

# define NAME_MAX _POSIX_NAME_MAX

int UndoRedoLimitToSave = 0;

int UndoRedoLimitToLoad = 0;

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

int prefRevisionsToRetain = 32;

int WritePNGInSFD = true;

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };

#define FONT_PROPS	"font.props"

#define STRIKE_PROPS	"strike.props"

#define EXT_CHAR	'.'

#define GLYPH_EXT	".glyph"

#define BITMAP_EXT	".bitmap"

#define STRIKE_EXT	".strike"

#define SUBFONT_EXT	".subfont"

#define INSTANCE_EXT	".instance"


static void SFDFixupUndoRefsUndoList(SplineFont *sf,Undoes *undo) {
    for( ; undo; undo = undo->next ) {
	if( undo->undotype == ut_state && undo->u.state.refs ) {
	    RefChar *ref=NULL;
	    for ( ref=undo->u.state.refs; ref!=NULL; ref=ref->next ) {

		ref->sc = sf->glyphs[ ref->orig_pos ];
	    }
	}
    }
}


static void SFDDumpGuidelines(FILE *sfd, GuidelineSet *gl) {
    if (gl==NULL) {
	return;
    }

    for ( ; gl!=NULL; gl=gl->next )
    {
	fprintf( sfd, "Guideline: " );
	SFDDumpUTF7Str(sfd,gl->name);
	putc(' ',sfd);
	SFDDumpUTF7Str(sfd,gl->identifier);
	putc(' ',sfd);
	fprintf( sfd, "%g %g %g %u %d",
		(double) gl->point.x, (double) gl->point.y,
		(double) gl->angle, gl->color, gl->flags);
	putc('\n',sfd);
    }
}


static int SFDGetBitmapFont(FILE *sfd,SplineFont *sf,int fromdir,char *dirname) {
    BDFFont *bdf, *prev;
    char tok[2000];
    int pixelsize, ascent, descent, depth=1;
    int ch, enccount;

    if ( getint(sfd,&pixelsize)!=1 || pixelsize<=0 )
return( 0 );
    if ( getint(sfd,&enccount)!=1 || enccount<0 )
return( 0 );
    if ( getint(sfd,&ascent)!=1 || ascent<0 )
return( 0 );
    if ( getint(sfd,&descent)!=1 || descent<0 )
return( 0 );
    if ( getint(sfd,&depth)!=1 )
	depth = 1;	/* old sfds don't have a depth here */
    else if ( depth!=1 && depth!=2 && depth!=4 && depth!=8 )
return( 0 );
    while ( (ch = nlgetc(sfd))==' ' );
    ungetc(ch,sfd);		/* old sfds don't have a foundry */

    bdf = calloc(1,sizeof(BDFFont));
    if (bdf == NULL)
        return 0;

    if ( ch!='\n' && ch!='\r' ) {
	getname(sfd,tok);
	bdf->foundry = copy(tok);
    }
    bdf->pixelsize = pixelsize;
    bdf->ascent = ascent;
    bdf->descent = descent;
    if ( depth!=1 )
	BDFClut(bdf,(1<<(depth/2)));

    if ( sf->bitmaps==NULL )
	sf->bitmaps = bdf;
    else {
	for ( prev=sf->bitmaps; prev->next!=NULL; prev=prev->next );
	prev->next = bdf;
    }
    bdf->sf = sf;
    bdf->glyphcnt = bdf->glyphmax = sf->glyphcnt;
    bdf->glyphs = calloc(bdf->glyphcnt,sizeof(BDFChar *));

    while ( getname(sfd,tok)==1 ) {
	if ( strcmp(tok,"BDFStartProperties:")==0 )
	    SFDGetBitmapProps(sfd,bdf,tok);
	else if ( strcmp(tok,"BDFEndProperties")==0 )
	    /* Do Nothing */;
	else if ( strcmp(tok,"Resolution:")==0 )
	    getint(sfd,&bdf->res);
	else if ( strcmp(tok,"BDFChar:")==0 )
	    SFDGetBitmapChar(sfd,bdf);
	else if ( strcmp(tok,"BDFRefChar:")==0 )
	    SFDGetBitmapReference(sfd,bdf);
	else if ( strcmp(tok,"EndBitmapFont")==0 )
    break;
    }
    if ( fromdir ) {
	DIR *dir;
	struct dirent *ent;
	char *name;

	dir = opendir(dirname);
	if ( dir==NULL )
return( 0 );
	name = malloc(strlen(dirname)+NAME_MAX+3);

	while ( (ent=readdir(dir))!=NULL ) {
	    char *pt = strrchr(ent->d_name,EXT_CHAR);
	    if ( pt==NULL )
		/* Nothing interesting */;
	    else if ( strcmp(pt,BITMAP_EXT)==0 ) {
		FILE *gsfd;
		sprintf(name,"%s/%s", dirname, ent->d_name);
		gsfd = fopen(name,"r");
		if ( gsfd!=NULL ) {
		    if ( getname(gsfd,tok) && strcmp(tok,"BDFChar:")==0)
			SFDGetBitmapChar(gsfd,bdf);
		    fclose(gsfd);
		    ff_progress_next();
		}
	    }
	}
	free(name);
	closedir(dir);
    }
    SFDFixupBitmapRefs( bdf );
return( 1 );
}

# define NAME_MAX _POSIX_NAME_MAX

int UndoRedoLimitToSave = 0;

int UndoRedoLimitToLoad = 0;

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

int prefRevisionsToRetain = 32;

int WritePNGInSFD = true;

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };

#define EXT_CHAR	'.'

#define BITMAP_EXT	".bitmap"


static struct pattern *SFDParsePattern(FILE *sfd,char *tok) {
    struct pattern *pat = chunkalloc(sizeof(struct pattern));
    int ch;

    getname(sfd,tok);
    pat->pattern = copy(tok);

    getreal(sfd,&pat->width);
    while ( isspace(ch=nlgetc(sfd)));
    if ( ch!=';' ) ungetc(ch,sfd);
    getreal(sfd,&pat->height);

    while ( isspace(ch=nlgetc(sfd)));
    if ( ch!='[' ) ungetc(ch,sfd);
    getreal(sfd,&pat->transform[0]);
    getreal(sfd,&pat->transform[1]);
    getreal(sfd,&pat->transform[2]);
    getreal(sfd,&pat->transform[3]);
    getreal(sfd,&pat->transform[4]);
    getreal(sfd,&pat->transform[5]);
    while ( isspace(ch=nlgetc(sfd)));
    if ( ch!=']' ) ungetc(ch,sfd);
return( pat );
}


static void SFDGetSpiros(FILE *sfd,SplineSet *cur) {
    int ch;
    spiro_cp cp;

    ch = nlgetc(sfd);		/* S */
    ch = nlgetc(sfd);		/* p */
    ch = nlgetc(sfd);		/* i */
    ch = nlgetc(sfd);		/* r */
    ch = nlgetc(sfd);		/* o */
    while ( fscanf(sfd,"%lg %lg %c", &cp.x, &cp.y, &cp.ty )==3 ) {
	if ( cur!=NULL ) {
	    if ( cur->spiro_cnt>=cur->spiro_max )
		cur->spiros = realloc(cur->spiros,
		                      (cur->spiro_max+=10)*sizeof(spiro_cp));
	    cur->spiros[cur->spiro_cnt++] = cp;
	}
    }
    if (    cur!=NULL && cur->spiro_cnt>0
         && (cur->spiros[cur->spiro_cnt-1].ty&0x7f)!=SPIRO_END ) {
	if ( cur->spiro_cnt>=cur->spiro_max )
	    cur->spiros = realloc(cur->spiros,
	                          (cur->spiro_max+=1)*sizeof(spiro_cp));
	memset(&cur->spiros[cur->spiro_cnt],0,sizeof(spiro_cp));
	cur->spiros[cur->spiro_cnt++].ty = SPIRO_END;
    }
    ch = nlgetc(sfd);
    if ( ch=='E' ) {
	ch = nlgetc(sfd);		/* n */
	ch = nlgetc(sfd);		/* d */
	ch = nlgetc(sfd);		/* S */
	ch = nlgetc(sfd);		/* p */
	ch = nlgetc(sfd);		/* i */
	ch = nlgetc(sfd);		/* r */
	ch = nlgetc(sfd);		/* o */
    } else
	ungetc(ch,sfd);
}


static void SFDDumpOtfFeatNames(FILE *sfd, SplineFont *sf) {
    struct otffeatname *fn;
    struct otfname *on;

    for ( fn=sf->feat_names; fn!=NULL; fn=fn->next ) {
	fprintf( sfd, "OtfFeatName: '%c%c%c%c' ",
		fn->tag>>24, fn->tag>>16, fn->tag>>8, fn->tag );
	for ( on=fn->names; on!=NULL; on=on->next ) {
	    fprintf( sfd, "%d ", on->lang );
	    SFDDumpUTF7Str(sfd, on->name);
	    if ( on->next!=NULL ) putc(' ',sfd);
	}
	putc('\n',sfd);
    }
}


static void SFDFpstClassNamesOut(FILE *sfd,int class_cnt,char **classnames,const char *keyword) {
    char buffer[20];
    int i;

    if ( class_cnt>0 && classnames!=NULL ) {
	fprintf( sfd, "  %s: ", keyword );
	for ( i=0; i<class_cnt; ++i ) {
	    if ( classnames[i]==NULL ) {
		sprintf( buffer,"%d", i );
		SFDDumpUTF7Str(sfd,buffer);
	    } else
		SFDDumpUTF7Str(sfd,classnames[i]);
	    if ( i<class_cnt-1 ) putc(' ',sfd);
	}
	putc('\n',sfd);
    }
}


int SFD_DumpSplineFontMetadata( FILE *sfd, SplineFont *sf )
{
    int i, j;
    struct ttflangname *ln;
    struct ttf_table *tab;
    KernClass *kc;
    FPST *fpst;
    ASM *sm;
    int isv;
    int err = false;
    int isgpos;
    OTLookup *otl;
    struct lookup_subtable *sub;
    FeatureScriptLangList *fl;
    struct scriptlanglist *sl;

    fprintf(sfd, "FontName: %s\n", sf->fontname );
    if ( sf->fullname!=NULL )
	fprintf(sfd, "FullName: %s\n", sf->fullname );
    if ( sf->familyname!=NULL )
	fprintf(sfd, "FamilyName: %s\n", sf->familyname );
    if ( sf->weight!=NULL )
	fprintf(sfd, "Weight: %s\n", sf->weight );
    if ( sf->copyright!=NULL )
	putstring(sfd, "Copyright: ", sf->copyright );
    if ( sf->comments!=NULL ) {
	fprintf( sfd, "UComments: " );
	SFDDumpUTF7Str(sfd,sf->comments);
	putc('\n',sfd);
    }
    if ( sf->fontlog!=NULL ) {
	fprintf( sfd, "FontLog: " );
	SFDDumpUTF7Str(sfd,sf->fontlog);
	putc('\n',sfd);
    }

    if ( sf->version!=NULL )
	fprintf(sfd, "Version: %s\n", sf->version );
    if ( sf->styleMapFamilyName!=NULL )
	fprintf(sfd, "StyleMapFamilyName: %s\n", sf->styleMapFamilyName );
    if ( sf->fondname!=NULL )
	fprintf(sfd, "FONDName: %s\n", sf->fondname );
    if ( sf->defbasefilename!=NULL )
	fprintf(sfd, "DefaultBaseFilename: %s\n", sf->defbasefilename );
    if ( sf->strokewidth!=0 )
	fprintf(sfd, "StrokeWidth: %g\n", (double) sf->strokewidth );
    fprintf(sfd, "ItalicAngle: %g\n", (double) sf->italicangle );
    fprintf(sfd, "UnderlinePosition: %g\n", (double) sf->upos );
    fprintf(sfd, "UnderlineWidth: %g\n", (double) sf->uwidth );
    fprintf(sfd, "Ascent: %d\n", sf->ascent );
    fprintf(sfd, "Descent: %d\n", sf->descent );
    fprintf(sfd, "InvalidEm: %d\n", sf->invalidem );
    if ( sf->sfntRevision!=sfntRevisionUnset )
	fprintf(sfd, "sfntRevision: 0x%08x\n", sf->sfntRevision );
    if ( sf->woffMajor!=woffUnset ) {
	fprintf(sfd, "woffMajor: %d\n", sf->woffMajor );
	fprintf(sfd, "woffMinor: %d\n", sf->woffMinor );
    }
    if ( sf->woffMetadata!=NULL ) {
	fprintf( sfd, "woffMetadata: " );
	SFDDumpUTF7Str(sfd,sf->woffMetadata);
	putc('\n',sfd);
    }
    if ( sf->ufo_ascent!=0 )
	fprintf(sfd, "UFOAscent: %g\n", (double) sf->ufo_ascent );
    if ( sf->ufo_descent!=0 )
	fprintf(sfd, "UFODescent: %g\n", (double) sf->ufo_descent );
    fprintf(sfd, "LayerCount: %d\n", sf->layer_cnt );
    for ( i=0; i<sf->layer_cnt; ++i ) {
	fprintf( sfd, "Layer: %d %d ", i, sf->layers[i].order2/*, sf->layers[i].background*/ );
	SFDDumpUTF7Str(sfd,sf->layers[i].name);
	fprintf( sfd, " %d", sf->layers[i].background );
	if (sf->layers[i].ufo_path != NULL) { putc(' ',sfd); SFDDumpUTF7Str(sfd,sf->layers[i].ufo_path); }
	putc('\n',sfd);
    }
    // TODO: Output U. F. O. layer path.
    if (sf->preferred_kerning != 0) fprintf(sfd, "PreferredKerning: %d\n", sf->preferred_kerning);
    if ( sf->strokedfont )
	fprintf(sfd, "StrokedFont: %d\n", sf->strokedfont );
    else if ( sf->multilayer )
	fprintf(sfd, "MultiLayer: %d\n", sf->multilayer );
    if ( sf->hasvmetrics )
	fprintf(sfd, "HasVMetrics: %d\n", sf->hasvmetrics );
    if ( sf->use_xuid && sf->changed_since_xuidchanged )
	fprintf(sfd, "NeedsXUIDChange: 1\n" );
    if ( sf->xuid!=NULL )
	fprintf(sfd, "XUID: %s\n", sf->xuid );
    if ( sf->uniqueid!=0 )
	fprintf(sfd, "UniqueID: %d\n", sf->uniqueid );
    if ( sf->use_xuid )
	fprintf(sfd, "UseXUID: 1\n" );
    if ( sf->use_uniqueid )
	fprintf(sfd, "UseUniqueID: 1\n" );
    if ( sf->horiz_base!=NULL )
	SFDDumpBase(sfd,"BaseHoriz:",sf->horiz_base);
    if ( sf->vert_base!=NULL )
	SFDDumpBase(sfd,"BaseVert:",sf->vert_base);
    if ( sf->pfminfo.stylemap!=-1 )
	fprintf(sfd, "StyleMap: 0x%04x\n", sf->pfminfo.stylemap );
    if ( sf->pfminfo.fstype!=-1 )
	fprintf(sfd, "FSType: %d\n", sf->pfminfo.fstype );
    fprintf(sfd, "OS2Version: %d\n", sf->os2_version );
    fprintf(sfd, "OS2_WeightWidthSlopeOnly: %d\n", sf->weight_width_slope_only );
    fprintf(sfd, "OS2_UseTypoMetrics: %d\n", sf->use_typo_metrics );
    fprintf(sfd, "CreationTime: %lld\n", sf->creationtime );
    fprintf(sfd, "ModificationTime: %lld\n", sf->modificationtime );
    if ( sf->pfminfo.pfmset ) {
	fprintf(sfd, "PfmFamily: %d\n", sf->pfminfo.pfmfamily );
	fprintf(sfd, "TTFWeight: %d\n", sf->pfminfo.weight );
	fprintf(sfd, "TTFWidth: %d\n", sf->pfminfo.width );
	fprintf(sfd, "LineGap: %d\n", sf->pfminfo.linegap );
	fprintf(sfd, "VLineGap: %d\n", sf->pfminfo.vlinegap );
	/*putc('\n',sfd);*/
    }
    if ( sf->pfminfo.panose_set ) {
	fprintf(sfd, "Panose:" );
	for ( i=0; i<10; ++i )
	    fprintf( sfd, " %d", sf->pfminfo.panose[i]);
	putc('\n',sfd);
    }
    fprintf(sfd, "OS2TypoAscent: %d\n", sf->pfminfo.os2_typoascent );
    fprintf(sfd, "OS2TypoAOffset: %d\n", sf->pfminfo.typoascent_add );
    fprintf(sfd, "OS2TypoDescent: %d\n", sf->pfminfo.os2_typodescent );
    fprintf(sfd, "OS2TypoDOffset: %d\n", sf->pfminfo.typodescent_add );
    fprintf(sfd, "OS2TypoLinegap: %d\n", sf->pfminfo.os2_typolinegap );
    fprintf(sfd, "OS2WinAscent: %d\n", sf->pfminfo.os2_winascent );
    fprintf(sfd, "OS2WinAOffset: %d\n", sf->pfminfo.winascent_add );
    fprintf(sfd, "OS2WinDescent: %d\n", sf->pfminfo.os2_windescent );
    fprintf(sfd, "OS2WinDOffset: %d\n", sf->pfminfo.windescent_add );
    fprintf(sfd, "HheadAscent: %d\n", sf->pfminfo.hhead_ascent );
    fprintf(sfd, "HheadAOffset: %d\n", sf->pfminfo.hheadascent_add );
    fprintf(sfd, "HheadDescent: %d\n", sf->pfminfo.hhead_descent );
    fprintf(sfd, "HheadDOffset: %d\n", sf->pfminfo.hheaddescent_add );
    if ( sf->pfminfo.subsuper_set ) {
	fprintf(sfd, "OS2SubXSize: %d\n", sf->pfminfo.os2_subxsize );
	fprintf(sfd, "OS2SubYSize: %d\n", sf->pfminfo.os2_subysize );
	fprintf(sfd, "OS2SubXOff: %d\n", sf->pfminfo.os2_subxoff );
	fprintf(sfd, "OS2SubYOff: %d\n", sf->pfminfo.os2_subyoff );
	fprintf(sfd, "OS2SupXSize: %d\n", sf->pfminfo.os2_supxsize );
	fprintf(sfd, "OS2SupYSize: %d\n", sf->pfminfo.os2_supysize );
	fprintf(sfd, "OS2SupXOff: %d\n", sf->pfminfo.os2_supxoff );
	fprintf(sfd, "OS2SupYOff: %d\n", sf->pfminfo.os2_supyoff );
	fprintf(sfd, "OS2StrikeYSize: %d\n", sf->pfminfo.os2_strikeysize );
	fprintf(sfd, "OS2StrikeYPos: %d\n", sf->pfminfo.os2_strikeypos );
    }
    if ( sf->pfminfo.os2_capheight!=0 )
    fprintf(sfd, "OS2CapHeight: %d\n", sf->pfminfo.os2_capheight );
    if ( sf->pfminfo.os2_xheight!=0 )
    fprintf(sfd, "OS2XHeight: %d\n", sf->pfminfo.os2_xheight );
    if ( sf->pfminfo.os2_family_class!=0 )
	fprintf(sfd, "OS2FamilyClass: %d\n", sf->pfminfo.os2_family_class );
    if ( sf->pfminfo.os2_vendor[0]!='\0' ) {
	fprintf(sfd, "OS2Vendor: '%c%c%c%c'\n",
		sf->pfminfo.os2_vendor[0], sf->pfminfo.os2_vendor[1],
		sf->pfminfo.os2_vendor[2], sf->pfminfo.os2_vendor[3] );
    }
    if ( sf->pfminfo.hascodepages )
	fprintf(sfd, "OS2CodePages: %08x.%08x\n", sf->pfminfo.codepages[0], sf->pfminfo.codepages[1]);
    if ( sf->pfminfo.hasunicoderanges )
	fprintf(sfd, "OS2UnicodeRanges: %08x.%08x.%08x.%08x\n",
		sf->pfminfo.unicoderanges[0], sf->pfminfo.unicoderanges[1],
		sf->pfminfo.unicoderanges[2], sf->pfminfo.unicoderanges[3] );
    if ( sf->macstyle!=-1 )
	fprintf(sfd, "MacStyle: %d\n", sf->macstyle );
    /* Must come before any kerning classes, anchor classes, conditional psts */
    /* state machines, psts, kerning pairs, etc. */
    for ( isgpos=0; isgpos<2; ++isgpos ) {
	for ( otl = isgpos ? sf->gpos_lookups : sf->gsub_lookups; otl!=NULL; otl = otl->next ) {
	    fprintf( sfd, "Lookup: %d %d %d ", otl->lookup_type, otl->lookup_flags, otl->store_in_afm );
	    SFDDumpUTF7Str(sfd,otl->lookup_name);
	    fprintf( sfd, " { " );
	    for ( sub=otl->subtables; sub!=NULL; sub=sub->next ) {
		SFDDumpUTF7Str(sfd,sub->subtable_name);
		putc(' ',sfd);
		if ( otl->lookup_type==gsub_single && sub->suffix!=NULL ) {
		    putc('(',sfd);
		    SFDDumpUTF7Str(sfd,sub->suffix);
		    putc(')',sfd);
		} else if ( otl->lookup_type==gpos_pair && sub->vertical_kerning )
		    fprintf(sfd,"(1)");
		if ( otl->lookup_type==gpos_pair && (sub->separation!=0 || sub->kerning_by_touch))
		    fprintf(sfd,"[%d,%d,%d]", sub->separation, sub->minkern, sub->kerning_by_touch+2*sub->onlyCloser+4*sub->dontautokern );
		putc(' ',sfd);
	    }
	    fprintf( sfd, "} [" );
	    for ( fl=otl->features; fl!=NULL; fl=fl->next ) {
		if ( fl->ismac )
		    fprintf( sfd, "<%d,%d> (",
			    (int) (fl->featuretag>>16),
			    (int) (fl->featuretag&0xffff));
		else
		    fprintf( sfd, "'%c%c%c%c' (",
			    (int) (fl->featuretag>>24), (int) ((fl->featuretag>>16)&0xff),
			    (int) ((fl->featuretag>>8)&0xff), (int) (fl->featuretag&0xff) );
		for ( sl= fl->scripts; sl!=NULL; sl = sl->next ) {
		    fprintf( sfd, "'%c%c%c%c' <",
			    (int) (sl->script>>24), (int) ((sl->script>>16)&0xff),
			    (int) ((sl->script>>8)&0xff), (int) (sl->script&0xff) );
		    for ( i=0; i<sl->lang_cnt; ++i ) {
			uint32 lang = i<MAX_LANG ? sl->langs[i] : sl->morelangs[i-MAX_LANG];
			fprintf( sfd, "'%c%c%c%c' ",
				(int) (lang>>24), (int) ((lang>>16)&0xff),
				(int) ((lang>>8)&0xff), (int) (lang&0xff) );
		    }
		    fprintf( sfd, "> " );
		}
		fprintf( sfd, ") " );
	    }
	    fprintf( sfd, "]\n" );
	}
    }

    if ( sf->mark_class_cnt!=0 ) {
	fprintf( sfd, "MarkAttachClasses: %d\n", sf->mark_class_cnt );
	for ( i=1; i<sf->mark_class_cnt; ++i ) {	/* Class 0 is unused */
	    SFDDumpUTF7Str(sfd, sf->mark_class_names[i]);
	    putc(' ',sfd);
	    if ( sf->mark_classes[i]!=NULL )
		fprintf( sfd, "%d %s\n", (int) strlen(sf->mark_classes[i]),
			sf->mark_classes[i] );
	    else
		fprintf( sfd, "0 \n" );
	}
    }
    if ( sf->mark_set_cnt!=0 ) {
	fprintf( sfd, "MarkAttachSets: %d\n", sf->mark_set_cnt );
	for ( i=0; i<sf->mark_set_cnt; ++i ) {	/* Set 0 is used */
	    SFDDumpUTF7Str(sfd, sf->mark_set_names[i]);
	    putc(' ',sfd);
	    if ( sf->mark_sets[i]!=NULL )
		fprintf( sfd, "%d %s\n", (int) strlen(sf->mark_sets[i]),
			sf->mark_sets[i] );
	    else
		fprintf( sfd, "0 \n" );
	}
    }

    fprintf( sfd, "DEI: 91125\n" );
    for ( isv=0; isv<2; ++isv ) {
	for ( kc=isv ? sf->vkerns : sf->kerns; kc!=NULL; kc = kc->next ) {
	  if (kc->firsts_names == NULL && kc->seconds_names == NULL && kc->firsts_flags == NULL && kc->seconds_flags == NULL) {
	    fprintf( sfd, "%s: %d%s %d ", isv ? "VKernClass2" : "KernClass2",
		    kc->first_cnt, kc->firsts[0]!=NULL?"+":"",
		    kc->second_cnt );
	    SFDDumpUTF7Str(sfd,kc->subtable->subtable_name);
	    putc('\n',sfd);
	    if ( kc->firsts[0]!=NULL )
	      fprintf( sfd, " %d %s\n", (int)strlen(kc->firsts[0]),
		       kc->firsts[0]);
	    for ( i=1; i<kc->first_cnt; ++i )
	      fprintf( sfd, " %d %s\n", (int)strlen(kc->firsts[i]),
		       kc->firsts[i]);
	    for ( i=1; i<kc->second_cnt; ++i )
	      fprintf( sfd, " %d %s\n", (int)strlen(kc->seconds[i]),
		       kc->seconds[i]);
	    for ( i=0; i<kc->first_cnt*kc->second_cnt; ++i ) {
		fprintf( sfd, " %d", kc->offsets[i]);
		putc(' ',sfd);
		SFDDumpDeviceTable(sfd,&kc->adjusts[i]);
	    }
	    fprintf( sfd, "\n" );
	  } else {
	    fprintf( sfd, "%s: %d%s %d ", isv ? "VKernClass3" : "KernClass3",
		    kc->first_cnt, kc->firsts[0]!=NULL?"+":"",
		    kc->second_cnt );
	    SFDDumpUTF7Str(sfd,kc->subtable->subtable_name);
	    putc('\n',sfd);
	    if ( kc->firsts[0]!=NULL ) {
	      fprintf( sfd, " %d ", ((kc->firsts_flags && kc->firsts_flags[0]) ? kc->firsts_flags[0] : 0));
	      SFDDumpUTF7Str(sfd, ((kc->firsts_names && kc->firsts_names[0]) ? kc->firsts_names[0] : ""));
	      fprintf( sfd, " " );
	      SFDDumpUTF7Str(sfd,kc->firsts[0]);
	      fprintf( sfd, "\n" );
	    }
	    for ( i=1; i<kc->first_cnt; ++i ) {
	      fprintf( sfd, " %d ", ((kc->firsts_flags && kc->firsts_flags[i]) ? kc->firsts_flags[i] : 0));
	      SFDDumpUTF7Str(sfd, ((kc->firsts_names && kc->firsts_names[i]) ? kc->firsts_names[i] : ""));
	      fprintf( sfd, " " );
	      SFDDumpUTF7Str(sfd,kc->firsts[i]);
	      fprintf( sfd, "\n" );
	    }
	    for ( i=1; i<kc->second_cnt; ++i ) {
	      fprintf( sfd, " %d ", ((kc->seconds_flags && kc->seconds_flags[i]) ? kc->seconds_flags[i] : 0));
	      SFDDumpUTF7Str(sfd, ((kc->seconds_names && kc->seconds_names[i]) ? kc->seconds_names[i] : ""));
	      fprintf( sfd, " " );
	      SFDDumpUTF7Str(sfd,kc->seconds[i]);
	      fprintf( sfd, "\n" );
	    }
	    for ( i=0; i<kc->first_cnt*kc->second_cnt; ++i ) {
		fprintf( sfd, " %d %d", ((kc->offsets_flags && kc->offsets_flags[i]) ? kc->offsets_flags[i] : 0), kc->offsets[i]);
		putc(' ',sfd);
		SFDDumpDeviceTable(sfd,&kc->adjusts[i]);
	    }
	    fprintf( sfd, "\n" );
	  }
	}
    }
    for ( fpst=sf->possub; fpst!=NULL; fpst=fpst->next ) {
	static const char *keywords[] = { "ContextPos2:", "ContextSub2:", "ChainPos2:", "ChainSub2:", "ReverseChain2:", NULL };
	static const char *formatkeys[] = { "glyph", "class", "coverage", "revcov", NULL };
	fprintf( sfd, "%s %s ", keywords[fpst->type-pst_contextpos],
		formatkeys[fpst->format] );
	SFDDumpUTF7Str(sfd,fpst->subtable->subtable_name);
	fprintf( sfd, " %d %d %d %d\n",
		fpst->nccnt, fpst->bccnt, fpst->fccnt, fpst->rule_cnt );
	if ( fpst->nccnt>0 && fpst->nclass[0]!=NULL )
	  fprintf( sfd, "  Class0: %d %s\n", (int)strlen(fpst->nclass[0]),
		   fpst->nclass[0]);
	for ( i=1; i<fpst->nccnt; ++i )
	  fprintf( sfd, "  Class: %d %s\n", (int)strlen(fpst->nclass[i]),
		   fpst->nclass[i]);
	for ( i=1; i<fpst->bccnt; ++i )
	  fprintf( sfd, "  BClass: %d %s\n", (int)strlen(fpst->bclass[i]),
		   fpst->bclass[i]);
	for ( i=1; i<fpst->fccnt; ++i )
	  fprintf( sfd, "  FClass: %d %s\n", (int)strlen(fpst->fclass[i]),
		   fpst->fclass[i]);
	for ( i=0; i<fpst->rule_cnt; ++i ) {
	    switch ( fpst->format ) {
	      case pst_glyphs:
		fprintf( sfd, " String: %d %s\n",
			 (int)strlen(fpst->rules[i].u.glyph.names),
			 fpst->rules[i].u.glyph.names);
		if ( fpst->rules[i].u.glyph.back!=NULL )
		  fprintf( sfd, " BString: %d %s\n",
			   (int)strlen(fpst->rules[i].u.glyph.back),
			   fpst->rules[i].u.glyph.back);
		else
		    fprintf( sfd, " BString: 0\n");
		if ( fpst->rules[i].u.glyph.fore!=NULL )
		  fprintf( sfd, " FString: %d %s\n",
			   (int)strlen(fpst->rules[i].u.glyph.fore),
			   fpst->rules[i].u.glyph.fore);
		else
		    fprintf( sfd, " FString: 0\n");
	      break;
	      case pst_class:
		fprintf( sfd, " %d %d %d\n  ClsList:", fpst->rules[i].u.class.ncnt, fpst->rules[i].u.class.bcnt, fpst->rules[i].u.class.fcnt );
		for ( j=0; j<fpst->rules[i].u.class.ncnt; ++j )
		    fprintf( sfd, " %d", fpst->rules[i].u.class.nclasses[j]);
		fprintf( sfd, "\n  BClsList:" );
		for ( j=0; j<fpst->rules[i].u.class.bcnt; ++j )
		    fprintf( sfd, " %d", fpst->rules[i].u.class.bclasses[j]);
		fprintf( sfd, "\n  FClsList:" );
		for ( j=0; j<fpst->rules[i].u.class.fcnt; ++j )
		    fprintf( sfd, " %d", fpst->rules[i].u.class.fclasses[j]);
		fprintf( sfd, "\n" );
	      break;
	      case pst_coverage:
	      case pst_reversecoverage:
		fprintf( sfd, " %d %d %d\n", fpst->rules[i].u.coverage.ncnt, fpst->rules[i].u.coverage.bcnt, fpst->rules[i].u.coverage.fcnt );
		for ( j=0; j<fpst->rules[i].u.coverage.ncnt; ++j )
		  fprintf( sfd, "  Coverage: %d %s\n",
			   (int)strlen(fpst->rules[i].u.coverage.ncovers[j]),
			   fpst->rules[i].u.coverage.ncovers[j]);
		for ( j=0; j<fpst->rules[i].u.coverage.bcnt; ++j )
		  fprintf( sfd, "  BCoverage: %d %s\n",
			   (int)strlen(fpst->rules[i].u.coverage.bcovers[j]),
			   fpst->rules[i].u.coverage.bcovers[j]);
		for ( j=0; j<fpst->rules[i].u.coverage.fcnt; ++j )
		  fprintf( sfd, "  FCoverage: %d %s\n",
			   (int)strlen(fpst->rules[i].u.coverage.fcovers[j]),
			   fpst->rules[i].u.coverage.fcovers[j]);
	      break;
	      default:
	      break;
	    }
	    switch ( fpst->format ) {
	      case pst_glyphs:
	      case pst_class:
	      case pst_coverage:
		fprintf( sfd, " %d\n", fpst->rules[i].lookup_cnt );
		for ( j=0; j<fpst->rules[i].lookup_cnt; ++j ) {
		    fprintf( sfd, "  SeqLookup: %d ",
			    fpst->rules[i].lookups[j].seq );
		    SFDDumpUTF7Str(sfd,fpst->rules[i].lookups[j].lookup->lookup_name);
		    putc('\n',sfd);
		}
	      break;
	      case pst_reversecoverage:
		fprintf( sfd, "  Replace: %d %s\n",
			 (int)strlen(fpst->rules[i].u.rcoverage.replacements),
			 fpst->rules[i].u.rcoverage.replacements);
	      break;
	      default:
	      break;
	    }
	}
	/* It would make more sense to output these up near the classes */
	/*  but that would break backwards compatibility (old parsers will */
	/*  ignore these entries if they are at the end, new parsers will */
	/*  read them */
	SFDFpstClassNamesOut(sfd,fpst->nccnt,fpst->nclassnames,"ClassNames");
	SFDFpstClassNamesOut(sfd,fpst->bccnt,fpst->bclassnames,"BClassNames");
	SFDFpstClassNamesOut(sfd,fpst->fccnt,fpst->fclassnames,"FClassNames");
	fprintf( sfd, "EndFPST\n" );
    }
    struct ff_glyphclasses *grouptmp;
    for ( grouptmp = sf->groups; grouptmp != NULL; grouptmp = grouptmp->next ) {
      fprintf(sfd, "Group: ");
      SFDDumpUTF7Str(sfd, grouptmp->classname); fprintf(sfd, " ");
      SFDDumpUTF7Str(sfd, grouptmp->glyphs); fprintf(sfd, "\n");
    }
    struct ff_rawoffsets *groupkerntmp;
    for ( groupkerntmp = sf->groupkerns; groupkerntmp != NULL; groupkerntmp = groupkerntmp->next ) {
      fprintf(sfd, "GroupKern: ");
      SFDDumpUTF7Str(sfd, groupkerntmp->left); fprintf(sfd, " ");
      SFDDumpUTF7Str(sfd, groupkerntmp->right); fprintf(sfd, " ");
      fprintf(sfd, "%d\n", groupkerntmp->offset);
    }
    for ( groupkerntmp = sf->groupvkerns; groupkerntmp != NULL; groupkerntmp = groupkerntmp->next ) {
      fprintf(sfd, "GroupVKern: ");
      SFDDumpUTF7Str(sfd, groupkerntmp->left); fprintf(sfd, " ");
      SFDDumpUTF7Str(sfd, groupkerntmp->right); fprintf(sfd, " ");
      fprintf(sfd, "%d\n", groupkerntmp->offset);
    }
    for ( sm=sf->sm; sm!=NULL; sm=sm->next ) {
	static const char *keywords[] = { "MacIndic2:", "MacContext2:", "MacLigature2:", "unused", "MacSimple2:", "MacInsert2:",
	    "unused", "unused", "unused", "unused", "unused", "unused",
	    "unused", "unused", "unused", "unused", "unused", "MacKern2:",
	    NULL };
	fprintf( sfd, "%s ", keywords[sm->type-asm_indic] );
	SFDDumpUTF7Str(sfd,sm->subtable->subtable_name);
	fprintf( sfd, " %d %d %d\n", sm->flags, sm->class_cnt, sm->state_cnt );
	for ( i=4; i<sm->class_cnt; ++i )
	  fprintf( sfd, "  Class: %d %s\n", (int)strlen(sm->classes[i]),
		   sm->classes[i]);
	for ( i=0; i<sm->class_cnt*sm->state_cnt; ++i ) {
	    fprintf( sfd, " %d %d ", sm->state[i].next_state, sm->state[i].flags );
	    if ( sm->type==asm_context ) {
		if ( sm->state[i].u.context.mark_lookup==NULL )
		    putc('~',sfd);
		else
		    SFDDumpUTF7Str(sfd,sm->state[i].u.context.mark_lookup->lookup_name);
		putc(' ',sfd);
		if ( sm->state[i].u.context.cur_lookup==0 )
		    putc('~',sfd);
		else
		    SFDDumpUTF7Str(sfd,sm->state[i].u.context.cur_lookup->lookup_name);
		putc(' ',sfd);
	    } else if ( sm->type == asm_insert ) {
		if ( sm->state[i].u.insert.mark_ins==NULL )
		    fprintf( sfd, "0 ");
		else
		  fprintf( sfd, "%d %s ",
			   (int)strlen(sm->state[i].u.insert.mark_ins),
			   sm->state[i].u.insert.mark_ins );
		if ( sm->state[i].u.insert.cur_ins==NULL )
		    fprintf( sfd, "0 ");
		else
		  fprintf( sfd, "%d %s ",
			   (int)strlen(sm->state[i].u.insert.cur_ins),
			   sm->state[i].u.insert.cur_ins );
	    } else if ( sm->type == asm_kern ) {
		fprintf( sfd, "%d ", sm->state[i].u.kern.kcnt );
		for ( j=0; j<sm->state[i].u.kern.kcnt; ++j )
		    fprintf( sfd, "%d ", sm->state[i].u.kern.kerns[j]);
	    }
	    putc('\n',sfd);
	}
	fprintf( sfd, "EndASM\n" );
    }
    SFDDumpMacFeat(sfd,sf->features);
    SFDDumpJustify(sfd,sf);
    for ( tab = sf->ttf_tables; tab!=NULL ; tab = tab->next )
	SFDDumpTtfTable(sfd,tab,sf);
    for ( tab = sf->ttf_tab_saved; tab!=NULL ; tab = tab->next )
	SFDDumpTtfTable(sfd,tab,sf);
    for ( ln = sf->names; ln!=NULL; ln=ln->next )
	SFDDumpLangName(sfd,ln);
    if ( sf->gasp_cnt!=0 )
	SFDDumpGasp(sfd,sf);
    if ( sf->design_size!=0 )
	SFDDumpDesignSize(sfd,sf);
    if ( sf->feat_names!=NULL )
	SFDDumpOtfFeatNames(sfd,sf);

return( err );
}

int UndoRedoLimitToSave = 0;

int UndoRedoLimitToLoad = 0;

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

int prefRevisionsToRetain = 32;

int WritePNGInSFD = true;

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };

#define GLYPH_EXT	".glyph"


static void SFDDumpGasp(FILE *sfd, SplineFont *sf) {
    int i;

    if ( sf->gasp_cnt==0 )
return;

    fprintf( sfd, "GaspTable: %d", sf->gasp_cnt );
    for ( i=0; i<sf->gasp_cnt; ++i )
	fprintf( sfd, " %d %d", sf->gasp[i].ppem, sf->gasp[i].flags );
    fprintf( sfd, " %d", sf->gasp_version);
    putc('\n',sfd);
}


static void SFDParseVertexKern(FILE *sfd, struct mathkernvertex *vertex) {
    int i,ch;

    getint(sfd,&vertex->cnt);
    vertex->mkd = calloc(vertex->cnt,sizeof(struct mathkerndata));
    for ( i=0; i<vertex->cnt; ++i ) {
	SFDParseMathValueRecord(sfd,&vertex->mkd[i].height,&vertex->mkd[i].height_adjusts);
	while ( (ch=nlgetc(sfd))==' ' );
	if ( ch!=EOF && ch!=',' )
	    ungetc(ch,sfd);
	SFDParseMathValueRecord(sfd,&vertex->mkd[i].kern,&vertex->mkd[i].kern_adjusts);
    }
}


static void SFDParseChainContext(FILE *sfd,SplineFont *sf,FPST *fpst, char *tok, int old) {
    int ch, i, j, k, temp;
    SplineFont *sli_sf = sf->cidmaster ? sf->cidmaster : sf;

    fpst->type = strnmatch(tok,"ContextPos",10)==0 ? pst_contextpos :
		strnmatch(tok,"ContextSub",10)==0 ? pst_contextsub :
		strnmatch(tok,"ChainPos",8)==0 ? pst_chainpos :
		strnmatch(tok,"ChainSub",8)==0 ? pst_chainsub : pst_reversesub;
    getname(sfd,tok);
    fpst->format = strmatch(tok,"glyph")==0 ? pst_glyphs :
		    strmatch(tok,"class")==0 ? pst_class :
		    strmatch(tok,"coverage")==0 ? pst_coverage : pst_reversecoverage;
    if ( old ) {
	fscanf(sfd, "%hu %hu", &((FPST1 *) fpst)->flags, &((FPST1 *) fpst)->script_lang_index );
	if ( ((FPST1 *) fpst)->script_lang_index>=((SplineFont1 *) sli_sf)->sli_cnt && ((FPST1 *) fpst)->script_lang_index!=SLI_NESTED ) {
	    static int complained=false;
	    if ( ((SplineFont1 *) sli_sf)->sli_cnt==0 )
		IError("'%c%c%c%c' has a script index out of bounds: %d\nYou MUST fix this manually",
			(((FPST1 *) fpst)->tag>>24), (((FPST1 *) fpst)->tag>>16)&0xff, (((FPST1 *) fpst)->tag>>8)&0xff, ((FPST1 *) fpst)->tag&0xff,
			((FPST1 *) fpst)->script_lang_index );
	    else if ( !complained )
		IError("'%c%c%c%c' has a script index out of bounds: %d",
			(((FPST1 *) fpst)->tag>>24), (((FPST1 *) fpst)->tag>>16)&0xff, (((FPST1 *) fpst)->tag>>8)&0xff, ((FPST1 *) fpst)->tag&0xff,
			((FPST1 *) fpst)->script_lang_index );
	    else
		IError("'%c%c%c%c' has a script index out of bounds: %d\n",
			(((FPST1 *) fpst)->tag>>24), (((FPST1 *) fpst)->tag>>16)&0xff, (((FPST1 *) fpst)->tag>>8)&0xff, ((FPST1 *) fpst)->tag&0xff,
			((FPST1 *) fpst)->script_lang_index );
	    if ( ((SplineFont1 *) sli_sf)->sli_cnt!=0 )
		((FPST1 *) fpst)->script_lang_index = ((SplineFont1 *) sli_sf)->sli_cnt-1;
	    complained = true;
	}
	while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
	if ( ch=='\'' ) {
	    ungetc(ch,sfd);
	    ((FPST1 *) fpst)->tag = gettag(sfd);
	} else
	    ungetc(ch,sfd);
    } else {
	fpst->subtable = SFFindLookupSubtableAndFreeName(sf,SFDReadUTF7Str(sfd));
        if ( !fpst->subtable )
            LogError(_("Missing Subtable definition found in chained context"));
        else
	    fpst->subtable->fpst = fpst;
    }
    fscanf(sfd, "%hu %hu %hu %hu", &fpst->nccnt, &fpst->bccnt, &fpst->fccnt, &fpst->rule_cnt );
    if ( fpst->nccnt!=0 || fpst->bccnt!=0 || fpst->fccnt!=0 ) {
	fpst->nclass = malloc(fpst->nccnt*sizeof(char *));
	fpst->nclassnames = calloc(fpst->nccnt,sizeof(char *));
	if ( fpst->nccnt!=0 ) fpst->nclass[0] = NULL;
	if ( fpst->bccnt!=0 || fpst->fccnt!=0 ) {
	    fpst->bclass = malloc(fpst->bccnt*sizeof(char *));
	    fpst->bclassnames = calloc(fpst->bccnt,sizeof(char *));
	    if (fpst->bccnt!=0 ) fpst->bclass[0] = NULL;
	    fpst->fclass = malloc(fpst->fccnt*sizeof(char *));
	    fpst->fclassnames = calloc(fpst->fccnt,sizeof(char *));
	    if (fpst->fccnt!=0 ) fpst->fclass[0] = NULL;
	}
    }

    for ( j=0; j<3; ++j ) {
	for ( i=1; i<(&fpst->nccnt)[j]; ++i ) {
	    getname(sfd,tok);
	    if ( i==1 && j==0 && strcmp(tok,"Class0:")==0 )
		i=0;
	    getint(sfd,&temp);
	    (&fpst->nclass)[j][i] = malloc(temp+1); (&fpst->nclass)[j][i][temp] = '\0';
	    nlgetc(sfd);	/* skip space */
	    fread((&fpst->nclass)[j][i],1,temp,sfd);
	}
    }

    fpst->rules = calloc(fpst->rule_cnt,sizeof(struct fpst_rule));
    for ( i=0; i<fpst->rule_cnt; ++i ) {
	switch ( fpst->format ) {
	  case pst_glyphs:
	    for ( j=0; j<3; ++j ) {
		getname(sfd,tok);
		getint(sfd,&temp);
		(&fpst->rules[i].u.glyph.names)[j] = malloc(temp+1);
		(&fpst->rules[i].u.glyph.names)[j][temp] = '\0';
		nlgetc(sfd);	/* skip space */
		fread((&fpst->rules[i].u.glyph.names)[j],1,temp,sfd);
	    }
	  break;
	  case pst_class:
	    fscanf( sfd, "%d %d %d", &fpst->rules[i].u.class.ncnt, &fpst->rules[i].u.class.bcnt, &fpst->rules[i].u.class.fcnt );
	    for ( j=0; j<3; ++j ) {
		getname(sfd,tok);
		(&fpst->rules[i].u.class.nclasses)[j] = malloc((&fpst->rules[i].u.class.ncnt)[j]*sizeof(uint16));
		for ( k=0; k<(&fpst->rules[i].u.class.ncnt)[j]; ++k ) {
		    getusint(sfd,&(&fpst->rules[i].u.class.nclasses)[j][k]);
		}
	    }
	  break;
	  case pst_coverage:
	  case pst_reversecoverage:
	    fscanf( sfd, "%d %d %d", &fpst->rules[i].u.coverage.ncnt, &fpst->rules[i].u.coverage.bcnt, &fpst->rules[i].u.coverage.fcnt );
	    for ( j=0; j<3; ++j ) {
		(&fpst->rules[i].u.coverage.ncovers)[j] = malloc((&fpst->rules[i].u.coverage.ncnt)[j]*sizeof(char *));
		for ( k=0; k<(&fpst->rules[i].u.coverage.ncnt)[j]; ++k ) {
		    getname(sfd,tok);
		    getint(sfd,&temp);
		    (&fpst->rules[i].u.coverage.ncovers)[j][k] = malloc(temp+1);
		    (&fpst->rules[i].u.coverage.ncovers)[j][k][temp] = '\0';
		    nlgetc(sfd);	/* skip space */
		    fread((&fpst->rules[i].u.coverage.ncovers)[j][k],1,temp,sfd);
		}
	    }
	  break;
	  default:
	  break;
	}
	switch ( fpst->format ) {
	  case pst_glyphs:
	  case pst_class:
	  case pst_coverage:
	    getint(sfd,&fpst->rules[i].lookup_cnt);
	    fpst->rules[i].lookups = malloc(fpst->rules[i].lookup_cnt*sizeof(struct seqlookup));
	    for ( j=k=0; j<fpst->rules[i].lookup_cnt; ++j ) {
		getname(sfd,tok);
		getint(sfd,&fpst->rules[i].lookups[j].seq);
		fpst->rules[i].lookups[k].lookup = SFD_ParseNestedLookup(sfd,sf,old);
		if ( fpst->rules[i].lookups[k].lookup!=NULL )
		    ++k;
	    }
	    fpst->rules[i].lookup_cnt = k;
	  break;
	  case pst_reversecoverage:
	    getname(sfd,tok);
	    getint(sfd,&temp);
	    fpst->rules[i].u.rcoverage.replacements = malloc(temp+1);
	    fpst->rules[i].u.rcoverage.replacements[temp] = '\0';
	    nlgetc(sfd);	/* skip space */
	    fread(fpst->rules[i].u.rcoverage.replacements,1,temp,sfd);
	  break;
	  default:
	  break;
	}
    }
    getname(sfd,tok);	/* EndFPST, or one of the ClassName tokens (in newer sfds) */
    while ( strcmp(tok,"ClassNames:")==0 || strcmp(tok,"BClassNames:")==0 ||
	    strcmp(tok,"FClassNames:")==0 ) {
	int which = strcmp(tok,"ClassNames:")==0 ? 0 :
		    strcmp(tok,"BClassNames:")==0 ? 1 : 2;
	int cnt = (&fpst->nccnt)[which];
	char **classnames = (&fpst->nclassnames)[which];
	int i;

	for ( i=0; i<cnt; ++i )
	    classnames[i] = SFDReadUTF7Str(sfd);
	getname(sfd,tok);	/* EndFPST, or one of the ClassName tokens (in newer sfds) */
    }

}


static int SFD_Dump( FILE *sfd, SplineFont *sf, EncMap *map, EncMap *normal,
		     int todir, char *dirname)
{
    int i, realcnt;
    BDFFont *bdf;
    int *newgids = NULL;
    int err = false;

    if ( normal!=NULL )
	map = normal;

    SFD_DumpSplineFontMetadata( sfd, sf ); //, map, normal, todir, dirname );

    if ( sf->MATH!=NULL ) {
	struct MATH *math = sf->MATH;
	for ( i=0; math_constants_descriptor[i].script_name!=NULL; ++i ) {
	    fprintf( sfd, "MATH:%s: %d", math_constants_descriptor[i].script_name,
		    *((int16 *) (((char *) (math)) + math_constants_descriptor[i].offset)) );
	    if ( math_constants_descriptor[i].devtab_offset>=0 ) {
		DeviceTable **devtab = (DeviceTable **) (((char *) (math)) + math_constants_descriptor[i].devtab_offset );
		putc(' ',sfd);
		SFDDumpDeviceTable(sfd,*devtab);
	    }
	    putc('\n',sfd);
	}
    }
    if ( sf->python_persistent!=NULL )
	SFDPickleMe(sfd,sf->python_persistent, sf->python_persistent_has_lists);
    if ( sf->subfontcnt!=0 ) {
	/* CID fonts have no encodings, they have registry info instead */
	fprintf(sfd, "Registry: %s\n", sf->cidregistry );
	fprintf(sfd, "Ordering: %s\n", sf->ordering );
	fprintf(sfd, "Supplement: %d\n", sf->supplement );
	fprintf(sfd, "CIDVersion: %g\n", (double) sf->cidversion );	/* This is a number whereas "version" is a string */
    } else
	SFDDumpEncoding(sfd,map->enc,"Encoding");
    if ( normal!=NULL )
	fprintf(sfd, "Compacted: 1\n" );
    fprintf( sfd, "UnicodeInterp: %s\n", unicode_interp_names[sf->uni_interp]);
    fprintf( sfd, "NameList: %s\n", sf->for_new_glyphs->title );

    if ( map->remap!=NULL ) {
	struct remap *remap;
	int n;
	for ( n=0,remap = map->remap; remap->infont!=-1; ++n, ++remap );
	fprintf( sfd, "RemapN: %d\n", n );
	for ( remap = map->remap; remap->infont!=-1; ++remap )
	    fprintf(sfd, "Remap: %x %x %d\n", (int) remap->firstenc, (int) remap->lastenc, (int) remap->infont );
    }
    if ( sf->display_size!=0 )
	fprintf( sfd, "DisplaySize: %d\n", sf->display_size );
    if ( sf->display_layer!=ly_fore )
	fprintf( sfd, "DisplayLayer: %d\n", sf->display_layer );
    fprintf( sfd, "AntiAlias: %d\n", sf->display_antialias );
    fprintf( sfd, "FitToEm: %d\n", sf->display_bbsized );
    if ( sf->extrema_bound!=0 )
	fprintf( sfd, "ExtremaBound: %d\n", sf->extrema_bound );
    if ( sf->width_separation!=0 )
	fprintf( sfd, "WidthSeparation: %d\n", sf->width_separation );
    {
	int rc, cc, te;
	if ( (te = FVWinInfo(sf->fv,&cc,&rc))!= -1 )
	    fprintf( sfd, "WinInfo: %d %d %d\n", te, cc, rc );
	else if ( sf->top_enc!=-1 )
	    fprintf( sfd, "WinInfo: %d %d %d\n", sf->top_enc, sf->desired_col_cnt,
		sf->desired_row_cnt);
    }
    if ( sf->onlybitmaps!=0 )
	fprintf( sfd, "OnlyBitmaps: %d\n", sf->onlybitmaps );
    if ( sf->private!=NULL )
	SFDDumpPrivate(sfd,sf->private);
#if HANYANG
    if ( sf->rules!=NULL )
	SFDDumpCompositionRules(sfd,sf->rules);
#endif
    if ( sf->grid.splines!=NULL ) {
	if ( sf->grid.order2 )
	    fprintf(sfd, "GridOrder2: %d\n", sf->grid.order2 );
	fprintf(sfd, "Grid\n" );
	SFDDumpSplineSet(sfd,sf->grid.splines,sf->grid.order2);
    }
    if ( sf->texdata.type!=tex_unset ) {
	fprintf(sfd, "TeXData: %d %d", (int) sf->texdata.type, (int) ((sf->design_size<<19)+2)/5 );
	for ( i=0; i<22; ++i )
	    fprintf(sfd, " %d", (int) sf->texdata.params[i]);
	putc('\n',sfd);
    }
    if ( sf->anchor!=NULL ) {
	AnchorClass *an;
	fprintf(sfd, "AnchorClass2:");
	for ( an=sf->anchor; an!=NULL; an=an->next ) {
	    putc(' ',sfd);
	    SFDDumpUTF7Str(sfd,an->name);
            if ( an->subtable!=NULL ) {
	        putc(' ',sfd);
	        SFDDumpUTF7Str(sfd,an->subtable->subtable_name);
            }
            else
                fprintf(sfd, "\"\" ");
	}
	putc('\n',sfd);
    }

    if ( sf->subfontcnt!=0 ) {
	if ( todir ) {
	    for ( i=0; i<sf->subfontcnt; ++i ) {
		char *subfont = malloc(strlen(dirname)+1+strlen(sf->subfonts[i]->fontname)+20);
		char *fontprops;
		FILE *ssfd;
		sprintf( subfont,"%s/%s" SUBFONT_EXT, dirname, sf->subfonts[i]->fontname );
		GFileMkDir(subfont, 0755);
		fontprops = malloc(strlen(subfont)+strlen("/" FONT_PROPS)+1);
		strcpy(fontprops,subfont); strcat(fontprops,"/" FONT_PROPS);
		ssfd = fopen( fontprops,"w");
		if ( ssfd!=NULL ) {
		    err |= SFD_Dump(ssfd,sf->subfonts[i],map,NULL,todir,subfont);
		    if ( ferror(ssfd) ) err = true;
		    if ( fclose(ssfd)) err = true;
		} else
		    err = true;
		free(fontprops);
		free(subfont);
	    }
	} else {
	    int max;
	    for ( i=max=0; i<sf->subfontcnt; ++i )
		if ( max<sf->subfonts[i]->glyphcnt )
		    max = sf->subfonts[i]->glyphcnt;
	    fprintf(sfd, "BeginSubFonts: %d %d\n", sf->subfontcnt, max );
	    for ( i=0; i<sf->subfontcnt; ++i )
		SFD_Dump(sfd,sf->subfonts[i],map,NULL,false, NULL);
	    fprintf(sfd, "EndSubFonts\n" );
	}
    } else {
	int enccount = map->enccount;
	if ( sf->cidmaster!=NULL ) {
	    realcnt = -1;
	    enccount = sf->glyphcnt;
	} else {
	    realcnt = 0;
	    for ( i=0; i<sf->glyphcnt; ++i ) if ( !SFDOmit(sf->glyphs[i]) )
		++realcnt;
	    if ( realcnt!=sf->glyphcnt ) {
		newgids = malloc(sf->glyphcnt*sizeof(int));
		realcnt = 0;
		for ( i=0; i<sf->glyphcnt; ++i )
		    if ( SFDOmit(sf->glyphs[i]) )
			newgids[i] = -1;
		    else
			newgids[i] = realcnt++;
	    }
	}
	if ( !todir )
	    fprintf(sfd, "BeginChars: %d %d\n",
	        enccount<map->enc->char_cnt? map->enc->char_cnt : enccount,
	        realcnt );
	for ( i=0; i<sf->glyphcnt; ++i ) {
	    if ( !SFDOmit(sf->glyphs[i]) ) {
		if ( !todir )
		SFDDumpChar(sfd,sf->glyphs[i],map,newgids,todir,1);
		else {
		    char *glyphfile = malloc(strlen(dirname)+2*strlen(sf->glyphs[i]->name)+20);
		    FILE *gsfd;
		    appendnames(glyphfile,dirname,"/",sf->glyphs[i]->name,GLYPH_EXT );
		    gsfd = fopen(glyphfile,"w");
		    if ( gsfd!=NULL ) {
			SFDDumpChar(gsfd,sf->glyphs[i],map,newgids,todir,1);
			if ( ferror(gsfd)) err = true;
			if ( fclose(gsfd)) err = true;
		    } else
			err = true;
		    free(glyphfile);
		}
	    }
	    ff_progress_next();
	}
	if ( !todir )
	    fprintf(sfd, "EndChars\n" );
    }

    if ( sf->bitmaps!=NULL )
	ff_progress_change_line2(_("Saving Bitmaps"));
    for ( bdf = sf->bitmaps; bdf!=NULL; bdf=bdf->next ) {
	if ( todir ) {
	    char *strike = malloc(strlen(dirname)+1+20+20);
	    char *strikeprops;
	    FILE *ssfd;
	    sprintf( strike,"%s/%d" STRIKE_EXT, dirname, bdf->pixelsize );
	    GFileMkDir(strike, 0755);
	    strikeprops = malloc(strlen(strike)+strlen("/" STRIKE_PROPS)+1);
	    strcpy(strikeprops,strike); strcat(strikeprops,"/" STRIKE_PROPS);
	    ssfd = fopen( strikeprops,"w");
	    if ( ssfd!=NULL ) {
		err |= SFDDumpBitmapFont(ssfd,bdf,map,newgids,todir,strike);
		if ( ferror(ssfd) ) err = true;
		if ( fclose(ssfd)) err = true;
	    } else
		err = true;
	    free(strikeprops);
	    free(strike);
	} else
	    SFDDumpBitmapFont(sfd,bdf,map,newgids,todir,dirname);
    }
    fprintf(sfd, sf->cidmaster==NULL?"EndSplineFont\n":"EndSubSplineFont\n" );
    free(newgids);
return( err );
}

int UndoRedoLimitToSave = 0;

int UndoRedoLimitToLoad = 0;

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

int prefRevisionsToRetain = 32;

int WritePNGInSFD = true;

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };

#define FONT_PROPS	"font.props"

#define STRIKE_PROPS	"strike.props"

#define GLYPH_EXT	".glyph"

#define STRIKE_EXT	".strike"

#define SUBFONT_EXT	".subfont"


static void SFDDumpTtfInstrsExplicit(FILE *sfd,uint8 *ttf_instrs, int16 ttf_instrs_len )
{
    char *instrs = _IVUnParseInstrs( ttf_instrs, ttf_instrs_len );
    char *pt;
    fprintf( sfd, "TtInstrs:\n" );
    for ( pt=instrs; *pt!='\0'; ++pt )
	putc(*pt,sfd);
    if ( pt[-1]!='\n' )
	putc('\n',sfd);
    free(instrs);
    fprintf( sfd, "%s\n", end_tt_instrs );
}

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };


static int getreal(FILE *sfd, real *val) {
    char tokbuf[100];
    int ch;
    char *pt=tokbuf, *end = tokbuf+100-2, *nend;

    while ( isspace(ch = nlgetc(sfd)));
    if ( ch!='e' && ch!='E' )		/* real's can't begin with exponants */
	while ( isdigit(ch) || ch=='-' || ch=='+' || ch=='e' || ch=='E' || ch=='.' || ch==',' ) {
	    if ( pt<end ) *pt++ = ch;
	    ch = nlgetc(sfd);
	}
    *pt='\0';
    ungetc(ch,sfd);
    *val = strtod(tokbuf,&nend);
    /* Beware of different locals! */
    if ( *nend!='\0' ) {
	if ( *nend=='.' )
	    *nend = ',';
	else if ( *nend==',' )
	    *nend = '.';
	*val = strtod(tokbuf,&nend);
    }
return( pt!=tokbuf && *nend=='\0'?1:ch==EOF?-1: 0 );
}


static void SFDDumpGradient(FILE *sfd, const char *keyword, struct gradient *gradient) {
    int i;

    /* Use ";" as a coord separator because we treat "," as a potential decimal point */
    fprintf( sfd, "%s %g;%g %g;%g %g %s %d ", keyword,
	    (double) gradient->start.x, (double) gradient->start.y,
	    (double) gradient->stop.x, (double) gradient->stop.y,
	    (double) gradient->radius,
	    spreads[gradient->sm],
	    gradient->stop_cnt );
    for ( i=0 ; i<gradient->stop_cnt; ++i ) {
	fprintf( sfd, "{%g #%06x %g} ", (double) gradient->grad_stops[i].offset,
		gradient->grad_stops[i].col, (double) gradient->grad_stops[i].opacity );
    }
    putc('\n',sfd);
}


static struct ttf_table *SFDGetTtTable(FILE *sfd, SplineFont *sf,struct ttf_table *lasttab[2]) {
    /* We've read the TtTable token, it is followed by a tag */
    /* and then the instructions in text format */
    int ch;
    int which;
    struct ttf_table *tab = chunkalloc(sizeof(struct ttf_table));
    char *buf=NULL, *pt=buf, *end=buf;
    int backlen = strlen(end_tt_instrs);

    tab->tag = gettag(sfd);

    if ( tab->tag==CHR('f','p','g','m') || tab->tag==CHR('p','r','e','p') ||
	    tab->tag==CHR('c','v','t',' ') || tab->tag==CHR('m','a','x','p'))
	which = 0;
    else
	which = 1;

    while ( (ch=nlgetc(sfd))!=EOF ) {
	if ( pt>=end ) {
	    char *newbuf = realloc(buf,(end-buf+200));
	    pt = newbuf+(pt-buf);
	    end = newbuf+(end+200-buf);
	    buf = newbuf;
	}
	*pt++ = ch;
	if ( pt-buf>backlen && strncmp(pt-backlen,end_tt_instrs,backlen)==0 ) {
	    pt -= backlen;
    break;
	}
    }
    *pt = '\0';
    tab->data = _IVParse(sf,buf,&tab->len,tterr,NULL);
    free(buf);

    if ( lasttab[which]!=NULL )
	lasttab[which]->next = tab;
    else if ( which==0 )
	sf->ttf_tables = tab;
    else
	sf->ttf_tab_saved = tab;
    lasttab[which] = tab;
return( tab );
}


static DStemInfo *SFDReadDHints( SplineFont *sf,FILE *sfd,int old ) {
    DStemInfo *head=NULL, *last=NULL, *cur;
    int i;
    BasePoint bp[4], *bpref[4], left, right, unit;
    double rstartoff, rendoff, lendoff;

    if ( old ) {
        for ( i=0 ; i<4 ; i++ ) bpref[i] = &bp[i];

        while ( getreal( sfd,&bp[0].x ) && getreal( sfd,&bp[0].y ) &&
	        getreal( sfd,&bp[1].x ) && getreal( sfd,&bp[1].y ) &&
	        getreal( sfd,&bp[2].x ) && getreal( sfd,&bp[2].y ) &&
	        getreal( sfd,&bp[3].x ) && getreal( sfd,&bp[3].y )) {

            /* Ensure point coordinates specified in the sfd file do */
            /* form a diagonal line */
            if ( PointsDiagonalable( sf,bpref,&unit )) {
	        cur = chunkalloc( sizeof( DStemInfo ));
	        cur->left = *bpref[0];
	        cur->right = *bpref[1];
                cur->unit = unit;
                /* Generate a temporary hint instance, so that the hint can */
                /* be visible in charview even if subsequent rebuilding instances */
                /* fails (e. g. for composite characters) */
                cur->where = chunkalloc( sizeof( HintInstance ));
                rstartoff = ( cur->right.x - cur->left.x ) * cur->unit.x +
                            ( cur->right.y - cur->left.y ) * cur->unit.y;
                rendoff =   ( bpref[2]->x - cur->left.x ) * cur->unit.x +
                            ( bpref[2]->y - cur->left.y ) * cur->unit.y;
                lendoff =   ( bpref[3]->x - cur->left.x ) * cur->unit.x +
                            ( bpref[3]->y - cur->left.y ) * cur->unit.y;
                cur->where->begin = ( rstartoff > 0 ) ? rstartoff : 0;
                cur->where->end   = ( rendoff > lendoff ) ? lendoff : rendoff;
                MergeDStemInfo( sf,&head,cur );
            }
        }
    } else {
        while ( getreal( sfd,&left.x ) && getreal( sfd,&left.y ) &&
                getreal( sfd,&right.x ) && getreal( sfd,&right.y ) &&
                getreal( sfd,&unit.x ) && getreal( sfd,&unit.y )) {
	    cur = chunkalloc( sizeof( DStemInfo ));
	    cur->left = left;
	    cur->right = right;
            cur->unit = unit;
	    cur->where = SFDReadHintInstances( sfd,NULL );
	    if ( head == NULL )
	        head = cur;
	    else
	        last->next = cur;
	    last = cur;
        }
    }
return( head );
}

int UndoRedoLimitToSave = 0;

int UndoRedoLimitToLoad = 0;

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

int prefRevisionsToRetain = 32;

int WritePNGInSFD = true;

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };

#define INSTANCE_EXT	".instance"

static char base64[64] = {
 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};

static const char *end_tt_instrs = "EndTTInstrs";

static void SFDConsumeUntil( FILE *sfd, const char** terminators );

static void SFDDumpRefs(FILE *sfd,RefChar *refs, int *newgids);

static void SFDDumpGuidelines(FILE *sfd,GuidelineSet *gl);

static RefChar *SFDGetRef(FILE *sfd, int was_enc);

static void SFDDumpImage(FILE *sfd,ImageList *img);

static void SFDDumpImagePNG(FILE *sfd,ImageList *img);

static AnchorPoint *SFDReadAnchorPoints(FILE *sfd,SplineChar *sc,AnchorPoint** alist, AnchorPoint *lastap);


static void SFDSetEncMap(SplineFont *sf,int orig_pos,int enc) {
    EncMap *map = sf->map;

    if ( map==NULL )
return;

    if ( orig_pos>=map->backmax ) {
	int old = map->backmax;
	map->backmax = orig_pos+10;
	map->backmap = realloc(map->backmap,map->backmax*sizeof(int));
	memset(map->backmap+old,-1,(map->backmax-old)*sizeof(int));
    }
    if ( map->backmap[orig_pos] == -1 )		/* backmap will not be unique if multiple encodings come from same glyph */
	map->backmap[orig_pos] = enc;
    if ( enc>=map->encmax ) {
	int old = map->encmax;
	map->encmax = enc+10;
	map->map = realloc(map->map,map->encmax*sizeof(int));
	memset(map->map+old,-1,(map->encmax-old)*sizeof(int));
    }
    if ( enc>=map->enccount )
	map->enccount = enc+1;
    if ( enc!=-1 )
	map->map[enc] = orig_pos;
}

int UndoRedoLimitToSave = 0;

int UndoRedoLimitToLoad = 0;

static const char *joins[] = { "miter", "round", "bevel", "inher", NULL };

static const char *caps[] = { "butt", "round", "square", "inher", NULL };

static const char *spreads[] = { "pad", "reflect", "repeat", NULL };

int prefRevisionsToRetain = 32;

int WritePNGInSFD = true;

static const char *charset_names[] = {
    "custom",
    "iso8859-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5",
    "iso8859-6", "iso8859-7", "iso8859-8", "iso8859-9", "iso8859-10",
    "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16",
    "koi8-r",
    "jis201",
    "win", "mac", "symbol", "zapfding", "adobestandard",
    "jis208", "jis212", "ksc5601", "gb2312", "big5", "big5hkscs", "johab",
    "unicode", "unicode4", "sjis", "wansung", "gb2312pk", NULL};

static const char *unicode_interp_names[] = { "none", "adobe", "greek",
    "japanese", "tradchinese", "simpchinese", "korean", "ams", NULL };

#define GLYPH_EXT	".glyph"

static char base64[64] = {
 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};

static const char *end_tt_instrs = "EndTTInstrs";

static void SFDConsumeUntil( FILE *sfd, const char** terminators );

static void SFDDumpRefs(FILE *sfd,RefChar *refs, int *newgids);

static void SFDDumpGuidelines(FILE *sfd,GuidelineSet *gl);

static RefChar *SFDGetRef(FILE *sfd, int was_enc);

static void SFDDumpImage(FILE *sfd,ImageList *img);

static void SFDDumpImagePNG(FILE *sfd,ImageList *img);

static AnchorPoint *SFDReadAnchorPoints(FILE *sfd,SplineChar *sc,AnchorPoint** alist, AnchorPoint *lastap);


static void SFDDumpAnchorPoints(FILE *sfd,AnchorPoint *ap) {
    if (ap==NULL) {
	return;
    }

    for ( ; ap!=NULL; ap=ap->next )
    {
	fprintf( sfd, "AnchorPoint: " );
	SFDDumpUTF7Str(sfd,ap->anchor->name);
	putc(' ',sfd);
	fprintf( sfd, "%g %g %s %d",
		(double) ap->me.x, (double) ap->me.y,
		ap->type==at_centry ? "entry" :
		ap->type==at_cexit ? "exit" :
		ap->type==at_mark ? "mark" :
		ap->type==at_basechar ? "basechar" :
		ap->type==at_baselig ? "baselig" : "basemark",
		ap->lig_index );
	if ( ap->xadjust.corrections!=NULL || ap->yadjust.corrections!=NULL ) {
	    putc(' ',sfd);
	    SFDDumpDeviceTable(sfd,&ap->xadjust);
	    putc(' ',sfd);
	    SFDDumpDeviceTable(sfd,&ap->yadjust);
	} else
	if ( ap->has_ttf_pt )
	    fprintf( sfd, " %d", ap->ttf_pt_index );
	putc('\n',sfd);
    }
}


static ImageList *SFDGetImagePNG(FILE *sfd) {
    int pnglen;
    ImageList *img;
    struct enc85 dec = {0};
    int i, ch;

    img = calloc(1,sizeof(ImageList));
    dec.pos = -1;
    dec.sfd = sfd;

    getint(sfd,&pnglen);
    getreal(sfd,&img->xoff);
    getreal(sfd,&img->yoff);
    getreal(sfd,&img->xscale);
    getreal(sfd,&img->yscale);

    while ( (ch=nlgetc(sfd))==' ' || ch=='\t' )
        /* skip */;

    char* pngbuf = malloc(pnglen * sizeof(char));
    if (pngbuf == NULL) {
        IError("Failed to allocate buffer to read PNG in SFD file");
        return NULL;
    }

    for (i = 0; i<pnglen; ++i) {
        pngbuf[i] = Dec85(&dec);
    }

    img->image = GImageReadPngBuf(pngbuf, pnglen);
    free(pngbuf);

    if (img->image == NULL) {
        IError("Failed to read PNG in SFD file, skipping it.");
        free(img);
        return NULL;
    }

    img->bb.minx = img->xoff; img->bb.maxy = img->yoff;
    img->bb.maxx = img->xoff + GImageGetWidth(img->image)*img->xscale;
    img->bb.miny = img->yoff - GImageGetHeight(img->image)*img->yscale;
    return img;
}


void SFDGetPSTs( FILE *sfd, SplineChar *sc, char* ttok ) {
    struct splinefont * sf = sc->parent;
    char tok[2001], ch;
    int isliga = 0, ispos, issubs, ismult, islcar, ispair, temp;
    PST *last = NULL;
    uint32 script = 0;
    SplineFont *sli_sf = sf->cidmaster ? sf->cidmaster : sf;

    strncpy(tok,ttok,sizeof(tok)-1);

    if ( strmatch(tok,"Script:")==0 ) {
	/* Obsolete. But still used for parsing obsolete ligature/subs tags */
	while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
	if ( ch=='\n' || ch=='\r' )
	    script = 0;
	else {
	    ungetc(ch,sfd);
	    script = gettag(sfd);
	}
    } else if ( (ispos = (strmatch(tok,"Position:")==0)) ||
		( ispos  = (strmatch(tok,"Position2:")==0)) ||
		( ispair = (strmatch(tok,"PairPos:")==0)) ||
		( ispair = (strmatch(tok,"PairPos2:")==0)) ||
		( islcar = (strmatch(tok,"LCarets:")==0)) ||
		( islcar = (strmatch(tok,"LCarets2:")==0)) ||
		( isliga = (strmatch(tok,"Ligature:")==0)) ||
		( isliga = (strmatch(tok,"Ligature2:")==0)) ||
		( issubs = (strmatch(tok,"Substitution:")==0)) ||
		( issubs = (strmatch(tok,"Substitution2:")==0)) ||
		( ismult = (strmatch(tok,"MultipleSubs:")==0)) ||
		( ismult = (strmatch(tok,"MultipleSubs2:")==0)) ||
		strmatch(tok,"AlternateSubs:")==0 ||
		strmatch(tok,"AlternateSubs2:")==0 ) {
	    PST *pst;
	    int old, type;
	    type = ispos ? pst_position :
			 ispair ? pst_pair :
			 islcar ? pst_lcaret :
			 isliga ? pst_ligature :
			 issubs ? pst_substitution :
			 ismult ? pst_multiple :
			 pst_alternate;
	    if ( strchr(tok,'2')!=NULL ) {
		old = false;
		pst = chunkalloc(sizeof(PST));
		if ( type!=pst_lcaret )
		    pst->subtable = SFFindLookupSubtableAndFreeName(sf,SFDReadUTF7Str(sfd));
	    } else {
		old = true;
		pst = chunkalloc(sizeof(PST1));
		((PST1 *) pst)->tag = CHR('l','i','g','a');
		((PST1 *) pst)->script_lang_index = 0xffff;
		while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
		if ( isdigit(ch)) {
		    int temp;
		    ungetc(ch,sfd);
		    getint(sfd,&temp);
		    ((PST1 *) pst)->flags = temp;
		    while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
		} else
		    ((PST1 *) pst)->flags = 0 /*PSTDefaultFlags(type,sc)*/;
		if ( isdigit(ch)) {
		    ungetc(ch,sfd);
		    getusint(sfd,&((PST1 *) pst)->script_lang_index);
		    while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
		} else
		    ((PST1 *) pst)->script_lang_index = SFFindBiggestScriptLangIndex(sf,
			    script!=0?script:SCScriptFromUnicode(sc),DEFAULT_LANG);
		if ( ch=='\'' ) {
		    ungetc(ch,sfd);
		    ((PST1 *) pst)->tag = gettag(sfd);
		} else if ( ch=='<' ) {
		    getint(sfd,&temp);
		    ((PST1 *) pst)->tag = temp<<16;
		    nlgetc(sfd);	/* comma */
		    getint(sfd,&temp);
		    ((PST1 *) pst)->tag |= temp;
		    nlgetc(sfd);	/* close '>' */
		    ((PST1 *) pst)->macfeature = true;
		} else
		    ungetc(ch,sfd);
		if ( type==pst_lcaret ) {
		/* These are meaningless for lcarets, set them to innocuous values */
		    ((PST1 *) pst)->script_lang_index = SLI_UNKNOWN;
		    ((PST1 *) pst)->tag = CHR(' ',' ',' ',' ');
		} else if ( ((PST1 *) pst)->script_lang_index>=((SplineFont1 *) sli_sf)->sli_cnt && ((PST1 *) pst)->script_lang_index!=SLI_NESTED ) {
		    static int complained=false;
		    if ( !complained )
			IError("'%c%c%c%c' in %s has a script index out of bounds: %d",
				(((PST1 *) pst)->tag>>24), (((PST1 *) pst)->tag>>16)&0xff, (((PST1 *) pst)->tag>>8)&0xff, ((PST1 *) pst)->tag&0xff,
				sc->name, ((PST1 *) pst)->script_lang_index );
		    else
			IError( "'%c%c%c%c' in %s has a script index out of bounds: %d\n",
				(((PST1 *) pst)->tag>>24), (((PST1 *) pst)->tag>>16)&0xff, (((PST1 *) pst)->tag>>8)&0xff, ((PST1 *) pst)->tag&0xff,
				sc->name, ((PST1 *) pst)->script_lang_index );
		    ((PST1 *) pst)->script_lang_index = SFFindBiggestScriptLangIndex(sli_sf,
			    SCScriptFromUnicode(sc),DEFAULT_LANG);
		    complained = true;
		}
	    }
	    if ( (sf->sfd_version<2)!=old ) {
		IError( "Version mixup in PST of sfd file." );
exit(1);
	    }
	    if ( last==NULL )
		sc->possub = pst;
	    else
		last->next = pst;
	    last = pst;
	    pst->type = type;
	    if ( pst->type==pst_position ) {
		fscanf( sfd, " dx=%hd dy=%hd dh=%hd dv=%hd",
			&pst->u.pos.xoff, &pst->u.pos.yoff,
			&pst->u.pos.h_adv_off, &pst->u.pos.v_adv_off);
		pst->u.pos.adjust = SFDReadValDevTab(sfd);
		ch = nlgetc(sfd);		/* Eat new line */
	    } else if ( pst->type==pst_pair ) {
		getname(sfd,tok);
		pst->u.pair.paired = copy(tok);
		pst->u.pair.vr = chunkalloc(sizeof(struct vr [2]));
		fscanf( sfd, " dx=%hd dy=%hd dh=%hd dv=%hd",
			&pst->u.pair.vr[0].xoff, &pst->u.pair.vr[0].yoff,
			&pst->u.pair.vr[0].h_adv_off, &pst->u.pair.vr[0].v_adv_off);
		pst->u.pair.vr[0].adjust = SFDReadValDevTab(sfd);
		fscanf( sfd, " dx=%hd dy=%hd dh=%hd dv=%hd",
			&pst->u.pair.vr[1].xoff, &pst->u.pair.vr[1].yoff,
			&pst->u.pair.vr[1].h_adv_off, &pst->u.pair.vr[1].v_adv_off);
		pst->u.pair.vr[0].adjust = SFDReadValDevTab(sfd);
		ch = nlgetc(sfd);
	    } else if ( pst->type==pst_lcaret ) {
		int i;
		fscanf( sfd, " %d", &pst->u.lcaret.cnt );
		pst->u.lcaret.carets = malloc(pst->u.lcaret.cnt*sizeof(int16));
		for ( i=0; i<pst->u.lcaret.cnt; ++i )
		    fscanf( sfd, " %hd", &pst->u.lcaret.carets[i]);
		geteol(sfd,tok);
	    } else {
		geteol(sfd,tok);
		pst->u.lig.components = copy(tok);	/* it's in the same place for all formats */
		if ( isliga ) {
		    pst->u.lig.lig = sc;
		    if ( old )
			last = (PST *) LigaCreateFromOldStyleMultiple((PST1 *) pst);
		}
	    }
#ifdef FONTFORGE_CONFIG_CVT_OLD_MAC_FEATURES
	    if ( old )
		CvtOldMacFeature((PST1 *) pst);
#endif
    } else {
	return;
    }

    // we matched something, grab the next top level token to ttok
    getname( sfd, ttok );
}


static void SFDDumpJustify(FILE *sfd,SplineFont *sf) {
    Justify *jscript;
    struct jstf_lang *jlang;
    int i;

    for ( jscript = sf->justify; jscript!=NULL; jscript=jscript->next ) {
	fprintf( sfd, "Justify: '%c%c%c%c'\n",
		jscript->script>>24,
		jscript->script>>16,
		jscript->script>>8,
		jscript->script);
	if ( jscript->extenders!=NULL )
	    fprintf( sfd, "JstfExtender: %s\n", jscript->extenders );
	for ( jlang = jscript->langs; jlang!=NULL; jlang = jlang->next ) {
	    fprintf( sfd, "JstfLang: '%c%c%c%c' %d\n",
		jlang->lang>>24,
		jlang->lang>>16,
		jlang->lang>>8,
		jlang->lang, jlang->cnt );
	    for ( i=0; i<jlang->cnt; ++i ) {
		fprintf( sfd, "JstfPrio:\n" );
		SFDDumpJSTFLookups(sfd,"JstfEnableShrink:", jlang->prios[i].enableShrink );
		SFDDumpJSTFLookups(sfd,"JstfDisableShrink:", jlang->prios[i].disableShrink );
		SFDDumpJSTFLookups(sfd,"JstfMaxShrink:", jlang->prios[i].maxShrink );
		SFDDumpJSTFLookups(sfd,"JstfEnableExtend:", jlang->prios[i].enableExtend );
		SFDDumpJSTFLookups(sfd,"JstfDisableExtend:", jlang->prios[i].disableExtend );
		SFDDumpJSTFLookups(sfd,"JstfMaxExtend:", jlang->prios[i].maxExtend );
	    }
	}
    }
    if ( sf->justify!=NULL )
	fprintf( sfd, "EndJustify\n" );
}


static void SFDGetSubrs(FILE *sfd) {
    /* Obselete, parse it in case there are any old sfds */
    int i, cnt, tot, len;
    struct enc85 dec;

    getint(sfd,&cnt);
    tot = 0;
    for ( i=0; i<cnt; ++i ) {
	getint(sfd,&len);
	tot += len;
    }

    memset(&dec,'\0', sizeof(dec)); dec.pos = -1;
    dec.sfd = sfd;
    for ( i=0; i<tot; ++i )
	Dec85(&dec);
}


SplineFont *SFRecoverFile(char *autosavename,int inquire,int *state) {
    FILE *asfd;
    SplineFont *ret;
    char tok[1025];

    if (!inquire) {
        *state = 1; //Default to recover all
    }
    if (!ask_about_file(autosavename, state, &asfd)) {
return( NULL );
    }
    locale_t tmplocale; locale_t oldlocale; // Declare temporary locale storage.
    switch_to_c_locale(&tmplocale, &oldlocale); // Switch to the C locale temporarily and cache the old locale.
    ret = SlurpRecovery(asfd,tok,sizeof(tok));
    if ( ret==NULL ) {
	const char *buts[3];
	buts[0] = "_Forget It"; buts[1] = "_Try Again"; buts[2] = NULL;
	if ( ff_ask(_("Recovery Failed"),(const char **) buts,0,1,_("Automagic recovery of changes to %.80s failed.\nShould FontForge try again to recover next time you start it?"),tok)==0 )
	    unlink(autosavename);
    }
    switch_to_old_locale(&tmplocale, &oldlocale); // Switch to the cached locale.
    fclose(asfd);
    if ( ret )
	ret->autosavename = copy(autosavename);
return( ret );
}


static void SFDCleanupAnchorClasses(SplineFont *sf) {
    AnchorClass *ac;
    AnchorPoint *ap;
    int i, j, scnt;
#define S_MAX	100
    uint32 scripts[S_MAX];
    int merge=0;

    for ( ac = sf->anchor; ac!=NULL; ac=ac->next ) {
	if ( ((AnchorClass1 *) ac)->script_lang_index==0xffff ) {
	    scnt = 0;
	    for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL ) {
		for ( ap = sf->glyphs[i]->anchor; ap!=NULL && ap->anchor!=ac; ap=ap->next );
		if ( ap!=NULL && scnt<S_MAX ) {
		    uint32 script = SCScriptFromUnicode(sf->glyphs[i]);
		    if ( script==0 )
	    continue;
		    for ( j=0; j<scnt; ++j )
			if ( scripts[j]==script )
		    break;
		    if ( j==scnt )
			scripts[scnt++] = script;
		}
	    }
	    ((AnchorClass1 *) ac)->script_lang_index = SFAddScriptIndex((SplineFont1 *) sf,scripts,scnt);
	}
	if ( ((AnchorClass1 *) ac)->merge_with == 0xffff )
	    ((AnchorClass1 *) ac)->merge_with = ++merge;
    }
#undef S_MAX
}


static void SFDDumpImage(FILE *sfd,ImageList *img) {
    GImage *image = img->image;
    struct _GImage *base = image->list_len==0?image->u.image:image->u.images[0];
    struct enc85 enc;
    int rlelen;
    uint8 *rle;
    int i;

    rle = image2rle(base,&rlelen);
    fprintf(sfd, "Image: %d %d %d %d %d %x %g %g %g %g %d\n",
	    (int) base->width, (int) base->height, base->image_type,
	    (int) (base->image_type==it_true?3*base->width:base->bytes_per_line),
	    base->clut==NULL?0:base->clut->clut_len,(int) base->trans,
	    (double) img->xoff, (double) img->yoff, (double) img->xscale, (double) img->yscale, rlelen );
    memset(&enc,'\0',sizeof(enc));
    enc.sfd = sfd;
    if ( base->clut!=NULL ) {
	for ( i=0; i<base->clut->clut_len; ++i ) {
	    SFDEnc85(&enc,base->clut->clut[i]>>16);
	    SFDEnc85(&enc,(base->clut->clut[i]>>8)&0xff);
	    SFDEnc85(&enc,base->clut->clut[i]&0xff);
	}
    }
    if ( rle!=NULL ) {
	uint8 *pt=rle, *end=rle+rlelen;
	while ( pt<end )
	    SFDEnc85(&enc,*pt++);
	free( rle );
    } else {
	for ( i=0; i<base->height; ++i ) {
	    if ( base->image_type==it_rgba ) {
		uint32 *ipt = (uint32 *) (base->data + i*base->bytes_per_line);
		uint32 *iend = (uint32 *) (base->data + (i+1)*base->bytes_per_line);
		while ( ipt<iend ) {
		    SFDEnc85(&enc,*ipt>>24);
		    SFDEnc85(&enc,(*ipt>>16)&0xff);
		    SFDEnc85(&enc,(*ipt>>8)&0xff);
		    SFDEnc85(&enc,*ipt&0xff);
		    ++ipt;
		}
	    } else if ( base->image_type==it_true ) {
		int *ipt = (int *) (base->data + i*base->bytes_per_line);
		int *iend = (int *) (base->data + (i+1)*base->bytes_per_line);
		while ( ipt<iend ) {
		    SFDEnc85(&enc,*ipt>>16);
		    SFDEnc85(&enc,(*ipt>>8)&0xff);
		    SFDEnc85(&enc,*ipt&0xff);
		    ++ipt;
		}
	    } else {
		uint8 *pt = (uint8 *) (base->data + i*base->bytes_per_line);
		uint8 *end = (uint8 *) (base->data + (i+1)*base->bytes_per_line);
		while ( pt<end ) {
		    SFDEnc85(&enc,*pt);
		    ++pt;
		}
	    }
	}
    }
    SFDEnc85EndEnc(&enc);
    fprintf(sfd,"\nEndImage\n" );
}


static void tterr(void *UNUSED(rubbish), char *message, int UNUSED(pos)) {
    LogError(_("When loading tt instrs from sfd: %s\n"), message );
}


static void SFDGetHintMask(FILE *sfd,HintMask *hintmask) {
    int nibble = 0, ch;

    memset(hintmask,0,sizeof(HintMask));
    for (;;) {
	ch = nlgetc(sfd);
	if ( isdigit(ch))
	    ch -= '0';
	else if ( ch>='a' && ch<='f' )
	    ch -= 'a'-10;
	else if ( ch>='A' && ch<='F' )
	    ch -= 'A'-10;
	else {
	    ungetc(ch,sfd);
    break;
	}
	if ( nibble<2*HntMax/8 )
	    (*hintmask)[nibble>>1] |= ch<<(4*(1-(nibble&1)));
	++nibble;
    }
}


static unsigned int read_le32(const unsigned char *p)
{
    return ((unsigned int) p[0])
        | ((unsigned int) p[1] << 8)
        | ((unsigned int) p[2] << 16)
        | ((unsigned int) p[3] << 24);
}

gzip: fix compression size calculation (oss-fuzz 27261)

Signed-off-by: davkor <david@adalogics.com>

#define FLB_GZIP_HEADER_OFFSET 10

typedef enum {
    FTEXT    = 1,
    FHCRC    = 2,
    FEXTRA   = 4,
    FNAME    = 8,
    FCOMMENT = 16
} flb_tinf_gzip_flag;


int flb_gzip_compress(void *in_data, size_t in_len,
                      void **out_data, size_t *out_len)
{
    int flush;
    int status;
    int footer_start;
    uint8_t *pb;
    size_t out_size;
    void *out_buf;
    z_stream strm;
    mz_ulong crc;

    /*
     * GZIP relies on an algorithm with worst-case expansion
     * of 5 bytes per 32KB data. This means we need to create a variable
     * length output, that depends on the input length.
     * See RFC 1951 for details.
     */
    int max_input_expansion = ((int)(in_len / 32000) + 1) * 5;

    /*
     * Max compressed size is equal to sum of:
     *   10 byte header
     *   8 byte foot
     *   max input expansion
     *   size of input
     */
    out_size = 10 + 8 + max_input_expansion + in_len;
    out_buf = flb_malloc(out_size);

    if (!out_buf) {
        flb_errno();
        flb_error("[gzip] could not allocate outgoing buffer");
        return -1;
    }

    /* Initialize streaming buffer context */
    memset(&strm, '\0', sizeof(strm));
    strm.zalloc    = Z_NULL;
    strm.zfree     = Z_NULL;
    strm.opaque    = Z_NULL;
    strm.next_in   = in_data;
    strm.avail_in  = in_len;
    strm.total_out = 0;

    /* Deflate mode */
    deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
                 Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY);

    /*
     * Miniz don't support GZip format directly, instead we will:
     *
     * - append manual GZip magic bytes
     * - deflate raw content
     * - append manual CRC32 data
     */
    gzip_header(out_buf);

    /* Header offset */
    pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET;

    flush = Z_NO_FLUSH;
    while (1) {
        strm.next_out  = pb + strm.total_out;
        strm.avail_out = out_size - (pb - (uint8_t *) out_buf);

        if (strm.avail_in == 0) {
            flush = Z_FINISH;
        }

        status = deflate(&strm, flush);
        if (status == Z_STREAM_END) {
            break;
        }
        else if (status != Z_OK) {
            deflateEnd(&strm);
            return -1;
        }
    }

    if (deflateEnd(&strm) != Z_OK) {
        flb_free(out_buf);
        return -1;
    }
    *out_len = strm.total_out;

    /* Construct the gzip checksum (CRC32 footer) */
    footer_start = FLB_GZIP_HEADER_OFFSET + *out_len;
    pb = (uint8_t *) out_buf + footer_start;

    crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len);
    *pb++ = crc & 0xFF;
    *pb++ = (crc >> 8) & 0xFF;
    *pb++ = (crc >> 16) & 0xFF;
    *pb++ = (crc >> 24) & 0xFF;
    *pb++ = in_len & 0xFF;
    *pb++ = (in_len >> 8) & 0xFF;
    *pb++ = (in_len >> 16) & 0xFF;
    *pb++ = (in_len >> 24) & 0xFF;

    /* Set the real buffer size for the caller */
    *out_len += FLB_GZIP_HEADER_OFFSET + 8;
    *out_data = out_buf;

    return 0;
}


static unsigned int read_le16(const unsigned char *p)
{
    return ((unsigned int) p[0]) | ((unsigned int) p[1] << 8);
}