about summary refs log tree commit diff
path: root/converter/other/svgtopam.c
blob: 060d8cde063b3ead20d06d8c8f34bef3a24c077e (plain) (blame)
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
/*============================================================================
                               svgtopam
==============================================================================
  This is not useful today.  It is merely a stub from which someone who
  cares about SVG can build a full converter.

  The framework is all there; it should be just a matter of coding to
  add each of the SVG features to it.

  Today, the program works fine on an image that consists solely of
  <path> elements, which use only the "M", "L", and "z" commands.

  By Bryan Henderson, San Jose, California.  May 2006

  Contributed to the public domain.

==============================================================================

  Implementation notes:

   A look at Libxml2 Subversion source code change history says the type
   'xmlReaderTypes' was added (in <libxml/xmlreader.h>) in 2.5.9.  But a MacOS
   10.3.9 user reports in April 2007 that he has 2.6.16 installed and it
   doesn't have xmlReaderTypes.  Another MacOS user reported that in December
   2008.  Apparently that OS has a broken libxml2 installation.

============================================================================*/

#define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
#define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
#define _BSD_SOURCE  /* Make sure strdup() is in <string.h> */
#define _POSIX_SOURCE   /* Make sure fileno() is in <stdio.h> */
#include <assert.h>
#include <string.h>
#include <stdio.h>

#include <libxml/xmlreader.h>

#include "pm_c_util.h"
#include "mallocvar.h"
#include "nstring.h"
#include "shhopt.h"
#include "pam.h"
#include "ppm.h"
#include "ppmdraw.h"


static bool traceDraw;

struct cmdlineInfo {
    const char * inputFileName;
    unsigned int trace;
};



static void
parseCommandLine(int argc,
                 char ** argv,
                 struct cmdlineInfo  * const cmdlineP) {
/* --------------------------------------------------------------------------
   Parse program command line described in Unix standard form by argc
   and argv.  Return the information in the options as *cmdlineP.

   If command line is internally inconsistent (invalid options, etc.),
   issue error message to stderr and abort program.

   Note that the strings we return are stored in the storage that
   was passed to us as the argv array.  We also trash *argv.
--------------------------------------------------------------------------*/
    optEntry *option_def;
        /* Instructions to pm_optParseOptions3 on how to parse our options. */
    optStruct3 opt;

    unsigned int option_def_index;

    MALLOCARRAY_NOFAIL(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENT3 */
    OPTENT3(0, "trace",     OPT_FLAG,   NULL,
            &cmdlineP->trace,       0);

    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = FALSE;   /* We have no parms that are negative numbers */

    pm_optParseOptions3( &argc, argv, opt, sizeof(opt), 0 );
    /* Uses and sets argc, argv, and some of *cmdlineP and others. */

    if (argc-1 < 1)
        cmdlineP->inputFileName = "-";
    else {
        cmdlineP->inputFileName = argv[1];

        if (argc-1 > 1)
            pm_error("Too many arguments (%u).  The only non-option argument "
                     "is the input file name.", argc-1);
    }
}



/*============================================================================
   Wrappers for libxml2 routines.

   The difference is that these use conventional C data types, have shorter
   names, and abort the program instead of returning a special value when they
   fail.
=============================================================================*/

static const char *
getAttribute(xmlTextReaderPtr const xmlReaderP,
             const char *     const attributeName) {

    const char * const rc = (const char *)
        xmlTextReaderGetAttribute(xmlReaderP, (const xmlChar *)attributeName);

    if (rc == NULL)
        pm_error("xmlTextReaderGetAttribute(\"%.256s\") failed.  ",
                 attributeName);

    return rc;
}



static const char *
currentNodeName(xmlTextReaderPtr const xmlReaderP) {

    const char * const rc = (const char *)
        xmlTextReaderConstName(xmlReaderP);

    if (rc == NULL)
        pm_error("xmlTextReaderConstName() failed.  ");

    return rc;
}



/*===========================================================================*/

#define OUTPUT_MAXVAL 255

typedef struct {
    unsigned int width;
    unsigned int height;
    pixel ** pixels;
    pixval maxval;
} Canvas;

typedef struct {
    pixel fillColor;
} Style;



typedef struct {
    const char * pathText;
        /* This is e.g. "M0 0 L1 1 L9 8 Z" */
    Style        style;
        /* This is the style as given by a 'style' attribute of <path> */
    unsigned int pathTextLength;
        /* This is the length in characters of 'pathText'.  It's redundant
           with 'pathText' and exists for convenience.
        */
} Path;

static void
createPath(const char * const pathText,
           Style        const style,
           Path **      const pathPP) {
/*----------------------------------------------------------------------------
   Create a path as described by a <path> element whose "style" attribute
   indicates style 'style' and whose "d" attribute indicates path data
   'pathText'.
-----------------------------------------------------------------------------*/
    bool error;
    Path * pathP;

    MALLOCVAR(pathP);
    if (pathP == NULL)
        error = TRUE;
    else {
        pathP->style = style;

        pathP->pathText = strdup(pathText);
        if (pathP->pathText == NULL)
            error = TRUE;
        else {
            pathP->pathTextLength = strlen(pathP->pathText);

            error = FALSE;
        }
        if (error)
            free(pathP);
    }
    if (error )
        *pathPP = NULL;
    else
        *pathPP = pathP;
}



static void
destroyPath(Path * const pathP) {

    assert(pathP->pathTextLength == strlen(pathP->pathText));

    pm_strfree(pathP->pathText);

    free(pathP);
}



typedef struct {
    unsigned int x;
    unsigned int y;
} Point;

static Point
makePoint(unsigned int const x,
          unsigned int const y) {

    Point p;

    p.x = x;
    p.y = y;

    return p;
}



static ppmd_point
makePpmdPoint(Point const arg) {

    ppmd_point p;

    p.x = arg.x;
    p.y = arg.y;

    return p;
}



typedef enum {
    PATH_MOVETO,
    PATH_LINETO,
    PATH_CLOSEPATH,
    PATH_CUBIC
} PathCommandVerb;

typedef struct {
    Point dest;
} PathMovetoArgs;

typedef struct {
    /* Draw a line segment from current point to 'dest' */
    Point dest;
} PathLinetoArgs;

typedef struct {
    /* Draw a cubic spline from current point to 'dest' with control points
       'ctl1' at the beginning of the curve and 'ctl2' at the end.

       I.e. it's a section of a cubic curve which passes through the
       current point and 'dest' and whose slope at the current point
       is that of the line through the current point and 'ctl1' and
       whose slope at 'dest' is that of the line through 'dest' and
       'ctl2';

       A cubic curve is a plot of a polynomial equation of degree 3
       (or less, for our purposes).
    */
    Point dest;
    Point ctl1;
    Point ctl2;
} PathCubicArgs;

typedef struct {
    PathCommandVerb verb;
    union {
        PathMovetoArgs moveto;
        PathLinetoArgs lineto;
        PathCubicArgs  cubic;
    } args;
} PathCommand;



typedef struct {
/*----------------------------------------------------------------------------
   This is an object for reading through a path from beginning to end.
-----------------------------------------------------------------------------*/
    Path *       pathP;
    unsigned int cursor;
} PathReader;

static void
pathReader_create(Path *        const pathP,
                  PathReader ** const pathReaderPP) {

    PathReader * pathReaderP;

    MALLOCVAR_NOFAIL(pathReaderP);

    pathReaderP->pathP = pathP;
    pathReaderP->cursor = 0;

    *pathReaderPP = pathReaderP;
}



static void
pathReader_destroy(PathReader * const pathReaderP) {
    free(pathReaderP);
}



static const char *
pathReader_context(PathReader * const pathReaderP) {

    const char * retval;

    pm_asprintf(&retval, "Character position %u (starting at 0) in '%s'",
                pathReaderP->cursor, pathReaderP->pathP->pathText);

    return retval;
}



static void
pathReader_skipWhiteSpace(PathReader * const pathReaderP) {
/*----------------------------------------------------------------------------
   Move the cursor over any white space where it now points.
-----------------------------------------------------------------------------*/
    const Path * const pathP = pathReaderP->pathP;

    while (isspace(pathP->pathText[pathReaderP->cursor]) &&
           pathReaderP->cursor < pathP->pathTextLength)
        ++pathReaderP->cursor;
}



static void
pathReader_getNumber(PathReader *   const pathReaderP,
                     unsigned int * const numberP) {

    const Path * const pathP          = pathReaderP->pathP;
    const char * const pathText       = pathP->pathText;
    size_t       const pathTextLength = pathP->pathTextLength;

    assert(!isspace(pathText[pathReaderP->cursor]));

    if (pathReaderP->cursor >= pathTextLength)
        pm_error("Path description ends where a number was expected.");
    else if (!isdigit(pathText[pathReaderP->cursor])) {
        pm_error("Character '%c' instead of a digit where number expected",
                 pathText[pathReaderP->cursor]);
    } else {
        unsigned int number;

        number = 0;  /* initial value */

        while (pathReaderP->cursor < pathTextLength &&
               isdigit(pathText[pathReaderP->cursor])) {
            number = 10 * number + (pathText[pathReaderP->cursor] - '0');
            ++pathReaderP->cursor;
        }
        if (pathText[pathReaderP->cursor] == '.')
            pm_error("Number contains decimal point.  This program does not "
                     "know how to deal with fractional positions");

        *numberP = number;
    }
}



static void
pathReader_getNextCommand(PathReader *  const pathReaderP,
                          PathCommand * const pathCommandP,
                          bool *        const endOfPathP) {

    const Path * const pathP          = pathReaderP->pathP;
    const char * const pathText       = pathP->pathText;
    size_t       const pathTextLength = pathP->pathTextLength;

    pathReader_skipWhiteSpace(pathReaderP);

    if (pathReaderP->cursor >= pathTextLength)
        *endOfPathP = true;
    else {
        switch (pathText[pathReaderP->cursor++]) {
        case 'M':
            pathCommandP->verb = PATH_MOVETO;
            pathReader_skipWhiteSpace(pathReaderP);
            pathReader_getNumber(pathReaderP,
                                 &pathCommandP->args.moveto.dest.x);
            pathReader_skipWhiteSpace(pathReaderP);
            pathReader_getNumber(pathReaderP,
                                 &pathCommandP->args.moveto.dest.y);
            break;
        case 'L':
            pathCommandP->verb = PATH_LINETO;
            pathReader_skipWhiteSpace(pathReaderP);
            pathReader_getNumber(pathReaderP,
                                 &pathCommandP->args.lineto.dest.x);
            pathReader_skipWhiteSpace(pathReaderP);
            pathReader_getNumber(pathReaderP,
                                 &pathCommandP->args.lineto.dest.y);
            break;
        case 'C':
            pathCommandP->verb = PATH_CUBIC;
            pathReader_skipWhiteSpace(pathReaderP);
            pathReader_getNumber(pathReaderP, &pathCommandP->args.cubic.ctl1.x);
            pathReader_skipWhiteSpace(pathReaderP);
            pathReader_getNumber(pathReaderP, &pathCommandP->args.cubic.ctl1.y);
            pathReader_skipWhiteSpace(pathReaderP);
            pathReader_getNumber(pathReaderP, &pathCommandP->args.cubic.ctl2.x);
            pathReader_skipWhiteSpace(pathReaderP);
            pathReader_getNumber(pathReaderP, &pathCommandP->args.cubic.ctl2.y);
            pathReader_skipWhiteSpace(pathReaderP);
            pathReader_getNumber(pathReaderP, &pathCommandP->args.cubic.dest.x);
            pathReader_skipWhiteSpace(pathReaderP);
            pathReader_getNumber(pathReaderP, &pathCommandP->args.cubic.dest.y);
            break;
        case 'z':
            pathCommandP->verb = PATH_CLOSEPATH;
            break;
        default: {
            const char * const context = pathReader_context(pathReaderP);

            pm_errormsg("Unrecognized command in <path>: '%c'.  %s",
                        pathText[pathReaderP->cursor++], context);

            pm_strfree(context);

            pm_longjmp();
        }
        }
    }
}



static void
outlineObject(Path *           const pathP,
              struct fillobj * const fillObjP) {
/*----------------------------------------------------------------------------
  Create a fill object, which contains and outline of the object and
  can be used with ppmd_fill() to fill the figure.  The outline is as
  described by *pathP.
-----------------------------------------------------------------------------*/
    PathReader * pathReaderP;
    bool endOfPath;
    Point currentPos;
    Point subpathStart;
        /* Point at which the current subpath starts */

    endOfPath = false;
    subpathStart = makePoint(0,0);
    currentPos = subpathStart;

    pathReader_create(pathP, &pathReaderP);

    while (!endOfPath) {
        PathCommand pathCommand;
        pathReader_getNextCommand(pathReaderP, &pathCommand, &endOfPath);
        if (!endOfPath) {
            switch (pathCommand.verb) {
            case PATH_MOVETO:
                if (traceDraw)
                    pm_message("Moving to (%u, %u)",
                               pathCommand.args.moveto.dest.x,
                               pathCommand.args.moveto.dest.y);
                subpathStart = pathCommand.args.moveto.dest;
                currentPos = subpathStart;
                break;
            case PATH_LINETO: {
                Point const dest = pathCommand.args.lineto.dest;
                if (traceDraw)
                    pm_message("Lining to (%u, %u)", dest.x, dest.y);
                ppmd_line(NULL, 0, 0, 0,
                          currentPos.x, currentPos.y, dest.x, dest.y,
                          ppmd_fill_drawproc, fillObjP);
                currentPos = dest;
            } break;
            case PATH_CLOSEPATH:
                if (traceDraw)
                    pm_message("Closing.");
                ppmd_line(NULL, 0, 0, 0,
                          currentPos.x, currentPos.y,
                          subpathStart.x, subpathStart.y,
                          ppmd_fill_drawproc, fillObjP);
                currentPos = subpathStart;
                break;
            case PATH_CUBIC: {
                Point const dest = pathCommand.args.cubic.dest;
                Point const ctl1 = pathCommand.args.cubic.ctl1;
                Point const ctl2 = pathCommand.args.cubic.ctl2;
                if (traceDraw)
                    pm_message("Doing cubic spline to (%u, %u)",
                               dest.x, dest.y);
                pm_error("SVG image contains a cubic spline path.  "
                         "This program cannot process cubic splines.");
                /* We need to write ppmd_spline4() */
                ppmd_spline4p(NULL, 0, 0, 0,
                              makePpmdPoint(currentPos),
                              makePpmdPoint(dest),
                              makePpmdPoint(ctl1),
                              makePpmdPoint(ctl2),
                              ppmd_fill_drawprocp, fillObjP);
                currentPos = dest;
            } break;
            }
        }
    }
    pathReader_destroy(pathReaderP);
}



static void
drawPath(Canvas * const canvasP,
         Path *   const pathP) {
/*----------------------------------------------------------------------------
   Draw the path 'pathP' on the canvas 'canvasP'.
-----------------------------------------------------------------------------*/
    struct fillobj * fillObjP;

    if (traceDraw)
        pm_message("Drawing path '%s' with fill color (%u, %u, %u)",
                   pathP->pathText,
                   pathP->style.fillColor.r,
                   pathP->style.fillColor.g,
                   pathP->style.fillColor.b);

    fillObjP = ppmd_fill_create();

    outlineObject(pathP, fillObjP);

    ppmd_fill(canvasP->pixels, canvasP->width, canvasP->height,
              canvasP->maxval,
              fillObjP,
              PPMD_NULLDRAWPROC, &pathP->style.fillColor);

    ppmd_fill_destroy(fillObjP);
}



static Style
interpretStyle(const char * const styleAttr) {

    Style style;

    char * buffer;

    char * p;

    buffer = strdup(styleAttr);
    if (buffer == NULL)
        pm_error("Could not get memory for a buffer to parse style attribute");

    p = &buffer[0];

    while (p) {
        const char * const token = pm_strsep(&p, ";");
        const char * strippedToken;
        const char * p;
        char * buffer;

        for (p = &token[0]; isspace(*p); ++p);

        strippedToken = p;

        buffer = strdup(strippedToken);

        if (strlen(strippedToken) > 0) {
            char * const colonPos = strchr(buffer, ':');

            if (colonPos == NULL)
                pm_error("There is no colon in the attribute specification "
                         "'%s' in the 'style' attribute of a <path> "
                         "element.", strippedToken);
            else {
                const char * const value = colonPos + 1;
                const char * const name  = &buffer[0];

                *colonPos = '\0';

                if (streq(name, "fill")) {
                    style.fillColor = ppm_parsecolor(value, OUTPUT_MAXVAL);
                } else if (streq(name, "stroke")) {
                    if (!streq(value, "none"))
                        pm_error("Value of 'stroke' attribute in the 'style' "
                                 "attribute of a <path> element is '%s'.  We "
                                 "understand only 'none'", value);
                } else
                    pm_error("Unrecognized attribute '%s' "
                             "in the 'style' attribute "
                             "of a <path> element", name);
            }
        }
        free(buffer);
    }

    free(buffer);

    return style;
}



static void
getPathAttributes(xmlTextReaderPtr const xmlReaderP,
                  Style *          const styleP,
                  const char **    const pathP) {

    const char * const style = getAttribute(xmlReaderP, "style");
    const char * const d     = getAttribute(xmlReaderP, "d");

    *styleP = interpretStyle(style);
    *pathP = d;
}



static void
processSubPathNode(xmlTextReaderPtr const xmlReaderP,
                   bool *           const endOfPathP) {

    /* See comment above about xmlReaderTypes not being defined */

    xmlReaderTypes const nodeType  = xmlTextReaderNodeType(xmlReaderP);

    *endOfPathP = FALSE;  /* initial assumption */

    switch (nodeType) {
    case XML_READER_TYPE_ELEMENT:
        pm_error("<path> contains a <%s> element.  <path> should have "
                 "no contents", currentNodeName(xmlReaderP));
        break;
    case XML_READER_TYPE_END_ELEMENT: {
        const char * nodeName = currentNodeName(xmlReaderP);
        if (streq(nodeName, "path"))
            *endOfPathP = TRUE;
        else
            pm_error("</%s> found where </path> expected", nodeName);
        } break;
    default:
        /* Just ignore whatever this is.  Contents of <path> are
           meaningless; all the information is in the attributes
        */
        break;
    }
}



static void
processPathElement(xmlTextReaderPtr const xmlReaderP,
                   Canvas *         const canvasP) {

    Style style;
    const char * pathData;
    Path * pathP;
    bool endOfPath;

    assert(xmlTextReaderNodeType(xmlReaderP) == XML_READER_TYPE_ELEMENT);
    assert(streq(currentNodeName(xmlReaderP), "path"));

    getPathAttributes(xmlReaderP, &style, &pathData);

    createPath(pathData, style, &pathP);

    if (pathP) {
        drawPath(canvasP, pathP);
        destroyPath(pathP);
    }

    endOfPath = xmlTextReaderIsEmptyElement(xmlReaderP);

    while (!endOfPath) {
        int rc;

        rc = xmlTextReaderRead(xmlReaderP);

        switch (rc) {
        case 1:
            processSubPathNode(xmlReaderP, &endOfPath);
            break;
        case 0:
            pm_error("Input file ends in the middle of a <path>");
            break;
        default:
            pm_error("xmlTextReaderRead() failed, rc=%d", rc);
        }
    }
}



static void
getSvgAttributes(xmlTextReaderPtr const xmlReaderP,
                 unsigned int *   const colsP,
                 unsigned int *   const rowsP) {

    const char * const width  = getAttribute(xmlReaderP, "width");
    const char * const height = getAttribute(xmlReaderP, "height");

    const char * error;

    pm_string_to_uint(width, colsP, &error);
    if (error) {
        pm_error("'width' attribute of <svg> has invalid value '%s'.  %s",
                 width, error);
        pm_strfree(error);
    }
    pm_string_to_uint(height, rowsP, &error);
    if (error) {
        pm_error("'height' attribute of <svg> has invalid value '%s'.  %s",
                 height, error);
        pm_strfree(error);
    }
}



static void
processSubSvgElement(xmlTextReaderPtr const xmlReaderP,
                     Canvas *         const canvasP) {

    const char * const nodeName = currentNodeName(xmlReaderP);

    assert(xmlTextReaderNodeType(xmlReaderP) == XML_READER_TYPE_ELEMENT);

    if (streq(nodeName, "path"))
        processPathElement(xmlReaderP, canvasP);
    else
        pm_error("This image contains a <%s> element.  This program "
                 "understands only <path>!", nodeName);
}



static void
processSubSvgNode(xmlTextReaderPtr const xmlReaderP,
                  Canvas *         const canvasP,
                  bool *           const endOfSvgP) {

    xmlReaderTypes const nodeType = xmlTextReaderNodeType(xmlReaderP);

    *endOfSvgP = FALSE;  /* initial assumption */

    switch (nodeType) {
    case XML_READER_TYPE_ELEMENT:
        processSubSvgElement(xmlReaderP, canvasP);
        break;
    case XML_READER_TYPE_END_ELEMENT: {
        const char * const nodeName = currentNodeName(xmlReaderP);
        if (streq(nodeName, "svg"))
            *endOfSvgP = TRUE;
        else
            pm_error("</%s> found where </svg> expected", nodeName);
    } break;
    default:
        /* Just ignore whatever this is */
        break;
    }
}



static void
createCanvas(unsigned int const width,
             unsigned int const height,
             pixval       const maxval,
             Canvas **    const canvasPP) {

    Canvas * canvasP;

    MALLOCVAR_NOFAIL(canvasP);

    canvasP->width  = width;
    canvasP->height = height;
    canvasP->pixels = ppm_allocarray(width, height);
    canvasP->maxval = maxval;

    *canvasPP = canvasP;
}



static void
destroyCanvas(Canvas * const canvasP) {

    ppm_freearray(canvasP->pixels, canvasP->height);

    free(canvasP);
}



static void
writePam(FILE *   const ofP,
         Canvas * const canvasP) {

    unsigned int row;
    struct pam pam;
    tuple * tuplerow;

    pam.size             = sizeof(pam);
    pam.len              = PAM_STRUCT_SIZE(tuple_type);
    pam.file             = ofP;
    pam.format           = PAM_FORMAT;
    pam.plainformat      = 0;
    pam.width            = canvasP->width;
    pam.height           = canvasP->height;
    pam.depth            = 3;
    pam.maxval           = OUTPUT_MAXVAL;
    strcpy(pam.tuple_type, PAM_PPM_TUPLETYPE);

    pnm_writepaminit(&pam);

    tuplerow = pnm_allocpamrow(&pam);

    for (row = 0; row < (unsigned)pam.height; ++row) {
        pixel * const pixelrow = canvasP->pixels[row];
        unsigned int col;

        for (col = 0; col < (unsigned)pam.width; ++col) {
            pixel const thisPixel = pixelrow[col];
            assert(pam.depth >= 3);

            tuplerow[col][PAM_RED_PLANE] = PPM_GETR(thisPixel);
            tuplerow[col][PAM_GRN_PLANE] = PPM_GETG(thisPixel);
            tuplerow[col][PAM_BLU_PLANE] = PPM_GETB(thisPixel);
        }
        pnm_writepamrow(&pam, tuplerow);
    }
    pnm_freepamrow(tuplerow);
}



static void
processSvgElement(xmlTextReaderPtr const xmlReaderP,
                  FILE *           const ofP) {

    unsigned int width, height;
    bool endOfSvg;
    Canvas * canvasP;

    assert(xmlTextReaderNodeType(xmlReaderP) == XML_READER_TYPE_ELEMENT);
    assert(streq(currentNodeName(xmlReaderP), "svg"));

    getSvgAttributes(xmlReaderP, &width, &height);

    createCanvas(width, height, 255, &canvasP);

    endOfSvg = xmlTextReaderIsEmptyElement(xmlReaderP);

    while (!endOfSvg) {
        int rc;

        rc = xmlTextReaderRead(xmlReaderP);

        switch (rc) {
        case 1:
            processSubSvgNode(xmlReaderP, canvasP, &endOfSvg);
            break;
        case 0:
            pm_error("Input file ends in the middle of a <svg>");
            break;
        default:
            pm_error("xmlTextReaderRead() failed, rc=%d", rc);
        }
    }
    writePam(ofP, canvasP);

    destroyCanvas(canvasP);
}



static void
processTopLevelElement(xmlTextReaderPtr const xmlReaderP,
                       FILE *           const ofP) {

    const char * const nodeName = currentNodeName(xmlReaderP);

    assert(xmlTextReaderNodeType(xmlReaderP) == XML_READER_TYPE_ELEMENT);
    assert(xmlTextReaderDepth(xmlReaderP) == 0);

    if (!streq(nodeName, "svg"))
        pm_error("Not an SVG image.  This XML document consists of "
                 "a <%s> element, whereas an SVG image is an <svg> "
                 "element.", nodeName);
    else
        processSvgElement(xmlReaderP, ofP);
}



static void
processTopLevelNode(xmlTextReaderPtr const xmlReaderP,
                    FILE *           const ofP) {

    unsigned int   const depth    = xmlTextReaderDepth(xmlReaderP);
    xmlReaderTypes const nodeType = xmlTextReaderNodeType(xmlReaderP);

    assert(depth == 0);

    switch (nodeType) {
    case XML_READER_TYPE_ELEMENT:
        processTopLevelElement(xmlReaderP, ofP);
        break;
    default:
        /* Just ignore whatever this is */
        break;
    }
}



static void
processDocument(xmlTextReaderPtr const xmlReaderP,
                FILE *           const ofP) {

    bool eof;

    eof = false;

    while (!eof) {
        int rc;

        rc = xmlTextReaderRead(xmlReaderP);

        switch (rc) {
        case 1:
            processTopLevelNode(xmlReaderP, ofP);
            break;
        case 0:
            eof = true;
            break;
        default:
            pm_error("xmlTextReaderRead() failed, rc=%d", rc);
        }
    }
}



int
main(int argc, char **argv) {

    struct cmdlineInfo cmdline;
    FILE * ifP;
    xmlTextReaderPtr xmlReaderP;

    pnm_init(&argc, argv);

    xmlInitParser();

    LIBXML_TEST_VERSION;

    parseCommandLine(argc, argv, &cmdline);

    traceDraw = cmdline.trace;

    ifP = pm_openr(cmdline.inputFileName);

    xmlReaderP = xmlReaderForFd(fileno(ifP), "SVG_IMAGE", NULL, 0);
        /* 'xmlReaderForFd' issues an error message to Standard Error if it
           cannot interpret the XML document on *ifP; that message identifies
           the document as "SVG_IMAGE".  It issues the bogus message
           "Extra content at the end of the document" if the document is
           empty.  It issues the bogus message "Document is empty" if the
           file starts with something other than an XML element.
           libxml2 2.9.10 23.10.09
        */

    if (xmlReaderP) {
        processDocument(xmlReaderP, stdout);

        /* xmlTextReaderIsValid() does not appear to work.  It always says
           the document is invalid
        */

        xmlFreeTextReader(xmlReaderP);
    } else
        pm_error("Failed to create xmlReader");

    xmlCleanupParser();

    return 0;
}