[ipe-tools] 01/01: Imported Upstream version 20150406

Steven Michael Robbins smr at moszumanska.debian.org
Sun Jun 7 21:52:01 UTC 2015


This is an automated email from the git hooks/post-receive script.

smr pushed a commit to branch master
in repository ipe-tools.

commit 0e8545d66f3c76db5e07c091b3f641d6e6c72f90
Author: Steve M. Robbins <smr at sumost.ca>
Date:   Sun Jun 7 16:39:59 2015 -0500

    Imported Upstream version 20150406
---
 .gitignore                                 |    5 +
 README.md                                  |   64 ++
 figtoipe/Makefile                          |   28 +
 figtoipe/figtoipe.1                        |   93 ++
 figtoipe/figtoipe.cpp                      | 1412 ++++++++++++++++++++++++++++
 figtoipe/readme.txt                        |   43 +
 gpl.txt                                    |  674 +++++++++++++
 ipe5toxml/Makefile                         |   26 +
 ipe5toxml/ipe5toxml.1                      |   18 +
 ipe5toxml/ipe5toxml.c                      | 1231 ++++++++++++++++++++++++
 matplotlib/README.md                       |   88 ++
 matplotlib/backend_ipe.py                  |  524 +++++++++++
 matplotlib/run_test.py                     |   54 ++
 matplotlib/tests/barchart_demo.py          |   35 +
 matplotlib/tests/barh_demo.py              |   21 +
 matplotlib/tests/clip_test.py              |   23 +
 matplotlib/tests/collections_demo.py       |  108 +++
 matplotlib/tests/color_cycle_demo.py       |   32 +
 matplotlib/tests/colormaps_reference.py    |   49 +
 matplotlib/tests/date_demo.py              |   41 +
 matplotlib/tests/donut_demo.py             |   52 +
 matplotlib/tests/fill_demo.py              |   18 +
 matplotlib/tests/histogram_path_demo.py    |   35 +
 matplotlib/tests/image_demo.py             |   11 +
 matplotlib/tests/image_demo_clip_path.py   |   15 +
 matplotlib/tests/joinstyle.py              |   28 +
 matplotlib/tests/legend_demo.py            |   20 +
 matplotlib/tests/line_demo_dash_control.py |   12 +
 matplotlib/tests/line_styles_reference.py  |   49 +
 matplotlib/tests/power_norm_demo.py        |   25 +
 matplotlib/tests/two_scales.py             |   24 +
 matplotlib/tests/watermark_image.py        |   18 +
 matplotlib/tests/watermark_image2.py       |   18 +
 pdftoipe/Makefile                          |   40 +
 pdftoipe/compile_on_windows.pdf            |  Bin 0 -> 83407 bytes
 pdftoipe/parseargs.cc                      |  208 ++++
 pdftoipe/parseargs.h                       |   85 ++
 pdftoipe/pdftoipe.1                        |  107 +++
 pdftoipe/pdftoipe.cpp                      |  166 ++++
 pdftoipe/readme.txt                        |  132 +++
 pdftoipe/xmloutputdev.cpp                  |  635 +++++++++++++
 pdftoipe/xmloutputdev.h                    |  108 +++
 svgtoipe/readme.txt                        |   76 ++
 svgtoipe/svgtoipe.1                        |   23 +
 svgtoipe/svgtoipe.py                       |  865 +++++++++++++++++
 45 files changed, 7339 insertions(+)

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b7ca92f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+*.o
+pdftoipe/pdftoipe
+figtoipe/figtoipe
+ipe5toxml/ipe5toxml
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..8a3c3fe
--- /dev/null
+++ b/README.md
@@ -0,0 +1,64 @@
+ipe-tools
+=========
+
+These are various tools and helper programs to be used 
+with the Ipe drawing editor (http://ipe7.sf.net)
+
+
+svgtoipe.py
+-----------
+
+A script that converts an SVG figure to Ipe format. It cannot handle
+all SVG features (many SVG features are not supported by Ipe anyway),
+but it works for gradients.
+
+
+Matplotlib backend
+------------------
+
+Matplotlib is a Python module for scientific plotting.  With this
+backend, you can create Ipe figures directly from matplotlib.
+
+
+pdftoipe
+--------
+
+You can convert arbitrary Postscript or PDF files into Ipe documents,
+making them editable.  The auxiliary program *pdftoipe* converts
+(pages from) a PDF file into an Ipe XML-file. (If your source is
+Postscript, you have to first convert it to PDF using Acrobat
+Distiller or *ps2pdf*.)  Once converted to XML, the file can be opened
+from Ipe as usual.
+
+The conversion process should handle any graphics in the PDF file
+fine, but doesn't do very well on text - Ipe's text model is just too
+different.
+
+
+ipe5toxml
+---------
+
+If you still have figures that were created with Ipe 5, you can use
+*ipe5toxml* to convert them to Ipe 6 format.  You can then use
+*ipe6upgrade* to convert them to Ipe 7 format.
+
+
+figtoipe
+--------
+
+Figtoipe converts a figure in FIG format into an Ipe XML-file.  This
+is useful if you used to make figures with Xfig before discovering
+Ipe, of if your co-authors made figures for your article with Xfig
+(converting them will have the added benefit of forcing your
+co-authors to learn to use Ipe).  Finally, there are quite a number of
+programs that can export to FIG format, and *figtoipe* effectively
+turns that into the possibility of exporting to Ipe.
+
+However, *figtoipe* is not quite complete.  The drawing models of FIG
+and Ipe are also somewhat different, which makes it impossible to
+properly render some FIG files in Ipe.  Ipe does not support depth
+ordering independent of grouping, pattern fill, and Postscript fonts.
+You may therefore have to edit the file after conversion.
+
+*figtoipe* is now maintained by Alexander Bürger.
+
diff --git a/figtoipe/Makefile b/figtoipe/Makefile
new file mode 100644
index 0000000..9da1f4a
--- /dev/null
+++ b/figtoipe/Makefile
@@ -0,0 +1,28 @@
+#############################################################################
+# Makefile for building figtoipe
+#############################################################################
+
+CXX           = g++
+CXXFLAGS      += -O2 -Wall -W
+RM            = rm -f
+LIBS          = -lz
+
+TARGET = figtoipe
+SOURCES = $(TARGET).cpp 
+SRCDISTFILES = $(TARGET).1 $(SOURCES) README Makefile GPL-2
+
+all: $(TARGET)
+
+clean:
+	-$(RM) $(TARGET)
+
+$(TARGET): $(SOURCES)
+	$(CXX) $(CXXFLAGS) -o $@ $^ $(LDFLAGS) $(LIBS)
+
+dist:
+	DATE=`date  +"%Y%m%d"`; D=/tmp/$(TARGET)-$$DATE; \
+	rm -rf $$D; mkdir $$D; \
+	cp $(SRCDISTFILES) $$D; \
+	tar czvf $$D.tar.gz -C /tmp $(TARGET)-$$DATE
+
+.PHONY: all
diff --git a/figtoipe/figtoipe.1 b/figtoipe/figtoipe.1
new file mode 100644
index 0000000..1eed23e
--- /dev/null
+++ b/figtoipe/figtoipe.1
@@ -0,0 +1,93 @@
+.\"                                      Hey, EMACS: -*- nroff -*-
+.\" First parameter, NAME, should be all caps
+.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
+.\" other parameters are allowed: see man(7), man(1)
+.\" TeX users may be more comfortable with the \fB<whatever>\fP and
+.\" \fI<whatever>\fP escape sequences to invode bold face and italics, 
+.\" respectively.
+.TH FIGTOIPE 1 "April 26, 2008"
+.\" Please adjust this date whenever revising the manpage.
+.\"
+.\" Some roff macros, for reference:
+.\" .nh        disable hyphenation
+.\" .hy        enable hyphenation
+.\" .ad l      left justify
+.\" .ad b      justify to both left and right margins
+.\" .nf        disable filling
+.\" .fi        enable filling
+.\" .br        insert line break
+.\" .sp <n>    insert n+1 empty lines
+.\" for manpage-specific macros, see man(7)
+.SH NAME
+figtoipe \- Convert FIG figures into Ipe format
+.SH SYNOPSIS
+.B figtoipe 
+\fP[\-g] [\-p \fIpreamble\fP]
+\fIFIGfile\fP \fIXMLfile\fP
+
+.SH DESCRIPTION
+
+\fBfigtoipe\fP converts files in FIG format (as created, e.g., by
+\fBxfig\fP) to Ipe's XML format.
+
+\fBfigtoipe\fP is not complete.  The main lacking feature is the
+conversion of splines.  Arc-boxes are replaced by rectangles.  Feel
+free to improve this version!
+
+The drawing models of FIG and Ipe are somewhat different.  Ipe does
+not support depth ordering independent of grouping, pattern fill, and
+Postscript fonts.  
+
+\fBfigtoipe\fP tries to include images specified in the XFIG file. For
+JPEG pictures, it tries include the compressed image data into the XML
+file. For files not recognized as JPEG, \fBanytopnm\fP is called; its
+output is compressed and included in the XML file. Some output of
+\fBanytopnm\fP might be rejected (e.g. images larger than 5000x5000
+pixels or B&W bitmaps), or misunderstood.
+
+.SH OPTIONS
+.B \-g
+group the figure in the output XML
+.TP
+.B \-c
+tell ipe to crop PDF output to the boundingbox
+.TP
+.B \-6
+write in ipe 6 format instead of ipe 7 format
+.TP
+.B \-p \fIlatex\fP
+add \fIlatex\fP as a preamble to the generated XML file, e.g.
+.nf
+.in +.5i
+\'\\usepackage{amsmath}\'
+.in -.5i
+.fi
+
+.SH AUTHORS
+.ft CW
+.nf
+\&Otfried Cheong
+\&Alexander B\[:u]rger <acfb at users.sf.net> (image handling)
+.ft R
+.fi
+
+.SH REPORTING BUGS
+.ad l
+Please report bugs using Ipe bugzilla at
+.I "https://github.com/otfried/ipe-tools/issues"
+
+.SH SEE ALSO
+.ad l
+More information about Ipe can be found in  
+.IR "The Ipe Manual" ,
+which can be found in your Ipe installation.
+
+.SH LICENSE & WARRANTY
+.ad l
+\fBfigtoipe\fP comes with ABSOLUTELY NO WARRANTY. It is free software;
+you can redistribute it and/or modify it under the terms of the GNU
+General Public License as published by the Free Software Foundation;
+either version 2 of the License, or (at your option) any later
+version.
+
+See the file \fBgpl.txt\fP accompanying the source for details.
diff --git a/figtoipe/figtoipe.cpp b/figtoipe/figtoipe.cpp
new file mode 100644
index 0000000..20fc747
--- /dev/null
+++ b/figtoipe/figtoipe.cpp
@@ -0,0 +1,1412 @@
+/*
+
+    This file is part of the extensible drawing editor Ipe.
+    Copyright (C) 1993-2008 Otfried Cheong <otfried at ipe.airpost.net>
+
+    Ipe is free software; you can redistribute it and/or modify it
+    under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    As a special exception, you have permission to link Ipe with the
+    CGAL library and distribute executables, as long as you follow the
+    requirements of the Gnu General Public License in regard to all of
+    the software in the executable aside from CGAL.
+
+    Ipe is distributed in the hope that it will be useful, but WITHOUT
+    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
+    License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+*/
+/*
+ * figtoipe.cpp
+ *
+ * This program converts files in FIG format (as used by Xfig) to XML
+ * format as used by Ipe 6.0.
+ *
+ * All versions of the FIG file format are documented here:
+ *  "http://duke.usask.ca/~macphed/soft/fig/formats.html"
+ *
+ * This program can read only versions 3.0, 3.1, and 3.2.
+ *
+ * Changes:
+ *
+ * 2005/10/31 - replace double backslash by single one in text.
+ * 2005/11/14 - generate correct header for Ipe 6.0 preview 25.
+ * 2007/08/19 - Alexander Buerger acfb at users.sf.net
+ *              + include some images with anytopnm
+ *              + correct FIG3.1 problem (bugzilla #237)
+ *              + fixed rotation of text and ellipses
+ *              + do not write invisible ellipses / polylines / arcs
+ *              + accept double values in some places (points, thickness, ...;
+ *                extends FIG format)
+ *              + skip comments between FIG objects
+ *              + replaced some %g formats as they illegally appear in the PDF
+ * 2007/09/26 - Alexander Buerger acfb at users.sf.net
+ *              + compress bitmap images
+ *              + include compressed JPEG images
+ * 2008/04/26 - Alexander Buerger acfb at users.sf.net
+ *              + support grayscale pnm
+ *              + added -g and -p options
+ * 2009/10/22 - Alexander Buerger acfb at users.sf.net
+ *              + added -c option to use cropbox for output figure
+ *              + check fgets/fscanf return values
+ * 2009/12/05 - Alexander Buerger acfb at users.sf.net
+ *              + write ipe 7 format by default
+ *              + added -6 option to write in ipe 6 format
+ *              + added simple_getopt function to parse options
+ *              + reduce filesize for images by putting 36 bytes per line
+ * 2015/02/28 - Alexander Buerger acfb at users.sf.net
+ *              + check color array indices
+ *              + limit image filename string length in fscanf
+ *              + thanks to Jodie Cunningham <jodie.cunningham at gmail.com>
+ *                for pointing out these problems
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+#include <zlib.h>
+
+#include <vector>
+#include <string>
+#include <sstream>
+#include <fstream>
+#include <algorithm>
+
+#define FIGTOIPE_VERSION "figtoipe 2015/02/28"
+
+const int MEDIABOX_WIDTH = 595;
+const int MEDIABOX_HEIGHT = 842;
+bool ipe7 = true;
+
+const int NFIXEDCOLORS = 32, NUSERCOLORS = 512,
+    NCOLORS = NFIXEDCOLORS + NUSERCOLORS;
+
+// --------------------------------------------------------------------
+
+struct Arrow {
+  int iType;
+  int iStyle;
+  double iThickness; // 1/80 inch
+  double iWidth;     // Fig units
+  double iHeight;    // Fig units
+};
+
+struct Point {
+  double iX, iY;
+};
+
+struct FigObject {
+  int iType;
+  int iSubtype;     // meaning depends on type
+  int iLinestyle;   // solid, dashed, etc
+  double iThickness;   // 0 means no stroke
+  int iPenColor;
+  int iFillColor;
+  int iDepth;       // depth ordering
+  int iPenStyle;    // not used by FIG
+  int iAreaFill;    // how to fill: color, pattern
+  double iStyle;    // length of dash/dot pattern
+  int iCapStyle;
+  int iJoinStyle;
+  int iDirection;
+  int iForwardArrow;
+  Arrow iForward;
+  int iBackwardArrow;
+  Arrow iBackward;
+  double iCenterX, iCenterY;  // center of ellipse and arc
+  Point iArc1, iArc2, iArc3;
+  double iAngle;    // orientation of main axis of ellipse
+  Point iRadius;    // half-axes of ellipse
+  int iArcBoxRadius;
+  Point iPos;       // position of text
+  int iFont;
+  int iFontFlags;
+  double iFontSize;
+  std::vector<char> iString;
+  std::vector<Point> iPoints;
+  std::string image_filename;
+  bool image_flipped;
+};
+
+// --------------------------------------------------------------------
+
+class FigReader {
+public:
+  FigReader(FILE *fig) :
+      iFig(fig) { }
+  bool ReadHeader();
+  double Magnification() const { return iMagnification; }
+  double UnitsPerPoint() const { return iUnitsPerPoint; }
+  bool ReadObjects();
+  const std::vector<FigObject> &Objects() const { return iObjects; }
+  const unsigned int *UserColors() const { return iUserColors; }
+private:
+  bool GetLine(char *buf);
+  int GetInt();
+  int GetColorInt();
+  double GetDouble();
+  Point GetPoint();
+  void GetColor();
+  void GetArc(FigObject &obj);
+  void GetEllipse(FigObject &obj);
+  void GetPolyline(FigObject &obj);
+  void GetSpline(FigObject &obj);
+  void GetText(FigObject &obj);
+  void GetArrow(Arrow &a);
+  void GetArrows(FigObject &obj);
+  int ComputeDepth(unsigned int &i);
+
+private:
+  FILE *iFig;
+  int iVersion;  // minor version of FIG format
+  double iMagnification;
+  double iUnitsPerPoint;
+  std::vector<FigObject> iObjects;
+  unsigned int iUserColors[NUSERCOLORS];
+};
+
+// --------------------------------------------------------------------
+
+const int BUFSIZE = 0x100;
+
+// skip comment lines (in the header)
+bool FigReader::GetLine(char *buf)
+{
+  do {
+    if (fgets(buf, BUFSIZE, iFig) == NULL)
+      return false;
+  } while (buf[0] == '#');
+  return true;
+}
+
+int FigReader::GetInt()
+{
+  int num = -1;
+  if( fscanf(iFig, "%d", &num) != 1 && !feof(iFig))
+      fprintf(stderr, "Could not read integer value.\n");
+  return num;
+}
+
+int FigReader::GetColorInt()
+{
+  int color = GetInt();
+  if( color < 0 || color >= NCOLORS ) {
+    fprintf(stderr, "Color value %d out of range.\n", color);
+    color = 0;
+  }
+  return color;
+}
+
+double FigReader::GetDouble()
+{
+  double num = -1;
+  if( fscanf(iFig, "%lg", &num) != 1 )
+      fprintf(stderr, "Could not read double value.\n");
+  return num;
+}
+
+Point FigReader::GetPoint()
+{
+  Point p;
+  p.iX = GetDouble();
+  p.iY = GetDouble();
+  return p;
+}
+
+void FigReader::GetArrow(Arrow &a)
+{
+  a.iType = GetInt();
+  a.iStyle = GetInt();
+  a.iThickness = GetDouble();
+  a.iWidth = GetDouble();
+  a.iHeight = GetDouble();
+}
+
+void FigReader::GetArrows(FigObject &obj)
+{
+  if (obj.iForwardArrow)
+    GetArrow(obj.iForward);
+  if (obj.iBackwardArrow)
+    GetArrow(obj.iBackward);
+}
+
+// --------------------------------------------------------------------
+
+bool FigReader::ReadHeader()
+{
+  char line[BUFSIZE];
+  if (fgets(line, BUFSIZE, iFig) != line)
+      return false;
+  if (strncmp(line, "#FIG", 4))
+    return false;
+
+  // check FIG version
+  int majorVersion;
+  sscanf(line + 4, "%d.%d", &majorVersion, &iVersion);
+  if (majorVersion != 3 || iVersion<0 || iVersion>2 ) {
+    fprintf(stderr, "Figtoipe supports FIG versions 3.0 - 3.2 only.\n");
+    return false;
+  }
+
+  fprintf(stderr, "FIG format version %d.%d\n", majorVersion, iVersion);
+
+  // skip orientation and justification
+  if (!GetLine(line))
+    return false;
+  if (!GetLine(line))
+    return false;
+
+  bool metric = false;
+  if (!GetLine(line))
+    return false;
+  if (!strncmp(line, "Metric", 6))
+    metric = true;
+  (void) metric; // not yet used
+
+  int magnification = 100, resolution=1200;
+  if (iVersion == 2) {
+    // Version 3.2:
+    // papersize
+    if (!GetLine(line))
+      return false;
+    // export and print magnification
+    if (!GetLine(line))
+      return false;
+    sscanf(line, "%d", &magnification);
+    // multi-page mode
+    if (!GetLine(line))
+      return false;
+    // transparent color
+    if (!GetLine(line))
+      return false;
+  }
+  // resolution and coord_system
+  if (!GetLine(line))
+      return false;
+  int coord_system;
+  sscanf(line, "%d %d", &resolution, &coord_system);
+  
+  iUnitsPerPoint = (resolution / 72.0);
+  iMagnification = magnification / 100.0;
+  return true;
+}
+
+// link start and end of compounds together,
+// and assign depth to compound object
+int FigReader::ComputeDepth(unsigned int &i)
+{
+  if (iObjects.at(i).iType != 6)
+    return iObjects.at(i++).iDepth;
+  int pos = i;
+  int depth = 1000;
+  ++i;
+  while (iObjects.at(i).iType != -6) {
+    int od = ComputeDepth(i);
+    if (od < depth) depth = od;
+  }
+  iObjects.at(pos).iDepth = depth;
+  iObjects.at(pos).iSubtype = i;
+  ++i;
+  return depth;
+}
+
+// --------------------------------------------------------------------
+
+// objects are appended to list
+bool FigReader::ReadObjects()
+{
+  int level = 0;
+  for (;;) {
+      int objType = GetInt();
+      //fprintf(stderr, "object type %d\n", objType);
+      if (objType == -1 && fgetc(iFig)=='#' ) {
+          char buf[1024];
+          if( fgets(buf, sizeof(buf), iFig) == NULL ) {
+              fprintf(stderr, "Read error while skipping comment.\n");
+              return false;
+          }
+         continue;
+     }
+    if (objType == -1) { // EOF
+      if (level > 0)
+	return false;
+      unsigned int i = 0;
+      while (i < iObjects.size())
+	ComputeDepth(i);
+      return true;
+    }
+    if (objType == 0) { // user-defined color
+      GetColor();
+    } else {
+      FigObject obj;
+      obj.iType = objType;
+      switch (obj.iType) {
+      case 1: // ELLIPSE
+	GetEllipse(obj);
+	break;
+      case 2: // POLYLINE
+	GetPolyline(obj);
+	break;
+      case 3: // SPLINE
+	GetSpline(obj);
+	break;
+      case 4: // TEXT
+	GetText(obj);
+	break;
+      case 5: // ARC
+	GetArc(obj);
+	break;
+      case 6: // COMPOUND
+	(void) GetInt(); // read and ignore bounding box
+	(void) GetInt();
+	(void) GetInt();
+	(void) GetInt();
+	++level;
+	break;
+      case -6: // END of COMPOUND
+	if (level == 0)
+	  return false;
+	--level;
+	break;
+      default:
+	fprintf(stderr, "Unknown object type in FIG file.\n");
+	return false;
+      }
+      iObjects.push_back(obj);
+    }
+  }
+}
+
+void FigReader::GetColor()
+{
+  int colorNum = GetInt();    // color number
+  int rgb = 0;
+  if( fscanf(iFig," #%x", &rgb) != 1 )  // RGB string in hex
+      fprintf(stderr, "Could not read rgb string.\n");
+  if( colorNum<NFIXEDCOLORS || colorNum>=NCOLORS ) {
+    fprintf(stderr, "User color number %d out of range, replacing with %d.\n",
+            colorNum, NFIXEDCOLORS);
+    colorNum = NFIXEDCOLORS;
+  }
+  iUserColors[colorNum - NFIXEDCOLORS] = rgb;
+}
+
+void FigReader::GetEllipse(FigObject &obj)
+{
+  obj.iSubtype = GetInt();
+  obj.iLinestyle = GetInt();
+  obj.iThickness = GetDouble();
+  obj.iPenColor = GetColorInt();
+  obj.iFillColor = GetColorInt();
+  obj.iDepth = GetInt();
+  obj.iPenStyle = GetInt();  // not used
+  obj.iAreaFill = GetInt();
+  obj.iStyle = GetDouble();
+  obj.iDirection = GetInt(); // always 1
+  obj.iAngle = GetDouble();  // radians, the angle of the x-axis
+  obj.iCenterX = GetDouble();
+  obj.iCenterY = GetDouble();
+  obj.iRadius = GetPoint();
+  (void) GetPoint(); // start
+  (void) GetPoint(); // end
+}
+
+void FigReader::GetPolyline(FigObject &obj)
+{
+  obj.iSubtype = GetInt();
+  obj.iLinestyle = GetInt();
+  obj.iThickness = GetDouble();
+  obj.iPenColor = GetColorInt();
+  obj.iFillColor = GetColorInt();
+  obj.iDepth = GetInt();
+  obj.iPenStyle = GetInt(); // not used
+  obj.iAreaFill = GetInt();
+  obj.iStyle = GetDouble();
+  obj.iJoinStyle = GetInt();
+  obj.iCapStyle = GetInt();
+  obj.iArcBoxRadius = GetInt();
+  obj.iForwardArrow = GetInt();
+  obj.iBackwardArrow = GetInt();
+  int nPoints = GetInt();
+  GetArrows(obj);
+  if (obj.iSubtype == 5) { // Imported image
+      int orientation;
+      char image_filename[1024];
+      // orientation and filename
+      if( fscanf(iFig, "%d %1020s", &orientation, image_filename) != 2 ) {
+          fprintf(stderr, "Could not read image orientation and/or filename. Exit.\n");
+          exit(-1);
+      }
+      obj.image_flipped = (orientation==1);
+      obj.image_filename = std::string(image_filename);
+  }
+  for (int i = 0; i < nPoints; ++i)
+      obj.iPoints.push_back( GetPoint() );
+}
+
+
+void FigReader::GetSpline(FigObject &obj)
+{
+  /* 0: opened approximated spline
+     1: closed approximated spline
+     2: opened interpolated spline
+     3: closed interpolated spline
+     4: opened x-spline (FIG 3.2)
+     5: closed x-spline (FIG 3.2)
+  */
+  obj.iSubtype = GetInt();
+  obj.iLinestyle = GetInt();
+  obj.iThickness = GetDouble();
+  obj.iPenColor = GetColorInt();
+  obj.iFillColor = GetColorInt();
+  obj.iDepth = GetInt();
+  obj.iPenStyle = GetInt(); // not used
+  obj.iAreaFill = GetInt();
+  obj.iStyle = GetDouble();
+  obj.iCapStyle = GetInt();
+  obj.iForwardArrow = GetInt();
+  obj.iBackwardArrow = GetInt();
+
+  int nPoints = GetInt();
+  GetArrows(obj);
+
+  for (int i = 0; i < nPoints; ++i)
+      obj.iPoints.push_back( GetPoint() );
+
+  if (iVersion == 2) {
+    // shape factors exist in FIG 3.2 only
+    for (int i = 0; i < nPoints; ++i) {
+      (void) GetDouble(); // double shapeFactor
+    }
+  } else {
+    if (obj.iSubtype > 1) {
+      for (int i = 0; i < nPoints; ++i) {
+	(void) GetDouble(); // double lx
+	(void) GetDouble(); // double ly
+	(void) GetDouble(); // double rx
+	(void) GetDouble(); // double ry
+      }
+    }
+  }
+}
+
+void FigReader::GetText(FigObject &obj)
+{
+  obj.iSubtype = GetInt();
+  obj.iThickness = 1;       // stroke
+  obj.iPenColor = GetColorInt();
+  obj.iDepth = GetInt();
+  obj.iPenStyle = GetInt(); // not used
+  obj.iFont = GetInt();
+  obj.iFontSize = GetDouble();
+  obj.iAngle = GetDouble();
+  obj.iFontFlags = GetInt();
+  (void) GetDouble(); // height
+  (void) GetDouble(); // length
+  obj.iPos = GetPoint();
+  // skip blank
+  fgetc(iFig);
+  std::vector<char> string;
+  for (;;) {
+    int ch = fgetc(iFig);
+    if (ch == EOF)
+      break;
+    if (ch < 0x80) {
+      string.push_back(char(ch));
+    } else {
+      // convert to UTF-8
+      string.push_back(char(0xc0 + ((ch >> 6) & 0x3)));
+      string.push_back(char(ch & 0x3f));
+    }
+    if (string.size() >= 4 &&
+	!strncmp(&string[string.size() - 4], "\\001", 4)) {
+      string.resize(string.size() - 4);
+      break;
+    }
+    // fig seems to store "\" as "\\"
+    if (string.size() >= 2 &&
+	!strncmp(&string[string.size() - 2], "\\\\", 2)) {
+      string.resize(string.size() - 1);
+    }
+  }
+  string.push_back('\0');
+  obj.iString = string;
+}
+
+void FigReader::GetArc(FigObject &obj)
+{
+  obj.iSubtype = GetInt();
+  obj.iLinestyle = GetInt();
+  obj.iThickness = GetDouble();
+  obj.iPenColor = GetColorInt();
+  obj.iFillColor = GetColorInt();
+  obj.iDepth = GetInt();
+  obj.iPenStyle = GetInt();  // not used
+  obj.iAreaFill = GetInt();
+  obj.iStyle = GetDouble();
+  obj.iCapStyle = GetInt();
+  obj.iDirection = GetInt();
+  obj.iForwardArrow = GetInt();
+  obj.iBackwardArrow = GetInt();
+  obj.iCenterX = GetDouble();
+  obj.iCenterY = GetDouble();
+  obj.iArc1 = GetPoint();
+  obj.iArc2 = GetPoint();
+  obj.iArc3 = GetPoint();
+  GetArrows(obj);
+}
+
+// --------------------------------------------------------------------
+
+unsigned int ColorTable[] = {
+  0x000000, 0x0000ff, 0x00ff00, 0x00ffff,
+  0xff0000, 0xff00ff, 0xffff00, 0xffffff,
+  0x000090, 0x0000b0, 0x0000d0, 0x87ceff,
+  0x009000, 0x00b000, 0x00d000, 0x009090,
+  0x00b0b0, 0x00d0d0, 0x900000, 0xb00000,
+  0xd00000, 0x900090, 0xb000b0, 0xd000d0,
+  0x803000, 0xa04000, 0xc06000, 0xff8080,
+  0xffa0a0, 0xffc0c0, 0xffe0e0, 0xffd700
+};
+
+class FigWriter {
+public:
+  FigWriter(FILE *xml, const std::string& figname,
+            double mag, double upp, const unsigned int *uc) :
+    iXml(xml), iFigName(figname), iMagnification(mag),  iUnitsPerPoint(upp),
+    iUserColors(uc) { }
+  void WriteObjects(const std::vector<FigObject> &objects, int start, int fin);
+
+private:
+  void WriteEllipse(const FigObject &obj);
+  void WriteImage(const FigObject &obj);
+  void WritePolyline(const FigObject &obj);
+  void WriteSpline(const FigObject &obj);
+  void WriteText(const FigObject &obj);
+  void WriteArc(const FigObject &obj);
+
+  void WriteStroke(const FigObject &obj);
+  void WriteFill(const FigObject &obj);
+  void WriteLineStyle(const FigObject &obj);
+  void WriteArrows(const FigObject &obj);
+
+  double X(double x);
+  double Y(double y);
+  unsigned int rgbColor(int colornum);
+
+private:
+  FILE *iXml;
+  const std::string iFigName;
+  double iMagnification;
+  double iUnitsPerPoint;
+  const unsigned int *iUserColors;
+};
+
+double FigWriter::X(double x)
+{
+  return (x / iUnitsPerPoint) * iMagnification;
+}
+
+double FigWriter::Y(double y)
+{
+  return MEDIABOX_HEIGHT - X(y);
+}
+
+unsigned int FigWriter::rgbColor(int colornum)
+{
+  if (colornum < 0 || colornum >= NCOLORS)
+    colornum = 0;
+  if (colornum < NFIXEDCOLORS)
+    return ColorTable[colornum];
+  else
+    return iUserColors[colornum - NCOLORS];
+}
+
+void FigWriter::WriteStroke(const FigObject &obj)
+{
+  if (obj.iThickness == 0)  // no stroke
+    return;
+  unsigned int rgb = rgbColor(obj.iPenColor);
+  fprintf(iXml, " stroke=\"%g %g %g\"",
+	  ((rgb >> 16) & 0xff) / 255.0,
+	  ((rgb >> 8) & 0xff) / 255.0,
+	  (rgb & 0xff) / 255.0);
+}
+
+void FigWriter::WriteFill(const FigObject &obj)
+{
+  // unfilled
+  if (obj.iAreaFill == -1)
+    return;
+
+  int fill = obj.iAreaFill;
+  if (fill > 40) {
+    fprintf(stderr, "WARNING: fill pattern %d replaced by solid filling.\n",
+	    fill);
+    fill = 20;
+  }
+
+  if (obj.iFillColor < 1) { // BLACK & DEFAULT
+    fprintf(iXml, " fill=\"%g\"", 1.0 - (fill / 20.0));
+  } else {
+    unsigned int rgb = rgbColor(obj.iFillColor);
+    double r = ((rgb >> 16) & 0xff) / 255.0;
+    double g = ((rgb >> 8) & 0xff) / 255.0;
+    double b = (rgb & 0xff) / 255.0;
+    if (fill < 20) {
+      // mix down to black
+      double scale = fill / 20.0;
+      r *= scale;
+      g *= scale;
+      b *= scale;
+    } else if (fill > 20) {
+      // mix up to white
+      double scale = (40 - fill) / 20.0;  // 40 is pure white
+      r = 1.0 - (1.0 - r) * scale;
+      g = 1.0 - (1.0 - g) * scale;
+      b = 1.0 - (1.0 - b) * scale;
+    }
+    fprintf(iXml, " fill=\"%g %g %g\"", r, g, b);
+  }
+}
+
+void FigWriter::WriteLineStyle(const FigObject &obj)
+{
+  if (obj.iThickness == 0)
+    return;
+  fprintf(iXml, " pen=\"%g\"",
+	  iMagnification * 72.0 * (obj.iThickness / 80.0));
+  switch (obj.iLinestyle) {
+  case -1: // Default
+  case 0:  // Solid
+    break;
+  case 1:
+    fprintf(iXml, " dash=\"dashed\"");
+    break;
+  case 2:
+    fprintf(iXml, " dash=\"dotted\"");
+    break;
+  case 3:
+    fprintf(iXml, " dash=\"dash dotted\"");
+    break;
+  case 4:
+    fprintf(iXml, " dash=\"dash dot dotted\"");
+    break;
+  case 5: // Dash-triple-dotted (maybe put this in a stylesheet)
+    fprintf(iXml, " dash=\"[4 2 1 2 1 2 1 2] 0\"");
+    break;
+  }
+}
+
+void FigWriter::WriteArrows(const FigObject &obj)
+{
+  if (obj.iForwardArrow)
+    fprintf(iXml, " arrow=\"%g\"", X(obj.iForward.iHeight));
+  if (obj.iBackwardArrow)
+    fprintf(iXml, " backarrow=\"%g\"", X(obj.iBackward.iHeight));
+}
+
+// --------------------------------------------------------------------
+
+class DepthCompare {
+public:
+  DepthCompare(const std::vector<FigObject> &objects)
+    : iObjects(objects) { /* nothing */ }
+  int operator()(int lhs, int rhs) const
+  {
+    return (iObjects.at(lhs).iDepth > iObjects.at(rhs).iDepth);
+  }
+private:
+  const std::vector<FigObject> &iObjects;
+};
+
+void FigWriter::WriteObjects(const std::vector<FigObject> &objects,
+			     int start, int fin)
+{
+  // collect indices of objects
+  std::vector<int> objs;
+  int i = start;
+  while (i < fin) {
+    objs.push_back(i);
+    if (objects.at(i).iType == 6)
+        i = objects.at(i).iSubtype;  // link to END OF COMPOUND
+    ++i;
+  }
+  // now sort the objects
+  DepthCompare comp(objects);
+  std::stable_sort(objs.begin(), objs.end(), comp);
+  // now render them
+  for (unsigned int j = 0; j < objs.size(); ++j) {
+    i = objs[j];
+    if (i<0 || i >= (int)objects.size())
+      continue;
+    switch (objects[i].iType) {
+    case 1: // ELLIPSE
+      WriteEllipse(objects[i]);
+      break;
+    case 2: // POLYLINE
+      WritePolyline(objects[i]);
+      break;
+    case 3: // SPLINE
+      WriteSpline(objects[i]);
+	break;
+    case 4: // TEXT
+      WriteText(objects[i]);
+      break;
+    case 5: // ARC
+      WriteArc(objects[i]);
+      break;
+    case 6: // COMPOUND
+      fprintf(iXml, "<group>\n");
+      // recursively render elements of the compound
+      WriteObjects(objects, i+1, objects[i].iSubtype);
+      fprintf(iXml, "</group>\n");
+      break;
+    }
+  }
+}
+
+// --------------------------------------------------------------------
+
+void FigWriter::WriteEllipse(const FigObject &obj)
+{
+    if (obj.iThickness == 0 && obj.iAreaFill==-1 ) {
+        fprintf(stderr, "WARNING: ellipse with neither fill nor line ignored.\n");
+        return;
+    }
+    fprintf(iXml, "<path ");
+    WriteStroke(obj);
+    WriteFill(obj);
+    WriteLineStyle(obj);
+    fprintf(iXml, ">\n");
+    const double ca = cos(obj.iAngle);
+    const double sa = sin(obj.iAngle);
+    fprintf(iXml, "%g %g %g %g %g %g e\n</path>\n",
+            X( obj.iRadius.iX * ca),
+            X( obj.iRadius.iX * sa),
+            X(-obj.iRadius.iY * sa),
+            X( obj.iRadius.iY * ca),
+            X( obj.iCenterX),
+            Y( obj.iCenterY) );
+}
+
+// --------------------------------------------------------------------
+
+namespace {
+
+unsigned int JPEG_read1( std::ifstream& jpeg_in )
+{
+    unsigned char c;
+    jpeg_in.read( reinterpret_cast<char*>(&c), 1 );
+    if( jpeg_in.fail() )
+        throw std::string( "Failed to read 1 byte." );
+    return c;
+}
+
+unsigned int JPEG_read2( std::ifstream& jpeg_in )
+{
+    return (JPEG_read1(jpeg_in) << 8) + JPEG_read1(jpeg_in);
+}
+
+typedef enum {
+    jpeg_SOF0 = 0xC0,
+    jpeg_SOF1 = 0xC1,
+    jpeg_SOF2 = 0xC2,
+    jpeg_SOF3 = 0xC3,
+    jpeg_SOF5 = 0xC5,
+    jpeg_SOF6 = 0xC6,
+    jpeg_SOF7 = 0xC7,
+    jpeg_SOF9 = 0xC9,
+    jpeg_SOF10 = 0xCA,
+    jpeg_SOF11 = 0xCB,
+    jpeg_SOF13 = 0xCD,
+    jpeg_SOF14 = 0xCE,
+    jpeg_SOF15 = 0xCF,
+    jpeg_SOI = 0xD8,
+    jpeg_EOI = 0xD9,
+    jpeg_SOS = 0xDA,
+    jpeg_APP0 = 0xE0,
+    jpeg_APP12 = 0xEC,
+    jpeg_COM = 0xFE
+} JPEG_markers;
+
+int JPEG_next_marker( std::ifstream& jpeg_in )
+{
+    unsigned int c;
+    do {
+        c = JPEG_read1(jpeg_in);
+    } while( c != 0xFF );
+    do {
+        c = JPEG_read1(jpeg_in);
+    } while( c == 0xFF );
+    return c;
+}
+
+void JPEG_skip_segment( std::ifstream& jpeg_in )
+{
+    unsigned int l = JPEG_read2(jpeg_in);
+    jpeg_in.seekg( l-2, std::ios::cur );
+}
+
+typedef enum { IMAGE_GRAY=0, IMAGE_RGB=1, IMAGE_CMYK=2 } IPE_COLORSPACE;
+
+bool ReadJPEGData( std::ifstream& jpeg_in, int& image_width, int& image_height,
+                   int& image_colorspace, int& bitspercomponent )
+{
+    int required_segments = 0;
+    try {
+        const unsigned int soi = JPEG_read2(jpeg_in);
+        if( (soi & 0xFF) != jpeg_SOI )
+            return false;
+
+        while( required_segments != 3 && !jpeg_in.eof() ) {
+            const unsigned int marker = JPEG_next_marker(jpeg_in);
+            switch( marker ) {
+            case jpeg_APP0: {
+                unsigned int l = JPEG_read2(jpeg_in);
+                const char* JFIF = "JFIF";
+                for( int i=0; i<5; ++i )
+                    if( JFIF[i] != (int)JPEG_read1(jpeg_in) )
+                        return false;
+                jpeg_in.seekg( l-5-2, std::ios::cur );
+
+                required_segments |= 1;
+                break;
+            }
+            case jpeg_SOF0: 
+            case jpeg_SOF1: 
+            case jpeg_SOF2: 
+            case jpeg_SOF3: {
+                unsigned int l = JPEG_read2(jpeg_in);
+                bitspercomponent = JPEG_read1(jpeg_in);
+                image_height = JPEG_read2(jpeg_in);
+                image_width  = JPEG_read2(jpeg_in);
+                unsigned int ncomponents = JPEG_read1(jpeg_in);
+                switch( ncomponents ) {
+                case 1: image_colorspace = IMAGE_GRAY; break;
+                case 3: image_colorspace = IMAGE_RGB;  break;
+                case 4: image_colorspace = IMAGE_CMYK; break;
+                default:
+                    return false;
+                }
+                if( l != 8 + 3*ncomponents )
+                    throw std::string("Unexpected SOFx length.");
+                
+                required_segments |= 2;
+                break;
+            }
+            default:
+                JPEG_skip_segment(jpeg_in);
+            }
+        }
+    } catch( std::string msg ) {
+        fprintf(stderr, "Error while reading JPEG: %s.\n", msg.c_str() );
+    }
+    return required_segments == 3;
+}
+
+std::string make_safe_filename( const std::string& filename )
+{
+    std::ostringstream s_sf;
+    s_sf << '\'';
+    for( unsigned i=0; i<filename.size(); ++i ) {
+        if( filename[i]=='\'' )
+            s_sf << "'\"'\"'";
+        else
+            s_sf << filename[i];
+    }
+    s_sf << '\'';
+    return s_sf.str();
+}
+
+} // anonymous namespace
+
+// --------------------------------------------------------------------
+
+void FigWriter::WriteImage(const FigObject &obj)
+{
+    if( obj.iPoints.size() != 5 ) {
+        fprintf(stderr, "WARNING: image with != 5 points. Skipping.\n" );
+        return;
+    }
+
+    // build filename from directory and image filename
+    std::string filename;
+    const size_t firstdash = iFigName.find_first_of("\\/");
+    const size_t  lastdash = iFigName.find_last_of ("\\/");
+    if( firstdash>0 && lastdash != std::string::npos )
+        filename = iFigName.substr( 0, lastdash+1 );
+    filename += obj.image_filename;
+
+    // try to build safe filename
+    const std::string safe_filename = make_safe_filename( filename );
+
+    // image data to be filled by reading procedure
+    int image_width=0, image_height=0;
+    int image_colorspace = IMAGE_RGB;
+    int bitspercomponent = 8;
+    std::string image_data, filter;
+
+    std::ifstream jpeg_in( filename.c_str() );
+    
+    // try reading a JPEG file
+    if( ReadJPEGData( jpeg_in, image_width, image_height,
+                      image_colorspace, bitspercomponent ) ) {
+
+        // determine file size
+        jpeg_in.seekg( 0, std::ios::end );
+        const unsigned jpeg_size = jpeg_in.tellg();
+        jpeg_in.seekg( 0, std::ios::beg );
+
+        // copy file contents
+        image_data.resize( jpeg_size );
+        jpeg_in.read( const_cast<char*>(image_data.data()), jpeg_size );
+
+        if( jpeg_in.fail() ) {
+            fprintf(stderr, "WARNING: reading jpeg data failed. Skipping image.\n");
+            return;
+        }
+
+        filter = "DCTDecode";
+    } else {
+        // other images are read by anytopnm and then compressed
+
+        // build anytopnm command line
+        std::string cmd = "anytopnm ";
+        cmd += safe_filename;
+
+        // open pipe to read anytopnm output
+        FILE* anytopnm = popen( cmd.c_str(), "r" );
+        
+        // running anytopnm somehow failed
+        if( !anytopnm ) {
+            fprintf(stderr, "WARNING: anytopnm failed to run. Skipping image.\n");
+            return;
+        }
+        
+        try {
+            // check image type; should be P4 (pbm), P5 (pgm) or P6 (ppm)
+            char type_P, fmt;
+            if( fscanf( anytopnm, "%c%c", &type_P, &fmt ) != 2 )
+                throw std::string("anytopnm output not understood");
+            if( type_P!='P' || ( fmt!='4' && fmt!='5' && fmt!='6' ) )
+                throw std::string("anytopnm output not understood");
+            
+            if( fscanf( anytopnm, "%d %d", &image_width, &image_height ) != 2 )
+                throw std::string("anytopnm output not understood (w&h)");
+            if( image_width<=0 || image_width>5000 )
+                throw std::string("image width out of range [0,5000])");
+            if( image_height<=0 || image_height>5000 )
+                throw std::string("image height out of range [0,5000])");
+            
+            if( fmt=='4' ) {
+                // bitmap
+                throw std::string("bitmap not implemented");
+            } else {
+                int maxcolor;
+                if( fscanf( anytopnm, "%d", &maxcolor ) != 1 )
+                    throw std::string("anytopnm output not understood (maxcolor)");
+                if( maxcolor<=0 || maxcolor>65535 )
+                    throw std::string("anytopnm output not understood (maxcolor)");
+
+                bitspercomponent = 8;
+                image_colorspace = (fmt=='5') ? IMAGE_GRAY : IMAGE_RGB;
+
+                // skip single whitespace
+                (void)fgetc( anytopnm );
+                std::ostringstream idata;
+                for( int r=0; r<image_height; ++r ) {
+                    for( int c=0; c<image_width; ++c ) {
+                        for( int i=0; i<(fmt=='5' ? 1 : 3); ++i ) {
+                            int component = fgetc( anytopnm );
+                            if( component<0 )
+                                throw std::string("anytopnm output: eof");
+                            if( maxcolor>=256 ) {
+                                int component2 = fgetc( anytopnm );
+                                if( component2<0 )
+                                    throw std::string("anytopnm output: eof");
+                                if( maxcolor == 65535 ) {
+                                    component = component2;
+                                } else {
+                                    component = (component<<8) | component2;
+                                    component = int(255.0*component/float(maxcolor));
+                                }
+                            } else if( maxcolor!=255 ) {
+                                component = int(255.0*component/float(maxcolor));
+                            }
+                            const unsigned char c = (unsigned char)component;
+                            idata.write( (const char*)&c, 1 );
+                        }
+                    }
+                }
+                image_data = idata.str();
+            }
+            pclose( anytopnm );
+        } catch( std::string msg ) {
+            pclose( anytopnm );
+            fprintf(stderr, "WARNING: anytopnm problem. Skipping image.\n");
+            return;
+        }
+        
+        if( true ) {
+            // compress image
+            const uLongf zbuf_size = compressBound( image_data.size() );
+            uLongf compressed_size = zbuf_size;
+            char zbuf[zbuf_size];
+            const int ok = compress2( (Bytef*)zbuf, &compressed_size,
+                                      (const Bytef*)image_data.data(),
+                                      image_data.size(), 9 );
+            if( ok == Z_OK ) {
+                image_data = std::string(zbuf, zbuf+compressed_size);
+                filter = "FlateDecode";
+            } else {
+                fprintf(stderr, "Failed to compress image (%d)."
+                        " Will store uncompressed image.\n", ok );
+            }
+        }
+    }
+
+    if( bitspercomponent != 8 ) {
+        fprintf(stderr, "WARNING: Unsupported n.o. bits per component. Skipping image.\n");
+        return;
+    }
+
+    fprintf(iXml, "<image " );
+    if( image_width>0 && image_height>0 )
+        fprintf(iXml, "width=\"%d\" height=\"%d\" ", image_width, image_height );
+
+    const char* image_colorspaces[3] = { "DeviceGray", "DeviceRGB", "DeviceCMYK" };
+    fprintf(iXml, "ColorSpace=\"%s\" BitsPerComponent=\"8\" ",
+            image_colorspaces[image_colorspace] );
+    if( !filter.empty() )
+         fprintf(iXml, " length=\"%ld\" Filter=\"%s\"", long(image_data.size()), filter.c_str() );
+
+    const double x1 = X(obj.iPoints[0].iX), y1 = Y(obj.iPoints[0].iY);
+    const double x2 = X(obj.iPoints[2].iX), y2 = Y(obj.iPoints[2].iY);
+    if( obj.image_flipped ) {
+        const double r = (x2-x1)/(y2-y1);
+        const double tx = (x1+x2)/2, ty = (y1+y2)/2;
+        fprintf(iXml, " matrix=\"0 %f %f 0 %f %f\"", 1/r, r, tx-r*ty, ty-tx/r );
+    }
+    fprintf(iXml, " rect=\"%g %g %g %g\"", x1, y1, x2, y2 );
+    
+    fprintf(iXml, ">\n" );
+
+    int linebreak=0;
+    for( unsigned i=0; i<image_data.size(); ++i ) {
+        const char hexchars[] = "0123456789abcdef";
+        const unsigned char c = image_data[i];
+        fprintf(iXml, "%c%c", hexchars[(c/16)&0xF], hexchars[c&0xF] );
+        if( ++linebreak == 36 ) {
+            linebreak = 0;
+            fputc( '\n', iXml );
+        }
+    }
+    if( linebreak > 0 )
+        fputc( '\n', iXml );
+    
+    fprintf(iXml, "</image>\n");
+    return;
+}
+
+void FigWriter::WritePolyline(const FigObject &obj)
+{
+  /* 1: polyline
+     2: box
+     3: polygon
+     4: arc-box
+     5: imported-picture bounding-box
+  */
+  if (obj.iPoints.size() < 2) {
+    fprintf(stderr, "WARNING: polyline with less than two vertices ignored.\n");
+    return;
+  }
+  if (obj.iThickness == 0 && obj.iAreaFill==-1 ) {
+      fprintf(stderr, "WARNING: polyline with neither fill nor line ignored.\n");
+      return;
+  }
+  if (obj.iSubtype == 4)
+    fprintf(stderr, "WARNING: turning arc-box into rectangle.\n");
+  if (obj.iSubtype == 5) {
+      WriteImage( obj );
+      return;
+  }
+  fprintf(iXml, "<path ");
+  WriteStroke(obj);
+  WriteFill(obj);
+  WriteLineStyle(obj);
+  WriteArrows(obj);
+  if (obj.iJoinStyle)
+    fprintf(iXml, " join=\"%d\"", obj.iJoinStyle);
+  if (obj.iCapStyle)
+    fprintf(iXml, " cap=\"%d\"", obj.iCapStyle);
+  fprintf(iXml, ">\n");
+  for (unsigned int i = 0; i < obj.iPoints.size(); ++i) {
+    double x = obj.iPoints[i].iX;
+    double y = obj.iPoints[i].iY;
+    if (i == 0) {
+      fprintf(iXml, "%g %g m\n", X(x), Y(y));
+    } else if (i == obj.iPoints.size() - 1 && obj.iSubtype > 1) {
+      fprintf(iXml, "h\n"); // close path
+    } else {
+      fprintf(iXml, "%g %g l\n", X(x), Y(y));
+    }
+  }
+  fprintf(iXml, "</path>\n");
+}
+
+void FigWriter::WriteSpline(const FigObject &obj)
+{
+  /* 0: opened approximated spline
+     1: closed approximated spline
+     2: opened interpolated spline
+     3: closed interpolated spline
+     4: opened x-spline (FIG 3.2)
+     5: closed x-spline (FIG 3.2)
+  */
+  FigObject obj1 = obj;
+  obj1.iJoinStyle = 0;
+  obj1.iSubtype = (obj.iSubtype & 1) ? 3 : 1;
+  fprintf(stderr, "WARNING: spline replaced by polyline.\n");
+  WritePolyline(obj1);
+}
+
+void FigWriter::WriteText(const FigObject &obj)
+{
+  const double tx = X(obj.iPos.iX), ty = Y(obj.iPos.iY);
+  fprintf(iXml, "<text size=\"%g\" pos=\"%g %g\"",
+	  iMagnification * obj.iFontSize, tx, ty );
+  WriteStroke(obj);
+  // 0: Left justified; 1: Center justified; 2: Right justified
+  if (obj.iSubtype == 1)
+    fprintf(iXml, " halign=\"center\"");
+  else if (obj.iSubtype == 2)
+    fprintf(iXml, " halign=\"right\"");
+  if (!(obj.iFontFlags & 1) || obj.iAngle != 0.0) {
+    if( ipe7 )
+      fprintf(iXml, " transformations=\"affine\"");
+    else
+      fprintf(iXml, " transformable=\"yes\"");
+  }
+  if (obj.iAngle != 0.0) {
+    double ca = 0, sa = 0;
+    if( obj.iAngle == 1.5708 )
+      sa = 1;
+    else if( obj.iAngle == -1.5708 )
+      sa = -1;
+    else {
+      ca = cos(obj.iAngle);
+      sa = sin(obj.iAngle);
+    }
+    const double mtx = -sa*ty + ca*tx - tx, mty = ca*ty - ty + sa*tx;
+    fprintf(iXml, " matrix=\"%f %f %f %f %f %f\"", ca, sa, -sa, ca, -mtx, -mty);
+  }
+  fprintf(iXml, " type=\"label\">");
+  int font = obj.iFont;
+  if (obj.iFontFlags & 2) {
+    // "special" Latex text
+    font = 0; // needs no special treatment
+  } else if (obj.iFontFlags & 4) {
+    // Postscript font: set font to default
+    font = 0;
+    fprintf(stderr, "WARNING: postscript font ignored.\n");
+  }
+  switch (font) {
+  case 0: // Default font
+    fprintf(iXml, "%s", &obj.iString[0]);
+    break;
+  case 1: // Roman
+    fprintf(iXml, "\\textrm{%s}", &obj.iString[0]);
+    break;
+  case 2: // Bold
+    fprintf(iXml, "\\textbf{%s}", &obj.iString[0]);
+    break;
+  case 3: // Italic
+    fprintf(iXml, "\\emph{%s}", &obj.iString[0]);
+    break;
+  case 4: // Sans Serif
+    fprintf(iXml, "\\textsf{%s}", &obj.iString[0]);
+    break;
+  case 5: // Typewriter
+    fprintf(iXml, "\\texttt{%s}", &obj.iString[0]);
+    break;
+  }
+  fprintf(iXml, "</text>\n");
+}
+
+void FigWriter::WriteArc(const FigObject &obj)
+{
+  if (obj.iThickness == 0 && obj.iAreaFill==-1 ) {
+      fprintf(stderr, "WARNING: arc with neither fill nor line ignored.\n");
+      return;
+  }
+  // 0: pie-wedge (closed); 1: open ended arc
+  fprintf(iXml, "<path ");
+  WriteStroke(obj);
+  WriteFill(obj);
+  WriteLineStyle(obj);
+  fprintf(iXml, ">\n");
+  Point beg = (obj.iDirection == 0) ? obj.iArc3 : obj.iArc1;
+  Point end = (obj.iDirection == 0) ? obj.iArc1 : obj.iArc3;
+  fprintf(iXml, "%g %g m\n", X(beg.iX), Y(beg.iY));
+  double dx = obj.iArc1.iX - obj.iCenterX;
+  double dy = obj.iArc1.iY - obj.iCenterY;
+  double radius = sqrt(dx*dx + dy*dy);
+  fprintf(iXml, "%g 0 0 %g %g %g %g %g a\n</path>\n",
+	  X(radius), X(radius),
+	  X(obj.iCenterX), Y(obj.iCenterY),
+	  X(end.iX), Y(end.iY));
+}
+
+// --------------------------------------------------------------------
+
+static void print_help_message()
+{
+  fprintf(stderr, "figtoipe is part of the extensible drawing editor Ipe.\n"
+	  "  Copyright (C) 1993-2008 Otfried Cheong <otfried at ipe.airpost.net>\n"
+	  "  This is free software with ABSOLUTELY NO WARRANTY.\n"
+	  "\n"
+	  "Use: figtoipe [-g] [-c] [-p preamble] <figfile> <xmlfile>\n"
+	  "  converts a file in FIG format to Ipe's XML format\n"
+	  "  -g          -- puts the produced figure into a group\n"
+          "  -c          -- use cropbox for size of figure\n"
+          "  -6          -- write in ipe 6 format instead of ipe 7 format\n"
+	  "  -p preamble -- inserts a preamble (e.g. '\\usepackage{amsmath}')\n"
+	  );
+  exit(9);
+}
+
+// --------------------------------------------------------------------
+
+static bool simple_getopt( const char* option, bool has_arg, const char* &value, int &argc, char** argv )
+{
+    bool found = false;
+    for( int a=1; a<argc; a++ ) {
+        if( strcmp( option, argv[a] ) == 0 && (!has_arg || a+1 < argc) ) {
+            const int shift = has_arg ? 2 : 1;
+            value = has_arg ? argv[a+1] : 0;
+            for( int aa=a; aa<argc-shift; aa++ )
+                argv[aa] = argv[aa+shift];
+            argc -= shift;
+            a--;
+            found = true;
+        }
+    }
+    return found;
+}
+
+// --------------------------------------------------------------------
+
+int main(int argc, char **argv)
+{
+  bool group = false, cropbox = false;
+  std::string preamble = "";
+  const char* arg;
+
+  if( simple_getopt("-6", false, arg, argc, argv) )
+      ipe7 = false;
+  if( simple_getopt("-g", false, arg, argc, argv) )
+      group = true;
+  if( simple_getopt("-c", false, arg, argc, argv) )
+      cropbox = true;
+  if( simple_getopt("-p", true, arg, argc, argv) )
+      preamble = arg;
+  if( argc != 3 )
+      print_help_message();
+
+  const char *figname = argv[1];
+  const char *xmlname = argv[2];
+
+  FILE *fig = fopen(figname, "r");
+  if (!fig) {
+    fprintf(stderr,"figtoipe: cannot open '%s'\n", figname);
+    exit(-1);
+  }
+
+  FigReader fr(fig);
+  if (!fr.ReadHeader()) {
+    fprintf(stderr, "figtoipe: cannot parse header of '%s'\n", figname);
+    exit(-1);
+  }
+
+  fprintf(stderr,
+	  "Converting at %g FIG units per point, magnification %g.\n",
+	  fr.UnitsPerPoint(), fr.Magnification());
+
+  if (!fr.ReadObjects()) {
+    fprintf(stderr, "Error reading FIG file.\n");
+    exit(9);
+  }
+  fclose(fig);
+
+  FILE *xml = fopen(xmlname, "w");
+  if (!xml) {
+    fprintf(stderr, "figtoipe: cannot open '%s'\n", xmlname);
+    exit(-1);
+  }
+
+  FigWriter fw(xml, figname, fr.Magnification(), fr.UnitsPerPoint(), fr.UserColors());
+
+  if( ipe7 ) {
+      fprintf(xml, "<?xml version=\"1.0\"?>\n"
+              "<!DOCTYPE ipe SYSTEM \"ipe.dtd\">\n");
+  }
+  fprintf(xml, "<ipe version=\"%s\" creator=\"%s\">\n",
+          ipe7 ? "70000" : "60028",
+          FIGTOIPE_VERSION);
+  if( ipe7 ) {
+      fprintf(xml, "<info/>\n");
+  } else {
+      fprintf(xml, "<info media=\"%d %d %d %d\"%s/>\n",
+              0, 0, MEDIABOX_WIDTH, MEDIABOX_HEIGHT,
+              cropbox ? " bbox=\"cropbox\"" : "");
+  }
+
+  if( !preamble.empty() )
+    fprintf(xml, "<preamble>%s\n</preamble>\n", preamble.c_str());
+
+  if( ipe7 ) {
+      fprintf(xml, "<ipestyle name=\"ipe6colors\">\n"
+              "<color name=\"red\" value=\"1 0 0\"/>\n"
+              "<color name=\"green\" value=\"0 1 0\"/>\n"
+              "<color name=\"blue\" value=\"0 0 1\"/>\n"
+              "<color name=\"yellow\" value=\"1 1 0\"/>\n"
+              "<color name=\"gray1\" value=\"0.125\"/>\n"
+              "<color name=\"gray2\" value=\"0.25\"/>\n"
+              "<color name=\"gray3\" value=\"0.375\"/>\n"
+              "<color name=\"gray4\" value=\"0.5\"/>\n"
+              "<color name=\"gray5\" value=\"0.625\"/>\n"
+              "<color name=\"gray6\" value=\"0.75\"/>\n"
+              "<color name=\"gray7\" value=\"0.875\"/>\n"
+              "</ipestyle>\n");
+
+      fprintf(xml, "<ipestyle>\n<layout paper=\"%d %d\" origin=\"0 0\" frame=\"%d %d\"%s/>\n</ipestyle>\n",
+              MEDIABOX_WIDTH, MEDIABOX_HEIGHT,
+              MEDIABOX_WIDTH, MEDIABOX_HEIGHT,
+              cropbox ? "" : " crop=\"no\"");
+  }
+  fprintf(xml, "<page>\n");
+
+  if( group )
+    fprintf(xml, "<group>\n");
+
+  fw.WriteObjects(fr.Objects(), 0, fr.Objects().size());
+
+  if( group )
+    fprintf(xml, "</group>\n");
+
+  fprintf(xml, "</page>\n");
+  fprintf(xml, "</ipe>\n");
+
+  fclose(xml);
+  return 0;
+}
+
+// --------------------------------------------------------------------
diff --git a/figtoipe/readme.txt b/figtoipe/readme.txt
new file mode 100644
index 0000000..eafdb3d
--- /dev/null
+++ b/figtoipe/readme.txt
@@ -0,0 +1,43 @@
+
+Figtoipe
+========
+
+This is Figtoipe, a program that reads FIG files (as generated by
+xfig) and generates an XML file readable by Ipe.
+
+Compile by saying
+	make
+
+A changelog is in the source file "figtoipe.cpp".
+
+Before reporting a bug, check that you have the latest version, and
+check that it is not yet mentioned in the FAQ on the Ipe webpage.
+
+You can report bugs on the issue tracking system at
+"https://github.com/otfried/ipe-tools/issues".
+
+Check the existing reports to see whether your bug has already been
+reported.  Please do not send bug reports directly to us (the first
+thing we would do with the report is to enter it into the bug tracking
+system).
+
+Suggestions for features, or random comments on Figtoipe can be sent
+to the Ipe discussion mailing list at <ipe-discuss at cs.uu.nl>.  You can
+also send suggestions or comments directly to us by Email, but you
+should then not expect a reply.
+
+        Alexander Bürger, acfb at users.sourceforge.net
+	Otfried Cheong, otfried at ipe.airpost.net
+
+	Ipe webpage: http://ipe7.sf.net
+
+--------------------------------------------------------------------
+
+figtoipe comes with ABSOLUTELY NO WARRANTY. It is free software; you
+can redistribute it and/or modify it under the terms of the GNU
+General Public License as published by the Free Software Foundation;
+either version 2 of the License, or (at your option) any later
+version.
+
+See the file gpl.txt for details.
+
diff --git a/gpl.txt b/gpl.txt
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/gpl.txt
@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/ipe5toxml/Makefile b/ipe5toxml/Makefile
new file mode 100644
index 0000000..15e502b
--- /dev/null
+++ b/ipe5toxml/Makefile
@@ -0,0 +1,26 @@
+#
+# Makefile for ipe5toxml
+#
+
+ifdef COMSPEC
+TARGET = ipe5toxml.exe
+LDFLAGS = -mconsole
+else
+TARGET = ipe5toxml
+endif
+
+LIBS = -lm
+
+all: $(TARGET)
+
+sources	= ipe5toxml.c
+
+objects = ipe5toxml.o
+
+$(TARGET): $(objects)
+	$(CC) $(LDFLAGS) -o $(TARGET) $(objects) $(LIBS)
+
+.PHONY: clean
+clean:
+	@-rm -f $(objects) $(TARGET) 
+
diff --git a/ipe5toxml/ipe5toxml.1 b/ipe5toxml/ipe5toxml.1
new file mode 100644
index 0000000..95291e9
--- /dev/null
+++ b/ipe5toxml/ipe5toxml.1
@@ -0,0 +1,18 @@
+.TH IPE5TOXML "1" "December 2011" "Ipe" "User Commands"
+
+.SH NAME
+ipe5toxml \- Convert Ipe 5 file to Ipe 6 format
+
+.SH SYNOPSIS
+.B ipe5toxml
+\fIfile.ipe file.xml\fR
+
+.SH DESCRIPTION
+\fBipe5toxml\fR converts an Ipe version 5 format file to one understood by Ipe version 6.
+Use \fBipe6upgrade\fR to convert the output XML file to one understood by Ipe version 7.
+
+.SH AUTHOR
+Otfried Cheong
+
+.SH "SEE ALSO"
+\fBipe6upgrade\fR(1)
diff --git a/ipe5toxml/ipe5toxml.c b/ipe5toxml/ipe5toxml.c
new file mode 100644
index 0000000..11e4ee1
--- /dev/null
+++ b/ipe5toxml/ipe5toxml.c
@@ -0,0 +1,1231 @@
+/*
+ * ipe5toxml.c
+ * 
+ * This program converts files in Ipe format (as used by Ipe up to
+ * version 5.0) to XML format as used by Ipe 6.0.
+ */
+
+#define IPE5TOXML_VERSION "ipe5toxml 2015/04/04"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <math.h>
+
+/* Ipe Object Types */
+
+#define IPE_LINE       0
+#define IPE_TEXT       1
+#define IPE_CIRCLE     2
+#define IPE_MARK       3
+#define IPE_ARC        4
+#define IPE_BITMAP     5
+#define IPE_SPLINE     6
+#define IPE_BEGINGROUP 7
+#define IPE_ENDGROUP   8
+#define IPE_SEGMENTS   9
+
+const double SPLINE_MULTI_THRESHOLD_SQUARED = 0.01;
+
+const double IpePi = 3.1415926535897932385;
+
+/* Ipe Color Type
+   the empty color has entry -1 for red */
+
+typedef struct _IpeColor {
+  double red, green, blue;
+} IpeColor;
+
+/* Ipe Font Type */
+
+#define IPE_ROMAN   0
+#define IPE_ITALIC  1
+#define IPE_BOLD    2
+#define IPE_MATH    3
+
+typedef int bool;
+typedef struct { double x, y; } vertex;
+typedef struct { double xmin, xmax, ymin, ymax; } bbox;
+
+/* the Environment where the IUM is called */
+
+typedef struct _IpeEnvironment {
+  IpeColor stroke, fill;	/* current stroke and fill colors  */
+  unsigned short linestyle;     /* solid, dashed etc. as 16 bits   */
+  double linewidth;		/* linewidth of stroke             */
+  short arrow;			/* two bits for two arrows         */
+  double arsize;                 /* size of arrows                  */
+  double marksize;               /* size of marks                   */
+  double gridsize;               /* grid size                       */
+  double snapangle;              /* snap angle                      */
+  short marktype;               /* type of mark (1 .. 5)           */
+  short font;                   /* font of text object             */
+  double fontsize;               /* fontsize                        */
+  bool  axisset;                /* is an axis system defined ?     */
+  vertex origin;                /* if so, this is the origin       */
+  double axisdir;                /*    and this the base direction  */
+} IpeEnvironment;
+
+typedef struct _Line {		/* also used for splines	   */
+  bool closed;		        /* true if closed curve (polygon)  */
+  short arrow;			/* two bits for two arrows         */
+  double arsize;                 /* size of arrows                  */
+  int n;                        /* number of vertices              */
+  vertex *v;                    /* pointer to array of vertices    */
+  char *vtype;                  /* pointer to array of vertex type */
+                                /* indicators N L E C              */
+} Line;
+
+typedef struct _Circle {
+  vertex center;                /* center of circle                */
+  double radius;                 /* radius of circle                */
+  bool  ellipse;                /* is object an ellipse ?          */
+  double tfm[4];                 /* tfm values from file            */
+} Circle;
+
+typedef struct _Mark {
+  vertex pos;                   /* position                        */
+  short type;                   /* type of mark (1 .. 5)           */
+  double size;                   /* size of mark                    */
+} Mark;
+
+typedef struct _Arc {
+  short arrow;			/* two bits for two arrows         */
+  double arsize;                 /* size of arrows                  */
+  vertex center;                /* center of arc                   */
+  double radius;                 /* radius of arc                   */
+  double begangle, endangle;     /* two angles in radians           */
+} Arc;
+
+typedef struct _Text {
+  char *str;                    /* the string                      */
+  short font;                   /* font                            */
+  double fontsize;               /* LaTeX fontsize                  */
+  vertex pos;                   /* position of text                */
+  bool minipage;                /* true if text is minipage        */
+  vertex ll, ur;                /* ll and ur vertex of bounding box*/
+} Text;
+
+typedef struct _Bitmap {
+  vertex ll, ur;      		/* lower left, upper right corner  */
+  short width, height;          /* no of bits in bitmap            */
+  unsigned long *words;         /* pointer to width*height pixels  */
+  bool in_color;                /* color bitmap ?                  */
+} Bitmap;
+
+typedef struct _IpeObject {
+  int type;                     /* type of this object             */
+  IpeColor stroke, fill;        /* stroke and fill color of object */
+  unsigned short linestyle;	/* solid, dashed etc. as 16 bits   */
+  double linewidth;		/* linewidth of stroke             */
+  struct _IpeObject *next;      /* pointer to next object          */
+
+  union W {
+    Line   *line;
+    Circle *circle;
+    Mark   *mark;
+    Text   *text;
+    Arc    *arc;
+    Bitmap *bitmap;
+  } w ;
+
+} IpeObject;
+
+/* the current Ipe environment when IUM is called */
+
+extern IpeEnvironment ipe_environment;
+
+/* input and output for IUM */
+
+extern IpeObject *ium_input;     /* selected objects from Ipe       */
+extern IpeObject *ium_output;    /* IUM generated things to Ipe     */
+
+#define MAX_LINE_LENGTH 1024
+
+#define FALSE 0
+#define TRUE 1
+
+#ifdef __cplusplus
+#define NEWOBJECT(Type) (new Type)
+#define NEWARRAY(Type, Size) (new Type[Size])
+#define FREEARRAY(Ptr) delete [] Ptr
+#else
+#define NEWOBJECT(Type) ((Type *) malloc(sizeof(Type)))
+#define NEWARRAY(Type, Size) ((Type *) malloc(Size * sizeof(Type)))
+#define FREEARRAY(Ptr) free(Ptr)
+#endif
+
+#ifdef sun
+#define BITS char
+#else
+#define BITS void
+#endif
+
+#define SETXY(v, x, y) v.x = x; v.y = y
+#define XCOORD x
+#define YCOORD y
+
+/* the current Ipe environment when IUM is called */
+
+IpeEnvironment ipe_environment;
+
+/* IUM input and output */
+
+IpeObject *ium_input;
+IpeObject *ium_output;
+
+static char *ipename;
+static char *xmlname;
+static FILE *fh;
+static char linebuf[MAX_LINE_LENGTH];
+static int grouplevel = 0;
+static int firstpage = 0;
+static bool in_settings = TRUE;
+
+/******************** reading ******************************************/
+
+static void assert_n(int n_expected, int n_actual)
+{
+  if (n_expected != n_actual)  {
+    fprintf(stderr, "Fatal error: failed to parse input\n");
+    exit(9);
+  }
+  return;
+}
+
+static void assert_fgets(char* s, int size, FILE* stream)
+{
+  if (fgets(s, size, stream) != s) {
+    fprintf(stderr, "Fatal error: failed to read input\n");
+    exit(9);
+  }
+  return;
+}
+
+static char *read_next(void)
+{
+  int ch2, ch1, ch;
+  char *p;
+  
+  /* read words until we find a sole "%" */
+  ch2 = ch1 = ch = ' ';
+  
+  while ((ch = fgetc(fh)) != EOF &&
+	 !(ch1 == '%' && isspace(ch2) && isspace(ch))) {
+    ch2 = ch1;
+    ch1 = ch;
+  }
+
+  if (ch == EOF) {
+    /* read error (could be EOF, then it's a format error) */
+    fprintf(stderr, "Error reading IPE file %s\n", ipename);
+    exit(9);
+  }
+
+  /* next word is keyword */
+  
+  p = linebuf;
+  while ((*p = fgetc(fh)), *p != EOF && (p < (linebuf + sizeof(linebuf) -1)) && !isspace(*p))
+    p++;
+  *p = '\0';
+
+  /* fprintf(stderr, " %s ", linebuf);*/
+  return linebuf;
+}
+
+/* temporary storage for read_env and read_entry */
+
+static struct {
+  bool closed;
+  vertex xy;
+  bool minipage;
+  double wd, ht, dp;
+  double radius;
+  double begangle, endangle;
+  char *str;
+  int n;
+  vertex *v;
+  char *vtype;
+  bool ellipse;
+  double tfm[4];
+  unsigned long *words;
+  int xbits, ybits;
+  bool bmcolor;
+} rd;
+
+static void read_env(IpeEnvironment *ienv)
+{
+  char *wk;
+  double x, y;
+  int i;
+  
+  ienv->stroke.red = ienv->stroke.green = ienv->stroke.blue = -1;
+  ienv->fill.red = ienv->fill.green = ienv->fill.blue = -1;
+  ienv->linestyle = 0;
+  ienv->linewidth = 0.4;
+  ienv->arrow = 0;
+  ienv->axisset = FALSE;
+  rd.closed = FALSE;
+  /* init transformation to identity */
+  rd.tfm[0] = rd.tfm[3] = 1.0;
+  rd.tfm[1] = rd.tfm[2] = 0.0;
+  rd.minipage = FALSE;
+  rd.ellipse = FALSE;
+  rd.str = NULL;
+  rd.v = NULL;
+  rd.vtype = NULL;
+  
+  while (TRUE) {
+    wk = read_next();
+    if (!strcmp(wk, "sk")) {
+      assert_n(1, fscanf(fh, "%lf", &ienv->stroke.red));
+      ienv->stroke.blue = ienv->stroke.green = ienv->stroke.red;
+    } else if (!strcmp(wk, "fi")) {
+      assert_n(1, fscanf(fh, "%lf", &ienv->fill.red));
+      ienv->fill.blue = ienv->fill.green = ienv->fill.red;
+    } else if (!strcmp(wk, "skc")) {
+      assert_n(3, fscanf(fh, "%lf%lf%lf",
+              &ienv->stroke.red, &ienv->stroke.green, &ienv->stroke.blue));
+    } else if (!strcmp(wk, "fic")) {
+      assert_n(3, fscanf(fh, "%lf%lf%lf",
+              &ienv->fill.red, &ienv->fill.green, &ienv->fill.blue));
+    } else if (!strcmp(wk, "ss")) {
+      assert_n(2, fscanf(fh, "%hu%lf", &ienv->linestyle, &ienv->linewidth));
+    } else if (!strcmp(wk, "ar")) {
+      assert_n(2, fscanf(fh, "%hu%lf", &ienv->arrow, &ienv->arsize));
+    } else if (!strcmp(wk, "cl")) {
+      rd.closed = TRUE;
+    } else if (!strcmp(wk, "f")) {
+      assert_n(2, fscanf(fh, "%hu%lf", &ienv->font, &ienv->fontsize));
+    } else if (!strcmp(wk, "grid")) {
+      assert_n(2, fscanf(fh, "%lf%lf", &ienv->gridsize, &ienv->snapangle));
+    } else if (!strcmp(wk, "ty")) {
+      assert_n(1, fscanf(fh, "%hu", &ienv->marktype));
+    } else if (!strcmp(wk, "sz")) {
+      assert_n(1, fscanf(fh, "%lf",  &ienv->marksize));
+    } else if (!strcmp(wk, "xy")) {
+      assert_n(2, fscanf(fh, "%lf%lf", &x, &y));
+      SETXY(rd.xy, x, y);
+    } else if (!strcmp(wk, "px")) {
+      assert_n(2, fscanf(fh, "%d%d", &rd.xbits, &rd.ybits));
+    } else if (!strcmp(wk, "bb")) {
+      rd.minipage = TRUE;
+      assert_n(2, fscanf(fh, "%lf%lf", &rd.wd, &rd.ht));
+      rd.dp = rd.ht;
+    } else if (!strcmp(wk, "tbb")) {
+      rd.minipage = FALSE;
+      assert_n(2, fscanf(fh, "%lf%lf%lf", &rd.wd, &rd.ht, &rd.dp));
+    } else if (!strcmp(wk, "ang")) {
+      assert_n(2, fscanf(fh, "%lf%lf", &rd.begangle, &rd.endangle));
+    } else if (!strcmp(wk, "r")) {
+      assert_n(1, fscanf(fh, "%lf", &rd.radius));
+    } else if (!strcmp(wk, "tfm")) {
+      rd.ellipse = TRUE;
+      assert_n(4, fscanf(fh, "%lf%lf%lf%lf", &rd.tfm[0], &rd.tfm[1], &rd.tfm[2], &rd.tfm[3]));
+    } else if (!strcmp(wk, "axis")) {
+      ienv->axisset = TRUE;
+      assert_n(3, fscanf(fh, "%lf%lf%lf", &x, &y, &ienv->axisdir));
+      SETXY(ienv->origin, x, y);
+    } else if (!strcmp(wk, "#")) {
+      /* vertices of a polyline */
+      int ch;
+      assert_n(1, fscanf(fh, "%d", &rd.n));
+      rd.v = NEWARRAY(vertex, rd.n);
+      rd.vtype = NEWARRAY(char, rd.n);
+      for (i = 0; i < rd.n; i++ ) {
+	assert_n(2, fscanf(fh, "%lf%lf", &x, &y));
+	SETXY(rd.v[i], x, y);
+	/* find character */
+	do {
+	  ch = fgetc(fh);
+	} while (ch != EOF && isspace(ch) && ch != '\n');
+	if (ch == '\n') {
+	  rd.vtype[i] = ' ';
+	} else {
+	  rd.vtype[i] = (char) (ch & 0xff);
+	  /* skip to next line */
+	  while ((ch = fgetc(fh)) != EOF && ch != '\n')
+	    ;
+	}
+      }
+    } else if (!strcmp(wk, "s")) {
+      /* get string */
+      assert_fgets(linebuf, MAX_LINE_LENGTH, fh);
+      linebuf[strlen(linebuf) - 1] = '\0';
+      if (!rd.str) {
+	/* first string */
+	rd.str = strdup(linebuf);
+      } else {
+	char *ns = NEWARRAY(char, (strlen(rd.str) + strlen(linebuf) + 2));
+	strcpy(ns, rd.str);
+	strcat(ns, "\n");
+	strcat(ns, linebuf);
+	free(rd.str);
+	rd.str = ns;
+      }
+    } else if (!strcmp(wk, "bits")) {
+      /* get bitmap */
+      unsigned long nwords;
+      long i, incolor, nchars;
+      int ch, mode;
+      char *p, *strbits, buf[3];
+      short red, green, blue;
+      
+      assert_n(2, fscanf(fh, "%ld%d", &nwords, &mode));
+      incolor = mode & 1;
+      if (mode & 0x8) {
+	/* read RAW bitmap */
+	do {
+	  if ((ch = fgetc(fh)) == EOF) {
+	    fprintf(stderr, "EOF while reading RAW bitmap\n");
+	    exit(9);
+	  }
+	} while (ch != '\n');
+	rd.bmcolor = incolor ? TRUE : FALSE;
+	rd.words = NEWARRAY(unsigned long, nwords);
+	if (mode & 0x01) {
+	  /* color bitmap: 32 bits per pixel */
+	  if (fread((BITS *) rd.words, sizeof(unsigned long),
+		    ((unsigned int) nwords), fh)
+	      != nwords) {
+	    fprintf(stderr, "Error reading RAW bitmap\n");
+	    exit(9);
+	  }
+	} else {
+	  /* gray bitmap: 8 bits per pixel */
+	  register char *inp, *end;
+	  register unsigned long *out;
+	  char *pix = NEWARRAY(char, nwords);
+	  if (fread((BITS *) pix, sizeof(char), ((unsigned int) nwords), fh)
+	      != nwords) {
+	    fprintf(stderr, "Error reading RAW bitmap\n");
+	    exit(9);
+	  }
+	  /* convert to unsigned longs */
+	  inp = pix;
+	  end = pix + nwords;
+	  out = rd.words;
+	  while (inp < end) {
+	    *out++ = (*inp << 16) | (*inp << 8) | (*inp);
+	    inp++;
+	  }
+	  FREEARRAY(pix);
+	}	  
+      } else {
+	/* read Postscript style bitmap */
+	nchars = (incolor ? 6 : 2) * nwords;
+	p = strbits = NEWARRAY(char, nchars);
+	for (i = 0; i < nchars; i++) {
+	  do {
+	    if ((ch = fgetc(fh)) == EOF) {
+	      fprintf(stderr, "EOF while reading bitmap\n");
+	      exit(9);
+	    }
+	  } while (!(('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'f')));
+	  *p++ = ch;
+	}
+	p = strbits;
+	rd.words = NEWARRAY(unsigned long, nwords);
+	rd.bmcolor = incolor ? TRUE : FALSE;
+	buf[2] = '\0';
+	for (i = 0; i < ((int) nwords); ) {
+	  buf[0] = *p++;
+	  buf[1] = *p++;
+	  red = ((short) strtol(buf, NULL, 16));
+	  if (incolor) {
+	    buf[0] = *p++;
+	    buf[1] = *p++;
+	    green = ((short) strtol(buf, NULL, 16));
+	    buf[0] = *p++;
+	    buf[1] = *p++;
+	    blue = ((short) strtol(buf, NULL, 16));
+	    rd.words[i++] = (blue * 0x10000) | (green * 0x100) | red;
+	  } else {
+	    rd.words[i++] = (red * 0x10000) | (red * 0x100) | red;
+	  }
+	}
+	free(strbits);
+      }
+    } else if (!strcmp(wk, "End")) {
+      return;
+    } else {
+      if (in_settings) {
+	/* unknown keyword in settings: ignore this line */
+	assert_fgets(linebuf, MAX_LINE_LENGTH, fh);
+      } else {
+	/* unknown keyword in an object: this is serious */
+	fprintf(stderr, "Illegal keyword %s in IPE file %s\n",
+		wk, ipename);
+	exit(9);
+      }
+    }
+  }
+}
+
+static void addtobox(bbox *bb, double x, double y)
+{
+  if (x < bb->xmin)
+    bb->xmin = x;
+  if (x > bb->xmax)
+    bb->xmax = x;
+  if (y < bb->ymin)
+    bb->ymin = y;
+  if (y > bb->ymax)
+    bb->ymax = y;
+}
+
+static IpeObject *read_entry(bbox *bb)
+{
+  char *wk;
+  int i;
+  IpeObject *iobj;
+  IpeEnvironment ienv;
+
+  iobj = NEWOBJECT(IpeObject);
+  
+  iobj->next = NULL;
+
+  wk = read_next();
+  
+  if (!strcmp(wk, "Group")) {
+    iobj->type = IPE_BEGINGROUP;
+    grouplevel++;
+    return iobj;
+  } else if (!strcmp(wk, "End")) {
+    iobj->type = IPE_ENDGROUP;
+    grouplevel--;
+    return ((grouplevel >= 0) ? iobj : NULL);
+  } else if (!strcmp(wk, "Line")) {
+    iobj->type = IPE_LINE;
+  } else if (!strcmp(wk, "Segments")) {
+    iobj->type = IPE_SEGMENTS;
+  } else if (!strcmp(wk, "Spline")) {
+    iobj->type = IPE_SPLINE;
+  } else if (!strcmp(wk, "Text")) {
+    iobj->type = IPE_TEXT;
+  } else if (!strcmp(wk, "Circle")) {
+    iobj->type = IPE_CIRCLE;
+  } else if (!strcmp(wk, "Arc")) {
+    iobj->type = IPE_ARC;
+  } else if (!strcmp(wk, "Mark")) {
+    iobj->type = IPE_MARK;
+  } else if (!strcmp(wk, "Bitmap")) {
+    iobj->type = IPE_BITMAP;
+  } else {
+    fprintf(stderr, "Illegal keyword %s in IPE file %s\n",
+	    wk, ipename);
+    exit(9);
+  }
+
+  /* read header, now read data */
+  read_env(&ienv);
+
+  /* read data, now fill in object */
+  iobj->stroke = ienv.stroke;
+  iobj->fill = ienv.fill;
+  iobj->linestyle = ienv.linestyle;
+  iobj->linewidth = ienv.linewidth;
+  
+  switch (iobj->type) {
+    /* we treat polylines and splines alike */
+  case IPE_LINE:
+  case IPE_SEGMENTS:
+  case IPE_SPLINE:
+    iobj->w.line = NEWOBJECT(Line);
+    iobj->w.line->closed = rd.closed;
+    iobj->w.line->arrow = ienv.arrow;
+    iobj->w.line->arsize = ienv.arsize;
+    iobj->w.line->n = rd.n;
+    iobj->w.line->v = rd.v;
+    {
+      int k;
+      for (k = 0; k < rd.n; k++)
+	addtobox(bb, rd.v[k].x, rd.v[k].y);
+    }
+    iobj->w.line->vtype = rd.vtype;
+    if (iobj->type == IPE_SEGMENTS) {
+      /* check keys */
+      int i;
+      for (i = 0; i < rd.n; i++) {
+	switch (rd.vtype[i]) {
+	case 'N': case 'E': case 'L': case 'C':
+	  /* good */
+	  break;
+	default:
+	  fprintf(stderr, "Illegal code '%c' in Segments object\n", 
+		  rd.vtype[i]);
+	  exit(9);
+	}
+      }
+    }
+    break;
+
+  case IPE_ARC:
+    iobj->w.arc = NEWOBJECT(Arc);
+    iobj->w.arc->arrow = ienv.arrow;
+    iobj->w.arc->arsize = ienv.arsize;
+    iobj->w.arc->center = rd.xy;
+    iobj->w.arc->radius = rd.radius;
+    iobj->w.arc->begangle = rd.begangle;
+    iobj->w.arc->endangle = rd.endangle;
+    /* ignore in bbox computation */
+    break;
+
+  case IPE_CIRCLE:
+    iobj->w.circle = NEWOBJECT(Circle);
+    iobj->w.circle->center = rd.xy;
+    iobj->w.circle->radius = rd.radius;
+    iobj->w.circle->ellipse = rd.ellipse;
+    for (i = 0; i < 4; i++) {
+      iobj->w.circle->tfm[i] = rd.tfm[i];
+    }
+    /* just use bounding box of circle, ignoring tfm */
+    addtobox(bb, rd.xy.x - rd.radius, rd.xy.y - rd.radius);
+    addtobox(bb, rd.xy.x + rd.radius, rd.xy.y + rd.radius);
+    break;
+    
+  case IPE_MARK:
+    iobj->w.mark = NEWOBJECT(Mark);
+    iobj->w.mark->pos = rd.xy;
+    iobj->w.mark->type = ienv.marktype;
+    iobj->w.mark->size = ienv.marksize;
+    addtobox(bb, rd.xy.x, rd.xy.y);
+    break;
+
+  case IPE_BITMAP:
+    iobj->w.bitmap = NEWOBJECT(Bitmap);
+    iobj->w.bitmap->ll = rd.xy;
+    iobj->w.bitmap->width = rd.xbits;
+    iobj->w.bitmap->height = rd.ybits;
+    iobj->w.bitmap->words = rd.words;
+    iobj->w.bitmap->in_color = rd.bmcolor;
+    iobj->w.bitmap->ur.x = rd.xy.x + rd.wd;
+    iobj->w.bitmap->ur.y = rd.xy.y + rd.ht;
+    addtobox(bb, rd.xy.x, rd.xy.y);
+    addtobox(bb, rd.xy.x + rd.wd, rd.xy.y + rd.ht);
+    break;
+    
+  case IPE_TEXT:
+    iobj->w.text = NEWOBJECT(Text);
+    iobj->w.text->pos = rd.xy;
+    iobj->w.text->font = ienv.font;
+    iobj->w.text->fontsize = ienv.fontsize;
+    iobj->w.text->minipage = rd.minipage;
+    iobj->w.text->ll = rd.xy;
+    iobj->w.text->ll.y -= rd.dp;
+    iobj->w.text->ur = iobj->w.text->ll;
+    iobj->w.text->ur.x += rd.wd;
+    iobj->w.text->ur.y += rd.ht;
+    iobj->w.text->str = rd.str;
+    addtobox(bb, rd.xy.x, rd.xy.y - rd.dp);
+    addtobox(bb, rd.xy.x + rd.wd, rd.xy.y + rd.ht - rd.dp);
+    break;
+  }
+
+  /* now set all values in IpeObject, return it */
+  return iobj;
+}
+
+/******************** writing ******************************************/
+
+static void write_color(IpeColor *color)
+{
+  if (color->red == color->green && color->red == color->blue) {
+    if (color->red == 0.0)
+      fprintf(fh, "black");
+    else if (color->red == 1.0)
+      fprintf(fh, "white");
+    else 
+      fprintf(fh, "%g", color->red);
+  } else if (color->red == 1.0 && color->green == 0.0 && color->blue == 0.0)
+    fprintf(fh, "red");
+  else if (color->red == 0.0 && color->green == 1.0 && color->blue == 0.0)
+    fprintf(fh, "green");
+  else if (color->red == 0.0 && color->green == 0.0 && color->blue == 1.0)
+    fprintf(fh, "blue");
+  else 
+    fprintf(fh, "%g %g %g", color->red, color->green, color->blue);
+}
+
+static void write_colors(IpeObject *iobj)
+{
+  if (iobj->stroke.red != -1) {
+    fprintf(fh, " stroke=\"");
+    write_color(&iobj->stroke);
+    fprintf(fh, "\"");
+  }
+  if (iobj->fill.red != -1) {
+    fprintf(fh, " fill=\"");
+    write_color(&iobj->fill);
+    fprintf(fh, "\"");
+  }
+}
+
+static void write_dashes(short dash)
+{
+  static int p[32];
+  int len = 0;
+  unsigned int onoff = 1;
+  unsigned int rot = dash;
+  int count = 0;
+  int good;
+  int i;
+  int k = 0;
+
+  if (!(rot & 0x0001))
+    rot = 0xffff ^ rot;
+  for (i = 0; i < 16; i++) {
+    if (onoff != (rot & 1)) {
+      p[len++] = count;
+      count = 0;
+      onoff = 1 - onoff;
+    }
+    rot >>= 1;
+    count++;
+  }
+  p[len++] = count;
+  if (onoff)
+    p[len++] = 0;
+  for (i = 0; i < len; i++)
+    p[i+len] = p[i];
+  // now determine period
+  do {
+    k++;
+    good = TRUE;
+    for (i = 0; i < len; i++)
+      if (p[i] != p[i+k]) {
+	good = FALSE;
+      }
+  } while (!good);
+  // k is period of what we want
+  fprintf(fh, "[%d", p[0]);
+  for (i = 1; i < k; i++)
+    fprintf(fh, " %d", p[i]);
+  fprintf(fh, "] 0");
+}
+
+static void write_linestyle(IpeObject *iobj)
+{
+  if (iobj->stroke.red == -1) {
+    fprintf(fh, " dash=\"void\"");
+  } else if (iobj->linestyle != 0 && iobj->linestyle != 0xffff) {
+    fprintf(fh, " dash=\"");
+    write_dashes(iobj->linestyle);
+    fprintf(fh, "\"");
+  }
+  fprintf(fh, " pen=\"%g\"", iobj->linewidth);
+}
+
+static int cmp_spl_vtx(vertex *v0, vertex *v1) 
+{
+  double dx = v1->x - v0->x;
+  double dy = v1->y - v0->y;
+  return (dx*dx + dy*dy < SPLINE_MULTI_THRESHOLD_SQUARED);
+}
+
+static void midpoint(vertex *res, vertex *u, vertex *v)
+{
+  res->x = 0.5 * (u->x + v->x);
+  res->y = 0.5 * (u->y + v->y);
+}
+
+static void thirdpoint(vertex *res, vertex *u, vertex *v)
+{
+  res->x = (1.0/3.0) * ((2 * u->x) + v->x);
+  res->y = (1.0/3.0) * ((2 * u->y) + v->y);
+}
+
+static void convert_spline_to_bezier(FILE *fh, int n, vertex *v)
+{
+  int i;
+  vertex q0, q1, q2, q3;
+  vertex u, w;
+
+  for (i = 0; i < n - 3; i++ ) {
+    thirdpoint(&q1, &v[i+1], &v[i+2]);
+    thirdpoint(&q2, &v[i+2], &v[i+1]);
+    thirdpoint(&u, &v[i+1], &v[i]);
+    midpoint(&q0, &u, &q1);
+    thirdpoint(&w, &v[i+2], &v[i+3]);
+    midpoint(&q3, &w, &q2);
+    if (i == 0)
+      fprintf(fh, "\n%g %g m\n", q0.x, q0.y);
+    fprintf(fh, "%g %g %g %g %g %g c\n", q1.x, q1.y, q2.x, q2.y, q3.x, q3.y);
+  }
+}
+
+static void write_entry(IpeObject *iobj)
+/*  write a single Ipe Object to output file */
+{
+  int i;
+  char *p;
+  
+  switch (iobj->type) {
+  case IPE_BEGINGROUP:
+    if (grouplevel > 0)
+      fprintf(fh, "<group>\n");
+    else {
+      if (firstpage) {
+	fprintf(fh, "<ipestyle>\n<template name=\"Background\">\n<group>\n");
+      } else {
+	fprintf(fh, "<page>\n");
+      }
+    }
+    grouplevel++;
+    return;
+  case IPE_ENDGROUP:
+    grouplevel--;
+    if (grouplevel > 0)
+      fprintf(fh, "</group>\n");
+    else { 
+      if (firstpage) {
+	fprintf(fh, "</group>\n</template>\n</ipestyle>\n");
+	firstpage = 0;
+      } else {
+	fprintf(fh, "</page>\n");
+      }
+    }
+    break;
+
+  case IPE_SPLINE:
+    fprintf(fh, "<path");
+    write_colors(iobj);
+    write_linestyle(iobj);
+    if (iobj->w.line->arrow & 2)
+      fprintf(fh, " arrow=\"%g\"", iobj->w.line->arsize);
+    if (iobj->w.line->arrow & 1)
+      fprintf(fh, " backarrow=\"%g\"", iobj->w.line->arsize);
+    fprintf(fh, ">");
+    if (iobj->w.line->n == 2) {
+      /* line segment */
+      fprintf(fh, "\n%g %g m\n", iobj->w.line->v[0].x, iobj->w.line->v[0].y);
+      fprintf(fh, "%g %g l\n", iobj->w.line->v[1].x, iobj->w.line->v[1].y);
+    } else if (iobj->w.line->n == 3) {
+      /* quadratic B-spline */
+      if (iobj->w.line->closed) {
+	/* closed quadratic B-spline */
+	int i;
+	for (i = 0; i < 3; ++i) {
+	  vertex q0, q2;
+	  midpoint(&q0, &iobj->w.line->v[i], &iobj->w.line->v[(i+1) % 3]);
+	  midpoint(&q2, &iobj->w.line->v[(i+1) % 3], 
+		   &iobj->w.line->v[(i+2) % 3]);
+	  if (i == 0)
+	    fprintf(fh, "\n%g %g m", q0.x, q0.y);
+	  fprintf(fh, "\n%g %g ", iobj->w.line->v[(i+1) % 3].x, 
+		  iobj->w.line->v[(i+1) % 3].y);
+	  fprintf(fh, "%g %g q", q2.x, q2.y);
+	}
+	fprintf(fh, " h\n");
+      } else {
+	/* open quadratic B-spline */
+	vertex q0, q2;
+	midpoint(&q0, &iobj->w.line->v[0], &iobj->w.line->v[1]);
+	midpoint(&q2, &iobj->w.line->v[1], &iobj->w.line->v[2]);
+	fprintf(fh, "\n%g %g m\n", q0.x, q0.y);
+	fprintf(fh, "%g %g ", iobj->w.line->v[1].x, iobj->w.line->v[1].y);
+	fprintf(fh, "%g %g q\n", q2.x, q2.y);
+      }
+    } else if (iobj->w.line->closed) {
+      /* Closed cubic B-spline */
+      for (i = 0; i < iobj->w.line->n; i++ )
+	fprintf(fh, "\n%g %g", iobj->w.line->v[i].x, iobj->w.line->v[i].y);
+      fprintf(fh, " u\n");
+    } else {
+      /* Check whether first and last point have multiplicity 3 */
+      int n = iobj->w.line->n;
+      if (n >= 8 && 
+	  cmp_spl_vtx(&iobj->w.line->v[0], &iobj->w.line->v[1]) &&
+	  cmp_spl_vtx(&iobj->w.line->v[0], &iobj->w.line->v[2]) &&
+	  cmp_spl_vtx(&iobj->w.line->v[n-1], &iobj->w.line->v[n-2]) &&
+	  cmp_spl_vtx(&iobj->w.line->v[n-1], &iobj->w.line->v[n-3])) {
+	/* Yes, can convert to Ipe 6 B-Spline object */
+	fprintf(fh, "\n%g %g m", iobj->w.line->v[2].x, iobj->w.line->v[2].y);
+	for (i = 3; i < iobj->w.line->n - 2; i++ )
+	  fprintf(fh, "\n%g %g", iobj->w.line->v[i].x, iobj->w.line->v[i].y);
+	fprintf(fh, " s\n");
+      } else {
+	/* Have to convert to Ipe 6 Bezier path */
+	convert_spline_to_bezier(fh, n, iobj->w.line->v);
+      }
+    }
+    fprintf(fh, "</path>\n");
+    break;
+
+  case IPE_LINE:
+  case IPE_SEGMENTS:
+    fprintf(fh, "<path");
+    write_colors(iobj);
+    write_linestyle(iobj);
+    if (iobj->w.line->arrow & 2)
+      fprintf(fh, " arrow=\"%g\"", iobj->w.line->arsize);
+    if (iobj->w.line->arrow & 1)
+      fprintf(fh, " backarrow=\"%g\"", iobj->w.line->arsize);
+    fprintf(fh, ">\n");
+    for (i = 0; i < iobj->w.line->n; i++ ) {
+      fprintf(fh, "%g %g ", (iobj->w.line->v[i].x), (iobj->w.line->v[i].y) );
+      if (iobj->type == IPE_SEGMENTS) {
+	switch (iobj->w.line->vtype[i]) {
+	case 'N':
+	  fprintf(fh, "m\n");
+	  break;
+	case 'L':
+	case 'E':
+	  fprintf(fh, "l\n");
+	  break;
+	case 'C':
+	  fprintf(fh, "l h\n");
+	  break;
+	}
+      } else {
+	if (i == 0) {
+	  fprintf(fh, "m\n");
+	} else if (i + 1 == iobj->w.line->n) {
+	  if (iobj->w.line->closed)
+	    fprintf(fh, "l h\n");
+	  else 
+	    fprintf(fh, "l\n");
+	} else {
+	  fprintf(fh, "l\n");
+	}
+      }
+    }
+    fprintf(fh, "</path>\n");
+    break;
+
+  case IPE_MARK:
+    fprintf(fh, "<mark");
+    iobj->fill.red = -1;
+    write_colors(iobj);
+    fprintf(fh, " pos=\"%g %g\"",
+	    (iobj->w.mark->pos.XCOORD), (iobj->w.mark->pos.YCOORD));
+    fprintf(fh, " shape=\"%d\"", iobj->w.mark->type);
+    fprintf(fh, " size=\"%g\"/>\n", (iobj->w.mark->size));
+    break;
+   
+  case IPE_CIRCLE:
+    fprintf(fh, "<path");
+    write_colors(iobj);
+    write_linestyle(iobj);
+    fprintf(fh, ">\n");
+    if (iobj->w.circle->ellipse) {
+      double r = (iobj->w.circle->radius);
+      fprintf(fh, "%g %g %g %g %g %g e\n",
+	      r * iobj->w.circle->tfm[0], r * iobj->w.circle->tfm[1],
+	      r * iobj->w.circle->tfm[2], r * iobj->w.circle->tfm[3],
+	      (iobj->w.circle->center.XCOORD),
+	      (iobj->w.circle->center.YCOORD));
+    } else {
+      fprintf(fh, "%g 0 0 %g %g %g e\n",
+	      (iobj->w.circle->radius),
+	      (iobj->w.circle->radius),
+	      (iobj->w.circle->center.XCOORD),
+	      (iobj->w.circle->center.YCOORD));
+    }
+    fprintf(fh, "</path>\n");
+    break;
+    
+  case IPE_ARC:
+    // ignore zero radius arcs
+    if (iobj->w.arc->radius != 0.0) {
+      fprintf(fh, "<path");
+      write_colors(iobj);
+      write_linestyle(iobj);
+      if (iobj->w.arc->arrow & 2)
+	fprintf(fh, " arrow=\"%g\"", (iobj->w.arc->arsize));
+      if (iobj->w.arc->arrow & 1)
+	fprintf(fh, " backarrow=\"%g\"", (iobj->w.arc->arsize));
+      fprintf(fh, ">\n");
+      {
+	double alpha = (iobj->w.arc->begangle * IpePi / 180.0 );
+	double beta = (iobj->w.arc->endangle * IpePi / 180.0 );
+	double radius = iobj->w.arc->radius;
+	double x = (iobj->w.arc->center.x);
+	double y = (iobj->w.arc->center.y);
+	while (beta <= alpha)
+	  beta += IpePi + IpePi;
+	fprintf(fh, "%g %g m\n", x + radius * cos(alpha), 
+		y + radius * sin(alpha));
+	fprintf(fh, "%g 0 0 %g %g %g ", radius, radius, x, y);
+	fprintf(fh, "%g %g a\n", x + radius * cos(beta), 
+		y + radius * sin(beta));
+	
+      }
+      fprintf(fh, "</path>\n");
+    }
+    break;
+
+  case IPE_TEXT:
+    fprintf(fh, "<text");
+    iobj->fill.red = -1;
+    write_colors(iobj);
+    fprintf(fh, " pos=\"%g %g\"",
+	    (iobj->w.text->pos.XCOORD), (iobj->w.text->pos.YCOORD));
+    fprintf(fh, " size=\"%.2g\"", iobj->w.text->fontsize);
+    if (iobj->w.text->minipage) {
+      fprintf(fh, " type=\"minipage\" valign=\"top\" width=\"%g\"",
+	      (iobj->w.text->ur.XCOORD - iobj->w.text->ll.XCOORD));
+    } else {
+      fprintf(fh, " type=\"label\" valign=\"bottom\"");
+    }
+    fprintf(fh, ">");
+    switch (iobj->w.text->font) {
+    case IPE_ROMAN:
+    default:
+      break;
+    case IPE_ITALIC:
+      fprintf(fh, "\\textit{");
+      break;
+    case IPE_BOLD:
+      fprintf(fh, "\\textbf{");
+      break;
+    case IPE_MATH:
+      fprintf(fh, "$");
+      break;
+    }
+    for (p = iobj->w.text->str; *p; p++) {
+      switch (*p) {
+      case '<':
+	fprintf(fh, "<");
+	break;
+      case '>':
+	fprintf(fh, ">");
+	break;
+      case '&':
+	fprintf(fh, "&");
+	break;
+      case '\r': /* skip CR */ 
+	break;
+      default:
+	fputc(*p, fh);
+	break;
+      }
+    }
+    switch (iobj->w.text->font) {
+    case IPE_ROMAN:
+    default:
+      break;
+    case IPE_ITALIC:
+    case IPE_BOLD:
+      fprintf(fh, "}");
+      break;
+    case IPE_MATH:
+      fprintf(fh, "$");
+      break;
+    }
+    fprintf(fh, "</text>\n");
+    break;
+
+  case IPE_BITMAP:
+    fprintf(fh, "<image");
+    fprintf(fh, " rect=\"%g %g %g %g\"",
+	    iobj->w.bitmap->ll.XCOORD, iobj->w.bitmap->ll.YCOORD,
+	    iobj->w.bitmap->ur.XCOORD, iobj->w.bitmap->ur.YCOORD); 
+    fprintf(fh, " width=\"%d\" height=\"%d\"",
+	    iobj->w.bitmap->width, iobj->w.bitmap->height);
+    if (iobj->w.bitmap->in_color)
+      fprintf(fh, " ColorSpace=\"DeviceRGB\"");
+    else 
+      fprintf(fh, " ColorSpace=\"DeviceGray\"");
+    fprintf(fh, " BitsPerComponent=\"8\">\n");
+    /* write bitmap in hex */
+    if (iobj->w.bitmap->in_color) {
+      int nwords = iobj->w.bitmap->width * iobj->w.bitmap->height;
+      int i;
+      /* write a color bitmap: 32 bits per pixel */
+      for (i = 0; i < nwords; ++i) {
+	int val = iobj->w.bitmap->words[i] & 0x00ffffff;
+	fprintf(fh, "%06x", val);
+      }
+    } else {
+      int nwords = iobj->w.bitmap->width * iobj->w.bitmap->height;
+      int i;
+      /* write a color bitmap: 32 bits per pixel */
+      for (i = 0; i < nwords; ++i) {
+	int val = iobj->w.bitmap->words[i] & 0x000000ff;
+	fprintf(fh, "%02x", val );
+      }
+    }
+    fprintf(fh, "\n</image>\n");
+    break;
+    
+  default:
+    /* this should never happen */
+    fprintf(stderr, "Fatal error: trying to write unknown type %d\n",
+	    iobj->type);
+    exit(1);
+  }
+  return;
+}
+
+static void ipetoxml(void)
+{
+  IpeObject *last, *iobj;
+  char *wk;
+  char preamble[MAX_LINE_LENGTH];
+  char pspreamble[MAX_LINE_LENGTH];
+  int no_pages = 0;
+  bbox bb = { 99999.0, -99999.0, 99999.0, -99999.0 };
+
+  ium_input = NULL;
+
+  /* read IPE file */
+
+  if (!(fh = fopen(ipename, "rb"))) {
+    fprintf(stderr, "Cannot open IPE file %s\n", ipename);
+    exit(9);
+  }
+  
+  grouplevel = 0;
+  preamble[0] = '\0';
+  pspreamble[0] = '\0';
+  
+  wk = read_next();
+  if (!strcmp(wk, "Preamble")) {
+    int nlines;
+    int ch;
+    char *p = preamble;
+    assert_n(1, fscanf(fh, "%d", &nlines));
+    /* skip to next line */
+    while ((ch = fgetc(fh)) != '\n' && ch != EOF)
+      ;
+    while (nlines > 0 && ch != EOF && (p < (preamble + sizeof(preamble) - 1))) {
+      ch = fgetc(fh);
+      if (ch == EOF) {
+        fprintf(stderr, "EOF while reading preamble\n");
+        exit(9);
+      }
+      if (ch != '%')
+	*p++ = ch;
+      if (ch == '\n')
+	nlines--;
+    }
+    *p = '\0';
+    wk = read_next();
+  }
+
+  if (!strcmp(wk, "PSpreamble")) {
+    int nlines;
+    int ch;
+    char *p = pspreamble;
+    assert_n(1, fscanf(fh, "%d", &nlines));
+    /* skip to next line */
+    while ((ch = fgetc(fh)) != '\n' && ch != EOF)
+      ;
+    while (nlines > 0 && ch != EOF && (p < (pspreamble + sizeof(pspreamble) -1 ))) {
+      ch = fgetc(fh);
+      if (ch == EOF) {
+        fprintf(stderr, "EOF while reading PSpreamble\n");
+        exit(9);
+      }
+      *p++ = ch;
+      if (ch == '\n')
+	nlines--;
+    }
+    *p = '\0';
+    wk = read_next();
+  }
+
+  if (!strcmp(wk, "Pages")) {
+    assert_n(1, fscanf(fh, "%d", &no_pages));
+  } else if (strcmp(wk, "Group")) {
+    fprintf(stderr, "Not an IPE file: %s\n", ipename);
+    exit(9);
+  }
+  
+  last = NULL;
+  while ((iobj = read_entry(&bb)) != NULL) {
+    if (last)
+      last->next = iobj;
+    else
+      ium_input = iobj;
+    last = iobj;
+  }
+  fclose(fh);
+
+  /* testing only? */
+  if (xmlname == 0)
+    return;
+
+  /* write file in XML format */
+
+  if (!(fh = fopen(xmlname, "wb"))) {
+    fprintf(stderr, "Cannot open XML file %s for writing\n", xmlname);
+    exit(9);
+  }
+
+  fprintf(fh, "<ipe creator=\"%s\">\n", IPE5TOXML_VERSION);
+  {
+    char *p = preamble;
+    while (*p && *p != '}')
+      p++;
+    if (*p)
+      p++;
+    while (*p && (*p == ' ' || *p == '\n' || *p == '\r'))
+      p++;
+    if (*p) {
+      fprintf(fh, "<preamble>");
+      while (*p) {
+	char *q = strstr(p, "\\usepackage{ipe}");
+	if (q) {
+	  while (p < q)
+	    fputc(*p++, fh);
+	  p = q + 16;
+	} else {
+	  while (*p)
+	    fputc(*p++, fh);
+	}
+      }
+      fprintf(fh, "</preamble>\n");
+    }
+  }
+  /*
+  if (pspreamble[0]) {
+    fprintf(fh, "<pspreamble>%s</pspreamble>\n", pspreamble);
+  }
+  */
+  if (no_pages > 0) {
+    firstpage = 1;
+    grouplevel = 0;
+  } else {
+    fprintf(fh, "<page>\n");
+    grouplevel = 1;
+  }
+  for (iobj = ium_input; iobj; iobj = iobj->next) {
+    write_entry(iobj);
+  }
+  if (no_pages == 0)
+    fprintf(fh, "</page>\n");
+  fprintf(fh, "</ipe>\n");
+  
+  if (fclose(fh) == EOF) {
+    fprintf(stderr, "Write error on XML file %s\n", xmlname);
+    exit(9);
+  }
+}
+
+int main(int argc, char **argv)
+{
+  if (argc >= 3 && !strcmp(argv[1], "-test")) {
+    /* test mode */
+    int i;
+    for (i = 2; i < argc; i++) {
+      ipename = argv[i];
+      xmlname = 0;
+      fprintf(stderr, "Testing %s\n", ipename);
+      ipetoxml();
+    }
+  } else {
+    if (argc != 3) {
+      /* something is wrong here, we should have exactly two arguments */
+      fprintf(stderr, "Usage: %s file.ipe file.xml\n", argv[0]);
+      exit(9);
+    }
+    ipename = argv[1];
+    xmlname = argv[2];
+    ipetoxml();
+  }
+  return 0;
+}
+
diff --git a/matplotlib/README.md b/matplotlib/README.md
new file mode 100644
index 0000000..4625523
--- /dev/null
+++ b/matplotlib/README.md
@@ -0,0 +1,88 @@
+matplotlib backend
+==================
+
+This is an Ipe backend for the [Matplotlib plotting
+library](http://matplotlib.org/) for Python, written by Soyeon Baek
+and Otfried Cheong.
+
+You can create Ipe files directly from Matplotlib.
+
+To use the backend, copy the file *backend_ipe.py* somewhere on your
+Python path. (The current directory will do.)
+
+You activate the backend like this:
+
+```python
+  import matplotlib
+  matplotlib.use('module://backend_ipe')
+```
+
+The Ipe backend allows you to save in Ipe format:
+
+```python
+  plt.savefig("my_plot.ipe", format="ipe")
+```
+
+
+Options
+-------
+
+Some plots need to measure the size of text to place labels correctly
+(see the *legend_demo* test for an example).  The Ipe backend can use
+a background Latex process to measure the dimensions of text as it
+will appear in the Ipe document.  By default this is not enabled, as
+most plots don't need it and it slows down the processing of the plot.
+
+If you want to enable text size measuring, set the matplotlib option
+*ipe.textsize* to True, for instance like this:
+
+```python
+  import matplotlib
+  matplotlib.use('module://backend_ipe')
+  import matplotlib.pyplot as plt
+  matplotlib.rcParams['ipe.textsize'] = True
+```
+
+(Note that the *ipe* options are only available after the backend has
+been loaded, here caused by importing *pyplot*.)
+
+
+If you want your plot to include an Ipe stylesheet, specify this using
+the option *ipe.stylesheet*, with a full pathname.  (If you don't know
+where your style sheets are, use Ipe -> Help -> Show Configuration.)
+Here is an example:
+
+```python
+  import matplotlib
+  matplotlib.use('module://backend_ipe')
+  import matplotlib.pyplot as plt
+  matplotlib.rcParams['ipe.stylesheet'] = "/sw/ipe/share/ipe/7.1.6/styles/basic.isy"
+```
+
+You can set the preamble of the Ipe document using the option
+*ipe.preamble*.  This is useful, for instance, when you want to use
+font sizes that are not available with the standard fonts (the test
+*watermark_image* needs this).  You can then switch to a Postscript
+font that can be scaled to any size:
+
+```python
+  import matplotlib
+  matplotlib.use('module://backend_ipe')
+  import matplotlib.pyplot as plt
+  matplotlib.rcParams['ipe.preamble'] = r"""
+\usepackage{times}
+"""
+```
+
+
+
+Problems?
+---------
+
+If you need to report a problem, please include your matplotlib version.
+You can find it as follows:
+
+```python
+  import matplotlib
+  print matplotlib.__version__
+```
diff --git a/matplotlib/backend_ipe.py b/matplotlib/backend_ipe.py
new file mode 100644
index 0000000..a0132b0
--- /dev/null
+++ b/matplotlib/backend_ipe.py
@@ -0,0 +1,524 @@
+"""
+This is a matplotlib backend to save in the Ipe file format.
+(ipe7.sourceforge.net).
+
+(c) 2014 Soyeon Baek, Otfried Cheong
+
+You can find the most current version at:
+http://www.github.com/otfried/ipe-tools/matplotlib
+
+You can use this backend by saving it anywhere on your PYTHONPATH.
+Use it as an external backend from matplotlib like this:
+
+  import matplotlib
+  matplotlib.use('module://backend_ipe')
+
+"""
+
+# --------------------------------------------------------------------
+
+from __future__ import division, print_function
+
+import os, base64, tempfile, urllib, gzip, io, sys, codecs, re
+
+import matplotlib
+from matplotlib import rcParams
+from matplotlib._pylab_helpers import Gcf
+from matplotlib.backend_bases import RendererBase, GraphicsContextBase
+from matplotlib.backend_bases import FigureManagerBase, FigureCanvasBase
+from matplotlib.figure import Figure
+from matplotlib.transforms import Bbox
+from matplotlib.cbook import is_string_like, is_writable_file_like, maxdict
+from matplotlib.path import Path
+
+from xml.sax.saxutils import escape as escape_xml_text
+
+from math import sin, cos, radians
+
+from matplotlib.backends.backend_pgf import LatexManagerFactory, \
+    LatexManager, common_texification
+import atexit
+
+from matplotlib.rcsetup import validate_bool, validate_path_exists
+
+negative_number = re.compile(u"^\u2212([0-9]+)(\.[0-9]*)?$")
+
+rcParams.validate['ipe.textsize'] = validate_bool
+rcParams.validate['ipe.stylesheet'] = validate_path_exists
+rcParams.validate['ipe.preamble'] = lambda (s) : s
+
+# ----------------------------------------------------------------------
+# SimpleXMLWriter class
+#
+# Based on an original by Fredrik Lundh, but modified here to:
+#   1. Support modern Python idioms
+#   2. Remove encoding support (it's handled by the file writer instead)
+#   3. Support proper indentation
+#   4. Minify things a little bit
+
+# --------------------------------------------------------------------
+# The SimpleXMLWriter module is
+#
+# Copyright (c) 2001-2004 by Fredrik Lundh
+#
+# By obtaining, using, and/or copying this software and/or its
+# associated documentation, you agree that you have read, understood,
+# and will comply with the following terms and conditions:
+#
+# Permission to use, copy, modify, and distribute this software and
+# its associated documentation for any purpose and without fee is
+# hereby granted, provided that the above copyright notice appears in
+# all copies, and that both that copyright notice and this permission
+# notice appear in supporting documentation, and that the name of
+# Secret Labs AB or the author not be used in advertising or publicity
+# pertaining to distribution of the software without specific, written
+# prior permission.
+#
+# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
+# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
+# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
+# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
+# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+# OF THIS SOFTWARE.
+# --------------------------------------------------------------------
+
+def escape_cdata(s):
+    s = s.replace(u"&", u"&")
+    s = s.replace(u"<", u"<")
+    s = s.replace(u">", u">")
+    return s
+
+def escape_attrib(s):
+    s = s.replace(u"&", u"&")
+    s = s.replace(u"'", u"'")
+    s = s.replace(u"\"", u""")
+    s = s.replace(u"<", u"<")
+    s = s.replace(u">", u">")
+    return s
+
+##
+# XML writer class.
+#
+# @param file A file or file-like object.  This object must implement
+#    a <b>write</b> method that takes an 8-bit string.
+
+class XMLWriter:
+    def __init__(self, file):
+        self.__write = file.write
+        if hasattr(file, "flush"):
+            self.flush = file.flush
+        self.__open = 0 # true if start tag is open
+        self.__tags = []
+        self.__data = []
+        self.__indentation = u" " * 64
+
+    def __flush(self, indent=True):
+        # flush internal buffers
+        if self.__open:
+            if indent:
+                self.__write(u">\n")
+            else:
+                self.__write(u">")
+            self.__open = 0
+        if self.__data:
+            data = u''.join(self.__data)
+            self.__write(escape_cdata(data))
+            self.__data = []
+
+    ## Opens a new element.  Attributes can be given as keyword
+    # arguments, or as a string/string dictionary. The method returns
+    # an opaque identifier that can be passed to the <b>close</b>
+    # method, to close all open elements up to and including this one.
+    #
+    # @param tag Element tag.
+    # @param attrib Attribute dictionary.  Alternatively, attributes
+    #    can be given as keyword arguments.
+    # @return An element identifier.
+
+    def start(self, tag, attrib={}, **extra):
+        self.__flush()
+        tag = escape_cdata(tag)
+        self.__data = []
+        self.__tags.append(tag)
+        self.__write(self.__indentation[:len(self.__tags) - 1])
+        self.__write(u"<%s" % tag)
+        if attrib or extra:
+            attrib = attrib.copy()
+            attrib.update(extra)
+            attrib = attrib.items()
+            attrib.sort()
+            for k, v in attrib:
+                if not v == '':
+                    k = escape_cdata(k)
+                    v = escape_attrib(v)
+                    self.__write(u" %s=\"%s\"" % (k, v))
+        self.__open = 1
+        return len(self.__tags)-1
+
+    ##
+    # Adds a comment to the output stream.
+    #
+    # @param comment Comment text, as a Unicode string.
+
+    def comment(self, comment):
+        self.__flush()
+        self.__write(self.__indentation[:len(self.__tags)])
+        self.__write(u"<!-- %s -->\n" % escape_cdata(comment))
+
+    ##
+    # Adds character data to the output stream.
+    #
+    # @param text Character data, as a Unicode string.
+
+    def data(self, text):
+        self.__data.append(text)
+
+    ##
+    # Closes the current element (opened by the most recent call to
+    # <b>start</b>).
+    #
+    # @param tag Element tag.  If given, the tag must match the start
+    #    tag.  If omitted, the current element is closed.
+
+    def end(self, tag=None, indent=True):
+        if tag:
+            assert self.__tags, "unbalanced end(%s)" % tag
+            assert escape_cdata(tag) == self.__tags[-1],\
+                   "expected end(%s), got %s" % (self.__tags[-1], tag)
+        else:
+            assert self.__tags, "unbalanced end()"
+        tag = self.__tags.pop()
+        if self.__data:
+            self.__flush(indent)
+        elif self.__open:
+            self.__open = 0
+            self.__write(u"/>\n")
+            return
+        if indent:
+            self.__write(self.__indentation[:len(self.__tags)])
+        self.__write(u"</%s>\n" % tag)
+
+    ##
+    # Closes open elements, up to (and including) the element identified
+    # by the given identifier.
+    #
+    # @param id Element identifier, as returned by the <b>start</b> method.
+
+    def close(self, id):
+        while len(self.__tags) > id:
+            self.end()
+
+    ##
+    # Adds an entire element.  This is the same as calling <b>start</b>,
+    # <b>data</b>, and <b>end</b> in sequence. The <b>text</b> argument
+    # can be omitted.
+
+    def element(self, tag, text=None, attrib={}, **extra):
+        apply(self.start, (tag, attrib), extra)
+        if text:
+            self.data(text)
+        self.end(indent=False)
+
+    def insertSheet(self, fname):
+        self.__flush()
+        data = open(fname, "rb").read()
+        i = data.find("<ipestyle")
+        if i >= 0:
+            self.__write(data[i:].decode("utf-8"))
+
+# ----------------------------------------------------------------------
+
+class RendererIpe(RendererBase):
+    """
+    The renderer handles drawing/rendering operations.
+    Refer to backend_bases.RendererBase for documentation of 
+    the classes methods.
+    """
+    def __init__(self, width, height, ipewriter, basename):
+        self.width = width
+        self.height = height
+        self.writer = XMLWriter(ipewriter)
+        self.basename = basename
+
+        RendererBase.__init__(self)
+
+        # use same latex as Ipe (default is xelatex)
+        rcParams['pgf.texsystem'] = "pdflatex"
+        self.latexManager = None
+        if rcParams.get("ipe.textsize", False):
+            self.latexManager = LatexManagerFactory.get_latex_manager()
+
+        self._start_id = self.writer.start(
+            u'ipe',
+            version=u"70005",
+            creator="matplotlib")
+        pre = rcParams.get('ipe.preamble', "")
+        if pre <> "":
+            self.writer.start(u'preamble')
+            self.writer.data(pre)
+            self.writer.end(indent=False)
+        sheet = rcParams.get('ipe.stylesheet', "")
+        if sheet <> "":
+            self.writer.insertSheet(sheet)
+        self.writer.start(u'ipestyle', name=u"opacity")
+        
+        for i in range(10,100,10):
+            self.writer.element(u'opacity', name=u'%02d%%'% i, 
+                                value=u'%g'% (i/100.0))
+        self.writer.end()
+        self.writer.start(u'page')
+
+
+    def finalize(self):
+        self.writer.close(self._start_id)
+        self.writer.flush()
+
+    def draw_path(self, gc, path, transform, rgbFace=None):
+        capnames = ('butt', 'round', 'projecting')
+        cap = capnames.index(gc.get_capstyle())
+        
+        joinnames = ('miter', 'round', 'bevel')
+        join = joinnames.index(gc.get_joinstyle())
+        
+        # filling
+        has_fill = rgbFace is not None
+        
+        offs, dl = gc.get_dashes()
+        attrib = {}
+        if offs != None:
+            if type(dl) == float:
+                dashes = "[%g] %g" % (dl, offs)
+            else:
+                dashes = "[" + " ".join(["%g" % x for x in dl]) + "] %g" % offs
+            attrib['dash'] = dashes
+        if has_fill:
+            attrib['fill'] = "%g %g %g" % tuple(rgbFace)[:3]
+        opaq = gc.get_rgb()[3]
+        if rgbFace is not None and len(rgbFace) > 3:
+            opaq =  rgbFace[3]
+        self.gen_opacity(attrib, opaq)  
+        self._print_ipe_clip(gc)
+        self.writer.start(
+            u'path',
+            attrib=attrib,
+            stroke="%g %g %g" % gc.get_rgb()[:3],
+            pen="%g" % gc.get_linewidth(),
+            cap="%d" % cap,
+            join="%d" % join,
+            fillrule="wind"
+        )
+        self.writer.data(self._make_ipe_path(gc, path, transform))
+        self.writer.end()
+        self._print_ipe_clip_end()
+        
+
+    def draw_image(self, gc, x, y, im, dx=None, dy=None, transform=None):
+        h,w = im.get_size_out()
+        
+        if dx is not None:
+            w = dx
+        if dy is not None:
+            h = dy
+        rows, cols, buffer = im.as_rgba_str()
+        self._print_ipe_clip(gc)
+        self.writer.start(
+            u'image',
+            width=u"%d" % cols,
+            height=u"%d" % rows,
+            ColorSpace=u"DeviceRGB",
+            BitsPerComponent=u"8",
+            matrix=u"1 0 0 -1 %g %g" % (x, y),
+            rect="%g %g %g %g" % (0, -h, w, 0)
+        )
+        for i in xrange(rows * cols):
+            rgb = buffer[4*i:4*i+3]
+            self.writer.data(u"%02x%02x%02x" % (ord(rgb[0]), ord(rgb[1]),
+                                                ord(rgb[2])))
+        self.writer.end()
+        self._print_ipe_clip_end() 
+        
+    def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
+        if negative_number.match(s):
+            s = u"$" + s.replace(u'\u2212', u'-') + "$"
+        attrib = {}
+        if mtext:
+            # if text anchoring can be supported, get the original coordinates
+            # and add alignment information
+            x, y = mtext.get_transform().transform_point(mtext.get_position())
+        
+            attrib['halign'] = mtext.get_ha()
+            attrib['valign'] = mtext.get_va()
+        
+        if angle != 0.0:
+            ra = radians(angle)
+            sa = sin(ra); ca = cos(ra)
+            attrib['matrix'] = "%g %g %g %g %g %g" % (ca, sa, -sa, ca, x, y)
+            x, y  = 0, 0
+ 
+        self.gen_opacity(attrib, gc.get_rgb()[3])
+        
+        self.writer.start(
+            u'text',
+            stroke="%g %g %g" % gc.get_rgb()[:3],
+            type="label",
+            size="%g" % prop.get_size_in_points(),
+            pos="%g %g" % (x,y),
+            attrib=attrib            
+        )
+
+        s = common_texification(s)
+        self.writer.data(u"%s" % s)
+        self.writer.end(indent=False)
+        
+    def _make_ipe_path(self, gc, path, transform):
+        elem = ""
+        for points, code in path.iter_segments(transform):
+            if code == Path.MOVETO:
+                x, y = tuple(points)
+                elem += "%g %g m\n" % (x, y)
+            elif code == Path.CLOSEPOLY:
+                elem += "h\n"
+            elif code == Path.LINETO:
+                x, y = tuple(points)
+                elem += "%g %g l\n" % (x, y)
+            elif code == Path.CURVE3:
+                cx, cy, px, py = tuple(points)
+                elem += "%g %g %g %g q\n" % (cx, cy, px, py)
+            elif code == Path.CURVE4:
+                c1x, c1y, c2x, c2y, px, py = tuple(points)
+                elem += ("%g %g %g %g %g %g c\n" % 
+                                (c1x, c1y, c2x, c2y, px, py))
+        return elem
+                
+    def _print_ipe_clip(self, gc):
+        bbox = gc.get_clip_rectangle()
+        self.use_clip_box = bbox is not None
+        if self.use_clip_box:
+            p1, p2 = bbox.get_points()
+            x1, y1 = p1
+            x2, y2 = p2
+            self.writer.start(
+                            u'group',
+                            clip=u"%g %g m %g %g l %g %g l %g %g l h" %
+                             (x1, y1, x2, y1, x2, y2, x1, y2)
+                        )            
+        # check for clip path
+        clippath, clippath_trans = gc.get_clip_path()
+        self.use_clip_group = clippath is not None
+        if self.use_clip_group:
+            self.writer.start(
+                u'group',
+                clip=u"%s" % self._make_ipe_path(gc, clippath, clippath_trans)
+            )
+            
+    def _print_ipe_clip_end(self):
+        if self.use_clip_group:
+            self.writer.end()
+        if self.use_clip_box:
+            self.writer.end()
+        
+    def flipy(self):
+        return True
+
+    def get_canvas_width_height(self):
+        return self.width, self.height
+
+    def get_text_width_height_descent(self, s, prop, ismath):
+        if self.latexManager:
+            s = common_texification(s)
+            w, h, d = self.latexManager.get_width_height_descent(s, prop)
+            return w, h, d
+        else:
+            return 1, 1, 1
+
+    def new_gc(self):
+        return GraphicsContextIpe()
+
+    def points_to_pixels(self, points):
+        return points
+    
+    def gen_opacity(self, attrib, opaq):
+        if opaq > 0.99: return
+        opaq += 0.05
+        o = int(opaq * 10) * 10
+        if o > 90: o = 90
+        if o < 10: o = 10
+        attrib["opacity"] = u"%02d%%" % o
+        
+# --------------------------------------------------------------------
+
+class GraphicsContextIpe(GraphicsContextBase):
+    pass
+    
+# --------------------------------------------------------------------
+
+class FigureCanvasIpe(FigureCanvasBase):
+    filetypes = FigureCanvasBase.filetypes.copy()
+    filetypes['ipe'] = 'Ipe 7 file format'
+
+    def print_ipe(self, filename, *args, **kwargs):
+        if is_string_like(filename):
+            fh_to_close = ipewriter = io.open(filename, 'w', encoding='utf-8')
+        elif is_writable_file_like(filename):
+            if not isinstance(filename, io.TextIOBase):
+                if sys.version_info[0] >= 3:
+                    ipewriter = io.TextIOWrapper(filename, 'utf-8')
+                else:
+                    ipewriter = codecs.getwriter('utf-8')(filename)
+            else:
+                ipewriter = filename
+            fh_to_close = None
+        else:
+            raise ValueError("filename must be a path or a file-like object")
+        return self._print_ipe(filename, ipewriter, fh_to_close, **kwargs)
+
+    def _print_ipe(self, filename, ipewriter, fh_to_close=None, **kwargs):
+        try:
+            self.figure.set_dpi(72.0)
+            width, height = self.figure.get_size_inches()
+            w, h = width*72, height*72
+            renderer = RendererIpe(w, h, ipewriter, filename)
+            self.figure.draw(renderer)
+            renderer.finalize()
+        finally:
+            if fh_to_close is not None:
+                ipewriter.close()
+
+    def get_default_filetype(self):
+        return 'ipe'
+
+# --------------------------------------------------------------------
+
+# Provide the standard names that backend.__init__ is expecting
+
+class FigureManagerIpe(FigureManagerBase):
+    pass
+
+FigureManager = FigureManagerIpe
+
+def new_figure_manager(num, *args, **kwargs):
+    FigureClass = kwargs.pop('FigureClass', Figure)
+    thisFig = FigureClass(*args, **kwargs)
+    return new_figure_manager_given_figure(num, thisFig)
+
+def new_figure_manager_given_figure(num, figure):
+    """
+    Create a new figure manager instance for the given figure.
+    """
+    canvas  = FigureCanvasIpe(figure)
+    manager = FigureManagerIpe(canvas, num)
+    return manager
+
+# --------------------------------------------------------------------
+
+def _cleanup():
+    LatexManager._cleanup_remaining_instances()
+    # This is necessary to avoid a spurious error
+    # caused by the atexit at the end of the PGF backend
+    LatexManager.__del__ = lambda (self) : None
+
+atexit.register(_cleanup)
+
+# --------------------------------------------------------------------
diff --git a/matplotlib/run_test.py b/matplotlib/run_test.py
new file mode 100644
index 0000000..8b32d42
--- /dev/null
+++ b/matplotlib/run_test.py
@@ -0,0 +1,54 @@
+#
+# Run all the tests in tests subdirectory
+# and save plots in ipe and svg format
+# 
+
+import os, sys
+
+def fix_file(f):
+  data = open("tests/%s" % f, "rb").readlines()
+  os.rename("tests/%s" % f, "tests/%s.bak" % f)
+  out = open("tests/%s" % f, "wb")
+  for l in data:
+    ll = l.strip()
+    if ll == "import matplotlib as mpl": continue
+    if ll == "print mpl.__file__": continue
+    if ll == "mpl.use('module://backend_ipe')": continue
+    if ll == "#mpl.use('module://backend_ipe')": continue    
+    if ll == "#plt.show()" or ll == "plt.show()": continue
+    if ll[:12] == "#plt.savefig": continue
+    if ll[:11] == "plt.savefig": continue
+    out.write(l)
+  out.close()
+
+def runall(form):
+  tests = [f[:-3] for f in os.listdir("tests") if f[-3:] == ".py"]
+  for f in tests:
+    # doesn't work on my matplotlib version
+    if f == "power_norm_demo": continue
+    run(form, f)
+
+def run(form, f):
+  sys.stderr.write("# %s\n" % f)
+  t = open("tmp.py", "wb")
+  t.write("""# %s
+import matplotlib as mpl
+""" % f)
+  if form=="ipe":
+    t.write("mpl.use('module://backend_ipe')\n")
+  t.write(open("tests/%s.py" % f, "rb").read())
+  t.write("plt.savefig('out/%s.%s', format='%s')\n" % (f, form, form))
+  t.close()
+  os.system("python tmp.py")
+
+if len(sys.argv) != 3:
+  sys.stderr.write("Usage: run_test.py <format> <test>\n")
+  sys.exit(9)
+
+form = sys.argv[1]
+test = sys.argv[2]
+if test == 'all':
+  runall(form)
+else:
+  run(form, test)
+
diff --git a/matplotlib/tests/barchart_demo.py b/matplotlib/tests/barchart_demo.py
new file mode 100644
index 0000000..91f88a8
--- /dev/null
+++ b/matplotlib/tests/barchart_demo.py
@@ -0,0 +1,35 @@
+# a bar plot with errorbars
+import numpy as np
+import matplotlib.pyplot as plt
+
+N = 5
+menMeans = (20, 35, 30, 35, 27)
+menStd =   (2, 3, 4, 1, 2)
+
+ind = np.arange(N)  # the x locations for the groups
+width = 0.35       # the width of the bars
+
+fig, ax = plt.subplots()
+rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)
+
+womenMeans = (25, 32, 34, 20, 25)
+womenStd =   (3, 5, 2, 3, 3)
+rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)
+
+# add some text for labels, title and axes ticks
+ax.set_ylabel('Scores')
+ax.set_title('Scores by group and gender')
+ax.set_xticks(ind+width)
+ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )
+
+ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )
+
+def autolabel(rects):
+    # attach some text labels
+    for rect in rects:
+        height = rect.get_height()
+        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
+                ha='center', va='bottom')
+
+autolabel(rects1)
+autolabel(rects2)
diff --git a/matplotlib/tests/barh_demo.py b/matplotlib/tests/barh_demo.py
new file mode 100644
index 0000000..6686966
--- /dev/null
+++ b/matplotlib/tests/barh_demo.py
@@ -0,0 +1,21 @@
+
+"""
+Simple demo of a horizontal bar chart.
+"""
+import matplotlib.pyplot as plt; plt.rcdefaults()
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+# Example data
+people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
+y_pos = np.arange(len(people))
+performance = 3 + 10 * np.random.rand(len(people))
+error = np.random.rand(len(people))
+
+plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4)
+plt.yticks(y_pos, people)
+plt.xlabel('Performance')
+plt.title('How fast do you want to go today?')
+
+
diff --git a/matplotlib/tests/clip_test.py b/matplotlib/tests/clip_test.py
new file mode 100644
index 0000000..3932628
--- /dev/null
+++ b/matplotlib/tests/clip_test.py
@@ -0,0 +1,23 @@
+import numpy as np
+import matplotlib.cm as cm
+import matplotlib.mlab as mlab
+import matplotlib.pyplot as plt
+from matplotlib.path import Path
+from matplotlib.patches import PathPatch
+
+delta = 0.025
+x = y = np.arange(-3.0, 3.0, delta)
+X, Y = np.meshgrid(x, y)
+Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
+Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
+Z = Z2-Z1  # difference of Gaussians
+
+path = Path([[0, 1], [1, 0], [0, -1], [-1, 0], [0, 1]])
+patch = PathPatch(path, facecolor='none')
+plt.gca().add_patch(patch)
+
+im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray,
+                origin='lower', extent=[-3,3,-3,3],
+                clip_path=patch, clip_on=True)
+im.set_clip_path(patch)
+
diff --git a/matplotlib/tests/collections_demo.py b/matplotlib/tests/collections_demo.py
new file mode 100644
index 0000000..88bc989
--- /dev/null
+++ b/matplotlib/tests/collections_demo.py
@@ -0,0 +1,108 @@
+
+
+import matplotlib.pyplot as plt
+from matplotlib import collections, transforms
+from matplotlib.colors import colorConverter
+import numpy as np
+
+nverts = 50
+npts = 100
+
+# Make some spirals
+r = np.array(range(nverts))
+theta = np.array(range(nverts)) * (2*np.pi)/(nverts-1)
+xx = r * np.sin(theta)
+yy = r * np.cos(theta)
+spiral = list(zip(xx,yy))
+
+# Make some offsets
+rs = np.random.RandomState([12345678])
+xo = rs.randn(npts)
+yo = rs.randn(npts)
+xyo = list(zip(xo, yo))
+
+# Make a list of colors cycling through the rgbcmyk series.
+colors = [colorConverter.to_rgba(c) for c in ('r','g','b','c','y','m','k')]
+
+fig, axes = plt.subplots(2,2)
+((ax1, ax2), (ax3, ax4)) = axes # unpack the axes
+
+
+col = collections.LineCollection([spiral], offsets=xyo,
+                                transOffset=ax1.transData)
+trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0/72.0)
+col.set_transform(trans)  # the points to pixels transform
+    # Note: the first argument to the collection initializer
+    # must be a list of sequences of x,y tuples; we have only
+    # one sequence, but we still have to put it in a list.
+ax1.add_collection(col, autolim=True)
+    # autolim=True enables autoscaling.  For collections with
+    # offsets like this, it is neither efficient nor accurate,
+    # but it is good enough to generate a plot that you can use
+    # as a starting point.  If you know beforehand the range of
+    # x and y that you want to show, it is better to set them
+    # explicitly, leave out the autolim kwarg (or set it to False),
+    # and omit the 'ax1.autoscale_view()' call below.
+
+# Make a transform for the line segments such that their size is
+# given in points:
+col.set_color(colors)
+
+ax1.autoscale_view()  # See comment above, after ax1.add_collection.
+ax1.set_title('LineCollection using offsets')
+
+
+# The same data as above, but fill the curves.
+col = collections.PolyCollection([spiral], offsets=xyo,
+                                transOffset=ax2.transData)
+trans = transforms.Affine2D().scale(fig.dpi/72.0)
+col.set_transform(trans)  # the points to pixels transform
+ax2.add_collection(col, autolim=True)
+col.set_color(colors)
+
+
+ax2.autoscale_view()
+ax2.set_title('PolyCollection using offsets')
+
+# 7-sided regular polygons
+
+col = collections.RegularPolyCollection(7,
+                                        sizes = np.fabs(xx)*10.0, offsets=xyo,
+                                        transOffset=ax3.transData)
+trans = transforms.Affine2D().scale(fig.dpi/72.0)
+col.set_transform(trans)  # the points to pixels transform
+ax3.add_collection(col, autolim=True)
+col.set_color(colors)
+ax3.autoscale_view()
+ax3.set_title('RegularPolyCollection using offsets')
+
+
+# Simulate a series of ocean current profiles, successively
+# offset by 0.1 m/s so that they form what is sometimes called
+# a "waterfall" plot or a "stagger" plot.
+
+nverts = 60
+ncurves = 20
+offs = (0.1, 0.0)
+
+yy = np.linspace(0, 2*np.pi, nverts)
+ym = np.amax(yy)
+xx = (0.2 + (ym-yy)/ym)**2 * np.cos(yy-0.4) * 0.5
+segs = []
+for i in range(ncurves):
+    xxx = xx + 0.02*rs.randn(nverts)
+    curve = list(zip(xxx, yy*100))
+    segs.append(curve)
+
+col = collections.LineCollection(segs, offsets=offs)
+ax4.add_collection(col, autolim=True)
+col.set_color(colors)
+ax4.autoscale_view()
+ax4.set_title('Successive data offsets')
+ax4.set_xlabel('Zonal velocity component (m/s)')
+ax4.set_ylabel('Depth (m)')
+# Reverse the y-axis so depth increases downward
+ax4.set_ylim(ax4.get_ylim()[::-1])
+
+
+
diff --git a/matplotlib/tests/color_cycle_demo.py b/matplotlib/tests/color_cycle_demo.py
new file mode 100644
index 0000000..42bdfe4
--- /dev/null
+++ b/matplotlib/tests/color_cycle_demo.py
@@ -0,0 +1,32 @@
+"""
+Demo of custom color-cycle settings to control colors for multi-line plots.
+
+This example demonstrates two different APIs:
+
+    1. Setting the default rc-parameter specifying the color cycle.
+       This affects all subsequent plots.
+    2. Setting the color cycle for a specific axes. This only affects a single
+       axes.
+"""
+import numpy as np
+import matplotlib.pyplot as plt
+
+x = np.linspace(0, 2 * np.pi)
+offsets = np.linspace(0, 2*np.pi, 4, endpoint=False)
+# Create array with shifted-sine curve along each column
+yy = np.transpose([np.sin(x + phi) for phi in offsets])
+
+plt.rc('lines', linewidth=4)
+fig, (ax0, ax1)  = plt.subplots(nrows=2)
+
+plt.rc('axes', color_cycle=['r', 'g', 'b', 'y'])
+ax0.plot(yy)
+ax0.set_title('Set default color cycle to rgby')
+
+ax1.set_color_cycle(['c', 'm', 'y', 'k'])
+ax1.plot(yy)
+ax1.set_title('Set axes color cycle to cmyk')
+
+# Tweak spacing between subplots to prevent labels from overlapping
+plt.subplots_adjust(hspace=0.3)
+
diff --git a/matplotlib/tests/colormaps_reference.py b/matplotlib/tests/colormaps_reference.py
new file mode 100644
index 0000000..cec8f0f
--- /dev/null
+++ b/matplotlib/tests/colormaps_reference.py
@@ -0,0 +1,49 @@
+
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+cmaps = [('Sequential',     ['Blues', 'BuGn', 'BuPu',
+                             'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd',
+                             'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu',
+                             'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']),
+         ('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool', 'copper',
+                             'gist_heat', 'gray', 'hot', 'pink',
+                             'spring', 'summer', 'winter']),
+         ('Diverging',      ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr',
+                             'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
+                             'seismic']),
+         ('Qualitative',    ['Accent', 'Dark2', 'Paired', 'Pastel1',
+                             'Pastel2', 'Set1', 'Set2', 'Set3']),
+         ('Miscellaneous',  ['gist_earth', 'terrain', 'ocean', 'gist_stern',
+                             'brg', 'CMRmap', 'cubehelix',
+                             'gnuplot', 'gnuplot2', 'gist_ncar',
+#                             'nipy_spectral', 'jet', 'rainbow',
+                             'jet', 'rainbow', 'gist_rainbow', 
+                             'hsv', 'flag', 'prism'])]
+
+
+nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps)
+gradient = np.linspace(0, 1, 256)
+gradient = np.vstack((gradient, gradient))
+
+def plot_color_gradients(cmap_category, cmap_list):
+    fig, axes = plt.subplots(nrows=nrows)
+    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)
+    axes[0].set_title(cmap_category + ' colormaps', fontsize=14)
+
+    for ax, name in zip(axes, cmap_list):
+        ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
+        pos = list(ax.get_position().bounds)
+        x_text = pos[0] - 0.01
+        y_text = pos[1] + pos[3]/2.
+        fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)
+
+    # Turn off *all* ticks & spines, not just the ones with colormaps.
+    for ax in axes:
+        ax.set_axis_off()
+
+for cmap_category, cmap_list in cmaps:
+    plot_color_gradients(cmap_category, cmap_list)
+
+
diff --git a/matplotlib/tests/date_demo.py b/matplotlib/tests/date_demo.py
new file mode 100644
index 0000000..f88ee65
--- /dev/null
+++ b/matplotlib/tests/date_demo.py
@@ -0,0 +1,41 @@
+
+import datetime
+import numpy as np
+import matplotlib.pyplot as plt
+import matplotlib.dates as mdates
+import matplotlib.cbook as cbook
+
+years    = mdates.YearLocator()   # every year
+months   = mdates.MonthLocator()  # every month
+yearsFmt = mdates.DateFormatter('%Y')
+
+# load a numpy record array from yahoo csv data with fields date,
+# open, close, volume, adj_close from the mpl-data/example directory.
+# The record array stores python datetime.date as an object array in
+# the date column
+datafile = cbook.get_sample_data('goog.npy')
+r = np.load(datafile).view(np.recarray)
+
+fig, ax = plt.subplots()
+ax.plot(r.date, r.adj_close)
+
+
+# format the ticks
+ax.xaxis.set_major_locator(years)
+ax.xaxis.set_major_formatter(yearsFmt)
+ax.xaxis.set_minor_locator(months)
+
+datemin = datetime.date(r.date.min().year, 1, 1)
+datemax = datetime.date(r.date.max().year+1, 1, 1)
+ax.set_xlim(datemin, datemax)
+
+# format the coords message box
+def price(x): return '$%1.2f'%x
+ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
+ax.format_ydata = price
+ax.grid(True)
+
+# rotates and right aligns the x labels, and moves the bottom of the
+# axes up to make room for them
+fig.autofmt_xdate()
+
diff --git a/matplotlib/tests/donut_demo.py b/matplotlib/tests/donut_demo.py
new file mode 100644
index 0000000..4bd3f93
--- /dev/null
+++ b/matplotlib/tests/donut_demo.py
@@ -0,0 +1,52 @@
+
+import numpy as np
+import matplotlib.path as mpath
+import matplotlib.patches as mpatches
+import matplotlib.pyplot as plt
+
+def wise(v):
+    if v == 1:
+        return "CCW"
+    else:
+        return "CW"
+
+def make_circle(r):
+    t = np.arange(0, np.pi * 2.0, 0.01)
+    t = t.reshape((len(t), 1))
+    x = r * np.cos(t)
+    y = r * np.sin(t)
+    return np.hstack((x, y))
+
+Path = mpath.Path
+
+fig, ax = plt.subplots()
+
+inside_vertices = make_circle(0.5)
+outside_vertices = make_circle(1.0)
+codes = np.ones(len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO
+codes[0] = mpath.Path.MOVETO
+
+for i, (inside, outside) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))):
+    # Concatenate the inside and outside subpaths together, changing their
+    # order as needed
+    vertices = np.concatenate((outside_vertices[::outside],
+                               inside_vertices[::inside]))
+    # Shift the path
+    vertices[:, 0] += i * 2.5
+    # The codes will be all "LINETO" commands, except for "MOVETO"s at the
+    # beginning of each subpath
+    all_codes = np.concatenate((codes, codes))
+    # Create the Path object
+    path = mpath.Path(vertices, all_codes)
+    # Add plot it
+    patch = mpatches.PathPatch(path, facecolor='#885500', edgecolor='black')
+    ax.add_patch(patch)
+
+    ax.annotate("Outside %s,\nInside %s" % (wise(outside), wise(inside)),
+                (i * 2.5, -1.5), va="top", ha="center")
+
+ax.set_xlim(-2,10)
+ax.set_ylim(-3,2)
+ax.set_title('Mmm, donuts!')
+ax.set_aspect(1.0)
+
diff --git a/matplotlib/tests/fill_demo.py b/matplotlib/tests/fill_demo.py
new file mode 100644
index 0000000..a91038e
--- /dev/null
+++ b/matplotlib/tests/fill_demo.py
@@ -0,0 +1,18 @@
+
+"""
+Demo of the fill function with a few features.
+
+In addition to the basic fill plot, this demo shows a few optional features:
+
+    * Multiple curves with a single command.
+    * Setting the fill color.
+    * Setting the opacity (alpha value).
+"""
+import numpy as np
+import matplotlib.pyplot as plt
+
+x = np.linspace(0, 2 * np.pi, 100)
+y1 = np.sin(x)
+y2 = np.sin(3 * x)
+plt.fill(x, y1, 'b', x, y2, 'r', alpha=0.3)
+
diff --git a/matplotlib/tests/histogram_path_demo.py b/matplotlib/tests/histogram_path_demo.py
new file mode 100644
index 0000000..a3a9d2e
--- /dev/null
+++ b/matplotlib/tests/histogram_path_demo.py
@@ -0,0 +1,35 @@
+
+import numpy as np
+import matplotlib.pyplot as plt
+import matplotlib.patches as patches
+import matplotlib.path as path
+
+fig, ax = plt.subplots()
+
+# histogram our data with numpy
+data = np.random.randn(1000)
+n, bins = np.histogram(data, 50)
+
+# get the corners of the rectangles for the histogram
+left = np.array(bins[:-1])
+right = np.array(bins[1:])
+bottom = np.zeros(len(left))
+top = bottom + n
+
+
+# we need a (numrects x numsides x 2) numpy array for the path helper
+# function to build a compound path
+XY = np.array([[left,left,right,right], [bottom,top,top,bottom]]).T
+
+# get the Path object
+barpath = path.Path.make_compound_path_from_polys(XY)
+
+# make a patch out of it
+patch = patches.PathPatch(barpath, facecolor='blue', edgecolor='gray', alpha=0.8)
+ax.add_patch(patch)
+
+# update the view limits
+ax.set_xlim(left[0], right[-1])
+ax.set_ylim(bottom.min(), top.max())
+
+
diff --git a/matplotlib/tests/image_demo.py b/matplotlib/tests/image_demo.py
new file mode 100644
index 0000000..6e6d128
--- /dev/null
+++ b/matplotlib/tests/image_demo.py
@@ -0,0 +1,11 @@
+"""
+Simple demo of the imshow function.
+"""
+import matplotlib.pyplot as plt
+import matplotlib.cbook as cbook
+
+datafile = cbook.get_sample_data('ada.png', asfileobj=False)
+image = plt.imread(datafile)
+
+plt.imshow(image)
+plt.axis('off') # clear x- and y-axes
diff --git a/matplotlib/tests/image_demo_clip_path.py b/matplotlib/tests/image_demo_clip_path.py
new file mode 100644
index 0000000..d23b294
--- /dev/null
+++ b/matplotlib/tests/image_demo_clip_path.py
@@ -0,0 +1,15 @@
+"""
+Demo of image that's been clipped by a circular patch.
+"""
+import matplotlib.pyplot as plt
+import matplotlib.patches as patches
+import matplotlib.cbook as cbook
+
+datafile = cbook.get_sample_data('grace_hopper.jpg', asfileobj=False)
+image = plt.imread(datafile)
+fig, ax = plt.subplots()
+im = ax.imshow(image)
+patch = patches.Circle((260, 200), radius=200, transform=ax.transData)
+im.set_clip_path(patch)
+
+plt.axis('off')
diff --git a/matplotlib/tests/joinstyle.py b/matplotlib/tests/joinstyle.py
new file mode 100644
index 0000000..c36c302
--- /dev/null
+++ b/matplotlib/tests/joinstyle.py
@@ -0,0 +1,28 @@
+"""
+Illustrate the three different join styles
+"""
+
+import numpy as np
+import matplotlib.pyplot as plt
+
+def plot_angle(ax, x, y, angle, style):
+    phi = angle/180*np.pi
+    xx = [x+.5,x,x+.5*np.cos(phi)]
+    yy = [y,y,y+.5*np.sin(phi)]
+    ax.plot(xx, yy, lw=8, color='blue', solid_joinstyle=style)
+    ax.plot(xx[1:], yy[1:], lw=1, color='black')
+    ax.plot(xx[1::-1], yy[1::-1], lw=1, color='black')
+    ax.plot(xx[1:2], yy[1:2], 'o', color='red', markersize=3)
+    ax.text(x,y+.2,'%.0f degrees' % angle)
+
+fig, ax = plt.subplots()
+ax.set_title('Join style')
+
+for x,style in enumerate((('miter', 'round', 'bevel'))):
+    ax.text(x, 5, style)
+    for i in range(5):
+        plot_angle(ax, x, i, pow(2.0,3+i), style)
+
+ax.set_xlim(-0.5,2.75)
+ax.set_ylim(-0.5,5.5)
+
diff --git a/matplotlib/tests/legend_demo.py b/matplotlib/tests/legend_demo.py
new file mode 100644
index 0000000..9d7d526
--- /dev/null
+++ b/matplotlib/tests/legend_demo.py
@@ -0,0 +1,20 @@
+
+import numpy as np
+import matplotlib.pyplot as plt
+mpl.rcParams['ipe.textsize'] = True
+
+# Make some fake data.
+a = b = np.arange(0,3, .02)
+c = np.exp(a)
+d = c[::-1]
+
+# Create plots with pre-defined labels.
+plt.plot(a, c, 'k--', label='Model length')
+plt.plot(a, d, 'k:', label='Data length')
+plt.plot(a, c+d, 'k', label='Total message length')
+
+legend = plt.legend(loc='upper center', shadow=True, fontsize='x-large')
+
+# Put a nicer background color on the legend.
+legend.get_frame().set_facecolor('#00FFCC')
+
diff --git a/matplotlib/tests/line_demo_dash_control.py b/matplotlib/tests/line_demo_dash_control.py
new file mode 100644
index 0000000..0b1fe89
--- /dev/null
+++ b/matplotlib/tests/line_demo_dash_control.py
@@ -0,0 +1,12 @@
+
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+x = np.linspace(0, 10)
+line, = plt.plot(x, np.sin(x), '--', linewidth=2)
+
+dashes = [10, 5, 100, 5] # 10 points on, 5 off, 100 on, 5 off
+line.set_dashes(dashes)
+
+
diff --git a/matplotlib/tests/line_styles_reference.py b/matplotlib/tests/line_styles_reference.py
new file mode 100644
index 0000000..9f13d02
--- /dev/null
+++ b/matplotlib/tests/line_styles_reference.py
@@ -0,0 +1,49 @@
+
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+cmaps = [('Sequential',     ['Blues', 'BuGn', 'BuPu',
+                             'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd',
+                             'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu',
+                             'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']),
+         ('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool', 'copper',
+                             'gist_heat', 'gray', 'hot', 'pink',
+                             'spring', 'summer', 'winter']),
+         ('Diverging',      ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr',
+                             'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
+                             'seismic']),
+         ('Qualitative',    ['Accent', 'Dark2', 'Paired', 'Pastel1',
+                             'Pastel2', 'Set1', 'Set2', 'Set3']),
+         ('Miscellaneous',  ['gist_earth', 'terrain', 'ocean', 'gist_stern',
+                             'brg', 'CMRmap', 'cubehelix',
+                             'gnuplot', 'gnuplot2', 'gist_ncar',
+#                             'nipy_spectral', 'jet', 'rainbow',
+                             'jet', 'rainbow',
+                             'gist_rainbow', 'hsv', 'flag', 'prism'])]
+
+
+nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps)
+gradient = np.linspace(0, 1, 256)
+gradient = np.vstack((gradient, gradient))
+
+def plot_color_gradients(cmap_category, cmap_list):
+    fig, axes = plt.subplots(nrows=nrows)
+    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)
+    axes[0].set_title(cmap_category + ' colormaps', fontsize=14)
+
+    for ax, name in zip(axes, cmap_list):
+        ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
+        pos = list(ax.get_position().bounds)
+        x_text = pos[0] - 0.01
+        y_text = pos[1] + pos[3]/2.
+        fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)
+
+    # Turn off *all* ticks & spines, not just the ones with colormaps.
+    for ax in axes:
+        ax.set_axis_off()
+
+for cmap_category, cmap_list in cmaps:
+    plot_color_gradients(cmap_category, cmap_list)
+
+
diff --git a/matplotlib/tests/power_norm_demo.py b/matplotlib/tests/power_norm_demo.py
new file mode 100644
index 0000000..cf105eb
--- /dev/null
+++ b/matplotlib/tests/power_norm_demo.py
@@ -0,0 +1,25 @@
+from matplotlib import pyplot as plt
+import matplotlib.colors as mcolors
+import numpy as np
+from numpy.random import multivariate_normal
+
+data = np.vstack([multivariate_normal([10, 10], [[3, 5],[4, 2]], size=100000),
+                  multivariate_normal([30, 20], [[2, 3],[1, 3]], size=1000)
+                 ])
+
+gammas = [0.8, 0.5, 0.3]
+xgrid = np.floor((len(gammas) + 1.) / 2)
+ygrid = np.ceil((len(gammas) + 1.) / 2)
+
+plt.subplot(xgrid, ygrid, 1)
+plt.title('Linear normalization')
+plt.hist2d(data[:,0], data[:,1], bins=100)
+
+for i, gamma in enumerate(gammas):
+    plt.subplot(xgrid, ygrid, i + 2)
+    plt.title('Power law normalization\n$(\gamma=%1.1f)$' % gamma)
+    plt.hist2d(data[:, 0], data[:, 1],
+               bins=100, norm=mcolors.PowerNorm(gamma))
+
+plt.subplots_adjust(hspace=0.39)
+
diff --git a/matplotlib/tests/two_scales.py b/matplotlib/tests/two_scales.py
new file mode 100644
index 0000000..1e184e3
--- /dev/null
+++ b/matplotlib/tests/two_scales.py
@@ -0,0 +1,24 @@
+
+
+import numpy as np
+import matplotlib.pyplot as plt
+
+fig, ax1 = plt.subplots()
+t = np.arange(0.01, 10.0, 0.01)
+s1 = np.exp(t)
+ax1.plot(t, s1, 'b-')
+ax1.set_xlabel('time (s)')
+# Make the y-axis label and tick labels match the line color.
+ax1.set_ylabel('exp', color='b')
+for tl in ax1.get_yticklabels():
+    tl.set_color('b')
+
+
+ax2 = ax1.twinx()
+s2 = np.sin(2*np.pi*t)
+ax2.plot(t, s2, 'r.')
+ax2.set_ylabel('sin', color='r')
+for tl in ax2.get_yticklabels():
+    tl.set_color('r')
+
+
diff --git a/matplotlib/tests/watermark_image.py b/matplotlib/tests/watermark_image.py
new file mode 100644
index 0000000..ab2c1e1
--- /dev/null
+++ b/matplotlib/tests/watermark_image.py
@@ -0,0 +1,18 @@
+"""
+Use a Text as a watermark
+"""
+
+import numpy as np
+import matplotlib.pyplot as plt
+
+mpl.rcParams['ipe.preamble'] = r"\usepackage{times}"
+
+fig, ax = plt.subplots()
+ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')
+ax.grid()
+
+# position bottom right
+fig.text(0.95, 0.05, 'Property of MPL',
+         fontsize=50, color='gray',
+         ha='right', va='bottom', alpha=0.5)
+
diff --git a/matplotlib/tests/watermark_image2.py b/matplotlib/tests/watermark_image2.py
new file mode 100644
index 0000000..0e0bcc5
--- /dev/null
+++ b/matplotlib/tests/watermark_image2.py
@@ -0,0 +1,18 @@
+
+"""
+Use a PNG file as a watermark
+"""
+import numpy as np
+import matplotlib.cbook as cbook
+import matplotlib.image as image
+import matplotlib.pyplot as plt
+
+datafile = cbook.get_sample_data('logo2.png', asfileobj=False)
+im = image.imread(datafile)
+im[:,:,-1] = 0.5  # set the alpha channel
+
+fig, ax = plt.subplots()
+
+ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')
+ax.grid()
+fig.figimage(im, 10, 10)
diff --git a/pdftoipe/Makefile b/pdftoipe/Makefile
new file mode 100644
index 0000000..ac11e78
--- /dev/null
+++ b/pdftoipe/Makefile
@@ -0,0 +1,40 @@
+# --------------------------------------------------------------------
+# Makefile for pdftoipe
+# --------------------------------------------------------------------
+
+ifdef COMSPEC
+  # compiling on Windows?
+  CPPFLAGS += -I/minglibs/include/poppler
+  LIBS += -L/minglibs/lib -lpoppler
+  LDFLAGS += -static
+  TARGET = pdftoipe.exe	
+else ifdef IPECROSS
+  # cross-compiling for Windows?
+  CXX=i686-w64-mingw32-g++
+  CPPFLAGS += -I/sw/mingwlibs/include/poppler
+  LIBS += -L/sw/mingwlibs/lib -lpoppler
+  LDFLAGS += -static
+  TARGET = pdftoipe.exe	
+else
+  CPPFLAGS += $(shell pkg-config --cflags poppler) 
+  LIBS += $(shell pkg-config --libs poppler)
+  TARGET = pdftoipe
+endif
+
+CXXFLAGS += -Wno-write-strings
+
+all: $(TARGET)
+
+objects = parseargs.o xmloutputdev.o pdftoipe.o 
+
+$(TARGET): $(objects)
+	$(CXX) $(LDFLAGS) -o $@ $^ $(LIBS)
+
+clean:
+	@-rm -f $(objects) $(TARGET)
+
+xmloutputdev.o: xmloutputdev.h
+pdftoipe.o: xmloutputdev.h parseargs.h
+parseargs.o: parseargs.h
+
+# --------------------------------------------------------------------
diff --git a/pdftoipe/compile_on_windows.pdf b/pdftoipe/compile_on_windows.pdf
new file mode 100644
index 0000000..2ef51b7
Binary files /dev/null and b/pdftoipe/compile_on_windows.pdf differ
diff --git a/pdftoipe/parseargs.cc b/pdftoipe/parseargs.cc
new file mode 100644
index 0000000..6d15044
--- /dev/null
+++ b/pdftoipe/parseargs.cc
@@ -0,0 +1,208 @@
+/*
+ * parseargs.h
+ *
+ * Command line argument parser.
+ *
+ * Copyright 1996-2003 Glyph & Cog, LLC
+ */
+
+//========================================================================
+//
+// Modified under the Poppler project - http://poppler.freedesktop.org
+//
+// Poppler project changes to this file are under the GPLv2 or later license
+//
+// All changes made under the Poppler project to this file are licensed
+// under GPL version 2 or later
+//
+// Copyright (C) 2008, 2009 Albert Astals Cid <aacid at kde.org>
+//
+// To see a description of the changes please see the Changelog file that
+// came with your tarball or type make ChangeLog if you are building from git
+//
+//========================================================================
+
+#include <stdio.h>
+#include <stddef.h>
+#include <string.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include "parseargs.h"
+
+/* #include "goo/gstrtod.h" */
+
+static const ArgDesc *findArg(const ArgDesc *args, char *arg);
+static GBool grabArg(const ArgDesc *arg, int i, int *argc, char *argv[]);
+
+GBool parseArgs(const ArgDesc *args, int *argc, char *argv[]) {
+  const ArgDesc *arg;
+  int i, j;
+  GBool ok;
+
+  ok = gTrue;
+  i = 1;
+  while (i < *argc) {
+    if (!strcmp(argv[i], "--")) {
+      --*argc;
+      for (j = i; j < *argc; ++j)
+	argv[j] = argv[j+1];
+      break;
+    } else if ((arg = findArg(args, argv[i]))) {
+      if (!grabArg(arg, i, argc, argv))
+	ok = gFalse;
+    } else {
+      ++i;
+    }
+  }
+  return ok;
+}
+
+void printUsage(char *program, char *otherArgs, const ArgDesc *args) {
+  const ArgDesc *arg;
+  char *typ;
+  int w, w1;
+
+  w = 0;
+  for (arg = args; arg->arg; ++arg) {
+    if ((w1 = strlen(arg->arg)) > w)
+      w = w1;
+  }
+
+  fprintf(stderr, "Usage: %s [options]", program);
+  if (otherArgs)
+    fprintf(stderr, " %s", otherArgs);
+  fprintf(stderr, "\n");
+
+  for (arg = args; arg->arg; ++arg) {
+    fprintf(stderr, "  %s", arg->arg);
+    w1 = 9 + w - strlen(arg->arg);
+    switch (arg->kind) {
+    case argInt:
+    case argIntDummy:
+      typ = " <int>";
+      break;
+    case argFP:
+    case argFPDummy:
+      typ = " <fp>";
+      break;
+    case argString:
+    case argStringDummy:
+      typ = " <string>";
+      break;
+    case argFlag:
+    case argFlagDummy:
+    default:
+      typ = "";
+      break;
+    }
+    fprintf(stderr, "%-*s", w1, typ);
+    if (arg->usage)
+      fprintf(stderr, ": %s", arg->usage);
+    fprintf(stderr, "\n");
+  }
+}
+
+static const ArgDesc *findArg(const ArgDesc *args, char *arg) {
+  const ArgDesc *p;
+
+  for (p = args; p->arg; ++p) {
+    if (p->kind < argFlagDummy && !strcmp(p->arg, arg))
+      return p;
+  }
+  return NULL;
+}
+
+static GBool grabArg(const ArgDesc *arg, int i, int *argc, char *argv[]) {
+  int n;
+  int j;
+  GBool ok;
+
+  ok = gTrue;
+  n = 0;
+  switch (arg->kind) {
+  case argFlag:
+    *(GBool *)arg->val = gTrue;
+    n = 1;
+    break;
+  case argInt:
+    if (i + 1 < *argc && isInt(argv[i+1])) {
+      *(int *)arg->val = atoi(argv[i+1]);
+      n = 2;
+    } else {
+      ok = gFalse;
+      n = 1;
+    }
+    break;
+  case argFP:
+    if (i + 1 < *argc && isFP(argv[i+1])) {
+      *(double *)arg->val = atof(argv[i+1]);
+      n = 2;
+    } else {
+      ok = gFalse;
+      n = 1;
+    }
+    break;
+  case argString:
+    if (i + 1 < *argc) {
+      strncpy((char *)arg->val, argv[i+1], arg->size - 1);
+      ((char *)arg->val)[arg->size - 1] = '\0';
+      n = 2;
+    } else {
+      ok = gFalse;
+      n = 1;
+    }
+    break;
+  default:
+    fprintf(stderr, "Internal error in arg table\n");
+    n = 1;
+    break;
+  }
+  if (n > 0) {
+    *argc -= n;
+    for (j = i; j < *argc; ++j)
+      argv[j] = argv[j+n];
+  }
+  return ok;
+}
+
+GBool isInt(char *s) {
+  if (*s == '-' || *s == '+')
+    ++s;
+  while (isdigit(*s))
+    ++s;
+  if (*s)
+    return gFalse;
+  return gTrue;
+}
+
+GBool isFP(char *s) {
+  int n;
+
+  if (*s == '-' || *s == '+')
+    ++s;
+  n = 0;
+  while (isdigit(*s)) {
+    ++s;
+    ++n;
+  }
+  if (*s == '.')
+    ++s;
+  while (isdigit(*s)) {
+    ++s;
+    ++n;
+  }
+  if (n > 0 && (*s == 'e' || *s == 'E')) {
+    ++s;
+    if (*s == '-' || *s == '+')
+      ++s;
+    n = 0;
+    if (!isdigit(*s))
+      return gFalse;
+    do {
+      ++s;
+    } while (isdigit(*s));
+  }
+  if (*s)
+    return gFalse;
+  return gTrue;
+}
diff --git a/pdftoipe/parseargs.h b/pdftoipe/parseargs.h
new file mode 100644
index 0000000..4418421
--- /dev/null
+++ b/pdftoipe/parseargs.h
@@ -0,0 +1,85 @@
+/*
+ * parseargs.h
+ *
+ * Command line argument parser.
+ *
+ * Copyright 1996-2003 Glyph & Cog, LLC
+ */
+
+//========================================================================
+//
+// Modified under the Poppler project - http://poppler.freedesktop.org
+//
+// All changes made under the Poppler project to this file are licensed
+// under GPL version 2 or later
+//
+// Copyright (C) 2008 Albert Astals Cid <aacid at kde.org>
+//
+// To see a description of the changes please see the Changelog file that
+// came with your tarball or type make ChangeLog if you are building from git
+//
+//========================================================================
+
+#ifndef PARSEARGS_H
+#define PARSEARGS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "goo/gtypes.h"
+
+/*
+ * Argument kinds.
+ */
+typedef enum {
+  argFlag,			/* flag (present / not-present) */
+				/*   [val: GBool *]             */
+  argInt,			/* integer arg    */
+				/*   [val: int *] */
+  argFP,			/* floating point arg */
+				/*   [val: double *]  */
+  argString,			/* string arg      */
+				/*   [val: char *] */
+  /* dummy entries -- these show up in the usage listing only; */
+  /* useful for X args, for example                            */
+  argFlagDummy,
+  argIntDummy,
+  argFPDummy,
+  argStringDummy
+} ArgKind;
+
+/*
+ * Argument descriptor.
+ */
+typedef struct {
+  char *arg;			/* the command line switch */
+  ArgKind kind;			/* kind of arg */
+  void *val;			/* place to store value */
+  int size;			/* for argString: size of string */
+  char *usage;			/* usage string */
+} ArgDesc;
+
+/*
+ * Parse command line.  Removes all args which are found in the arg
+ * descriptor list <args>.  Stops parsing if "--" is found (and removes
+ * it).  Returns gFalse if there was an error.
+ */
+extern GBool parseArgs(const ArgDesc *args, int *argc, char *argv[]);
+
+/*
+ * Print usage message, based on arg descriptor list.
+ */
+extern void printUsage(char *program, char *otherArgs, const ArgDesc *args);
+
+/*
+ * Check if a string is a valid integer or floating point number.
+ */
+extern GBool isInt(char *s);
+extern GBool isFP(char *s);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/pdftoipe/pdftoipe.1 b/pdftoipe/pdftoipe.1
new file mode 100644
index 0000000..f95dbef
--- /dev/null
+++ b/pdftoipe/pdftoipe.1
@@ -0,0 +1,107 @@
+.\" EMACS: -*- nroff -*-
+.\" First parameter, NAME, should be all caps
+.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
+.\" other parameters are allowed: see man(7), man(1)
+.\" TeX users may be more comfortable with the \fB<whatever>\fP and
+.\" \fI<whatever>\fP escape sequences to invode bold face and italics, 
+.\" respectively.
+.TH PDFTOIPE 1 "October 13, 2009"
+.\" Please adjust this date whenever revising the manpage.
+.\"
+.\" Some roff macros, for reference:
+.\" .nh        disable hyphenation
+.\" .hy        enable hyphenation
+.\" .ad l      left justify
+.\" .ad b      justify to both left and right margins
+.\" .nf        disable filling
+.\" .fi        enable filling
+.\" .br        insert line break
+.\" .sp <n>    insert n+1 empty lines
+.\" for manpage-specific macros, see man(7)
+.SH NAME
+pdftoipe \- Convert PDF files into editable Ipe format
+.SH SYNOPSIS
+.B pdftoipe
+{ \fIoptions\fP } \fIPDF file\fP [ \fIXML file\fP ]
+
+.SH DESCRIPTION
+
+\fBpdftoipe\fP converts arbitrary PDF files to Ipe's XML format.
+
+Note that \fBpdftoipe\fP is not related to Ipe's use of the PDF file
+format.  PDF files generated by Ipe contain an extra stream with Ipe
+markup information, which is necessary for Ipe to read the file again.
+If you wish to convert an Ipe-generated PDF-file to XML format, you
+should use \fIipetoipe -xml\fP!  \fBpdftoipe\fP is meant to allow you
+to take arbitrary PDF files and make them editable in Ipe.
+
+\fBpdftoipe\fP does a pretty good job on drawings, but doesn't handle
+text very well.  Ipe's text model is based on LaTeX, which is just
+very different from the text found in most PDF files.
+
+.TP
+\fB-notext\fR
+Ignore all text in the PDF file, convert graphics only
+.TP
+\fB-literal\fR
+Allow Latex markup in text objects.  The default is to escape all
+characters special in Latex.
+.TP
+\fB-math\fR
+Use LaTeX math mode for all text in the PDF file
+.TP
+\fB-merge\fR \fIint\fP
+Set the text merge level, an integer between 0 (the default) and 2.
+It determines how eagerly \fBpdftoipe\fP tries to combine consecutive
+text in the PDF document into a single Ipe text object.  At level 0,
+only characters consecutively rendered in PDF are combined. At level
+1, more text is combined.  At level 2, all text is combined until a
+path or image is drawn.
+.TP
+\fB-unicode\fR \fIint\fP 
+Determine what should be done with non-ASCII
+characters in text.  At level 0, all non-ASCII
+characters are represented as \fB[U+XXX]\fR.  At level 1 (the
+default), some often used characters (such as bullets) are replaced by
+Latex equivalents, others are represented as \fB[U+XXX]\fR.
+At level 2, characters that are not replaced by Latex equivalents
+are included in UTF-8.  At level 3, all characters are included as
+UTF-8.
+
+At level 2 and 3, UTF-8 is set as the input encoding in the Latex
+preamble of the generated Ipe document.
+
+Note that this only concerns characters for which the PDF file
+provides a mapping to Unicode.  Characters from embedded fonts without
+Unicode mapping (such as symbol fonts) are always represented as
+\fB[S+XX]\fR.
+.TP
+\fB-f\fR \fIint\fP
+First page to convert
+.TP
+\fB-l\fR \fIint\fP
+Last page to convert
+.TP
+\fB-opw\fR \fIstring\fP
+Owner password for encrypted PDF files
+.TP
+\fB-upw\fP \fIstring\fP
+User password for encrypted PDF files
+.TP
+\fB-q\fP
+Quiet mode (don't print any messages or errors)
+
+.SH AUTHOR
+Otfried Cheong
+
+.SH REPORTING BUGS
+.ad l
+Please report bugs at
+.I "http://ipe7.sourceforge.net/bugzilla.html"
+
+.SH SEE ALSO
+.ad l
+More information about Ipe can be found in  
+.IR "The Ipe Manual" , 
+available online at 
+.I "http://ipe7.sourceforge.net/manual/manual.html"
diff --git a/pdftoipe/pdftoipe.cpp b/pdftoipe/pdftoipe.cpp
new file mode 100644
index 0000000..1f02755
--- /dev/null
+++ b/pdftoipe/pdftoipe.cpp
@@ -0,0 +1,166 @@
+// --------------------------------------------------------------------
+// Pdftoipe: convert PDF file to editable Ipe XML file
+// --------------------------------------------------------------------
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+
+#include "goo/GooString.h"
+#include "goo/gmem.h"
+#include "Object.h"
+#include "Stream.h"
+#include "Array.h"
+#include "Dict.h"
+#include "XRef.h"
+#include "Catalog.h"
+#include "Page.h"
+#include "PDFDoc.h"
+#include "Error.h"
+#include "GlobalParams.h"
+
+#include "parseargs.h"
+#include "xmloutputdev.h"
+
+static int firstPage = 1;
+static int lastPage = 0;
+static int mergeLevel = 0;
+static int unicodeLevel = 1;
+static char ownerPassword[33] = "";
+static char userPassword[33] = "";
+static GBool quiet = gFalse;
+static GBool printHelp = gFalse;
+static GBool math = gFalse;
+static GBool literal = gFalse;
+static GBool notext = gFalse;
+
+static ArgDesc argDesc[] = {
+  {"-f",      argInt,      &firstPage,      0,
+   "first page to convert"},
+  {"-l",      argInt,      &lastPage,       0,
+   "last page to convert"},
+  {"-opw",    argString,   ownerPassword,   sizeof(ownerPassword),
+   "owner password (for encrypted files)"},
+  {"-upw",    argString,   userPassword,    sizeof(userPassword),
+   "user password (for encrypted files)"},
+  {"-q",      argFlag,     &quiet,          0,
+   "don't print any messages or errors"},
+  {"-math",   argFlag,     &math,           0,
+   "turn all text objects into math formulas"},
+  {"-literal", argFlag,    &literal,        0,
+   "allow math mode in input text objects"},
+  {"-notext", argFlag,     &notext,         0,
+   "discard all text objects"},
+  {"-merge",  argInt,      &mergeLevel,       0,
+   "how eagerly should consecutive text be merged: 0, 1, or 2 (default 0)"},
+  {"-unicode",  argInt,    &unicodeLevel,       0,
+   "how much Unicode should be used: 1, 2, or 3 (default 1)"},
+  {"-h",      argFlag,     &printHelp,      0,
+   "print usage information"},
+  {"-help",   argFlag,     &printHelp,      0,
+   "print usage information"},
+  {"--help",  argFlag,     &printHelp,      0,
+   "print usage information"},
+  {"-?",      argFlag,     &printHelp,      0,
+   "print usage information"},
+  {NULL, argFlag, 0, 0, 0}
+};
+
+int main(int argc, char *argv[])
+{
+  // parse args
+  GBool ok = parseArgs(argDesc, &argc, argv);
+  if (!ok || argc < 2 || argc > 3 || printHelp) {
+    fprintf(stderr, "pdftoipe version %s\n", PDFTOIPE_VERSION);
+    printUsage("pdftoipe", "<PDF-file> [<XML-file>]", argDesc);
+    return 1;
+  }
+
+  GooString *fileName = new GooString(argv[1]);
+
+  globalParams = new GlobalParams();
+  if (quiet)
+    globalParams->setErrQuiet(quiet);
+
+  GooString *ownerPW, *userPW;
+  if (ownerPassword[0]) {
+    ownerPW = new GooString(ownerPassword);
+  } else {
+    ownerPW = 0;
+  }
+  if (userPassword[0]) {
+    userPW = new GooString(userPassword);
+  } else {
+    userPW = 0;
+  }
+
+  // open PDF file
+  PDFDoc *doc = new PDFDoc(fileName, ownerPW, userPW);
+  delete userPW;
+  delete ownerPW;
+
+  if (!doc->isOk())
+    return 1;
+  
+  // construct XML file name
+  GooString *xmlFileName;
+  if (argc == 3) {
+    xmlFileName = new GooString(argv[2]);
+  } else {
+    char *p = fileName->getCString() + fileName->getLength() - 4;
+    if (!strcmp(p, ".pdf") || !strcmp(p, ".PDF")) {
+      xmlFileName = new GooString(fileName->getCString(),
+				  fileName->getLength() - 4);
+    } else {
+      xmlFileName = fileName->copy();
+    }
+    xmlFileName->append(".ipe");
+  }
+
+  // get page range
+  if (firstPage < 1)
+    firstPage = 1;
+
+  if (lastPage < 1 || lastPage > doc->getNumPages())
+    lastPage = doc->getNumPages();
+
+  // write XML file
+  XmlOutputDev *xmlOut = 
+    new XmlOutputDev(xmlFileName->getCString(), doc->getXRef(),
+		     doc->getCatalog(), firstPage, lastPage);
+
+  // tell output device about text handling
+  xmlOut->setTextHandling(math, notext, literal, mergeLevel, unicodeLevel);
+  
+  int exitCode = 2;
+  if (xmlOut->isOk()) {
+    doc->displayPages(xmlOut, firstPage, lastPage, 
+		      // double hDPI, double vDPI, int rotate,
+		      // GBool useMediaBox, GBool crop, GBool printing,
+		      72.0, 72.0, 0, gFalse, gFalse, gFalse);
+    exitCode = 0;
+  }
+
+  if (xmlOut->hasUnicode()) {
+    fprintf(stderr, "The document contains Unicode (non-ASCII) text.\n");
+    if (unicodeLevel <= 1)
+      fprintf(stderr, "Unknown Unicode characters were replaced by [U+XXX].\n");
+    else
+      fprintf(stderr, "UTF-8 was set as document encoding in the preamble.\n");
+  }
+
+  // clean up
+  delete xmlOut;
+  delete xmlFileName;
+  delete doc;
+  delete globalParams;
+
+  // check for memory leaks
+  Object::memCheck(stderr);
+  gMemReport(stderr);
+
+  return exitCode;
+}
+
+// --------------------------------------------------------------------
diff --git a/pdftoipe/readme.txt b/pdftoipe/readme.txt
new file mode 100644
index 0000000..182ea41
--- /dev/null
+++ b/pdftoipe/readme.txt
@@ -0,0 +1,132 @@
+
+Pdftoipe
+========
+
+This is Pdftoipe, a program that tries to read arbitrary PDF files and
+to generate an XML file readable by Ipe.
+
+You can report bugs on the issue tracking system at
+"https://github.com/otfried/ipe-tools/issues".
+
+Before reporting a bug, check that you have the latest version of
+Pdftoipe, and check the existing reports to see whether your bug has
+already been reported.  Please do not send bug reports directly to me
+(the first thing I would do with the report is to enter it into the
+tracking system).
+
+Suggestions for features, or random comments on Pdftoipe can be sent
+to the Ipe discussion mailing list at
+<ipe-discuss at lists.science.uu.nl>.  If you have problems installing or
+using Pdftoipe, the Ipe discussion mailing list would also be the best
+place to ask.
+
+You can send suggestions or comments directly to me by Email, but you
+should then not expect a reply.  I cannot dedicate much time to Ipe,
+and the little time I have I prefer to put into development.  I'm much
+more likely to get involved in a discussion of desirable features on
+the mailing list, where anyone interested can participate than by
+direct Email.
+
+	Otfried Cheong
+	Dept. of Computer Science
+	KAIST
+	Daejeon, South Korea
+	Email: otfried at ipe.airpost.net
+	Ipe webpage: http://ipe7.sourceforge.net
+
+--------------------------------------------------------------------
+
+Pdftoipe is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by the
+Free Software Foundation; either version 2 of the License, or (at your
+option) any later version.
+
+--------------------------------------------------------------------
+
+Compiling
+=========
+
+You need the Poppler library (http://poppler.freedesktop.org).  On
+Debian/Ubuntu, install the packages 'libpoppler-dev' and
+'libpoppler-private-dev'. 
+
+In source directory, say
+
+make
+
+This will create the single executable "pdftoipe".  Copy it to
+whereever you like.  You may also install the man page "pdftoipe.1".
+
+If you want to compile pdftoipe on Windows, please refer to
+"compile_on_windows.pdf", written by Daniel Beckmann.
+
+--------------------------------------------------------------------
+
+Changes
+=======
+
+ * 2014/03/03
+   Applied patch from bug #138 to fix compilation on newer poppler
+   versions, as well as fix missing dollar signs for some greek
+   letters. 
+
+ * 2013/01/24 
+   Applied patches from bugs #88 and #112 to fix compilation on
+   newer poppler versions.
+
+ * 2011/05/17 
+   Built Windows binary and included instructions by Daniel
+   Beckmann for compiling on Windows in the source download.
+
+ * 2011/01/16
+   Re-released to clarify that pdftoipe uses GPL V2, compatible with
+   the poppler license.
+
+ * 2009/10/14
+   Changed to use libpoppler instead of using Xpdf's code directly.
+   Generate Ipe 7 format.
+
+ * 2007/05/09
+   Applied patches provided by Philip Johnson (bug #160) to support
+   latex markup in text objects, and to handle text transformations.
+   Improved text transformations, and added -merge option to better
+   control separation/merging of text.
+
+ * 2005/11/14
+   Generating header correct for Ipe 6.0 preview 25.
+
+ * 2005/09/17
+   Fixed handling of transformation matrix for text objects.  (Text
+   was incorrectly positioned if pages had the /Rotate flag on.)
+
+   Added -cyberbit option to automatically insert style sheet for
+   using the Cyberbit font (but of course it has to be installed
+   properly to be used from Pdflatex).
+
+   Removed silly dependency on Qt.
+
+   Added conversion of some Unicode characters to Latex macros.
+
+ * 2003/06/30
+   Added recognition of Unicode text (results in a message to the
+   user) and escaping of the special Latex characters.
+
+   Fixed generation of incorrect XML files (unterminated <text>
+   objects).  
+   
+ * 2003/06/18
+   Added -notext option to completely ignore all text in PDF file.
+
+   Added man page.
+
+ * 2003/06/13
+   Packaged pdftoipe separately from Ipe.
+
+ * 2003/06/04
+   Fixed handling of transformation matrix in Pdftoipe.  Pdftoipe
+   is now actually considered supported.
+
+   Added option -math to pdftoipe.  With this option, all text objects 
+   are turned into math formulas. 
+
+--------------------------------------------------------------------
diff --git a/pdftoipe/xmloutputdev.cpp b/pdftoipe/xmloutputdev.cpp
new file mode 100644
index 0000000..757f626
--- /dev/null
+++ b/pdftoipe/xmloutputdev.cpp
@@ -0,0 +1,635 @@
+// --------------------------------------------------------------------
+// Output device writing XML stream
+// --------------------------------------------------------------------
+
+#include <stdio.h>
+#include <stddef.h>
+#include <stdarg.h>
+
+#include "Object.h"
+#include "Error.h"
+#include "Gfx.h"
+#include "GfxState.h"
+#include "GfxFont.h"
+#include "Catalog.h"
+#include "Page.h"
+#include "Stream.h"
+
+#include "xmloutputdev.h"
+
+#include <vector>
+#include <cmath> 
+
+//------------------------------------------------------------------------
+// XmlOutputDev
+//------------------------------------------------------------------------
+
+XmlOutputDev::XmlOutputDev(char *fileName, XRef *xrefA, Catalog *catalog,
+			   int firstPage, int lastPage)
+{
+  FILE *f;
+
+  if (!(f = fopen(fileName, "wb"))) {
+    fprintf(stderr, "Couldn't open output file '%s'\n", fileName);
+    ok = gFalse;
+    return;
+  }
+  outputStream = f;
+
+  // initialize
+  ok = gTrue;
+  xref = xrefA;
+  inText = false;
+  iUnicode = false;
+
+  // set defaults
+  iIsMath = false; 
+  iNoText = false;
+  iIsLiteral = false;
+  iMergeLevel = 0;
+  iUnicodeLevel = 1;
+
+  Page *page = catalog->getPage(firstPage);
+  double wid = page->getMediaWidth();
+  double ht = page->getMediaHeight();
+
+  /*
+  int rot = page->getRotate();
+  fprintf(stderr, "Page rotation: %d\n", rot);
+  if (rot == 90 || rot == 270) {
+    double t = wid;
+    wid = ht;
+    ht = t;
+  }
+  */
+
+  PDFRectangle *media = page->getMediaBox();
+  PDFRectangle *crop = page->getCropBox();
+
+  fprintf(stderr, "MediaBox: %g %g %g %g (%g x %g)\n", 
+	  media->x1, media->x2, media->y1, media->y2, wid, ht);
+  fprintf(stderr, "CropBox: %g %g %g %g\n", 
+	  crop->x1, crop->x2, crop->y1, crop->y2);
+
+  writePS("<?xml version=\"1.0\"?>\n");
+  writePS("<!DOCTYPE ipe SYSTEM \"ipe.dtd\">\n");
+  writePSFmt("<ipe version=\"70000\" creator=\"pdftoipe %s\">\n", 
+	     PDFTOIPE_VERSION);
+  writePS("<ipestyle>\n");
+  writePSFmt("<layout paper=\"%g %g\" frame=\"%g %g\" origin=\"%g %g\"/>\n", 
+	     wid, ht, crop->x2 - crop->x1, crop->y2 - crop->y1, 
+	     crop->x1 - media->x1, crop->y1 - media->y1);
+  writePS("<symbol name=\"bullet\"><path matrix=\"0.04 0 0 0.04 0 0\" fill=\"black\">\n");
+  writePS("18 0 0 18 0 0 e</path></symbol>\n");
+  writePS("</ipestyle>\n");
+
+  // initialize sequential page number
+  seqPage = 1;
+}
+
+XmlOutputDev::~XmlOutputDev()
+{
+  if (ok) {
+    finishText();
+    writePS("</ipe>\n");
+  }
+  fclose(outputStream);
+}
+
+// ----------------------------------------------------------
+
+void XmlOutputDev::setTextHandling(GBool math, GBool notext, 
+				   GBool literal, int mergeLevel,
+				   int unicodeLevel)
+{
+  iIsMath = math;
+  iNoText = notext;
+  iIsLiteral = literal;
+  iMergeLevel = mergeLevel;
+  iUnicodeLevel = unicodeLevel;
+  if (iUnicodeLevel >= 2) {
+    writePS("<ipestyle>\n");
+    writePS("<preamble>\\usepackage[utf8]{inputenc}</preamble>\n");
+    writePS("</ipestyle>\n");
+  }
+}
+
+// ----------------------------------------------------------
+
+void XmlOutputDev::startPage(int pageNum, GfxState *state)
+{
+  startPage(pageNum, state, NULL);  // for poppler <= 0.22
+}
+
+void XmlOutputDev::startPage(int pageNum, GfxState *state, XRef *xrefA)
+{
+  writePSFmt("<!-- Page: %d %d -->\n", pageNum, seqPage);
+  fprintf(stderr, "Converting page %d (numbered %d)\n", 
+	  seqPage, pageNum);
+  writePS("<page>\n");
+  ++seqPage;
+}
+
+void XmlOutputDev::endPage()
+{
+  finishText();
+  writePS("</page>\n");
+}
+
+// --------------------------------------------------------------------
+
+void XmlOutputDev::startDrawingPath()
+{
+  finishText();
+}
+
+void XmlOutputDev::stroke(GfxState *state)
+{
+  startDrawingPath();
+  GfxRGB rgb;
+  state->getStrokeRGB(&rgb);
+  writeColor("<path stroke=", rgb, 0);
+  writePSFmt(" pen=\"%g\"", state->getTransformedLineWidth());
+
+  double *dash;
+  double start;
+  int length, i;
+
+  state->getLineDash(&dash, &length, &start);
+  if (length) {
+    writePS(" dash=\"[");
+    for (i = 0; i < length; ++i)
+      writePSFmt("%g%s", state->transformWidth(dash[i]), 
+		 (i == length-1) ? "" : " ");
+    writePSFmt("] %g\"", state->transformWidth(start));
+  }
+    
+  if (state->getLineJoin() > 0)
+    writePSFmt(" join=\"%d\"", state->getLineJoin());
+  if (state->getLineCap())
+    writePSFmt(" cap=\"%d\"", state->getLineCap());
+
+  writePS(">\n");
+  doPath(state);
+  writePS("</path>\n");
+}
+
+void XmlOutputDev::fill(GfxState *state)
+{
+  startDrawingPath();
+  GfxRGB rgb;
+  state->getFillRGB(&rgb);
+  writeColor("<path fill=", rgb, " fillrule=\"wind\">\n");
+  doPath(state);
+  writePS("</path>\n");
+}
+
+void XmlOutputDev::eoFill(GfxState *state)
+{
+  startDrawingPath();
+  GfxRGB rgb;
+  state->getFillRGB(&rgb);
+  writeColor("<path fill=", rgb, ">\n"); 
+  doPath(state);
+  writePS("</path>\n");
+}
+
+void XmlOutputDev::doPath(GfxState *state)
+{
+  GfxPath *path = state->getPath();
+  GfxSubpath *subpath;
+  int n, m, i, j;
+
+  n = path->getNumSubpaths();
+
+  double x, y, x1, y1, x2, y2;
+  for (i = 0; i < n; ++i) {
+    subpath = path->getSubpath(i);
+    m = subpath->getNumPoints();
+    state->transform(subpath->getX(0), subpath->getY(0), &x, &y);
+    writePSFmt("%g %g m\n", x, y);
+    j = 1;
+    while (j < m) {
+      if (subpath->getCurve(j)) {
+	state->transform(subpath->getX(j), subpath->getY(j), &x, &y);
+	state->transform(subpath->getX(j+1), subpath->getY(j+1), &x1, &y1);
+	state->transform(subpath->getX(j+2), subpath->getY(j+2), &x2, &y2);
+	writePSFmt("%g %g %g %g %g %g c\n", x, y, x1, y1, x2, y2);
+	j += 3;
+      } else {
+	state->transform(subpath->getX(j), subpath->getY(j), &x, &y);
+	writePSFmt("%g %g l\n", x, y);
+	++j;
+      }
+    }
+    if (subpath->isClosed()) {
+      writePS("h\n");
+    }
+  }
+}
+
+// --------------------------------------------------------------------
+
+void XmlOutputDev::updateTextPos(GfxState *)
+{
+  if (iMergeLevel < 2)
+    finishText();
+}
+
+void XmlOutputDev::updateTextShift(GfxState *, double /*shift*/)
+{
+  if (iMergeLevel < 1)
+    finishText();
+}
+
+void XmlOutputDev::drawChar(GfxState *state, double x, double y,
+			    double dx, double dy,
+			    double originX, double originY,
+			    CharCode code, int nBytes, 
+			    Unicode *u, int uLen)
+{
+  // check for invisible text -- this is used by Acrobat Capture
+  if ((state->getRender() & 3) == 3)
+    return;
+
+  // get the font
+  if (!state->getFont())
+    return;
+
+  if (iNoText) // discard text objects
+    return;
+
+  startText(state, x - originX, y - originY);
+
+  if (uLen == 0) {
+    if (code == 0x62) {
+      // this is a hack to handle bullets created by pstricks and should 
+      // probably be an option
+      writePS("\\ipesymbol{bullet}{}{}{}");
+    } else
+      writePSFmt("[S+%02x]", code);
+  } else {
+    for (int i = 0; i < uLen; ++i)
+      writePSUnicode(u[i]);
+  }
+}
+
+void XmlOutputDev::startText(GfxState *state, double x, double y)
+{
+  if (inText)
+    return;
+
+  double xt, yt;
+  state->transform(x, y, &xt, &yt);
+
+  double *T = state->getTextMat();
+  double *C = state->getCTM();
+
+  /*
+  fprintf(stderr, "TextMatrix = %g %g %g %g %g %g\n", 
+	  T[0], T[1], T[2], T[3], T[4], T[5]);
+  fprintf(stderr, "CTM = %g %g %g %g %g %g\n", 
+	  C[0], C[1], C[2], C[3], C[4], C[5]);
+  */
+
+  double M[4];
+  M[0] = C[0] * T[0] + C[2] * T[1];
+  M[1] = C[1] * T[0] + C[3] * T[1];
+  M[2] = C[0] * T[2] + C[2] * T[3];
+  M[3] = C[1] * T[2] + C[3] * T[3];
+
+  GfxRGB rgb;
+  state->getFillRGB(&rgb);
+  writeColor("<text stroke=", rgb, " pos=\"0 0\" transformations=\"affine\" ");
+  writePS("valign=\"baseline\" ");
+  writePSFmt("size=\"%g\" matrix=\"%g %g %g %g %g %g\">",
+	     state->getFontSize(), M[0], M[1], M[2], M[3], xt, yt);
+
+  if (iIsMath)
+    writePS("$");
+  inText = true;
+}
+
+void XmlOutputDev::finishText()
+{
+  if (inText) {
+    if (iIsMath)
+      writePS("$");
+    writePS("</text>\n");
+  }
+  inText = false;
+}
+
+// --------------------------------------------------------------------
+
+void XmlOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
+			     int width, int height, GfxImageColorMap *colorMap,
+			     GBool interpolate, int *maskColors, 
+			     GBool inlineImg)
+{
+  finishText();
+
+  ImageStream *imgStr;
+  Guchar *p;
+  GfxRGB rgb;
+  int x, y;
+  int c;
+
+  writePSFmt("<image width=\"%d\" height=\"%d\"", width, height);
+
+  double *mat;
+  mat = state->getCTM();
+  double tx = mat[0] + mat[2] + mat[4];
+  double ty = mat[1] + mat[3] + mat[5];
+  writePSFmt(" rect=\"%g %g %g %g\"", mat[4], mat[5], tx, ty);
+  
+  if (str->getKind() == strDCT && !inlineImg &&
+      3 <= colorMap->getNumPixelComps() && colorMap->getNumPixelComps() <= 4) {
+    // dump JPEG stream
+    std::vector<char> buffer;
+    // initialize stream
+    str = str->getNextStream();
+    str->reset();
+    // copy the stream
+    while ((c = str->getChar()) != EOF)
+      buffer.push_back(char(c));
+    str->close();
+
+    if (colorMap->getNumPixelComps() == 3)
+      writePS(" ColorSpace=\"DeviceRGB\"");
+    else 
+      writePS(" ColorSpace=\"DeviceCMYK\"");
+    writePS(" BitsPerComponent=\"8\"");
+    writePS(" Filter=\"DCTDecode\"");
+    writePSFmt(" length=\"%d\"", buffer.size());
+    writePS(">\n");
+    
+    for (unsigned int i = 0; i < buffer.size(); ++i)
+      writePSFmt("%02x", buffer[i] & 0xff);
+
+#if 0
+  } else if (colorMap->getNumPixelComps() == 1 && colorMap->getBits() == 1) {
+    // 1 bit depth -- not implemented in Ipe
+
+    // initialize stream
+    str->reset();
+    // copy the stream
+    size = height * ((width + 7) / 8);
+    for (i = 0; i < size; ++i) {
+      writePSFmt("%02x", (str->getChar() ^ 0xff));
+    }
+    str->close();
+#endif
+  } else if (colorMap->getNumPixelComps() == 1) {
+    // write as gray level image
+    writePS(" ColorSpace=\"DeviceGray\"");
+    writePS(" BitsPerComponent=\"8\"");
+    writePS(">\n");
+    
+    // initialize stream
+    imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
+			     colorMap->getBits());
+    imgStr->reset();
+    
+    // for each line...
+    for (y = 0; y < height; ++y) {
+      
+      // write the line
+      p = imgStr->getLine();
+      for (x = 0; x < width; ++x) {
+	GfxGray gray;
+	colorMap->getGray(p, &gray);
+	writePSFmt("%02x", colToByte(gray));
+	p += colorMap->getNumPixelComps();
+      }
+    }
+    delete imgStr;
+
+  } else {
+    // write as RGB image
+    writePS(" ColorSpace=\"DeviceRGB\"");
+    writePS(" BitsPerComponent=\"8\"");
+    writePS(">\n");
+    
+    // initialize stream
+    imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
+			     colorMap->getBits());
+    imgStr->reset();
+    
+    // for each line...
+    for (y = 0; y < height; ++y) {
+      
+      // write the line
+      p = imgStr->getLine();
+      for (x = 0; x < width; ++x) {
+	colorMap->getRGB(p, &rgb);
+	writePSFmt("%02x%02x%02x", 
+		   colToByte(rgb.r), colToByte(rgb.g), colToByte(rgb.b));
+	p += colorMap->getNumPixelComps();
+      }
+    }
+    delete imgStr;
+  }
+  writePS("\n</image>\n");
+}
+
+// --------------------------------------------------------------------
+
+struct UnicodeToLatex {
+  int iUnicode;
+  const char *iLatex;
+};
+
+static const UnicodeToLatex unicode2latex[] = {
+  // { 0xed, "{\\'\\i}" },
+  // --------------------------------------------------------------------
+  { 0xb1,  "$\\pm$" },
+  { 0x391, "$\\Alpha$" },
+  { 0x392, "$\\Beta$" },
+  { 0x393, "$\\Gamma$" },
+  { 0x394, "$\\Delta$" },
+  { 0x395, "$\\Epsilon$" },
+  { 0x396, "$\\Zeta$" },
+  { 0x397, "$\\Eta$" },
+  { 0x398, "$\\Theta$" },
+  { 0x399, "$\\Iota$" },
+  { 0x39a, "$\\Kappa$" },
+  { 0x39b, "$\\Lambda$" },
+  { 0x39c, "$\\Mu$" },
+  { 0x39e, "$\\Nu$" },
+  { 0x39e, "$\\Xi$" },
+  { 0x39f, "$\\Omicron$" },
+  { 0x3a0, "$\\Pi$" },
+  { 0x3a1, "$\\Rho$" },
+  { 0x3a3, "$\\Sigma$" },   // sometimes \\sum would be better
+  { 0x3a4, "$\\Tau$" },
+  { 0x3a5, "$\\Upsilon$" },
+  { 0x3a6, "$\\Phi$" },
+  { 0x3a7, "$\\Chi$" },
+  { 0x3a8, "$\\Psi$" },
+  { 0x3a9, "$\\Omega$" },
+  // --------------------------------------------------------------------
+  { 0x3b1, "$\\alpha$" },
+  { 0x3b2, "$\\beta$" },
+  { 0x3b3, "$\\gamma$" },
+  { 0x3b4, "$\\delta$" },
+  { 0x3b5, "$\\varepsilon$" },
+  { 0x3b6, "$\\zeta$" },
+  { 0x3b7, "$\\eta$" },
+  { 0x3b8, "$\\theta$" },
+  { 0x3b9, "$\\iota$" },
+  { 0x3ba, "$\\kappa$" },
+  { 0x3bb, "$\\lambda$" },
+  { 0x3bc, "$\\mu$" },
+  { 0x3be, "$\\nu$" },
+  { 0x3be, "$\\xi$" },
+  { 0x3bf, "$\\omicron$" },
+  { 0x3c0, "$\\pi$" },
+  { 0x3c1, "$\\rho$" },
+  { 0x3c3, "$\\sigma$" },
+  { 0x3c4, "$\\tau$" },
+  { 0x3c5, "$\\upsilon$" },
+  { 0x3c6, "$\\phi$" },
+  { 0x3c7, "$\\chi$" },
+  { 0x3c8, "$\\psi$" },
+  { 0x3c9, "$\\omega$" },
+  // --------------------------------------------------------------------
+  { 0x2013, "-" },
+  { 0x2019, "'" },
+  { 0x2022, "$\\bullet$" },
+  { 0x2026, "$\\cdots$" },
+  { 0x2190, "$\\leftarrow$" },
+  { 0x21d2, "$\\Rightarrow$" },
+  { 0x2208, "$\\in$" },
+  { 0x2209, "$\\not\\in$" },
+  { 0x2211, "$\\sum$" },
+  { 0x2212, "-" },
+  { 0x221e, "$\\infty$" },
+  { 0x222a, "$\\cup$" },
+  { 0x2260, "$\\neq$" },
+  { 0x2264, "$\\leq$" },
+  { 0x2265, "$\\geq$" },
+  { 0x22c5, "$\\cdot$" },
+  { 0x2286, "$\\subseteq$" },
+  { 0x25aa, "$\\diamondsuit$" },
+  // --------------------------------------------------------------------
+  // ligatures
+  { 0xfb00, "ff" },
+  { 0xfb01, "fi" },
+  { 0xfb02, "fl" },
+  { 0xfb03, "ffi" },
+  { 0xfb04, "ffl" },
+  { 0xfb06, "st" },
+  // --------------------------------------------------------------------
+};
+
+#define UNICODE2LATEX_LEN (sizeof(unicode2latex) / sizeof(UnicodeToLatex))
+    
+void XmlOutputDev::writePSUnicode(int ch)
+{
+  if (iIsLiteral  &&  ch == '\\') {
+    writePSChar(ch);
+    return;
+  }
+
+  if (!iIsLiteral) {
+    if (ch == '&' || ch == '$' || ch == '#' || ch == '%'
+	|| ch == '_' || ch == '{' || ch == '}') {
+      writePS("\\");
+      writePSChar(ch);
+      return;
+    }
+    if (ch == '<') {
+      writePS("$<$");
+      return;
+    }
+    if (ch == '>') {
+      writePS("$>$");
+      return;
+    }
+    if (ch == '^') {
+      writePS("\\^{}");
+      return;
+    }
+    if (ch == '~') {
+      writePS("\\~{}");
+      return;
+    }
+    if (ch == '\\') {
+      writePS("$\\setminus$");
+      return;
+    }
+  }
+
+  // replace some common Unicode characters
+  if (1 <= iUnicodeLevel && iUnicodeLevel <= 2) {
+    for (int i = 0; i < UNICODE2LATEX_LEN; ++i) {
+      if (ch == unicode2latex[i].iUnicode) {
+	writePS(unicode2latex[i].iLatex);
+	return;
+      }
+    }
+  }
+  
+  writePSChar(ch);
+}
+
+void XmlOutputDev::writePSChar(int code)
+{
+  if (code == '<')
+    writePS("<");
+  else if (code == '>')
+    writePS(">");
+  else if (code == '&')
+    writePS("&");
+  else if (code < 0x80)
+    writePSFmt("%c", code);
+  else {
+    iUnicode = true;
+    if (iUnicodeLevel < 2) {
+      writePSFmt("[U+%x]", code);
+      fprintf(stderr, "Unknown Unicode character U+%x on page %d\n", 
+	      code, seqPage);
+    } else {
+      if (code < 0x800) {
+	writePSFmt("%c%c", 
+		   (((code & 0x7c0) >> 6) | 0xc0),
+		   ((code & 0x03f) | 0x80)); 
+      } else {
+	// Do we never need to write UCS larger than 0x10000?
+	writePSFmt("%c%c%c", 
+		   (((code & 0x0f000) >> 12) | 0xe0),
+		   (((code & 0xfc0) >> 6) | 0x80),
+		   ((code & 0x03f) | 0x80));
+      }
+    }
+  }
+}
+
+void XmlOutputDev::writeColor(const char *prefix, const GfxRGB &rgb, 
+			      const char *suffix)
+{
+  if (prefix)
+    writePS(prefix);
+  writePSFmt("\"%g %g %g\"", colToDbl(rgb.r), colToDbl(rgb.g), colToDbl(rgb.b));
+  if (suffix)
+    writePS(suffix);
+}
+
+void XmlOutputDev::writePS(const char *s)
+{
+  fwrite(s, 1, strlen(s), outputStream);
+}
+
+void XmlOutputDev::writePSFmt(const char *fmt, ...)
+{
+  va_list args;
+  char buf[512];
+
+  va_start(args, fmt);
+  vsprintf(buf, fmt, args);
+  va_end(args);
+  fwrite(buf, 1, strlen(buf), outputStream);
+}
+
+// --------------------------------------------------------------------
diff --git a/pdftoipe/xmloutputdev.h b/pdftoipe/xmloutputdev.h
new file mode 100644
index 0000000..225297b
--- /dev/null
+++ b/pdftoipe/xmloutputdev.h
@@ -0,0 +1,108 @@
+// -*- C++ -*-
+// --------------------------------------------------------------------
+// XmlOutputDev.h
+// --------------------------------------------------------------------
+
+#ifndef XMLOUTPUTDEV_H
+#define XMLOUTPUTDEV_H
+
+#include <stddef.h>
+#include "Object.h"
+#include "OutputDev.h"
+#include "GfxState.h"
+
+class GfxPath;
+class GfxFont;
+
+#define PDFTOIPE_VERSION "2014/03/03"
+
+class XmlOutputDev : public OutputDev
+{
+public:
+
+  // Open an XML output file, and write the prolog.
+  XmlOutputDev(char *fileName, XRef *xrefA, Catalog *catalog,
+	       int firstPage, int lastPage);
+  
+  // Destructor -- writes the trailer and closes the file.
+  virtual ~XmlOutputDev();
+
+  // Check if file was successfully created.
+  virtual GBool isOk() { return ok; }
+
+  bool hasUnicode() const { return iUnicode; }
+
+  void setTextHandling(GBool math, GBool notext, GBool literal,
+		       int mergeLevel, int unicodeLevel);
+  
+  //---- get info about output device
+
+  // Does this device use upside-down coordinates?
+  // (Upside-down means (0,0) is the top left corner of the page.)
+  virtual GBool upsideDown() { return gFalse; }
+
+  // Does this device use drawChar() or drawString()?
+  virtual GBool useDrawChar() { return gTrue; }
+
+  // Does this device use beginType3Char/endType3Char?  Otherwise,
+  // text in Type 3 fonts will be drawn with drawChar/drawString.
+  virtual GBool interpretType3Chars() { return gFalse; }
+
+  //----- initialization and control
+
+  // Start a page.
+  virtual void startPage(int pageNum, GfxState *state); // poppler <=0.22
+  virtual void startPage(int pageNum, GfxState *state, XRef *xrefA);
+
+  // End a page.
+  virtual void endPage();
+
+  //----- update graphics state
+  virtual void updateTextPos(GfxState *state);
+  virtual void updateTextShift(GfxState *state, double shift);
+
+  //----- path painting
+  virtual void stroke(GfxState *state);
+  virtual void fill(GfxState *state);
+  virtual void eoFill(GfxState *state);
+
+  //----- text drawing
+  virtual void drawChar(GfxState *state, double x, double y,
+			double dx, double dy,
+			double originX, double originY,
+			CharCode code, int nBytes, Unicode *u, int uLen);
+
+  //----- image drawing
+  virtual void drawImage(GfxState *state, Object *ref, Stream *str,
+			 int width, int height, GfxImageColorMap *colorMap,
+			 GBool interpolate, int *maskColors, GBool inlineImg);
+
+protected:
+  virtual void startDrawingPath();
+  virtual void startText(GfxState *state, double x, double y);
+  virtual void finishText();
+  virtual void writePSUnicode(int ch);
+  
+  void doPath(GfxState *state);
+  void writePSChar(int code);
+  void writePS(const char *s);
+  void writePSFmt(const char *fmt, ...);
+  void writeColor(const char *prefix, const GfxRGB &rgb, const char *suffix);
+
+protected:
+  FILE *outputStream;
+  int seqPage;			// current sequential page number
+  XRef *xref;			// the xref table for this PDF file
+  GBool ok;			// set up ok?
+  bool iUnicode;                // has a Unicode character been used?
+
+  bool iIsLiteral;              // take latex in text literally
+  bool iIsMath;                 // make text objects math formulas
+  bool iNoText;                 // discard text objects
+  bool inText;                  // inside a text object
+  int  iMergeLevel;             // text merge level
+  int iUnicodeLevel;            // unicode handling
+};
+
+// --------------------------------------------------------------------
+#endif
diff --git a/svgtoipe/readme.txt b/svgtoipe/readme.txt
new file mode 100644
index 0000000..3a385f7
--- /dev/null
+++ b/svgtoipe/readme.txt
@@ -0,0 +1,76 @@
+
+Svgtoipe
+========
+
+This is Svgtoipe, a Python script that reads SVG figures and generates
+an XML file readable by Ipe.
+
+You'll need Python installed on your system.  To process embedded
+images in SVG figures will also require the Python Image Library
+(PIL).  (On Ubuntu/Debian, install python-image).
+
+For installation, just copy "svgtoipe" to a suitable location on your
+system.
+
+You can report bugs on the issue tracking system at
+"https://github.com/otfried/ipe-tools/issues".
+
+Before reporting a bug, check that you have the latest version of
+Svgtoipe, and check the existing reports to see whether your bug has
+already been reported.  Please do not send bug reports directly to me
+(the first thing I would do with the report is to enter it into the
+bug tracking system).
+
+Suggestions for features, or random comments on Svgtoipe can be sent
+to the Ipe discussion mailing list at <ipe-discuss at cs.uu.nl>.  If you
+have problems installing or using Svgtoipe, the Ipe discussion mailing
+list would also be the best place to ask.
+
+You can send suggestions or comments directly to me by Email, but you
+should then not expect a reply.  I cannot dedicate much time to Ipe,
+and the little time I have I prefer to put into development.  I'm much
+more likely to get involved in a discussion of desirable features on
+the mailing list, where anyone interested can participate than by
+direct Email.
+
+	Otfried Cheong
+	Dept. of Computer Science
+	KAIST
+	Daejeon, South Korea
+	Email: otfried at ipe.airpost.net
+	Ipe webpage: http://ipe7.sourceforge.net
+
+--------------------------------------------------------------------
+
+Copyright (C) 2009-2014 Otfried Cheong
+
+svgtoipe is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by the
+Free Software Foundation; either version 3 of the License, or (at your
+option) any later version.
+
+svgtoipe is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with svgtoipe; if not, you can find it at
+"http://www.gnu.org/copyleft/gpl.html", or write to the Free Software
+Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+--------------------------------------------------------------------
+
+Changes
+=======
+
+ * 2013/11/07
+   Bugs in path parsing and Latex generation fixed by Will Evans.
+
+ * 2010/06/08
+   Added copyright notice and GPL license to svgtoipe distribution.
+
+ * 2009/10/18
+   First version of svgtoipe.
+
+--------------------------------------------------------------------
diff --git a/svgtoipe/svgtoipe.1 b/svgtoipe/svgtoipe.1
new file mode 100644
index 0000000..c93569a
--- /dev/null
+++ b/svgtoipe/svgtoipe.1
@@ -0,0 +1,23 @@
+.TH SVGTOIPE "1" "April 2015" "Ipe" "User Commands"
+
+.SH NAME
+svgtoipe \- Convert a SVG file to Ipe 7 format
+
+.SH SYNOPSIS
+.B svgtoipe
+\fIfigure.svg [ figure.svg ]\fR
+
+.SH DESCRIPTION
+\fBsvgtoipe\fR converts a SVG file to an XML file understood by Ipe
+version 7. If the output filename is not specified, it will be derived
+either by replacing \fI.ipe\fR at the end of the input filename with
+\fI.svg\fR, or by appending \fI.ipe\fR if the input filename does not
+end with with \fI.svg\fR.
+
+Images are converted if python-imaging is available.
+
+.SH AUTHOR
+Otfried Cheong
+
+.SH "SEE ALSO"
+\fBipe\fR(1)
diff --git a/svgtoipe/svgtoipe.py b/svgtoipe/svgtoipe.py
new file mode 100644
index 0000000..45f3e98
--- /dev/null
+++ b/svgtoipe/svgtoipe.py
@@ -0,0 +1,865 @@
+#!/usr/bin/env python
+# --------------------------------------------------------------------
+# convert SVG to Ipe format
+# --------------------------------------------------------------------
+# 
+# Copyright (C) 2009-2014  Otfried Cheong
+#
+# svgtoipe is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+# 
+# svgtoipe is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+# 
+# You should have received a copy of the GNU General Public License
+# along with svgtoipe; if not, you can find it at
+# "http://www.gnu.org/copyleft/gpl.html", or write to the Free
+# Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+#
+# --------------------------------------------------------------------
+
+svgtoipe_version = "20091018"
+
+import sys
+import xml.dom.minidom as xml
+from xml.dom.minidom import Node
+import re
+import math
+
+import base64
+import cStringIO
+
+try:
+  from PIL import Image
+  have_pil = True
+except:
+  have_pil = False
+
+# --------------------------------------------------------------------
+
+color_keywords = {
+  "black" : "rgb(0, 0, 0)",
+  "green" :"rgb(0, 128, 0)",
+  "silver" :"rgb(192, 192, 192)",
+  "lime" :"rgb(0, 255, 0)",
+  "gray" :"rgb(128, 128, 128)",
+  "olive" :"rgb(128, 128, 0)",
+  "white" :"rgb(255, 255, 255)",
+  "yellow" :"rgb(255, 255, 0)",
+  "maroon" :"rgb(128, 0, 0)",
+  "navy" :"rgb(0, 0, 128)",
+  "red" :"rgb(255, 0, 0)",
+  "blue" :"rgb(0, 0, 255)",
+  "purple" :"rgb(128, 0, 128)",
+  "teal" :"rgb(0, 128, 128)",
+  "fuchsia" :"rgb(255, 0, 255)",
+  "aqua" :"rgb(0, 255, 255)",
+}
+
+attribute_names = [ "stroke", 
+                    "fill",
+                    "stroke-opacity",
+                    "fill-opacity",
+                    "stroke-width",
+                    "fill-rule",
+                    "stroke-linecap",
+                    "stroke-linejoin",
+                    "stroke-dasharray",
+                    "stroke-dashoffset",
+                    "stroke-miterlimit",
+                    "opacity", 
+                    "font-size" ]
+  
+def printAttributes(n):
+  a = n.attributes
+  for i in range(a.length):
+    name = a.item(i).name
+    if name[:9] != "sodipodi:" and name[:9] != "inkscape:":
+      print "   ", name, n.getAttribute(name)
+
+def parse_float(txt):
+  if not txt:
+    return None
+  if txt.endswith('px') or txt.endswith('pt'):
+    return float(txt[:-2])
+  elif txt.endswith('pc'):
+    return 12 * float(txt[:-2])
+  elif txt.endswith('mm'):
+    return 72.0 * float(txt[:-2]) / 25.4
+  elif txt.endswith('cm'):
+    return 72.0 * float(txt[:-2]) / 2.54
+  elif txt.endswith('in'):
+    return 72.0 * float(txt[:-2])
+  else:
+    return float(txt)
+
+def parse_opacity(txt):
+  if not txt: 
+    return None
+  m = int(10 * (float(txt) + 0.05))
+  if m == 0: m = 1
+  return 10 * m
+
+def parse_list(string):
+  return re.findall("([A-Za-z]|-?[0-9]+\.?[0-9]*(?:e-?[0-9]*)?)", string)
+
+def parse_style(string):
+  sdict = {}
+  for item in string.split(';'):
+    if ':' in item:
+      key, value = item.split(':')
+      sdict[key.strip()] = value.strip()
+  return sdict
+
+def parse_color_component(txt):
+  if txt.endswith("%"):
+    return float(txt[:-1]) / 100.0
+  else:
+    return int(txt) / 255.0
+  
+def parse_color(c):
+  if not c or c == 'none':
+    return None
+  if c in color_keywords:
+    c = color_keywords[c]
+  m =  re.match(r"rgb\(([0-9\.]+%?),\s*([0-9\.]+%?),\s*([0-9\.]+%?)\s*\)", c)
+  if m:
+    r = parse_color_component(m.group(1))
+    g = parse_color_component(m.group(2))
+    b = parse_color_component(m.group(3))
+    return (r, g, b)
+  m = re.match(r"#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])$", c)
+  if m:
+    r = int(m.group(1), 16) / 15.0
+    g = int(m.group(2), 16) / 15.0
+    b = int(m.group(3), 16) / 15.0
+    return (r, g, b)
+  m = re.match(r"#([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])"
+               + r"([0-9a-fA-F][0-9a-fA-F])$", c)
+  if m:
+    r = int(m.group(1), 16) / 255.0
+    g = int(m.group(2), 16) / 255.0
+    b = int(m.group(3), 16) / 255.0
+    return (r, g, b)
+  sys.stderr.write("Unknown color: %s\n" % c)
+  return None
+
+def pnext(d, n):
+  l = []
+  while n > 0:
+    l.append(float(d.pop(0)))
+    n -= 1
+  return tuple(l)
+
+def parse_path(out, d):
+  d = re.findall("([A-Za-z]|-?[0-9]+\.?[0-9]*(?:e-?[0-9]*)?)", d)
+  x, y = 0.0, 0.0
+  xs, ys = 0.0, 0.0
+  while d:
+    if not d[0][0] in "01234567890.-":
+      opcode = d.pop(0)
+    if opcode == 'M':
+      x, y = pnext(d, 2)
+      out.write("%g %g m\n" % (x, y))
+      opcode = 'L'
+    elif opcode == 'm':
+      x1, y1 = pnext(d, 2)
+      x += x1
+      y += y1
+      out.write("%g %g m\n" % (x, y))
+      opcode = 'l'
+    elif opcode == 'L':
+      x, y = pnext(d, 2)
+      out.write("%g %g l\n" % (x, y))
+    elif opcode == 'l':
+      x1, y1 = pnext(d, 2)
+      x += x1
+      y += y1
+      out.write("%g %g l\n" % (x, y))
+    elif opcode == 'H':
+      x = pnext(d, 1)[0]
+      out.write("%g %g l\n" % (x, y))
+    elif opcode == 'h':
+      x += pnext(d, 1)[0]
+      out.write("%g %g l\n" % (x, y))
+    elif opcode == 'V':
+      y = pnext(d, 1)[0]
+      out.write("%g %g l\n" % (x, y))
+    elif opcode == 'v':
+      y += pnext(d, 1)[0]
+      out.write("%g %g l\n" % (x, y))
+    elif opcode == 'C':
+      x1, y1, xs, ys, x, y = pnext(d, 6)
+      out.write("%g %g %g %g %g %g c\n" % (x1, y1, xs, ys, x, y))
+    elif opcode == 'c':
+      x1, y1, xs, ys, xf, yf = pnext(d, 6)
+      x1 += x; y1 += y
+      xs += x; ys += y
+      x += xf; y += yf
+      out.write("%g %g %g %g %g %g c\n" % (x1, y1, xs, ys, x, y))
+    elif opcode == 'S' or opcode == 's':
+      x2, y2, xf, yf = pnext(d, 4)
+      if opcode == 's':
+        x2 += x; y2 += y
+        xf += x; yf += y
+      x1 = x + (x - xs); y1 = y + (y - ys)
+      out.write("%g %g %g %g %g %g c\n" % (x1, y1, x2, y2, xf, yf))
+      xs, ys = x2, y2
+      x, y = xf, yf
+    elif opcode == 'Q':
+      xs, ys, x, y = pnext(d, 4)
+      out.write("%g %g %g %g q\n" % (xs, ys, x, y))
+    elif opcode == 'q':
+      xs, ys, xf, yf = pnext(d, 4)
+      xs += x; ys += y
+      x += xf; y += yf
+      out.write("%g %g %g %g q\n" % (xs, ys, x, y))
+    elif opcode == 'T' or opcode == 't':
+      xf, yf = pnext(d, 2)
+      if opcode == 't':
+        xf += x; yf += y
+      x1 = x + (x - xs); y1 = y + (y - ys)
+      out.write("%g %g %g %g q\n" % (x1, y1, xf, yf))
+      xs, ys = x1, y1
+      x, y = xf, yf
+    elif opcode == 'A' or opcode == 'a':
+      rx, ry, phi, large_arc, sweep, x2, y2 = pnext(d, 7)
+      if opcode == 'a':
+        x2 += x; y2 += y
+      draw_arc(out, x, y, rx, ry, phi, large_arc, sweep, x2, y2)
+      x, y = x2, y2
+    elif opcode in 'zZ':
+      out.write("h\n")
+    else:
+      sys.stderr.write("Unrecognised opcode: %s\n" % opcode)
+
+def parse_transformation(txt):
+  d = re.findall("[a-zA-Z]+\([^)]*\)", txt)
+  m = Matrix()
+  while d:
+    m1 = Matrix(d.pop(0))
+    m = m * m1
+  return m
+
+def get_gradientTransform(n):
+  if n.hasAttribute("gradientTransform"):
+    return parse_transformation(n.getAttribute("gradientTransform"))
+  return Matrix()
+
+def parse_transform(n):
+  if n.hasAttribute("transform"):
+    return parse_transformation(n.getAttribute("transform"))
+  return None
+
+# Convert from endpoint to center parameterization
+# www.w3.org/TR/2003/REC-SVG11-20030114/implnote.html#ArcImplementationNotes
+def draw_arc(out, x1, y1, rx, ry, phi, large_arc, sweep, x2, y2):
+  phi = math.pi * phi / 180.0
+  cp = math.cos(phi); sp = math.sin(phi)
+  dx = .5 * (x1 - x2); dy = .5 * (y1 - y2)
+  x1p = cp * dx + sp * dy; y1p = -sp * dx + cp * dy
+  r2 = (((rx * ry)**2 - (rx * y1p)**2 - (ry * x1p)**2)/
+        ((rx * y1p)**2 + (ry * x1p)**2))
+  if r2 < 0: r2 = 0
+  r = math.sqrt(r2)
+  if large_arc == sweep:
+    r = -r
+  cxp = r * rx * y1p / ry; cyp = -r * ry * x1p / rx
+  cx = cp * cxp - sp * cyp + .5 * (x1 + x2)
+  cy = sp * cxp + cp * cyp + .5 * (y1 + y2)
+  m = Matrix([rx, 0, 0, ry, 0, 0])
+  m = Matrix([cp, sp, -sp, cp, cx, cy]) * m
+  if sweep == 0:
+    m = m * Matrix([1, 0, 0, -1, 0, 0])
+  out.write("%s %g %g a\n" % (str(m), x2, y2))
+
+# --------------------------------------------------------------------
+
+class Matrix(object):
+
+  # Default is identity matrix
+  def __init__(self, string = None):
+    self.values = [1, 0, 0, 1, 0, 0] 
+    if not string or string == "":
+      return
+    if isinstance(string, list):
+      self.values = string
+      return
+    mat = re.match(r"([a-zA-Z]+)\(([^)]*)\)$", string)
+    if not mat:
+      sys.stderr.write("Unknown transform: %s\n" % string)
+    op = mat.group(1)
+    d = [float(x) for x in parse_list(mat.group(2))]
+    if op == "matrix":
+      self.values = d
+    elif op == "translate":
+      if len(d) == 1: d.append(0.0)
+      self.values = [1, 0, 0, 1, d[0], d[1]]
+    elif op == "scale":
+      if len(d) == 1: d.append(d[0])
+      sx, sy = d
+      self.values = [sx, 0, 0, sy, 0, 0]
+    elif op == "rotate":
+      phi = math.pi * d[0] / 180.0
+      self.values = [math.cos(phi), math.sin(phi), 
+                     -math.sin(phi), math.cos(phi), 0, 0]           
+    elif op == "skewX":
+      tphi = math.tan(math.pi * d[0] / 180.0)
+      self.values = [1, 0, tphi, 1, 0, 0]
+    elif op == "skewY":
+      tphi = math.tan(math.pi * d[0] / 180.0)
+      self.values = [1, tphi, 0, 1, 0, 0]
+    else:
+      sys.stderr.write("Unknown transform: %s\n" % string)
+      
+  def __call__(self, other):
+    return (self.values[0]*other[0] + self.values[2]*other[1] + self.values[4],
+            self.values[1]*other[0] + self.values[3]*other[1] + self.values[5])
+  
+  def inverse(self):
+    d = float(self.values[0]*self.values[3] - self.values[1]*self.values[2])
+    return Matrix([self.values[3]/d, -self.values[1]/d, 
+                   -self.values[2]/d, self.values[0]/d,
+                   (self.values[2]*self.values[5] - 
+                    self.values[3]*self.values[4])/d,
+                   (self.values[1]*self.values[4] - 
+                    self.values[0]*self.values[5])/d])
+
+  def __mul__(self, other):
+    a, b, c, d, e, f = self.values
+    u, v, w, x, y, z = other.values
+    return Matrix([a*u + c*v, b*u + d*v, a*w + c*x, 
+                   b*w + d*x, a*y + c*z + e, b*y + d*z + f])
+  
+  def __str__(self):
+    a, b, c, d, e, f = self.values
+    return "%g %g %g %g %g %g" % (a, b, c, d, e, f)
+    
+# --------------------------------------------------------------------
+                               
+class Svg():
+
+  def __init__(self, fname):
+    self.dom = xml.parse(fname)
+    attr = { }
+    for a in attribute_names:
+      attr[a] = None
+    self.attributes = [ attr ]
+    self.defs = { }
+    for n in self.dom.childNodes:
+      if n.nodeType == Node.ELEMENT_NODE and n.tagName == "svg":
+        if n.hasAttribute("viewBox"):
+          x, y, w, h = [float(x) for x in parse_list(n.getAttribute("viewBox"))]
+          self.width = w
+          self.height = h
+          self.origin = (x, y)
+        else:
+          self.width = parse_float(n.getAttribute("width"))
+          self.height = parse_float(n.getAttribute("height"))
+          self.origin = (0, 0)
+        self.root = n
+        return
+
+# --------------------------------------------------------------------
+
+  def parse_svg(self, outname):
+    self.out = open(outname, "w")
+    self.out.write('<?xml version="1.0"?>\n')
+    self.out.write('<!DOCTYPE ipe SYSTEM "ipe.dtd">\n')
+    self.out.write('<ipe version="70005" creator="svgtoipe %s">\n' %
+                   svgtoipe_version)
+    self.out.write('<ipestyle>\n')
+    self.out.write(('<layout paper="%d %d" frame="%d %d" ' + 
+                    'origin="0 0" crop="no"/>\n') % 
+                   (self.width, self.height, self.width, self.height))
+    for t in range(10, 100, 10):
+      self.out.write('<opacity name="%d%%" value="0.%d"/>\n' % (t, t))
+    # set SVG defaults
+    self.out.write('<pathstyle cap="0" join="0" fillrule="wind"/>\n')
+    self.out.write('</ipestyle>\n')
+    # collect definitions
+    for n in self.root.childNodes:
+      if n.nodeType != Node.ELEMENT_NODE:
+        continue
+      if hasattr(self, "def_" + n.tagName):
+        getattr(self, "def_" + n.tagName)(n)
+    # write definitions into stylesheet
+    if len(self.defs) > 0:
+      self.out.write('<ipestyle>\n')
+      for k in self.defs:
+        if self.defs[k][0] == "linearGradient":
+          self.write_linear_gradient(k)
+        elif self.defs[k][0] == "radialGradient":
+          self.write_radial_gradient(k)
+      self.out.write('</ipestyle>\n')
+    # start real data
+    self.out.write('<page>\n')
+    m = Matrix([1, 0, 0, 1, 0, self.height / 2.0])
+    m = m * Matrix([1, 0, 0, -1, 0, 0])
+    m = m * Matrix([1, 0, 0, 1, 
+                    -self.origin[0], -(self.origin[1] + self.height / 2.0)])
+    self.out.write('<group matrix="%s">\n' % str(m))
+    for n in self.root.childNodes:
+      if n.nodeType != Node.ELEMENT_NODE:
+        continue
+      if hasattr(self, "node_" + n.tagName):
+        getattr(self, "node_" + n.tagName)(n)
+      else:
+        sys.stderr.write("Unhandled node: %s\n" % n.tagName)
+    self.out.write('</group>\n')
+    self.out.write('</page>\n')
+    self.out.write('</ipe>\n')
+    self.out.close()
+
+# --------------------------------------------------------------------
+
+  def write_linear_gradient(self, k):
+    typ, x1, x2, y1, y2, stops, matrix = self.defs[k]
+    self.out.write('<gradient name="g%s" type="axial" extend="yes"\n' % k)
+    self.out.write(' matrix="%s"' % str(matrix))
+    self.out.write(' coords="%g %g %g %g">\n' % (x1, y1, x2, y2))
+    for s in stops:
+      offset, color = s
+      self.out.write(' <stop offset="%g" color="%g %g %g"/>\n' % 
+                     (offset, color[0], color[1], color[2]))
+    self.out.write('</gradient>\n')
+    
+  def write_radial_gradient(self, k):
+    typ, cx, cy, r, fx, fy, stops, matrix = self.defs[k]
+    self.out.write('<gradient name="g%s" type="radial" extend="yes"\n' % k)
+    self.out.write(' matrix="%s"' % str(matrix))
+    self.out.write(' coords="%g %g %g %g %g %g">\n' % (fx, fy, 0, cx, cy, r))
+    for s in stops:
+      offset, color = s
+      self.out.write(' <stop offset="%g" color="%g %g %g"/>\n' % 
+                     (offset, color[0], color[1], color[2]))
+    self.out.write('</gradient>\n')
+
+  def get_stops(self, n):
+    stops = []
+    for m in n.childNodes:
+      if m.nodeType != Node.ELEMENT_NODE:
+        continue
+      if m.tagName != "stop":
+        continue # should not happen
+      offs = m.getAttribute("offset")
+      if offs.endswith("%"):
+        offs = float(offs[:-1]) / 100.0
+      else:
+        offs = float(offs)
+      color = parse_color(m.getAttribute("stop-color"))
+      if m.hasAttribute("style"):
+        sdict = parse_style(m.getAttribute("style"))
+        if "stop-color" in sdict:
+          color = parse_color(sdict["stop-color"])
+      stops.append((offs, color))
+    if len(stops) == 0:
+      if n.hasAttribute("xlink:href"):
+        ref = n.getAttribute("xlink:href")
+        if ref.startswith("#") and ref[1:] in self.defs:
+          stops = self.defs[ref[1:]][5]
+    return stops
+
+  def def_linearGradient(self, n):
+    #printAttributes(n)
+    kid = n.getAttribute("id")
+    x1 = 0; y1 = 0
+    x2 = self.width; y2 = self.height
+    if n.hasAttribute("x1"):
+      s = n.getAttribute("x1")
+      if s.endswith("%"):
+        x1 = self.width * float(s[:-1]) / 100.0
+      else:
+        x1 = parse_float(s)
+    if n.hasAttribute("x2"):
+      s = n.getAttribute("x2")
+      if s.endswith("%"):
+        x2 = self.width * float(s[:-1]) / 100.0
+      else:
+        x2 = parse_float(s)
+    if n.hasAttribute("y1"):
+      s = n.getAttribute("y1")
+      if s.endswith("%"):
+        y1 = self.width * float(s[:-1]) / 100.0
+      else:
+        y1 = parse_float(s)
+    if n.hasAttribute("y2"):
+      s = n.getAttribute("y2")
+      if s.endswith("%"):
+        y2 = self.width * float(s[:-1]) / 100.0
+      else:
+        y2 = parse_float(s)
+    matrix = get_gradientTransform(n)
+    stops = self.get_stops(n)
+    self.defs[kid] = ("linearGradient", x1, x2, y1, y2, stops, matrix)
+    
+  def def_radialGradient(self, n):
+    #printAttributes(n)
+    kid = n.getAttribute("id")
+    cx = "50%"; cy = "50%"; r = "50%"
+    if n.hasAttribute("cx"):
+      cx = n.getAttribute("cx")
+    if cx.endswith("%"):
+      cx = self.width * float(cx[:-1]) / 100.0
+    else:
+      cx = parse_float(cx)
+    if n.hasAttribute("cy"):
+      cy = n.getAttribute("cy")
+    if cy.endswith("%"):
+      cy = self.width * float(cy[:-1]) / 100.0
+    else:
+      cy = parse_float(cy)
+    if n.hasAttribute("r"):
+      r = n.getAttribute("r")
+    if r.endswith("%"):
+      r = self.width * float(r[:-1]) / 100.0
+    else:
+      r = parse_float(r)
+    if n.hasAttribute("fx"):
+      s = n.getAttribute("fx")
+      if s.endswith("%"):
+        fx = self.width * float(s[:-1]) / 100.0
+      else:
+        fx = parse_float(s)
+    else:
+      fx = cx
+    if n.hasAttribute("fy"):
+      s = n.getAttribute("fy")
+      if s.endswith("%"):
+        fy = self.width * float(s[:-1]) / 100.0
+      else:
+        fy = parse_float(s)
+    else:
+      fy = cy
+    matrix = get_gradientTransform(n)
+    stops = self.get_stops(n)
+    self.defs[kid] = ("radialGradient", cx, cy, r, fx, fy, stops, matrix)
+
+  def def_clipPath(self, node):
+    kid = node.getAttribute("id")
+    # only a single path is implemented
+    for n in node.childNodes:
+      if n.nodeType != Node.ELEMENT_NODE or n.tagName != "path":
+        continue
+      m = parse_transform(n)
+      d = n.getAttribute("d")
+      output = cStringIO.StringIO()
+      parse_path(output, d)
+      path = output.getvalue()
+      output.close()
+      self.defs[kid] = ("clipPath", m, path)
+      return
+
+  def def_g(self, group):
+    for n in group.childNodes:
+      if n.nodeType != Node.ELEMENT_NODE: 
+        continue
+      if hasattr(self, "def_" + n.tagName):
+        getattr(self, "def_" + n.tagName)(n)
+
+  def def_defs(self, node):
+    self.def_g(node)
+
+# --------------------------------------------------------------------
+
+  def parse_attributes(self, n):
+    pattr = self.attributes[-1]
+    attr = { }
+    for a in attribute_names:
+      if n.hasAttribute(a):
+        attr[a] = n.getAttribute(a)
+      else:
+        attr[a] = pattr[a]
+    if n.hasAttribute("style"):
+      sdict = parse_style(n.getAttribute("style"))
+      for a in attribute_names:
+        if a in sdict:
+          attr[a] = sdict[a]
+    return attr
+
+  def write_pathattributes(self, a):
+    stroke = parse_color(a["stroke"])
+    if stroke:
+      self.out.write(' stroke="%g %g %g"' % stroke)
+    fill = a["fill"]
+    if fill and fill.startswith("url("):
+      mat = re.match("url\(#([^)]+)\).*", fill)
+      if mat:
+        grad = mat.group(1)
+        if grad in self.defs and (self.defs[grad][0] == "linearGradient" or
+                                  self.defs[grad][0] == "radialGradient"):
+          self.out.write(' fill="1" gradient="g%s"' % grad)
+    else:
+      fill = parse_color(a["fill"])
+      if fill:
+        self.out.write(' fill="%g %g %g"' % fill)
+    opacity = parse_opacity(a["opacity"])
+    fill_opacity = parse_opacity(a["fill-opacity"])
+    stroke_opacity = parse_opacity(a["stroke-opacity"])
+    if fill and fill_opacity:
+      opacity = fill_opacity
+    if not fill and stroke and stroke_opacity:
+      opacity = stroke_opacity
+    if opacity and opacity != 100:
+      self.out.write(' opacity="%d%%"' % opacity)
+    stroke_width = parse_float(a["stroke-width"])
+    if a["stroke-width"]:
+      self.out.write(' pen="%g"' % stroke_width)
+    if a["fill-rule"] == "nonzero":
+      self.out.write(' fillrule="wind"')
+    k = {"butt" : 0, "round" : 1, "square" : 2 }
+    if a["stroke-linecap"] in k:
+      self.out.write(' cap="%d"' % k[a["stroke-linecap"]])
+    k = {"miter" : 0, "round" : 1, "bevel" : 2 }
+    if a["stroke-linejoin"] in k:
+      self.out.write(' join="%d"' % k[a["stroke-linejoin"]])
+    dasharray = a["stroke-dasharray"]
+    dashoffset = a["stroke-dashoffset"]
+    if dasharray and dashoffset and dasharray != "none":
+      d = parse_list(dasharray)
+      off = parse_float(dashoffset)
+      self.out.write(' dash="[%s] %g"' % (" ".join(d), off))
+
+# --------------------------------------------------------------------
+
+  def node_g(self, group):
+    # printAttributes(group)
+    attr = self.parse_attributes(group)
+    self.attributes.append(attr)
+    self.out.write('<group')
+    m = parse_transform(group)
+    if m:   
+      self.out.write(' matrix="%s"' % m)
+    self.out.write('>\n')
+    for n in group.childNodes:
+      if n.nodeType != Node.ELEMENT_NODE: 
+        continue
+      if hasattr(self, "node_" + n.tagName):
+        getattr(self, "node_" + n.tagName)(n)
+      else:
+        sys.stderr.write("Unhandled node: %s\n" % n.tagName)
+    self.out.write('</group>\n')
+    self.attributes.pop()
+
+  def collect_text(self, root):
+    for n in root.childNodes:
+      if n.nodeType == Node.TEXT_NODE:
+        self.text += n.data
+      if n.nodeType != Node.ELEMENT_NODE: 
+        continue
+      if n.tagName == "tspan":  # recurse
+        self.collect_text(n)
+        
+  def node_text(self, t):
+    if not t.hasAttribute("x") or not t.hasAttribute("y"):
+      sys.stderr.write("Text without coordinates ignored\n")
+      return
+    x = float(t.getAttribute("x"))
+    y = float(t.getAttribute("y"))
+    attr = self.parse_attributes(t)
+    self.out.write('<text pos="%g %g"' % (x,y))
+    self.out.write(' transformations="affine" valign="baseline"')
+    m = parse_transform(t)
+    if not m: m = Matrix()
+    m = m * Matrix([1, 0, 0, -1, x, y]) * Matrix([1, 0, 0, 1, -x, -y])
+    self.out.write(' matrix="%s"' % m)
+    if attr["font-size"]:
+      self.out.write(' size="%g"' % parse_float(attr["font-size"]))
+    color = parse_color(attr["fill"])
+    if color:
+      self.out.write(' stroke="%g %g %g"' % color)
+    self.text = ""
+    self.collect_text(t)
+    self.out.write('>%s</text>\n' % self.text.encode("UTF-8"))
+    
+  def node_image(self, node):
+    if not have_pil:
+      sys.stderr.write("No Python image library, <image> ignored\n")
+      return
+    href = node.getAttribute("xlink:href")
+    if not href.startswith("data:image/png;base64,"):
+      sys.stderr.write("Image ignored, href = %s...\n" % href[:40])
+      return
+    x = float(node.getAttribute("x"))
+    y = float(node.getAttribute("y"))
+    w = float(node.getAttribute("width"))
+    h = float(node.getAttribute("height"))
+    clipped = False
+    if node.hasAttribute("clip-path"):
+      mat = re.match("url\(#([^)]+)\).*", node.getAttribute("clip-path"))
+      if mat:
+        cp = mat.group(1)
+        if cp in self.defs and self.defs[cp][0] == "clipPath":
+          cp, m, path = self.defs[cp]
+          clipped = True
+          self.out.write('<group matrix="%s" clip="%s">\n' % (str(m), path))
+          self.out.write('<group matrix="%s">\n' % str(m.inverse()))
+    self.out.write('<image rect="%g %g %g %g"' % (x, y, x + w, y + h))
+    data = base64.b64decode(href[22:])
+    fin = cStringIO.StringIO(data)
+    image = Image.open(fin)
+    m = parse_transform(node)
+    if not m:   
+      m = Matrix()
+    m = m * Matrix([1, 0, 0, -1, x, y+h]) * Matrix([1, 0, 0, 1, -x, -y])
+    self.out.write(' matrix="%s"' % m)
+    self.out.write(' width="%d" height="%d" ColorSpace="DeviceRGB"' %
+                   image.size)
+    self.out.write(' BitsPerComponent="8" encoding="base64"> \n')
+    if True:
+      data = cStringIO.StringIO()
+      for pixel in image.getdata():
+        data.write("%c%c%c" % pixel[:3])
+      self.out.write(base64.b64encode(data.getvalue()))
+      data.close()
+    else:
+      count = 0
+      for pixel in image.getdata():
+        self.out.write("%02x%02x%02x" % pixel[:3])
+        count += 1
+        if count == 10:
+          self.out.write("\n")
+          count = 0
+    fin.close()
+    self.out.write('</image>\n')
+    if clipped:
+      self.out.write('</group>\n</group>\n')
+
+  # handled in def pass
+  def node_linearGradient(self, n):
+    pass 
+
+  def node_radialGradient(self, n):
+    pass 
+
+  def node_rect(self, n):
+    attr = self.parse_attributes(n)
+    self.out.write('<path')
+    m = parse_transform(n)
+    if m:   
+      self.out.write(' matrix="%s"' % m)
+    self.write_pathattributes(attr)
+    self.out.write('>\n')
+    x = float(n.getAttribute("x"))
+    y = float(n.getAttribute("y"))
+    w = float(n.getAttribute("width"))
+    h = float(n.getAttribute("height"))
+    self.out.write("%g %g m %g %g l %g %g l %g %g l h\n" %
+                   (x, y, x + w, y, x + w, y + h, x, y + h))
+    self.out.write('</path>\n')
+
+  def node_circle(self, n):
+    self.out.write('<path')
+    m = parse_transform(n)
+    if m:   
+      self.out.write(' matrix="%s"' % m)
+    attr = self.parse_attributes(n)
+    self.write_pathattributes(attr)
+    self.out.write('>\n')
+    cx = float(n.getAttribute("cx"))
+    cy = float(n.getAttribute("cy"))
+    r = float(n.getAttribute("r"))
+    self.out.write("%g 0 0 %g %g %g e\n" % (r, r, cx, cy))
+    self.out.write('</path>\n')
+
+  def node_ellipse(self, n):
+    self.out.write('<path')
+    m = parse_transform(n)
+    if m:   
+      self.out.write(' matrix="%s"' % m)
+    attr = self.parse_attributes(n)
+    self.write_pathattributes(attr)
+    self.out.write('>\n')
+    cx = 0
+    cy = 0
+    if n.hasAttribute("cx"):
+      cx = float(n.getAttribute("cx"))
+    if n.hasAttribute("cy"):
+      cy = float(n.getAttribute("cy"))
+    rx = float(n.getAttribute("rx"))
+    ry = float(n.getAttribute("ry"))
+    self.out.write("%g 0 0 %g %g %g e\n" % (rx, ry, cx, cy))
+    self.out.write('</path>\n')
+
+  def node_line(self, n):
+    self.out.write('<path')
+    m = parse_transform(n)
+    if m:   
+      self.out.write(' matrix="%s"' % m)
+    attr = self.parse_attributes(n)
+    self.write_pathattributes(attr)
+    self.out.write('>\n')
+    x1 = 0; y1 = 0; x2 = 0; y2 = 0
+    if n.hasAttribute("x1"):
+      x1 = float(n.getAttribute("x1"))
+    if n.hasAttribute("y1"):
+      y1 = float(n.getAttribute("y1"))
+    if n.hasAttribute("x2"):
+      x2 = float(n.getAttribute("x2"))
+    if n.hasAttribute("y2"):
+      y2 = float(n.getAttribute("y2"))
+    self.out.write("%g %g m %g %g l\n" % (x1, y1, x2, y2))
+    self.out.write('</path>\n')
+
+  def node_polyline(self, n):
+    self.polygon(n, closed=False)
+    
+  def node_polygon(self, n):
+    self.polygon(n, closed=True)
+
+  def polygon(self, n, closed):
+    self.out.write('<path')
+    m = parse_transform(n)
+    if m:   
+      self.out.write(' matrix="%s"' % m)
+    attr = self.parse_attributes(n)
+    self.write_pathattributes(attr)
+    self.out.write('>\n')
+    d = parse_list(n.getAttribute("points"))
+    op = "m"
+    while d:
+      x = float(d.pop(0))
+      y = float(d.pop(0))
+      self.out.write("%g %g %s\n" % (x, y, op))
+      op = "l"
+    if closed:
+      self.out.write("h\n")
+    self.out.write('</path>\n')
+
+  def node_path(self, n):
+    self.out.write('<path')
+    m = parse_transform(n)
+    if m:   
+      self.out.write(' matrix="%s"' % m)
+    attr = self.parse_attributes(n)
+    self.write_pathattributes(attr)
+    self.out.write('>\n')
+    d = n.getAttribute("d")
+    parse_path(self.out, d)
+    self.out.write('</path>\n')
+
+# --------------------------------------------------------------------
+
+def main():
+  if len(sys.argv) != 2 and len(sys.argv) != 3:
+    sys.stderr.write("Usage: svgtoipe <figure.svg> [ <figure.ipe> ]\n")
+    return
+  fname = sys.argv[1]
+  if len(sys.argv) > 2:
+    outname = sys.argv[2]
+  else:
+    if fname[-4:].lower() == ".svg":
+      outname = fname[:-4] + ".ipe"
+    else:
+      outname = fname + ".ipe"
+  svg = Svg(fname)
+  svg.parse_svg(outname)
+
+if __name__ == '__main__':
+  main()
+
+# --------------------------------------------------------------------

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-science/packages/ipe-tools.git



More information about the debian-science-commits mailing list