summaryrefslogtreecommitdiff
path: root/riscos/ufont.c
blob: 9cedcd79a0706957decbc7bd5d415e23c3feb275 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
/* ufont.c
 * Licensed under the GNU General Public License,
 *                http://www.opensource.org/licenses/gpl-license
 * Copyright 2000 James Bursa <bursa@users.sourceforge.net>
 * Copyright 2004 John Tytgat <John.Tytgat@aaug.net>
 */

/** \file
 * UFont - Unicode wrapper for non-Unicode aware FontManager
 *
 * This code allows non-Unicode aware FontManager to be used for
 * displaying Unicode encoded text lines.  It needs the !UFont
 * resource (accessed via UFont$Path).
 */

#include <assert.h>
#include <limits.h>
#include <wchar.h>

#include "oslib/osfile.h"

#include "ufont.h"

// #define DEBUG_UFONT
// #define DEBUG_ACTIVATE_SANITY_CHECK
// #define DEBUG_DUMP_INTERNALS

#ifdef DEBUG_UFONT
#  define dbg_fprintf fprintf
#else
#  define dbg_fprintf (1)?0:fprintf
#endif
#ifdef DEBUG_ACTIVATE_SANITY_CHECK
#  define do_sanity_check sanity_check
#else
#  define do_sanity_check (1)?0:sanity_check
#endif
#define MALLOC_CHUNK 256

typedef struct usage_chain_s usage_chain_t;
typedef struct virtual_fh_s virtual_fh_t;
/* Virtual font handle :
 */
struct virtual_fh_s
  {
  const char    *fontNameP;    /* => malloc'ed block holding RISC OS font name */
  int            xsize, ysize; /* font size */
  int            xres, yres;   /* requested or actual resolution */
  unsigned int   usage;        /* the higher, the more this font handle is used for setting its glyphs */
  unsigned int   refCount;     /* number of times this struct is refered from ufont_f element */
  usage_chain_t *usageP;       /* Ptr to element usage chain; if non NULL, we have a RISC OS font handle allocated. When refCount is 0, this is not necessary NULL. */
  };
#define kInitialFHArraySize 20
static virtual_fh_t *oVirtualFHArrayP;
static size_t oCurVirtualFHArrayElems;
static size_t oMaxVirtualFHArrayElems;

/* Usage chain (one element per open RISC OS font handle) :
 */
struct usage_chain_s
  {
  usage_chain_t *nextP;
  usage_chain_t *prevP;

  size_t         chainTimer;      /* When equal to oChainTimer, you can not throw this element out the chain. */
  font_f         ro_fhandle;      /* RISC OS font handle (garanteed non zero) */
  virtual_fh_t  *virFHP;
  };

typedef struct ufont_map_s ufont_map_t;

struct ufont_map_s
  {
  byte fontnr[65536];     /* Must be 1st (comes straight from 'Data' file). Each entry is an index in the virtual_font_index array. */
  byte character[65536];  /* Must be 2nd (comes straight from 'Data' file) */

  const char *uFontNameP; /* => malloc'ed block holding UFont name */
  unsigned int refCount;
  ufont_map_t *nextP;
  };
static const ufont_map_t *oMapCollectionP;

struct ufont_font
  {
  ufont_map_t *mapP;
  unsigned int virtual_handles_used; /* Number of filled virtual_font_index[] elements */
  size_t virtual_font_index[256]; /* Index in the oVirtualFHArrayP */
  };

/* Walking the chain starting with oUsageChain->nextP and continuing via
 * ->nextP until reaching oUsageChain again, results in equal or
 * decreasing ->virFHP->usage values.
 * Also walking the chain starting with oUsageChain->prevP and continuing
 * via ->prevP until reaching oUsageChain again, results in equal or
 * increasing ->virFHP->usage values.
 */
static usage_chain_t oUsageChain;
static size_t oCurUsageChainElems;
/* Maximum number of RISC OS handles open by UFont :
 */
#define kMaxUsageChainElems 80
static size_t oChainTimer;

static os_error *create_map(const char *fontNameP, const ufont_map_t **mapPP);
static os_error *delete_map(ufont_map_t *mapP);
static int eat_utf8(wchar_t *pwc, const byte *s, int n);
static os_error *addref_virtual_fonthandle(const char *fontNameP, int xsize, int ysize, int xres, int yres, int *xresOutP, int *yresOutP, size_t *offsetP);
static os_error *deref_virtual_fonthandle(size_t offset);
static os_error *activate_virtual_fh(virtual_fh_t *virFHP);
static os_error *remove_usage_chain_elem(usage_chain_t *usageElemP);
static void repos_usage_chain_elem(usage_chain_t *usageElemP);
static const char *get_rofontname(font_f rofhandle);
#ifdef DEBUG_DUMP_INTERNALS
static void dump_internals(void);
#endif
static int sanity_check(const char *testMsgP);

/* UFont error messages :
 */
static os_error error_badparams = { error_BAD_PARAMETERS, "Bad parameters" };
static os_error error_exists = { error_FONT_NOT_FOUND, "UFont Fonts/Data file not found" };
static os_error error_memory = { error_FONT_NO_ROOM, "Insufficient memory for font" };
static os_error error_size = { error_FONT_BAD_FONT_FILE, "Wrong size of font file" };
static os_error error_fnt_corrupt = { 1 /** \todo */, "UFont is corrupt" };
static os_error error_toomany_handles = { 2 /** \todo */, "Too many UFont handles are needed to fulfill current request" };
static os_error error_noufont = { 3 /** \todo */, "Unable to find UFont font" };
static os_error error_badrohandle = { 4 /** \todo */, "Invalid internal RISC OS font handle" };

/*
 *  UFont_FindFont
 *
 *  => as Font_FindFont, but
 *     font_name does not support '\' qualifiers
 *
 *  <= as Font_FindFont, but
 *     handle is 32-bit
 *     Results from xres_out and yres_out are questionable because we
 *     delay-loading the real font data.
 */
os_error *
xufont_find_font(char const *fontNameP,
                 int xsize,
                 int ysize,
                 int xres,
                 int yres,
                 ufont_f *font,
                 int *xresOutP,
                 int *yresOutP)
{
  ufont_f fontP;
  const char *old_font;
  char *fonts_file;
  char file_name[256]; // \todo: fixed size, i.e. not safe.
  fileswitch_object_type objType;
  int size;
  os_error *errorP;

if (font == NULL)
  return &error_badparams;
/* Be sure never to return garbage as result. */
*font = NULL;

/* Allocate memory for UFont font set */
if ((fontP = (ufont_f)calloc(1, sizeof(struct ufont_font))) == NULL)
  return &error_memory;

if ((errorP = create_map(fontNameP, &fontP->mapP)) != NULL)
  {
  (void)xufont_lose_font(fontP);
  return errorP;
  }
if (fontP->mapP == NULL)
  {
  (void)xufont_lose_font(fontP);
  return &error_noufont;
  }

/* Find size of Fonts file :
 */
strcpy(file_name, fontNameP);
strcat(file_name, ".Fonts");
if ((errorP = xosfile_read_stamped_path(file_name, "UFont:", &objType, NULL, NULL, &size, NULL, NULL)) != NULL)
  {
  (void)xufont_lose_font(fontP);
  return errorP;
  }
if (objType != fileswitch_IS_FILE)
  {
  (void)xufont_lose_font(fontP);
  return &error_exists;
  }

if ((fonts_file = (char *)malloc(size)) == NULL)
  {
  (void)xufont_lose_font(fontP);
  return &error_memory;
  }

/* Load Fonts :
 */
if ((errorP = xosfile_load_stamped_path(file_name, fonts_file, "UFont:", NULL, NULL, NULL, NULL, NULL)) != NULL)
  {
  (void)xufont_lose_font(fontP);
  free((void *)fonts_file);
  return errorP;
  }

/* Open all fonts listed in Fonts :
 */
for (old_font = fonts_file, fontP->virtual_handles_used = 0;
     old_font - fonts_file < size;
     old_font += strlen(old_font) + 1, ++fontP->virtual_handles_used)
  {
  /* UFont can maximum have 256 real RISC OS fonts :
   */
  if (fontP->virtual_handles_used < 256)
    {
    dbg_fprintf(stderr, "%i %s: ", fontP->virtual_handles_used, old_font);
    errorP = addref_virtual_fonthandle(old_font, xsize, ysize, xres, yres, xresOutP, yresOutP, &fontP->virtual_font_index[fontP->virtual_handles_used]);
    }
  else
    errorP = &error_fnt_corrupt;

  if (errorP != NULL)
    {
    (void)xufont_lose_font(fontP);
    free((void *)fonts_file);
    return errorP;
    }

  dbg_fprintf(stderr, "%i\n", fontP->virtual_font_index[fontP->virtual_handles_used]);
  }

/* free Fonts */
free((void *)fonts_file); fonts_file = NULL;

*font = fontP;
if (xresOutP != NULL)
  *xresOutP = 96;
if (yresOutP != NULL)
  *yresOutP = 96;
return NULL;
}


/*
 *  UFont_LoseFont
 *
 *  => font handle as returned by UFont_FindFont
 *  Even if there was an error returned, we tried to delete as much
 *  as possible.  The ufont_f is definately not reusable afterwards.
 */
os_error *
xufont_lose_font(ufont_f fontP)
{
  unsigned int index;
  os_error *theErrorP;

theErrorP = (fontP->mapP != NULL) ? delete_map(fontP->mapP) : NULL;

/* Close all fonts used :
 */
for (index = 0; index < fontP->virtual_handles_used; ++index)
  {
  os_error *errorP;
  dbg_fprintf(stderr, "About to deref virtual font handle %d\n", fontP->virtual_font_index[index]);
  if ((errorP = deref_virtual_fonthandle(fontP->virtual_font_index[index])) != NULL)
    theErrorP = errorP;
  }

/* Free ufont structure :
 */
free((void *)fontP);

return theErrorP;
}


/*
 *  UFont_Paint
 *
 *  => font handle as returned by UFont_FindFont
 *     string is Unicode UTF-8 encoded
 *     other parameters as Font_Paint
 */
os_error *
xufont_paint(ufont_f fontP,
             unsigned char const *string,
             font_string_flags flags,
             int xpos,
             int ypos,
             font_paint_block const *block,
             os_trfm const *trfm,
             int length)
{
  char *result;
  os_error *error;

  if ((flags & font_GIVEN_LENGTH) == 0)
    length = INT_MAX;

  dbg_fprintf(stderr, "xufont_paint() : size %d, consider len %d\n", strlen(string), length);
  if ((error = xufont_convert(fontP, string, length, &result, NULL)) != NULL)
    return error;
  if (result[0] == '\0')
    return NULL;

  assert(result[0] == font_COMMAND_FONT);
  error = xfont_paint(result[1], &result[2],
                      (flags & (~font_GIVEN_LENGTH)) | font_GIVEN_FONT,
                      xpos, ypos, block, trfm, 0);
  return error;
}


/*
 *  UFont_ScanString
 *
 *  => font handle as returned by UFont_FindFont
 *     string is Unicode UTF-8 encoded
 *     split length is index in string, not pointer
 *     other parameters as Font_ScanString
 *
 *  <= as Font_ScanString
 */
os_error *
xufont_scan_string(ufont_f fontP,
                   unsigned char const *string,
                   font_string_flags flags,
                   int x,
                   int y,
                   font_scan_block const *block,
                   os_trfm const *trfm,
                   int length,
                   unsigned char const **split_point,
                   int *x_out,
                   int *y_out,
                   int *length_out)
{
  char *result;
  char *split_point_i;
  unsigned int *table;
  os_error *error;

  if ((flags & font_GIVEN_LENGTH) == 0)
    length = INT_MAX;

  dbg_fprintf(stderr, "xufont_scan_string() : size %d, consider len %d\n", strlen(string), length);
  if ((error = xufont_convert(fontP, string, length, &result, &table)) != NULL)
    return error;
  if (result[0] == '\0')
    {
    if (split_point != NULL)
      *split_point = string;
    if (x_out != NULL)
      *x_out = 0;
    if (y_out != NULL)
      *y_out = 0;
    if (length_out != NULL)
      *length_out = 0;
    return NULL;
    }

  assert(result[0] == font_COMMAND_FONT);
  error = xfont_scan_string(result[1], &result[2],
                            (flags & (~font_GIVEN_LENGTH)) | font_GIVEN_FONT,
                            x, y, block, trfm, 0,
                            (split_point) ? &split_point_i : NULL,
                            x_out, y_out, length_out);
  if (error != NULL)
    return error;

  if (split_point != NULL)
    {
    dbg_fprintf(stderr, "RISC OS scan string split at offset %d (char %d)\n", split_point_i - result, *split_point_i);
    *split_point = &string[table[split_point_i - result]];
    dbg_fprintf(stderr, "UTF-8 Split offset at %d (char %d)\n", *split_point - string, **split_point);
    }

  return NULL;
}


/**
 * Given a text line, return the number of bytes which can be set using
 * one RISC OS font and the bounding box fitting that part of the text
 * only.
 *
 * \param font a ufont font handle, as returned by xufont_find_font().
 * \param string string text.  Does not have to be NUL terminated.
 * \param flags FontManger flags to be used internally
 * \param length length in bytes of the text to consider.
 * \param width returned width of the text which can be set with one RISC OS font. If 0, then error happened or initial text length was 0.
 * \param rofontname returned name of the RISC OS font which can be used to set the text. If NULL, then error happened or initial text length was 0.
 * \param rotext returned string containing the characters in returned RISC OS font. Not necessary NUL terminated. free() after use.  If NULL, then error happened or initial text length was 0.
 * \param rolength length of return rotext string. If 0, then error happened or initial text length was 0.
 * \param consumed number of bytes of the given text which can be set with one RISC OS font. If 0, then error happened or initial text length was 0.
 */
os_error *xufont_txtenum(ufont_f fontP,
		unsigned char const *string,
		font_string_flags flags,
		size_t length,
		int *widthP,
		unsigned char const **rofontnameP,
		unsigned char const **rotextP,
		size_t *rolengthP,
		size_t *consumedP)
{
	char *result, *end_result;
	unsigned int *table;
	os_error *errorP;

	int width;
	const char *rofontname;
	char *rotext;
	size_t rolength;

	*rotextP = *rofontnameP = NULL;
	*consumedP = *rolengthP = *widthP = 0;

	if ((flags & font_GIVEN_LENGTH) == 0)
		length = INT_MAX;

	if (length == 0)
		return NULL;

	if ((errorP = xufont_convert(fontP, string, length, &result, &table)) != NULL)
		return errorP;
	if (result[0] == '\0')
		return NULL;
	assert(result[0] == font_COMMAND_FONT);

	/* Find how many characters starting at <result + 2> onwards
	   are set using the RISC OS font with handle <result + 1> */
	for (end_result = result + 2; *end_result != '\0' && *end_result != font_COMMAND_FONT; ++end_result)
		;

	rolength = end_result - result - 2;
	if ((errorP = xfont_scan_string(result[1], &result[2],
			flags | font_GIVEN_LENGTH | font_GIVEN_FONT,
			0x7fffffff, 0x7fffffff,
			NULL, NULL,
			rolength,
			NULL,
			&width, NULL,
			NULL)) != NULL)
		return errorP;
	if ((rofontname = get_rofontname(result[1])) == NULL)
		return &error_badrohandle;
	if ((rotext = malloc(rolength)) == NULL)
		return &error_memory;
	memcpy(rotext, result + 2, rolength);

	*widthP = width;
	*rofontnameP = rofontname;
	*rotextP = rotext;
	*rolengthP = rolength;
	*consumedP = table[end_result - result];

	return NULL;
}


/*
 *  UFont_Convert
 *
 *  => initial font
 *     UTF-8 string to convert to RISC OS font numbers and codes.
 *     max length to convert (characters) or NUL char terminated.
 *
 *  <= string converted to Font_Paint format
 *     table of offsets in UTF-8 string
 */
os_error *
xufont_convert(ufont_f fontP,
               unsigned char const *string,
               size_t length,
               char **presult, /* may not be NULL ! */
               size_t **ptable /* may be NULL */)
{
  static char *resultP;
  static size_t *tableP;
  static size_t currentSize;

  size_t max_length;
  size_t string_index, new_string_index, result_index;
  virtual_fh_t *curVirFH = NULL;

assert(presult != NULL);

do_sanity_check("xufont_convert() : begin");

/* Find upfront if we're NUL char terminated or length terminated. */
for (max_length = 0; max_length < length && string[max_length] != '\0'; ++max_length)
  /* no body */;

/* Increase timer so we can enforce a set of usage elements to remain active.
 */
++oChainTimer;

/* Ensure memory block.
 */
if (resultP == NULL)
  {
  if ((resultP = (char *)malloc(MALLOC_CHUNK)) == NULL)
    return &error_memory;
  currentSize = MALLOC_CHUNK;
  }
if (tableP == NULL && (tableP = (size_t *)malloc(MALLOC_CHUNK * sizeof(size_t))) == NULL)
  return &error_memory;

dbg_fprintf(stderr, "xufont_convert() : ");
for (string_index = 0, result_index = 0;
     string_index < max_length;
     string_index = new_string_index)
  {
    wchar_t wchar;
    int result = eat_utf8(&wchar, &string[string_index], max_length - string_index);

  if (result == 0)
    {
    /* Too few input bytes : abort conversion */
    fprintf(stderr, "eat_utf8() : too few input bytes\n");
    break;
    }
  else if (result < 0)
    {
    /* Corrupt UTF-8 stream : skip <-result> input characters. */
    fprintf(stderr, "eat_utf8() : error %d\n", result);
fprintf(stderr, "String <%.*s> error pos %d\n", length, string, string_index);
    wchar = '?';
    new_string_index = string_index - result;
    }
  else
    {
    /* Normal case : one wchar_t produced, <result> bytes consumed. */
    if (wchar >= 0x10000)
      wchar = '?';
    new_string_index = string_index + result;
    }

  dbg_fprintf(stderr, "src offset 0x%x : 0x%x ", string_index, wchar);

  /* Reserve room for at least 32 more entries.
   */
  if (result_index + 32 > currentSize)
    {
    if ((resultP = realloc(resultP, currentSize*2)) == NULL
        || (tableP = realloc(tableP, currentSize*2 * sizeof(size_t))) == NULL)
      return &error_memory;

    currentSize *= 2;
    }

    {
      const byte fontnr = fontP->mapP->fontnr[wchar];
      virtual_fh_t *virFHP;
      usage_chain_t *usageP;

    assert(fontnr < fontP->virtual_handles_used);
    virFHP = &oVirtualFHArrayP[fontP->virtual_font_index[fontnr]];

    /* Check if current font is ok :
     */
    if (virFHP != curVirFH)
      {
        os_error *errorP;

      curVirFH = virFHP;

      /* Make sure we have a RISC OS font handle associated :
       */
      if ((errorP = activate_virtual_fh(virFHP)) != NULL)
        return errorP;
      usageP = virFHP->usageP;
      assert(usageP != NULL);
      assert(usageP->ro_fhandle != 0);
      tableP[result_index] = tableP[result_index + 1] = string_index;
      resultP[result_index++] = font_COMMAND_FONT;
      resultP[result_index++] = usageP->ro_fhandle;

      dbg_fprintf(stderr, "{%i} ", resultP[result_index - 1]);
      }
    else
      {
      usageP = virFHP->usageP;
      assert(usageP != NULL);
      }

    ++virFHP->usage;
    /* By increasing the usage counter, it might that the oUsageChain needs
     * reordering.
     */
    if (usageP != oUsageChain.nextP && virFHP->usage > usageP->prevP->virFHP->usage)
      repos_usage_chain_elem(usageP);

    tableP[result_index] = string_index;
    resultP[result_index++] = fontP->mapP->character[wchar];
    dbg_fprintf(stderr, "[0x%x] ", resultP[result_index - 1]);
    }
  }
resultP[result_index] = 0;
*presult = resultP;

tableP[result_index] = string_index;
if (ptable != NULL)
  *ptable = tableP;

#ifdef DEBUG_UFONT
fprintf(stderr, "\nRISC OS font string result:\n");

for (result_index = 0; resultP[result_index] != 0; ++result_index)
  fprintf(stderr, "  Dst offset %d : 0x%x (src offset %d)\n", result_index, resultP[result_index], tableP[result_index]);
#endif

do_sanity_check("xufont_convert() : end");

dbg_fprintf(stderr, "--- After convert()\n");
//dump_internals();

return NULL;
}


/* Creates or reuses an existing ufont_map_t
 */
static os_error *create_map(const char *uFontNameP, const ufont_map_t **mapPP)
{
  ufont_map_t *curMapP;
  size_t uFontNameLen = strlen(uFontNameP);
  char *fileNameP;
  os_error *errorP;

/* Make sure we never return garbage results.
 */
*mapPP = NULL;

if ((fileNameP = (char *)alloca(uFontNameLen + sizeof(".Data"))) == NULL)
  return &error_memory;
memcpy(fileNameP, uFontNameP, uFontNameLen);
do {
    fileswitch_object_type objType;
    int size;

  memcpy(&fileNameP[uFontNameLen], ".Data", sizeof(".Data"));
  if ((errorP = xosfile_read_stamped_path(fileNameP, "UFont:", &objType, NULL, NULL, &size, NULL, NULL)) != NULL)
    return errorP;

  if (objType == fileswitch_NOT_FOUND)
    {
    /* Look for the Data file one directory level up. */
    while (uFontNameLen != 0 && fileNameP[--uFontNameLen] != '.')
      /* no body */;
    if (uFontNameLen == 0)
      return &error_exists;
    }
  else if (objType == fileswitch_IS_FILE)
    {
    if (size != 2*65536)
      return &error_size;
    break;
    }
  else
     return &error_exists;
  } while (1);

/* Try to reuse an existing map :
 */
for (curMapP = oMapCollectionP; curMapP != NULL; curMapP = curMapP->nextP)
  {
    size_t curUFontNameLen = strlen(curMapP->uFontNameP);

  if (uFontNameLen != curUFontNameLen)
    continue;

  if (memcmp(fileNameP, curMapP->uFontNameP, curUFontNameLen) != 0)
    break;
  }
if (curMapP != NULL)
  {
  ++curMapP->refCount;
  *mapPP = curMapP;
  return NULL;
  }

/* We need to create & load new map into memory :
 */
if ((curMapP = (ufont_map_t *)malloc(sizeof(ufont_map_t))) == NULL)
  return &error_memory;

/* Load Data file :
 */
if ((errorP = xosfile_load_stamped_path(fileNameP, (byte *)&curMapP->fontnr[0], "UFont:", NULL, NULL, NULL, NULL, NULL)) != NULL)
  {
  free((void *)curMapP);
  return errorP;
  }
fileNameP[uFontNameLen] = '\0';
if ((curMapP->uFontNameP = strdup(fileNameP)) == NULL)
  {
  free((void *)curMapP);
  return &error_memory;
  }
curMapP->refCount = 1;
curMapP->nextP = oMapCollectionP;
oMapCollectionP = curMapP;

*mapPP = curMapP;
return NULL;
}


static os_error *delete_map(ufont_map_t *mapP)
{
assert(mapP->refCount > 0);
--mapP->refCount;
/** \todo: we don't remove the map from the oMapCollection list.  Should we ?
 */

return NULL;
}


/**
 * Convert next sequence of UTF-8 bytes into wchar_t
 *
 * \param pwc resulting wchar_t result.
 * \param s ptr to UTF-8 encoded string
 * \param n maximum of bytes which can be consumed via s
 * \return
 *   x > 0: number of bytes consumed at s, valid wchar_t returned at pwc[0]
 *   x = 0: too few input bytes, pwc[0] is undefined
 *   x < 0: illegal UTF-8 stream, skip -x characters at s, pwc[0] is undefined
 */
static int eat_utf8(wchar_t *pwc, const byte *s, int n)
{
	byte c;
	int i;

	if (n < 1)
		return 0; /* not enough input bytes */
	else if ((c = s[0]) < 0x80) {
		*pwc = c;
		return 1;
	} else if (c < 0xc2)
		goto do_sync;
	else if (c < 0xe0) {
		if (n < 2)
			return 0; /* not enough input bytes */
		if (!((s[1] ^ 0x80) < 0x40))
			goto do_sync;
		*pwc = ((wchar_t) (c & 0x1f) << 6) | (wchar_t) (s[1] ^ 0x80);
		return 2;
	} else if (c < 0xf0) {
		if (n < 3)
			return 0; /* not enough input bytes */
		if (!((s[1] ^ 0x80) < 0x40 && (s[2] ^ 0x80) < 0x40 && (c >= 0xe1 || s[1] >= 0xa0)))
			goto do_sync;
		*pwc = ((wchar_t) (c & 0x0f) << 12) | ((wchar_t) (s[1] ^ 0x80) << 6) | (wchar_t) (s[2] ^ 0x80);
		return 3;
	} else if (c < 0xf8) {
		if (n < 4)
			return 0; /* not enough input bytes */
		if (!((s[1] ^ 0x80) < 0x40 && (s[2] ^ 0x80) < 0x40 && (s[3] ^ 0x80) < 0x40 && (c >= 0xf1 || s[1] >= 0x90)))
			goto do_sync;
		*pwc = ((wchar_t) (c & 0x07) << 18) | ((wchar_t) (s[1] ^ 0x80) << 12) | ((wchar_t) (s[2] ^ 0x80) << 6) | (wchar_t) (s[3] ^ 0x80);
		return 4;
	} else if (c < 0xfc) {
		if (n < 5)
			return 0; /* not enough input bytes */
		if (!((s[1] ^ 0x80) < 0x40 && (s[2] ^ 0x80) < 0x40 && (s[3] ^ 0x80) < 0x40 && (s[4] ^ 0x80) < 0x40 && (c >= 0xf9 || s[1] >= 0x88)))
			goto do_sync;
		*pwc = ((wchar_t) (c & 0x03) << 24) | ((wchar_t) (s[1] ^ 0x80) << 18) | ((wchar_t) (s[2] ^ 0x80) << 12) | ((wchar_t) (s[3] ^ 0x80) << 6) | (wchar_t) (s[4] ^ 0x80);
		return 5;
	} else if (c < 0xfe) {
		if (n < 6)
			return 0; /* not enough input bytes */
		if (!((s[1] ^ 0x80) < 0x40 && (s[2] ^ 0x80) < 0x40 && (s[3] ^ 0x80) < 0x40 && (s[4] ^ 0x80) < 0x40 && (s[5] ^ 0x80) < 0x40 && (c >= 0xfd || s[1] >= 0x84)))
			goto do_sync;
		*pwc = ((wchar_t) (c & 0x01) << 30) | ((wchar_t) (s[1] ^ 0x80) << 24) | ((wchar_t) (s[2] ^ 0x80) << 18) | ((wchar_t) (s[3] ^ 0x80) << 12) | ((wchar_t) (s[4] ^ 0x80) << 6) | (wchar_t) (s[5] ^ 0x80);
		return 6;
	}

do_sync:
	/* The UTF-8 sequence at s is illegal, skipping from s onwards
	 * until first non top character is found or %11xxxxxx is found
	 * (both valid UTF-8 *starts* - not necessary valid sequences).
	 */
	for (i = 1; i < n && !((s[i] & 0x80) == 0x00 || (s[i] & 0xC0) == 0xC0); ++i)
		/* no body */;
	return -i;
}


/**
 * Adds the RISC OS font <fontNameP> to the oVirtualFHArrayP list and
 * returns the index in that array.
 * oVirtualFHArrayP can be reallocated (and all virFHP ptrs in oUsageChain).
 * Results in xresOutP and yresOutP are not always that meaningful because
 * of the delayed-loading of the real RISC OS font data.
 * xresOutP and/or yresOutP may be NULL.
 */
static os_error *addref_virtual_fonthandle(const char *fontNameP, int xsize, int ysize, int xres, int yres, int *xresOutP, int *yresOutP, size_t *offsetP)
{
	size_t curIndex;
	virtual_fh_t *unusedSlotP;

	assert(offsetP != NULL);

	do_sanity_check("addref_virtual_fonthandle() : begin");

	if (oVirtualFHArrayP == NULL) {
		if ((oVirtualFHArrayP = (virtual_fh_t *)calloc(kInitialFHArraySize, sizeof(virtual_fh_t))) == NULL)
			return &error_memory;
		/* oCurVirtualFHArrayElems = 0; Isn't really necessary because of static */
		oMaxVirtualFHArrayElems = kInitialFHArraySize;
	}

	/* Check for duplicate (and find first unused slot if any) :
	 */
	for (unusedSlotP = NULL, curIndex = 0;
	     curIndex < oCurVirtualFHArrayElems;
	     ++curIndex) {
		virtual_fh_t *virFHP = &oVirtualFHArrayP[curIndex];

		if (virFHP->fontNameP != NULL /* case strdup(fontNameP) failed */
		    && stricmp(virFHP->fontNameP, fontNameP) == 0
		    && virFHP->xsize == xsize && virFHP->ysize == ysize) {
			if (xresOutP != NULL)
				*xresOutP = virFHP->xres;
			if (yresOutP != NULL)
				*yresOutP = virFHP->yres;
			++virFHP->refCount;
			*offsetP = curIndex;
			do_sanity_check("addref_virtual_fonthandle() : case 1");
			return NULL;
			}

		if (virFHP->refCount == 0 && unusedSlotP == NULL)
			unusedSlotP = virFHP;
		}

	/* Can we reuse a slot ?
	 * I.e. a virtual FH which refCount is zero.
	 */
	if (unusedSlotP != NULL) {
		if (unusedSlotP->usageP != NULL) {
			os_error *errorP;

			/* This slot is refered in the usage chain, we have to unlink it.
			 */
			if ((errorP = remove_usage_chain_elem(unusedSlotP->usageP)) != NULL)
				return errorP;
			}

		unusedSlotP->usage = 0;
		if (unusedSlotP->fontNameP != NULL)
			free((void *)unusedSlotP->fontNameP);
		if ((unusedSlotP->fontNameP = strdup(fontNameP)) == NULL)
			return &error_memory;

		unusedSlotP->xsize = xsize;
		unusedSlotP->ysize = ysize;
		unusedSlotP->xres = (xres > 1) ? xres : 96;
		if (xresOutP != NULL)
			*xresOutP = unusedSlotP->xres;
		unusedSlotP->yres = (yres > 1) ? yres : 96;
		if (yresOutP != NULL)
			*yresOutP = unusedSlotP->yres;
		unusedSlotP->refCount = 1;
		*offsetP = unusedSlotP - oVirtualFHArrayP;
		do_sanity_check("addref_virtual_fonthandle() : case 2");
		return NULL;
		}

	/* Add new entry :
	 */
	if (oCurVirtualFHArrayElems == oMaxVirtualFHArrayElems) {
		virtual_fh_t *newVirtualFHArrayP;
		size_t extraOffset;
		usage_chain_t *usageP;

		/* Don't use realloc() as when that fails, we don't even have the original
		 * memory block anymore.
		 */
		if ((newVirtualFHArrayP = (virtual_fh_t *)calloc(2*oMaxVirtualFHArrayElems, sizeof(virtual_fh_t))) == NULL)
			return &error_memory;
		memcpy(newVirtualFHArrayP, oVirtualFHArrayP, oMaxVirtualFHArrayElems * sizeof(virtual_fh_t));
		free((void *)oVirtualFHArrayP);
		extraOffset = (const char *)newVirtualFHArrayP - (const char *)oVirtualFHArrayP;
		oVirtualFHArrayP = newVirtualFHArrayP;
		oMaxVirtualFHArrayElems *= 2;

		/* Update the virFHP pointers in the usage chain :
		 */
		if (oUsageChain.nextP != NULL) {
			for (usageP = oUsageChain.nextP; usageP != &oUsageChain; usageP = usageP->nextP)
				usageP->virFHP = (virtual_fh_t *)&((char *)usageP->virFHP)[extraOffset];
		}
	}

	unusedSlotP = &oVirtualFHArrayP[oCurVirtualFHArrayElems];
	if ((unusedSlotP->fontNameP = (const char *)strdup(fontNameP)) == NULL)
		return &error_memory;
	unusedSlotP->xsize = xsize;
	unusedSlotP->ysize = ysize;
	unusedSlotP->xres = (xres > 1) ? xres : 96;
	if (xresOutP != NULL)
		*xresOutP = unusedSlotP->xres;
	unusedSlotP->yres = (yres > 1) ? yres : 96;
	if (yresOutP != NULL)
		*yresOutP = unusedSlotP->yres;
	unusedSlotP->refCount = 1;
	*offsetP = oCurVirtualFHArrayElems++;

	do_sanity_check("addref_virtual_fonthandle() : case 3");
	return NULL;
}


/**
 * Deref virtual_fh_t element in oVirtualFHArrayP array.
 */
static os_error *deref_virtual_fonthandle(size_t offset)
{
	assert(/* offset >= 0 && */ offset < oCurVirtualFHArrayElems);
	assert(oVirtualFHArrayP[offset].refCount > 0);

	/* When the refCount reaches 0, it will be reused by preference when a
	 * new usageChain element is needed in addref_virtual_fonthandle().
	 */
	--oVirtualFHArrayP[offset].refCount;

	do_sanity_check("deref_virtual_fonthandle()");
	return NULL;
}


/**
 * Virtual font handle <virFHP> needs to have a RISC OS font handle
 * associated via virFHP->usageP.  For this we can throw out all other
 * usage chain elements which have a chainTimer different from oChainTimer.
 * However, we may not have more than kMaxUsageChainElems chain elements
 * active.
 * Afterwards: either an error, either virFHP->usageP points to an usage chain
 * element in the oUsageChain linked list and that usage chain element has
 * a valid RISC OS font handle associated.
 */
static os_error *activate_virtual_fh(virtual_fh_t *virFHP)
{
	usage_chain_t *usageP;

	dbg_fprintf(stderr, "+++ activate_virtual_fh(virFHP %p, usageP ? %p)\n", virFHP, virFHP->usageP);
	do_sanity_check("activate_virtual_fh() : begin");

	/* The easiest case : we already have a RISC OS font handle :
	 */
	if ((usageP = virFHP->usageP) != NULL) {
		usageP->chainTimer = oChainTimer;
		assert(usageP->ro_fhandle != 0);
		assert(usageP->virFHP == virFHP);
		do_sanity_check("activate_virtual_fh() : case 1");
		dbg_fprintf(stderr, "--- done, activate_virtual_fh(), case 1\n");
		return NULL;
		}

	/* The second easiest case : we're still allowed to create an extra
	 * chain element :
	 */
	if (oCurUsageChainElems < kMaxUsageChainElems) {
		os_error *errorP;

		if ((usageP = (usage_chain_t *)malloc(sizeof(usage_chain_t))) == NULL)
			return &error_memory;
		usageP->chainTimer = oChainTimer;

		if ((errorP = xfont_find_font(virFHP->fontNameP,
		                              virFHP->xsize, virFHP->ysize,
		                              virFHP->xres, virFHP->yres,
		                              &usageP->ro_fhandle,
		                              &virFHP->xres, &virFHP->yres)) != NULL) {
			free((void *)usageP);
			return errorP;
			}
		usageP->virFHP = virFHP;
		virFHP->usageP = usageP;
		++oCurUsageChainElems;

		/* Make sure oUsageChain nextP and prevP point to at least something (is
		 * only executed once and should probably better be done in a global
		 * init routine).
		 */
		if (oUsageChain.nextP == NULL)
			oUsageChain.nextP = oUsageChain.prevP = &oUsageChain;
		}
	else {
		os_error *errorP;

		/* The more difficult one : we need to reuse a usage chain element.
		 * Take the last one because that is least used but skip the onces
		 * with chainTimer equal to the current oChainTimer because those
		 * RISC OS font handles are still used in the font string we're
		 * currently processing.
		 */
		for (usageP = oUsageChain.prevP;
		     usageP != &oUsageChain && usageP->chainTimer == oChainTimer;
		     usageP = usageP->prevP)
		  /* no body */;
		if (usageP == &oUsageChain) {
			/* Painful : all usage chain elements are in use and we already have the
			 * maximum of chain elements reached.
			 */
			return &error_toomany_handles;
			}

		usageP->chainTimer = oChainTimer;
		/* The virtual font handle currently in usageP->virFHP no longer has a real
		 * RISC OS font handle anymore.
		 */
		usageP->virFHP->usageP = NULL;
		if ((errorP = xfont_lose_font(usageP->ro_fhandle)) != NULL)
			return errorP;
		if ((errorP = xfont_find_font(virFHP->fontNameP,
		                              virFHP->xsize, virFHP->ysize,
		                              virFHP->xres, virFHP->yres,
		                              &usageP->ro_fhandle,
		                              &virFHP->xres, &virFHP->yres)) != NULL)
			return errorP;
		usageP->virFHP = virFHP;
		virFHP->usageP = usageP;

		/* Delink :
		 */
		usageP->prevP->nextP = usageP->nextP;
		usageP->nextP->prevP = usageP->prevP;
		}

	/* Link usageP in the oUsageChain based on its current virFHP->usage value :
	 */
		{
		const unsigned int usage = virFHP->usage;
		usage_chain_t *runUsageP;

		for (runUsageP = &oUsageChain;
		     runUsageP != oUsageChain.nextP && runUsageP->prevP->virFHP->usage <= usage;
		     runUsageP = runUsageP->prevP)
			/* no body */;

		/* We have to link usageP between runUsageP and runUsageP->prevP
		 * because runUsageP->prevP has higher usage than the one we need to
		 * link in -or- we're at the end/start.
		 */
		usageP->nextP = runUsageP;
		usageP->prevP = runUsageP->prevP;
		runUsageP->prevP->nextP = usageP;
		runUsageP->prevP = usageP;
		}
	do_sanity_check("activate_virtual_fh() : case 2");
	dbg_fprintf(stderr, "--- done, activate_virtual_fh(), case 2\n");

	return NULL;
}


/**
 * Remove the usage_chaint_t element from the usage chain
 */
static os_error *remove_usage_chain_elem(usage_chain_t *usageP)
{
	os_error *errorP;

	assert(usageP != NULL);
	assert(oCurUsageChainElems > 0);
	assert(usageP->ro_fhandle != 0);
	assert(usageP->virFHP != NULL);

	if ((errorP = xfont_lose_font(usageP->ro_fhandle)) != NULL)
		return errorP;

	usageP->virFHP->usageP = NULL;

	/* Delink it :
	 */
	usageP->prevP->nextP = usageP->nextP;
	usageP->nextP->prevP = usageP->prevP;

	--oCurUsageChainElems;
	free((void *)usageP);

	do_sanity_check("remove_usage_chain_elem() : end");
	return NULL;
}


/***
 * Should be called when the usage_chain_t element is no longer in the right
 * place in the chain based on its virFHP->usage value.
 *
 * usageP is no longer in the right place in the chain because its
 * ->virFHP->usage value increased.  Reposition it towards prev
 * direction.
 */
static void repos_usage_chain_elem(usage_chain_t *usageP)
{
	usage_chain_t *prev1P, *prev2P;
	const unsigned int curUsage = usageP->virFHP->usage;

	dbg_fprintf(stderr, "+++ repos_usage_chain_elem(%p)\n", usageP);

	/* If this assert goes off, then it means that this routine shouldn't
	 * have been called.
	 */
	assert(curUsage > usageP->prevP->virFHP->usage);

	/* Delink :
	 */
	usageP->prevP->nextP = usageP->nextP;
	usageP->nextP->prevP = usageP->prevP;

	/* Place usageElemP between prev1P and prev2P.
	 */
	for (prev1P = usageP->prevP, prev2P = prev1P->prevP;
	     prev2P != &oUsageChain && curUsage > prev2P->virFHP->usage;
	     prev1P = prev2P, prev2P = prev2P->prevP) {
		dbg_fprintf(stderr, "> prev1P %p (%d), usageElemP %p (%d), prev2P %p (%d), dummy %p\n", prev1P, prev1P->virFHP->usage, usageP, usageP->virFHP->usage, prev2P, prev2P->virFHP->usage, &oUsageChain);
		assert(prev1P->virFHP->usage <= prev2P->virFHP->usage);
		}

	dbg_fprintf(stderr, "prev1P %p (%d), usageElemP %p (%d), prev2P %p (%d), dummy %p\n", prev1P, prev1P->virFHP->usage, usageP, usageP->virFHP->usage, prev2P, prev2P->virFHP->usage, &oUsageChain);

	/* Relink between prev1P and prev2P :
	 */
	prev1P->prevP = usageP;
	usageP->prevP = prev2P;
	prev2P->nextP = usageP;
	usageP->nextP = prev1P;

	do_sanity_check("repos_usage_chain_elem() : end");
	dbg_fprintf(stderr, "--- done, repos_usage_chain_elem()\n");
}


/**
 * Retrieves the RISC OS font name of given RISC OS fonthandle.
 *
 * \param rofhandle RISC OS font handle
 */
static const char *get_rofontname(font_f rofhandle)
{
	usage_chain_t *usageP;

	if (oUsageChain.nextP == NULL)
		return NULL;

	for (usageP = oUsageChain.nextP; usageP != &oUsageChain; usageP = usageP->nextP)
		if (usageP->ro_fhandle == rofhandle)
			return usageP->virFHP->fontNameP;

	return NULL;
}


#ifdef DEBUG_DUMP_INTERNALS
/**
 * Prints to stderr the complete internal state of UFont.
 */
static void dump_internals(void)
{
	fprintf(stderr, "Dump UFont internals:\n  - Virtual font handle array at %p (length %d, max length %d)\n  - Usage chain elements %d\n  - Chain timer is %d\n  Dump usage chain (first dummy at %p):\n", oVirtualFHArrayP, oCurVirtualFHArrayElems, oMaxVirtualFHArrayElems, oCurUsageChainElems, oChainTimer, &oUsageChain);
	if (oUsageChain.prevP == NULL || oUsageChain.nextP == NULL) {
		fprintf(stderr, "  Empty usage chain\n");
		if (oUsageChain.prevP != oUsageChain.nextP)
			fprintf(stderr, "  *** Corrupted empty usage chain: next %p, prev %p\n", oUsageChain.nextP, oUsageChain.prevP);
		if (oCurUsageChainElems != 0)
			fprintf(stderr, "  *** Current usage chain length is wrong\n");
		}
	else {
		size_t usageCount;
		const usage_chain_t *usageP;

		for (usageCount = 0, usageP = oUsageChain.nextP; usageP != &oUsageChain; ++usageCount, usageP = usageP->nextP) {
			fprintf(stderr, "  -%d- : cur %p, next %p, prev %p, timer %d, RISC OS font handle %d, virtual font %p (%d, %s), usage %d\n", usageCount, usageP, usageP->nextP, usageP->prevP, usageP->chainTimer, usageP->ro_fhandle, usageP->virFHP, usageP->virFHP - oVirtualFHArrayP, usageP->virFHP->fontNameP, usageP->virFHP->usage);
			if (usageP->nextP->prevP != usageP)
				fprintf(stderr, "  *** Bad usageP->nextP->prevP != usageP\n");
			if (usageP->prevP->nextP != usageP)
				fprintf(stderr, "  *** Bad usageP->prevP->nextP != usageP\n");
			if (usageP->virFHP < oVirtualFHArrayP || usageP->virFHP >= &oVirtualFHArrayP[oCurVirtualFHArrayElems])
				fprintf(stderr, "  *** Bad virtual font handle\n");
			}
		if (usageCount != oCurUsageChainElems)
			fprintf(stderr, "  *** Current usage chain length is wrong\n");
		if (usageCount > kMaxUsageChainElems)
			fprintf(stderr, "  *** Current usage chain is too long\n");
	}

	if (oVirtualFHArrayP != NULL) {
		size_t fhIndex;

		fprintf(stderr, "  Dump virtual font handles:\n");
		for (fhIndex = 0; fhIndex < oCurVirtualFHArrayElems; ++fhIndex) {
			const virtual_fh_t *virFHP = &oVirtualFHArrayP[fhIndex];

			fprintf(stderr, "  -%d (%p)- : <%s>, size %d,%d, res %d,%d, usage %d, ref count %d, usage chain ptr %p\n", fhIndex, virFHP, virFHP->fontNameP, virFHP->xsize, virFHP->ysize, virFHP->xres, virFHP->yres, virFHP->usage, virFHP->refCount, virFHP->usageP);
			if (virFHP->usageP != NULL) {
				const usage_chain_t *usageP;

				for (usageP = oUsageChain.nextP;
				     usageP != virFHP->usageP && usageP != &oUsageChain;
				     usageP = usageP->nextP)
				  /* no body */;
				if (usageP != virFHP->usageP)
					fprintf(stderr, "  *** Usage chain ptr could not be found in usage chain\n");
			}
		}
	}
}
#endif


/**
 * Does do a full sanity check of UFont internal datastructures.
 * Will assert() when something odd if found.
 */
static int sanity_check(const char *testMsgP)
{
	dbg_fprintf(stderr, "Sanity check <%s>\n", testMsgP);
	if (oUsageChain.prevP == NULL || oUsageChain.nextP == NULL) {
		assert(oUsageChain.prevP == oUsageChain.nextP);
		assert(oCurUsageChainElems == 0);
		}
	else {
		 size_t usageCount;
		 const usage_chain_t *usageP;

		/* We should see equal or decreasing usage values.
		 */
		for (usageCount = 0, usageP = oUsageChain.nextP; usageP != &oUsageChain; ++usageCount, usageP = usageP->nextP) {
			assert(usageP->nextP->prevP == usageP);
			assert(usageP->prevP->nextP == usageP);
			assert(usageP->chainTimer <= oChainTimer);
			assert(usageP->ro_fhandle != 0);
			assert(oVirtualFHArrayP != NULL);
			assert(usageP->virFHP >= oVirtualFHArrayP && usageP->virFHP < &oVirtualFHArrayP[oCurVirtualFHArrayElems]);
			assert(usageP->virFHP->usageP == usageP);
			assert(usageP == oUsageChain.prevP || usageP->virFHP->usage >= usageP->nextP->virFHP->usage);
			}
		assert(usageCount == oCurUsageChainElems);
		assert(usageCount <= kMaxUsageChainElems);
		}

	if (oVirtualFHArrayP != NULL) {
		size_t fhIndex;

		for (fhIndex = 0; fhIndex < oCurVirtualFHArrayElems; ++fhIndex) {
			const virtual_fh_t *virFHP = &oVirtualFHArrayP[fhIndex];

			if (virFHP->usageP != NULL) {
				const usage_chain_t *usageP;

				assert(virFHP->fontNameP != NULL);
				assert(virFHP->xsize > 0 && virFHP->ysize > 0);
				assert(virFHP->xres > 0 && virFHP->yres > 0);
				for (usageP = oUsageChain.nextP;
				     usageP != virFHP->usageP && usageP != &oUsageChain;
				     usageP = usageP->nextP)
					/* no body */;
				assert(usageP == virFHP->usageP);
				}
			}
		}

	return 0;
}