[
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\nend_of_line = lf\ninsert_final_newline = false\nindent_style = space\nindent_size = 2\n"
  },
  {
    "path": ".gitignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\n\n# Runtime data\npids\n*.pid\n*.seed\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n\n# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (http://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directory\nnode_modules\n\n# Optional npm cache directory\n.npm\n\n# Optional REPL history\n.node_repl_history\n\n# JetBrains IDEs\n.idea\n\n# Test case output\ntest/output*.svg"
  },
  {
    "path": ".npmignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\n\n# Runtime data\npids\n*.pid\n*.seed\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (http://nodejs.org/api/addons.html)\nbuild/Release\n\n# IDE files\n.project\n.idea\n*.iml\n\n# Test directory\ntest/\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\nnode_js:\n  - \"0.12\"\n  - \"4\"\n  - \"6\"\nsudo: false"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {description}\n    Copyright (C) {year}  {fullname}\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  {signature of Ty Coon}, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n"
  },
  {
    "path": "README.md",
    "content": "# node-potrace\nA NodeJS-compatible fork of [Potrace in JavaScript][potrace-by-kilobtye] with some additions, which is in turn a port of [the original Potrace][potrace] — a tool for tracing bitmaps.\n\n## Example and demo\n\n| **Original image**        | **Potrace output**           | **Posterized output**                   |\n|---------------------------|------------------------------|-----------------------------------------|\n| ![](test/sources/yao.jpg) | ![](https://cdn.rawgit.com/tooolbox/node-potrace/9ee822d/test/example-output.svg) | ![](https://cdn.rawgit.com/tooolbox/node-potrace/9ee822d/test/example-output-posterized.svg) |\n\n(Example image inherited from [online demo of the browser version][potrace-js-demo])\n\n## Usage\n\nInstall\n\n```sh\nnpm install potrace\n```\n\nBasic usage\n\n```js\nvar potrace = require('potrace'),\n    fs = require('fs');\n\npotrace.trace('./path/to/image.png', function(err, svg) {\n  if (err) throw err;\n  fs.writeFileSync('./output.svg', svg);\n});\n```\n\nYou can also provide a configuration object as a second argument.\n\n```js\nvar params = {\n  background: '#49ffd2',\n  color: 'blue',\n  threshold: 120\n};\n\npotrace.trace('./path/to/image.png', params, function(err, svg) {\n  /*...*/\n});\n```\n\nIf you want to run Potrace algorithm multiple times on the same image with different threshold setting and merge results together in a single file - `posterize` method does exactly that.\n\n```js\npotrace.posterize('./path/to/image.png', { threshold: 180, steps: 4 }, function(err, svg) {\n  /*...*/\n});\n\n// or if you know exactly where you want to break it on different levels\n\npotrace.posterize('./path/to/image.png', { steps: [40, 85, 135, 180] }, function(err, svg) {\n  /*...*/\n});\n```\n\n### Advanced usage and configuration\n\nBoth `trace` and `posterize` methods return instances of `Potrace` and `Posterizer` classes respectively to a callback function as third argument. \n\nYou can also instantiate these classes directly:\n\n```js\nvar potrace = require('potrace');\n\n// Tracing\n\nvar trace = new potrace.Potrace();\n\n// You can also pass configuration object to the constructor\ntrace.setParameters({\n  threshold: 128,\n  color: '#880000'\n});\n\ntrace.loadImage('path/to/image.png', function(err) {\n  if (err) throw err;\n\n  trace.getSVG(); // returns SVG document contents\n  trace.getPathTag(); // will return just <path> tag\n  trace.getSymbol('traced-image'); // will return <symbol> tag with given ID\n});\n\n// Posterization\n\nvar posterizer = new potrace.Posterize();\n\nposterizer.loadImage('path/to/image.png', function(err) {\n  if (err) throw err;\n  \n  posterizer.setParameter({\n    color: '#ccc',\n    background: '#222',\n    steps: 3,\n    threshold: 200,\n    fillStrategy: potrace.Posterize.FILL_MEAN\n  });\n  \n  posterizer.getSVG();\n  // or\n  posterizer.getSymbol('posterized-image');\n});\n```\n\nCallback function provided to `loadImage` methods will be executed in context of the `Potrace`/`Posterizer` instance, so if it doesn't go against your code style - you can just do\n\n```js\nnew potrace.Potrace()\n  .loadImage('path/to/image.bmp', function() {\n    if (err) throw err;\n    this.getSymbol('foo');\n  });\n```\n\n[Jimp module][jimp] is used on the back end, so first argument accepted by `loadImage` method could be anything Jimp can read: a `Buffer`, local path or a url string. Supported formats are: PNG, JPEG or BMP. It also could be a Jimp instance (provided bitmap is not modified)\n\n### Parameters\n\n`Potrace` class expects following parameters:\n\n- **turnPolicy** - how to resolve ambiguities in path decomposition. Possible values are exported as constants: `TURNPOLICY_BLACK`, `TURNPOLICY_WHITE`, `TURNPOLICY_LEFT`, `TURNPOLICY_RIGHT`, `TURNPOLICY_MINORITY`, `TURNPOLICY_MAJORITY`. Refer to [this document][potrace-algorithm] for more information (page 4)  \n  (default: `TURNPOLICY_MINORITY`)\n- **turdSize** - suppress speckles of up to this size   \n  (default: 2)\n- **alphaMax** - corner threshold parameter   \n  (default: 1)\n- **optCurve** - curve optimization   \n  (default: true)\n- **optTolerance** - curve optimization tolerance   \n  (default: 0.2)\n- **threshold** - threshold below which color is considered black.\n  Should be a number in range 0..255 or `THRESHOLD_AUTO` in which case threshold will be selected automatically using [Algorithm For Multilevel Thresholding][multilevel-thresholding]  \n  (default: `THRESHOLD_AUTO`)  \n- **blackOnWhite** - specifies colors by which side from threshold should be turned into vector shape  \n  (default: `true`)  \n- **color** - Fill color. Will be ignored when exporting as \\<symbol\\>. (default: `COLOR_AUTO`, which means black or white, depending on `blackOnWhite` property)\n- **background** - Background color. Will be ignored when exporting as \\<symbol\\>. By default is not present (`COLOR_TRANSPARENT`)\n\n---------------\n\n`Posterizer` class has same methods as `Potrace`, in exception of `.getPathTag()`. \nConfiguration object is extended with following properties:\n\n- **fillStrategy** - determines how fill color for each layer should be selected. Possible values are exported as constants:  \n    - `FILL_DOMINANT` - most frequent color in range (used by default), \n    - `FILL_MEAN` - arithmetic mean (average), \n    - `FILL_MEDIAN` - median color, \n    - `FILL_SPREAD` - ignores color information of the image and just spreads colors equally in range 0..\\<threshold\\> (or \\<threshold\\>..255 if `blackOnWhite` is set to `false`),\n- **rangeDistribution** - how color stops for each layer should be selected. Ignored if `steps` is an array. Possible values are:\n    - `RANGES_AUTO` - Performs automatic thresholding (using [Algorithm For Multilevel Thresholding][multilevel-thresholding]). Preferable method for already posterized sources, but takes long time to calculate 5 or more thresholds (exponential time complexity)  \n      *(used by default)*\n    - `RANGES_EQUAL` - Ignores color information of the image and breaks available color space into equal chunks\n- **steps** - Specifies desired number of layers in resulting image. If a number provided - thresholds for each layer will be automatically calculated according to `rangeDistribution` parameter. If an array provided it expected to be an array with precomputed thresholds for each layer (in range 0..255)  \n  (default: `STEPS_AUTO` which will result in `3` or `4`, depending on `threshold` value)\n- **threshold** - Breaks image into foreground and background (and only foreground being broken into desired number of layers). Basically when provided it becomes a threshold for last (least opaque) layer and then `steps - 1` intermediate thresholds calculated. If **steps** is an array of thresholds and every value from the array is lower (or larger if **blackOnWhite** parameter set to `false`) than threshold - threshold will be added to the array, otherwise just ignored.  \n  (default: `Potrace.THRESHOLD_AUTO`)\n- *all other parameters that Potrace class accepts*\n\n**Notes:**\n\n- When number of `steps` is greater than 10 - an extra layer could be added to ensure presence of darkest/brightest colors if needed to ensure presence of probably-important-at-this-point details like shadows or line art.\n- With big number of layers produced image will be looking brighter overall than original due to math error at the rendering phase because of how layers are composited.\n- With default configuration `steps`, `threshold` and `rangeDistribution` settings all set to auto, resulting in a 4 thresholds/color stops being calculated with Multilevel Thresholding algorithm mentioned above. Calculation of 4 thresholds takes 3-5 seconds on average laptop. You may want to explicitly limit number of `steps` to 3 to moderately improve processing speed.  \n\n## Thanks to\n\n- Peter Selinger for [original Potrace tool and algorithm][potrace]\n- @kilobtye for original [javascript port][potrace-by-kilobtye]\n\n## License\n\nThe GNU General Public License version 2 (GPLv2). Please see [License File](LICENSE) for more information.\n\n[potrace]: http://potrace.sourceforge.net/\n[potrace-algorithm]: http://potrace.sourceforge.net/potrace.pdf\n[multilevel-thresholding]: http://www.iis.sinica.edu.tw/page/jise/2001/200109_01.pdf\n[potrace-by-kilobtye]: https://github.com/kilobtye/potrace\n[potrace-js-demo]: http://kilobtye.github.io/potrace/\n[jimp]: https://github.com/oliver-moran/jimp"
  },
  {
    "path": "lib/Posterizer.js",
    "content": "'use strict';\n\nvar Potrace = require('./Potrace');\nvar utils = require('./utils');\n\n/**\n * Takes multiple samples using {@link Potrace} with different threshold\n * settings and combines output into a single file.\n *\n * @param {Posterizer~Options} [options]\n * @constructor\n */\nfunction Posterizer(options) {\n  this._potrace = new Potrace();\n\n  this._calculatedThreshold = null;\n  \n  this._params = {\n    threshold: Potrace.THRESHOLD_AUTO,\n    blackOnWhite: true,\n    steps: Posterizer.STEPS_AUTO,\n    background: Potrace.COLOR_TRANSPARENT,\n    fillStrategy: Posterizer.FILL_DOMINANT,\n    rangeDistribution: Posterizer.RANGES_AUTO\n  };\n\n  if (options) {\n    this.setParameters(options);\n  }\n}\n\n// Inherit constants from Potrace class\nfor (var key in Potrace) {\n  if (Object.prototype.hasOwnProperty.call(Potrace, key) && key === key.toUpperCase()) {\n    Posterizer[key] = Potrace[key];\n  }\n}\n\nPosterizer.STEPS_AUTO = -1;\nPosterizer.FILL_SPREAD = 'spread';\nPosterizer.FILL_DOMINANT = 'dominant';\nPosterizer.FILL_MEDIAN = 'median';\nPosterizer.FILL_MEAN = 'mean';\n\nPosterizer.RANGES_AUTO = 'auto';\nPosterizer.RANGES_EQUAL = 'equal';\n\nPosterizer.prototype = {\n  /**\n   * Fine tuning to color ranges.\n   *\n   * If last range (featuring most saturated color) is larger than 10% of color space (25 units)\n   * then we want to add another color stop, that hopefully will include darkest pixels, improving presence of\n   * shadows and line art\n   *\n   * @param ranges\n   * @private\n   */\n  _addExtraColorStop: function(ranges) {\n    var blackOnWhite = this._params.blackOnWhite;\n    var lastColorStop = ranges[ranges.length - 1];\n    var lastRangeFrom = blackOnWhite ? 0 : lastColorStop.value;\n    var lastRangeTo = blackOnWhite ? lastColorStop.value : 255;\n\n    if (lastRangeTo - lastRangeFrom > 25 && lastColorStop.colorIntensity !== 1) {\n      var histogram = this._getImageHistogram();\n      var levels = histogram.getStats(lastRangeFrom, lastRangeTo).levels;\n\n      var newColorStop = levels.mean + levels.stdDev <= 25 ? levels.mean + levels.stdDev\n        : levels.mean - levels.stdDev <= 25 ? levels.mean - levels.stdDev\n        : 25;\n\n      var newStats = (blackOnWhite ? histogram.getStats(0, newColorStop) : histogram.getStats(newColorStop, 255));\n      var color = newStats.levels.mean;\n\n      ranges.push({\n        value: Math.abs((blackOnWhite ? 0 : 255) - newColorStop),\n        colorIntensity: isNaN(color) ? 0 : ((blackOnWhite ? 255 - color : color) / 255)\n      });\n    }\n\n    return ranges;\n  },\n\n\n  /**\n   * Calculates color intensity for each element of numeric array\n   * \n   * @param {number[]} colorStops\n   * @returns {{ levels: number, colorIntensity: number }[]}\n   * @private\n   */\n  _calcColorIntensity: function(colorStops) {\n    var blackOnWhite = this._params.blackOnWhite;\n    var colorSelectionStrat = this._params.fillStrategy;\n    var histogram = colorSelectionStrat !== Posterizer.FILL_SPREAD ? this._getImageHistogram() : null;\n    var fullRange = Math.abs(this._paramThreshold() - (blackOnWhite ? 0 : 255));\n\n    return colorStops.map(function(threshold, index) {\n      var nextValue = index + 1 === colorStops.length ? (blackOnWhite ? -1 : 256) : colorStops[index + 1];\n      var rangeStart = Math.round(blackOnWhite ? nextValue + 1 : threshold);\n      var rangeEnd = Math.round(blackOnWhite ? threshold : nextValue - 1);\n      var factor = index / (colorStops.length - 1);\n      var intervalSize = rangeEnd - rangeStart;\n      var stats = histogram.getStats(rangeStart, rangeEnd);\n      var color = -1;\n\n      if (stats.pixels === 0) {\n        return {\n          value: threshold,\n          colorIntensity: 0\n        };\n      }\n\n      switch (colorSelectionStrat) {\n        case Posterizer.FILL_SPREAD:\n          // We want it to be 0 (255 when white on black) at the most saturated end, so...\n          color = (blackOnWhite ? rangeStart : rangeEnd)\n            + (blackOnWhite ? 1 : -1) * intervalSize * Math.max(0.5, fullRange / 255) * factor;\n          break;\n        case Posterizer.FILL_DOMINANT:\n          color = histogram.getDominantColor(rangeStart, rangeEnd, utils.clamp(intervalSize, 1, 5));\n          break;\n        case Posterizer.FILL_MEAN:\n          color = stats.levels.mean;\n          break;\n        case Posterizer.FILL_MEDIAN:\n          color = stats.levels.median;\n          break;\n      }\n\n      // We don't want colors to be too close to each other, so we introduce some spacing in between\n      if (index !== 0) {\n        color = blackOnWhite\n          ? utils.clamp(color, rangeStart, rangeEnd - Math.round(intervalSize * 0.1))\n          : utils.clamp(color, rangeStart + Math.round(intervalSize * 0.1), rangeEnd);\n      }\n\n      return {\n        value: threshold,\n        colorIntensity: color === -1 ? 0 : ((blackOnWhite ? 255 - color : color) / 255)\n      };\n    });\n  },\n\n  /**\n   * @returns {Histogram}\n   * @private\n   */\n  _getImageHistogram: function() {\n    return this._potrace._luminanceData.histogram();\n  },\n\n  /**\n   * Processes threshold, steps and rangeDistribution parameters and returns normalized array of color stops\n   * @returns {*}\n   * @private\n   */\n  _getRanges: function() {\n    var steps = this._paramSteps();\n\n    if (!Array.isArray(steps)) {\n      return this._params.rangeDistribution === Posterizer.RANGES_AUTO\n        ? this._getRangesAuto()\n        : this._getRangesEquallyDistributed();\n    }\n\n    // Steps is array of thresholds and we want to preprocess it\n\n    var colorStops = [];\n    var threshold = this._paramThreshold();\n    var lookingForDarkPixels = this._params.blackOnWhite;\n\n    steps.forEach(function(item) {\n      if (colorStops.indexOf(item) === -1 && utils.between(item, 0, 255)) {\n        colorStops.push(item);\n      }\n    });\n\n    if (!colorStops.length) {\n      colorStops.push(threshold);\n    }\n\n    colorStops = colorStops.sort(function (a, b) {\n      return a < b === lookingForDarkPixels ? 1 : -1;\n    });\n\n    if (lookingForDarkPixels && colorStops[0] < threshold) {\n      colorStops.unshift(threshold);\n    } else if (!lookingForDarkPixels && colorStops[colorStops.length - 1] < threshold) {\n      colorStops.push(threshold);\n    }\n\n    return this._calcColorIntensity(colorStops);\n  },\n\n  /**\n   * Calculates given (or lower) number of thresholds using automatic thresholding algorithm\n   * @returns {*}\n   * @private\n   */\n  _getRangesAuto: function() {\n    var histogram = this._getImageHistogram();\n    var steps = this._paramSteps(true);\n    var colorStops;\n\n    if (this._params.threshold === Potrace.THRESHOLD_AUTO) {\n      colorStops = histogram.multilevelThresholding(steps);\n    } else {\n      var threshold = this._paramThreshold();\n\n      colorStops = this._params.blackOnWhite\n        ? histogram.multilevelThresholding(steps - 1, 0, threshold)\n        : histogram.multilevelThresholding(steps - 1, threshold, 255);\n\n      if (this._params.blackOnWhite) {\n        colorStops.push(threshold);\n      } else {\n        colorStops.unshift(threshold);\n      }\n    }\n\n    if (this._params.blackOnWhite) {\n      colorStops = colorStops.reverse();\n    }\n\n    return this._calcColorIntensity(colorStops);\n  },\n\n  /**\n   * Calculates color stops and color representing each segment, returning them\n   * from least to most intense color (black or white, depending on blackOnWhite parameter)\n   *\n   * @private\n   */\n  _getRangesEquallyDistributed: function() {\n    var blackOnWhite = this._params.blackOnWhite;\n    var colorsToThreshold = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold();\n    var steps = this._paramSteps();\n\n    var stepSize = colorsToThreshold / steps;\n    var colorStops = [];\n    var i = steps - 1,\n        factor,\n        threshold;\n\n    while (i >= 0) {\n      factor = i / (steps - 1);\n      threshold = Math.min(colorsToThreshold, (i + 1) * stepSize);\n      threshold = blackOnWhite ? threshold : 255 - threshold;\n      i--;\n\n      colorStops.push(threshold);\n    }\n\n    return this._calcColorIntensity(colorStops);\n  },\n\n  /**\n   * Returns valid steps value\n   * @param {Boolean} [count=false]\n   * @returns {number|number[]}\n   * @private\n   */\n  _paramSteps: function(count) {\n    var steps = this._params.steps;\n\n    if (Array.isArray(steps)) {\n      return count ? steps.length : steps;\n    }\n\n    if (steps === Posterizer.STEPS_AUTO && this._params.threshold === Potrace.THRESHOLD_AUTO) {\n      return 4;\n    }\n\n    var blackOnWhite = this._params.blackOnWhite;\n    var colorsCount = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold();\n\n    return steps === Posterizer.STEPS_AUTO\n      ? (colorsCount > 200 ? 4 : 3)\n      : Math.min(colorsCount, Math.max(2, steps));\n  },\n\n  /**\n   * Returns valid threshold value\n   * @returns {number}\n   * @private\n   */\n  _paramThreshold: function() {\n    if (this._calculatedThreshold !== null) {\n      return this._calculatedThreshold;\n    }\n\n    if (this._params.threshold !== Potrace.THRESHOLD_AUTO) {\n      this._calculatedThreshold = this._params.threshold;\n      return this._calculatedThreshold;\n    }\n\n    var twoThresholds = this._getImageHistogram().multilevelThresholding(2);\n    this._calculatedThreshold = this._params.blackOnWhite ? twoThresholds[1] : twoThresholds[0];\n    this._calculatedThreshold = this._calculatedThreshold || 128;\n\n    return this._calculatedThreshold;\n  },\n\n  /**\n   * Running potrace on the image multiple times with different thresholds and returns an array\n   * of path tags\n   *\n   * @param {Boolean} [noFillColor]\n   * @returns {string[]}\n   * @private\n   */\n  _pathTags: function(noFillColor) {\n    var ranges = this._getRanges();\n    var potrace = this._potrace;\n    var blackOnWhite = this._params.blackOnWhite;\n\n    if (ranges.length >= 10) {\n      ranges = this._addExtraColorStop(ranges);\n    }\n\n    potrace.setParameters({ blackOnWhite: blackOnWhite });\n\n    var actualPrevLayersOpacity = 0;\n\n    return ranges.map(function(colorStop) {\n      var thisLayerOpacity = colorStop.colorIntensity;\n\n      if (thisLayerOpacity === 0) {\n        return '';\n      }\n\n      // NOTE: With big number of layers (something like 70) there will be noticeable math error on rendering side.\n      // In Chromium at least image will end up looking brighter overall compared to the same layers painted in solid colors.\n      // However it works fine with sane number of layers, and it's not like we can do much about it.\n\n      var calculatedOpacity = (!actualPrevLayersOpacity || thisLayerOpacity === 1)\n        ? thisLayerOpacity\n        : ((actualPrevLayersOpacity - thisLayerOpacity) / (actualPrevLayersOpacity - 1));\n\n      calculatedOpacity = utils.clamp(parseFloat(calculatedOpacity.toFixed(3)), 0, 1);\n      actualPrevLayersOpacity = actualPrevLayersOpacity + (1 - actualPrevLayersOpacity) * calculatedOpacity;\n\n      potrace.setParameters({ threshold: colorStop.value });\n\n      var element = noFillColor ? potrace.getPathTag('') : potrace.getPathTag();\n      element = utils.setHtmlAttr(element, 'fill-opacity', calculatedOpacity.toFixed(3));\n\n      var canBeIgnored = calculatedOpacity === 0 || element.indexOf(' d=\"\"') !== -1;\n\n      // var c = Math.round(Math.abs((blackOnWhite ? 255 : 0) - 255 * thisLayerOpacity));\n      // element = utils.setHtmlAttr(element, 'fill', 'rgb('+c+', '+c+', '+c+')');\n      // element = utils.setHtmlAttr(element, 'fill-opacity', '');\n\n      return canBeIgnored ? '' : element;\n    });\n  },\n\n  /**\n   * Loads image.\n   *\n   * @param {string|Buffer|Jimp} target Image source. Could be anything that {@link Jimp} can read (buffer, local path or url). Supported formats are: PNG, JPEG or BMP\n   * @param {Function} callback\n   */\n  loadImage: function(target, callback) {\n    var self = this;\n\n    this._potrace.loadImage(target, function(err) {\n      self._calculatedThreshold = null;\n      callback.call(self, err);\n    });\n  },\n\n  /**\n   * Sets parameters. Accepts same object as {Potrace}\n   *\n   * @param {Posterizer~Options} params\n   */\n  setParameters: function(params) {\n    if (!params) {\n      return;\n    }\n\n    this._potrace.setParameters(params);\n\n    if (params.steps && !Array.isArray(params.steps) && (!utils.isNumber(params.steps) || !utils.between(params.steps, 1, 255))) {\n      throw new Error('Bad \\'steps\\' value');\n    }\n\n    for (var key in this._params) {\n      if (this._params.hasOwnProperty(key) && params.hasOwnProperty(key)) {\n        this._params[key] = params[key];\n      }\n    }\n\n    this._calculatedThreshold = null;\n  },\n\n  /**\n   * Returns image as <symbol> tag. Always has viewBox specified\n   *\n   * @param {string} id\n   */\n  getSymbol: function(id) {\n    var width = this._potrace._luminanceData.width;\n    var height = this._potrace._luminanceData.height;\n    var paths = this._pathTags(true);\n\n    return '<symbol viewBox=\"0 0 ' + width + ' ' + height + '\" id=\"' + id + '\">' +\n      paths.join('') +\n      '</symbol>';\n  },\n\n  /**\n   * Generates SVG image\n   * @returns {String}\n   */\n  getSVG: function() {\n    var width = this._potrace._luminanceData.width,\n        height = this._potrace._luminanceData.height;\n\n    var tags = this._pathTags(false);\n\n    var svg = '<svg xmlns=\"http://www.w3.org/2000/svg\" ' +\n      'width=\"' + width + '\" ' +\n      'height=\"' + height + '\" ' +\n      'viewBox=\"0 0 ' + width + ' ' + height + '\" ' +\n      'version=\"1.1\">\\n\\t' +\n      (this._params.background !== Potrace.COLOR_TRANSPARENT\n        ? '<rect x=\"0\" y=\"0\" width=\"100%\" height=\"100%\" fill=\"' + this._params.background + '\" />\\n\\t'\n        : '') +\n      tags.join('\\n\\t') +\n      '\\n</svg>';\n\n    return svg.replace(/\\n(?:\\t*\\n)+(\\t*)/g, '\\n$1');\n  }\n};\n\nmodule.exports = Posterizer;\n\n/**\n * Posterizer options\n *\n * @typedef {Potrace~Options} Posterizer~Options\n * @property {Number} [steps]   - Number of samples that needs to be taken (and number of layers in SVG). (default: Posterizer.STEPS_AUTO, which most likely will result in 3, sometimes 4)\n * @property {*} [fillStrategy] - How to select fill color for color ranges - equally spread or dominant. (default: Posterizer.FILL_DOMINANT)\n * @property {*} [rangeDistribution] - How to choose thresholds in-between - after equal intervals or automatically balanced. (default: Posterizer.RANGES_AUTO)\n */\n"
  },
  {
    "path": "lib/Potrace.js",
    "content": "'use strict';\n\nvar Jimp = require('jimp');\nvar Bitmap = require('./types/Bitmap');\nvar Curve = require('./types/Curve');\nvar Point = require('./types/Point');\nvar Path = require('./types/Path');\nvar Quad = require('./types/Quad');\nvar Sum = require('./types/Sum');\nvar Opti = require('./types/Opti');\n\nvar utils = require('./utils');\n\n/**\n * Potrace class\n *\n * @param {Potrace~Options} [options]\n * @constructor\n */\nfunction Potrace (options) {\n  this._luminanceData = null;\n  this._pathlist = [];\n\n  this._imageLoadingIdentifier = null;\n  this._imageLoaded = false;\n  this._processed = false;\n\n  this._params = {\n    turnPolicy: Potrace.TURNPOLICY_MINORITY,\n    turdSize: 2,\n    alphaMax: 1,\n    optCurve: true,\n    optTolerance: 0.2,\n    threshold: Potrace.THRESHOLD_AUTO,\n    blackOnWhite: true,\n    color: Potrace.COLOR_AUTO,\n    background: Potrace.COLOR_TRANSPARENT\n  };\n\n  if (options) {\n    this.setParameters(options);\n  }\n}\n\nPotrace.COLOR_AUTO = 'auto';\nPotrace.COLOR_TRANSPARENT = 'transparent';\nPotrace.THRESHOLD_AUTO = -1;\nPotrace.TURNPOLICY_BLACK = 'black';\nPotrace.TURNPOLICY_WHITE = 'white';\nPotrace.TURNPOLICY_LEFT = 'left';\nPotrace.TURNPOLICY_RIGHT = 'right';\nPotrace.TURNPOLICY_MINORITY = 'minority';\nPotrace.TURNPOLICY_MAJORITY = 'majority';\n\nvar SUPPORTED_TURNPOLICY_VALUES = [\n  Potrace.TURNPOLICY_BLACK, Potrace.TURNPOLICY_WHITE,\n  Potrace.TURNPOLICY_LEFT, Potrace.TURNPOLICY_RIGHT,\n  Potrace.TURNPOLICY_MINORITY, Potrace.TURNPOLICY_MAJORITY\n];\n\nPotrace.prototype = {\n  /**\n   * Creating a new {@link Path} for every group of black pixels.\n   * @private\n   */\n  _bmToPathlist: function() {\n    var self = this,\n        threshold = this._params.threshold,\n        blackOnWhite = this._params.blackOnWhite,\n        blackMap,\n        currentPoint = new Point(0, 0),\n        path;\n\n    if (threshold === Potrace.THRESHOLD_AUTO) {\n      threshold = this._luminanceData.histogram().autoThreshold() || 128;\n    }\n\n    blackMap = this._luminanceData.copy(function(lum) {\n      var pastTheThreshold = blackOnWhite\n        ? lum > threshold\n        : lum < threshold;\n\n      return pastTheThreshold ? 0 : 1;\n    });\n      \n    /**\n     * finds next black pixel of the image\n     *\n     * @param {Point} point\n     * @returns {boolean}\n     * @private\n     */\n    function findNext(point) {\n      var i = blackMap.pointToIndex(point);\n\n      while (i < blackMap.size && blackMap.data[i] !== 1) {\n        i++;\n      }\n\n      return i < blackMap.size && blackMap.indexToPoint(i);\n    }\n\n    function majority(x, y) {\n      var i, a, ct;\n\n      for (i = 2; i < 5; i++) {\n        ct = 0;\n        for (a = -i + 1; a <= i - 1; a++) {\n          ct += blackMap.getValueAt(x + a, y + i - 1) ? 1 : -1;\n          ct += blackMap.getValueAt(x + i - 1, y + a - 1) ? 1 : -1;\n          ct += blackMap.getValueAt(x + a - 1, y - i) ? 1 : -1;\n          ct += blackMap.getValueAt(x - i, y + a) ? 1 : -1;\n        }\n\n        if (ct > 0) {\n          return 1;\n        } else if (ct < 0) {\n          return 0;\n        }\n      }\n      return 0;\n    }\n\n    function findPath(point) {\n      var path = new Path(),\n          x = point.x,\n          y = point.y,\n          dirx = 0,\n          diry = 1,\n          tmp;\n\n      path.sign = blackMap.getValueAt(point.x, point.y) ? \"+\" : \"-\";\n\n      while (1) {\n        path.pt.push(new Point(x, y));\n        if (x > path.maxX)\n          path.maxX = x;\n        if (x < path.minX)\n          path.minX = x;\n        if (y > path.maxY)\n          path.maxY = y;\n        if (y < path.minY)\n          path.minY = y;\n        path.len++;\n\n        x += dirx;\n        y += diry;\n        path.area -= x * diry;\n\n        if (x === point.x && y === point.y)\n          break;\n\n        var l = blackMap.getValueAt(x + (dirx + diry - 1 ) / 2, y + (diry - dirx - 1) / 2);\n        var r = blackMap.getValueAt(x + (dirx - diry - 1) / 2, y + (diry + dirx - 1) / 2);\n\n        if (r && !l) {\n          if (self._params.turnPolicy === \"right\" ||\n            (self._params.turnPolicy === \"black\" && path.sign === '+') ||\n            (self._params.turnPolicy === \"white\" && path.sign === '-') ||\n            (self._params.turnPolicy === \"majority\" && majority(x, y)) ||\n            (self._params.turnPolicy === \"minority\" && !majority(x, y))) {\n            tmp = dirx;\n            dirx = -diry;\n            diry = tmp;\n          } else {\n            tmp = dirx;\n            dirx = diry;\n            diry = -tmp;\n          }\n        } else if (r) {\n          tmp = dirx;\n          dirx = -diry;\n          diry = tmp;\n        } else if (!l) {\n          tmp = dirx;\n          dirx = diry;\n          diry = -tmp;\n        }\n      }\n      return path;\n    }\n\n    function xorPath(path){\n      var y1 = path.pt[0].y,\n        len = path.len,\n        x, y, maxX, minY, i, j,\n        indx;\n\n      for (i = 1; i < len; i++) {\n        x = path.pt[i].x;\n        y = path.pt[i].y;\n\n        if (y !== y1) {\n          minY = y1 < y ? y1 : y;\n          maxX = path.maxX;\n          for (j = x; j < maxX; j++) {\n            indx = blackMap.pointToIndex(j, minY);\n            blackMap.data[indx] = blackMap.data[indx] ? 0 : 1;\n          }\n          y1 = y;\n        }\n      }\n    }\n\n    // Clear path list\n    this._pathlist = [];\n\n    while (currentPoint = findNext(currentPoint)) {\n      path = findPath(currentPoint);\n      xorPath(path);\n\n      if (path.area > self._params.turdSize) {\n        this._pathlist.push(path);\n      }\n    }\n  },\n\n  /**\n   * Processes path list created by _bmToPathlist method creating and optimizing {@link Curve}'s\n   * @private\n   */\n  _processPath: function() {\n    var self = this;\n\n    function calcSums(path) {\n      var i, x, y;\n      path.x0 = path.pt[0].x;\n      path.y0 = path.pt[0].y;\n\n      path.sums = [];\n      var s = path.sums;\n      s.push(new Sum(0, 0, 0, 0, 0));\n      for(i = 0; i < path.len; i++){\n        x = path.pt[i].x - path.x0;\n        y = path.pt[i].y - path.y0;\n        s.push(new Sum(s[i].x + x, s[i].y + y, s[i].xy + x * y,\n            s[i].x2 + x * x, s[i].y2 + y * y));\n      }\n    }\n\n    function calcLon(path) {\n\n      var n = path.len,\n          pt = path.pt,\n          dir,\n          pivk = new Array(n),\n          nc = new Array(n),\n          ct = new Array(4);\n\n      path.lon = new Array(n);\n\n      var constraint = [new Point(), new Point()],\n          cur = new Point(),\n          off = new Point(),\n          dk = new Point(),\n          foundk;\n\n      var i, j, k1, a, b, c, d, k = 0;\n      for(i = n - 1; i >= 0; i--){\n        if (pt[i].x != pt[k].x && pt[i].y != pt[k].y) {\n          k = i + 1;\n        }\n        nc[i] = k;\n      }\n\n      for (i = n - 1; i >= 0; i--) {\n        ct[0] = ct[1] = ct[2] = ct[3] = 0;\n        dir = (3 + 3 * (pt[utils.mod(i + 1, n)].x - pt[i].x) +\n            (pt[utils.mod(i + 1, n)].y - pt[i].y)) / 2;\n        ct[dir]++;\n\n        constraint[0].x = 0;\n        constraint[0].y = 0;\n        constraint[1].x = 0;\n        constraint[1].y = 0;\n\n        k = nc[i];\n        k1 = i;\n        while (1) {\n          foundk = 0;\n          dir =  (3 + 3 * utils.sign(pt[k].x - pt[k1].x) +\n              utils.sign(pt[k].y - pt[k1].y)) / 2;\n          ct[dir]++;\n\n          if (ct[0] && ct[1] && ct[2] && ct[3]) {\n            pivk[i] = k1;\n            foundk = 1;\n            break;\n          }\n\n          cur.x = pt[k].x - pt[i].x;\n          cur.y = pt[k].y - pt[i].y;\n\n          if (utils.xprod(constraint[0], cur) < 0 || utils.xprod(constraint[1], cur) > 0) {\n            break;\n          }\n\n          if (Math.abs(cur.x) <= 1 && Math.abs(cur.y) <= 1) {\n\n          } else {\n            off.x = cur.x + ((cur.y >= 0 && (cur.y > 0 || cur.x < 0)) ? 1 : -1);\n            off.y = cur.y + ((cur.x <= 0 && (cur.x < 0 || cur.y < 0)) ? 1 : -1);\n            if (utils.xprod(constraint[0], off) >= 0) {\n              constraint[0].x = off.x;\n              constraint[0].y = off.y;\n            }\n            off.x = cur.x + ((cur.y <= 0 && (cur.y < 0 || cur.x < 0)) ? 1 : -1);\n            off.y = cur.y + ((cur.x >= 0 && (cur.x > 0 || cur.y < 0)) ? 1 : -1);\n            if (utils.xprod(constraint[1], off) <= 0) {\n              constraint[1].x = off.x;\n              constraint[1].y = off.y;\n            }\n          }\n          k1 = k;\n          k = nc[k1];\n          if (!utils.cyclic(k, i, k1)) {\n            break;\n          }\n        }\n        if (foundk === 0) {\n          dk.x = utils.sign(pt[k].x-pt[k1].x);\n          dk.y = utils.sign(pt[k].y-pt[k1].y);\n          cur.x = pt[k1].x - pt[i].x;\n          cur.y = pt[k1].y - pt[i].y;\n\n          a = utils.xprod(constraint[0], cur);\n          b = utils.xprod(constraint[0], dk);\n          c = utils.xprod(constraint[1], cur);\n          d = utils.xprod(constraint[1], dk);\n\n          j = 10000000;\n\n          if (b < 0) {\n            j = Math.floor(a / -b);\n          }\n          if (d > 0) {\n            j = Math.min(j, Math.floor(-c / d));\n          }\n\n          pivk[i] = utils.mod(k1+j,n);\n        }\n      }\n\n      j=pivk[n-1];\n      path.lon[n-1]=j;\n      for (i=n-2; i>=0; i--) {\n        if (utils.cyclic(i+1,pivk[i],j)) {\n          j=pivk[i];\n        }\n        path.lon[i]=j;\n      }\n\n      for (i=n-1; utils.cyclic(utils.mod(i+1,n),j,path.lon[i]); i--) {\n        path.lon[i] = j;\n      }\n    }\n\n    function bestPolygon(path) {\n\n      function penalty3(path, i, j) {\n\n        var n = path.len, pt = path.pt, sums = path.sums;\n        var x, y, xy, x2, y2,\n          k, a, b, c, s,\n          px, py, ex, ey,\n          r = 0;\n        if (j>=n) {\n          j -= n;\n          r = 1;\n        }\n\n        if (r === 0) {\n          x = sums[j+1].x - sums[i].x;\n          y = sums[j+1].y - sums[i].y;\n          x2 = sums[j+1].x2 - sums[i].x2;\n          xy = sums[j+1].xy - sums[i].xy;\n          y2 = sums[j+1].y2 - sums[i].y2;\n          k = j+1 - i;\n        } else {\n          x = sums[j+1].x - sums[i].x + sums[n].x;\n          y = sums[j+1].y - sums[i].y + sums[n].y;\n          x2 = sums[j+1].x2 - sums[i].x2 + sums[n].x2;\n          xy = sums[j+1].xy - sums[i].xy + sums[n].xy;\n          y2 = sums[j+1].y2 - sums[i].y2 + sums[n].y2;\n          k = j+1 - i + n;\n        }\n\n        px = (pt[i].x + pt[j].x) / 2.0 - pt[0].x;\n        py = (pt[i].y + pt[j].y) / 2.0 - pt[0].y;\n        ey = (pt[j].x - pt[i].x);\n        ex = -(pt[j].y - pt[i].y);\n\n        a = ((x2 - 2*x*px) / k + px*px);\n        b = ((xy - x*py - y*px) / k + px*py);\n        c = ((y2 - 2*y*py) / k + py*py);\n\n        s = ex*ex*a + 2*ex*ey*b + ey*ey*c;\n\n        return Math.sqrt(s);\n      }\n\n      var i, j, m, k,\n      n = path.len,\n      pen = new Array(n + 1),\n      prev = new Array(n + 1),\n      clip0 = new Array(n),\n      clip1 = new Array(n + 1),\n      seg0 = new Array (n + 1),\n      seg1 = new Array(n + 1),\n      thispen, best, c;\n\n      for (i=0; i<n; i++) {\n        c = utils.mod(path.lon[utils.mod(i-1,n)]-1,n);\n        if (c == i) {\n          c = utils.mod(i+1,n);\n        }\n        if (c < i) {\n          clip0[i] = n;\n        } else {\n          clip0[i] = c;\n        }\n      }\n\n      j = 1;\n      for (i=0; i<n; i++) {\n        while (j <= clip0[i]) {\n          clip1[j] = i;\n          j++;\n        }\n      }\n\n      i = 0;\n      for (j=0; i<n; j++) {\n        seg0[j] = i;\n        i = clip0[i];\n      }\n      seg0[j] = n;\n      m = j;\n\n      i = n;\n      for (j=m; j>0; j--) {\n        seg1[j] = i;\n        i = clip1[i];\n      }\n      seg1[0] = 0;\n\n      pen[0]=0;\n      for (j=1; j<=m; j++) {\n        for (i=seg1[j]; i<=seg0[j]; i++) {\n          best = -1;\n          for (k=seg0[j-1]; k>=clip1[i]; k--) {\n            thispen = penalty3(path, k, i) + pen[k];\n            if (best < 0 || thispen < best) {\n              prev[i] = k;\n              best = thispen;\n            }\n          }\n          pen[i] = best;\n        }\n      }\n      path.m = m;\n      path.po = new Array(m);\n\n      for (i=n, j=m-1; i>0; j--) {\n        i = prev[i];\n        path.po[j] = i;\n      }\n    }\n\n    function adjustVertices(path) {\n\n      function pointslope(path, i, j, ctr, dir) {\n\n        var n = path.len, sums = path.sums,\n          x, y, x2, xy, y2,\n          k, a, b, c, lambda2, l, r=0;\n\n        while (j>=n) {\n          j-=n;\n          r+=1;\n        }\n        while (i>=n) {\n          i-=n;\n          r-=1;\n        }\n        while (j<0) {\n          j+=n;\n          r-=1;\n        }\n        while (i<0) {\n          i+=n;\n          r+=1;\n        }\n\n        x = sums[j+1].x-sums[i].x+r*sums[n].x;\n        y = sums[j+1].y-sums[i].y+r*sums[n].y;\n        x2 = sums[j+1].x2-sums[i].x2+r*sums[n].x2;\n        xy = sums[j+1].xy-sums[i].xy+r*sums[n].xy;\n        y2 = sums[j+1].y2-sums[i].y2+r*sums[n].y2;\n        k = j+1-i+r*n;\n\n        ctr.x = x/k;\n        ctr.y = y/k;\n\n        a = (x2-x*x/k)/k;\n        b = (xy-x*y/k)/k;\n        c = (y2-y*y/k)/k;\n\n        lambda2 = (a+c+Math.sqrt((a-c)*(a-c)+4*b*b))/2;\n\n        a -= lambda2;\n        c -= lambda2;\n\n        if (Math.abs(a) >= Math.abs(c)) {\n          l = Math.sqrt(a*a+b*b);\n          if (l!==0) {\n            dir.x = -b/l;\n            dir.y = a/l;\n          }\n        } else {\n          l = Math.sqrt(c*c+b*b);\n          if (l!==0) {\n            dir.x = -c/l;\n            dir.y = b/l;\n          }\n        }\n        if (l===0) {\n          dir.x = dir.y = 0;\n        }\n      }\n\n      var m = path.m, po = path.po, n = path.len, pt = path.pt,\n        x0 = path.x0, y0 = path.y0,\n        ctr = new Array(m), dir = new Array(m),\n        q = new Array(m),\n        v = new Array(3), d, i, j, k, l,\n        s = new Point();\n\n      path.curve = new Curve(m);\n\n      for (i=0; i<m; i++) {\n        j = po[utils.mod(i+1,m)];\n        j = utils.mod(j-po[i],n)+po[i];\n        ctr[i] = new Point();\n        dir[i] = new Point();\n        pointslope(path, po[i], j, ctr[i], dir[i]);\n      }\n\n      for (i=0; i<m; i++) {\n        q[i] = new Quad();\n        d = dir[i].x * dir[i].x + dir[i].y * dir[i].y;\n        if (d === 0.0) {\n          for (j=0; j<3; j++) {\n            for (k=0; k<3; k++) {\n              q[i].data[j * 3 + k] = 0;\n            }\n          }\n        } else {\n          v[0] = dir[i].y;\n          v[1] = -dir[i].x;\n          v[2] = - v[1] * ctr[i].y - v[0] * ctr[i].x;\n          for (l=0; l<3; l++) {\n            for (k=0; k<3; k++) {\n              q[i].data[l * 3 + k] = v[l] * v[k] / d;\n            }\n          }\n        }\n      }\n\n      var Q, w, dx, dy, det, min, cand, xmin, ymin, z;\n      for (i=0; i<m; i++) {\n        Q = new Quad();\n        w = new Point();\n\n        s.x = pt[po[i]].x-x0;\n        s.y = pt[po[i]].y-y0;\n\n        j = utils.mod(i-1,m);\n\n        for (l=0; l<3; l++) {\n          for (k=0; k<3; k++) {\n            Q.data[l * 3 + k] = q[j].at(l, k) + q[i].at(l, k);\n          }\n        }\n\n        while(1) {\n\n          det = Q.at(0, 0)*Q.at(1, 1) - Q.at(0, 1)*Q.at(1, 0);\n          if (det !== 0.0) {\n            w.x = (-Q.at(0, 2)*Q.at(1, 1) + Q.at(1, 2)*Q.at(0, 1)) / det;\n            w.y = ( Q.at(0, 2)*Q.at(1, 0) - Q.at(1, 2)*Q.at(0, 0)) / det;\n            break;\n          }\n\n          if (Q.at(0, 0)>Q.at(1, 1)) {\n            v[0] = -Q.at(0, 1);\n            v[1] = Q.at(0, 0);\n          } else if (Q.at(1, 1)) {\n            v[0] = -Q.at(1, 1);\n            v[1] = Q.at(1, 0);\n          } else {\n            v[0] = 1;\n            v[1] = 0;\n          }\n          d = v[0] * v[0] + v[1] * v[1];\n          v[2] = - v[1] * s.y - v[0] * s.x;\n          for (l=0; l<3; l++) {\n            for (k=0; k<3; k++) {\n              Q.data[l * 3 + k] += v[l] * v[k] / d;\n            }\n          }\n        }\n        dx = Math.abs(w.x-s.x);\n        dy = Math.abs(w.y-s.y);\n        if (dx <= 0.5 && dy <= 0.5) {\n          path.curve.vertex[i] = new Point(w.x+x0, w.y+y0);\n          continue;\n        }\n\n        min = utils.quadform(Q, s);\n        xmin = s.x;\n        ymin = s.y;\n\n        if (Q.at(0, 0) !== 0.0) {\n          for (z=0; z<2; z++) {\n            w.y = s.y-0.5+z;\n            w.x = - (Q.at(0, 1) * w.y + Q.at(0, 2)) / Q.at(0, 0);\n            dx = Math.abs(w.x-s.x);\n            cand = utils.quadform(Q, w);\n            if (dx <= 0.5 && cand < min) {\n              min = cand;\n              xmin = w.x;\n              ymin = w.y;\n            }\n          }\n        }\n\n        if (Q.at(1, 1) !== 0.0) {\n          for (z=0; z<2; z++) {\n            w.x = s.x-0.5+z;\n            w.y = - (Q.at(1, 0) * w.x + Q.at(1, 2)) / Q.at(1, 1);\n            dy = Math.abs(w.y-s.y);\n            cand = utils.quadform(Q, w);\n            if (dy <= 0.5 && cand < min) {\n              min = cand;\n              xmin = w.x;\n              ymin = w.y;\n            }\n          }\n        }\n\n        for (l=0; l<2; l++) {\n          for (k=0; k<2; k++) {\n            w.x = s.x-0.5+l;\n            w.y = s.y-0.5+k;\n            cand = utils.quadform(Q, w);\n            if (cand < min) {\n              min = cand;\n              xmin = w.x;\n              ymin = w.y;\n            }\n          }\n        }\n\n        path.curve.vertex[i] = new Point(xmin + x0, ymin + y0);\n      }\n    }\n\n    function reverse(path) {\n      var curve = path.curve, m = curve.n, v = curve.vertex, i, j, tmp;\n\n      for (i=0, j=m-1; i<j; i++, j--) {\n        tmp = v[i];\n        v[i] = v[j];\n        v[j] = tmp;\n      }\n    }\n\n    function smooth(path) {\n      var m = path.curve.n, curve = path.curve;\n\n      var i, j, k, dd, denom, alpha,\n        p2, p3, p4;\n\n      for (i=0; i<m; i++) {\n        j = utils.mod(i+1, m);\n        k = utils.mod(i+2, m);\n        p4 = utils.interval(1/2.0, curve.vertex[k], curve.vertex[j]);\n\n        denom = utils.ddenom(curve.vertex[i], curve.vertex[k]);\n        if (denom !== 0.0) {\n          dd = utils.dpara(curve.vertex[i], curve.vertex[j], curve.vertex[k]) / denom;\n          dd = Math.abs(dd);\n          alpha = dd>1 ? (1 - 1.0/dd) : 0;\n          alpha = alpha / 0.75;\n        } else {\n          alpha = 4/3.0;\n        }\n        curve.alpha0[j] = alpha;\n\n        if (alpha >= self._params.alphaMax) {\n          curve.tag[j] = \"CORNER\";\n          curve.c[3 * j + 1] = curve.vertex[j];\n          curve.c[3 * j + 2] = p4;\n        } else {\n          if (alpha < 0.55) {\n            alpha = 0.55;\n          } else if (alpha > 1) {\n            alpha = 1;\n          }\n          p2 = utils.interval(0.5+0.5*alpha, curve.vertex[i], curve.vertex[j]);\n          p3 = utils.interval(0.5+0.5*alpha, curve.vertex[k], curve.vertex[j]);\n          curve.tag[j] = \"CURVE\";\n          curve.c[3 * j + 0] = p2;\n          curve.c[3 * j + 1] = p3;\n          curve.c[3 * j + 2] = p4;\n        }\n        curve.alpha[j] = alpha;\n        curve.beta[j] = 0.5;\n      }\n      curve.alphaCurve = 1;\n    }\n\n    function optiCurve(path) {\n\n      function opti_penalty(path, i, j, res, opttolerance, convc, areac) {\n        var m = path.curve.n, curve = path.curve, vertex = curve.vertex,\n          k, k1, k2, conv, i1,\n          area, alpha, d, d1, d2,\n          p0, p1, p2, p3, pt,\n          A, R, A1, A2, A3, A4,\n          s, t;\n\n        if (i==j) {\n          return 1;\n        }\n\n        k = i;\n        i1 = utils.mod(i+1, m);\n        k1 = utils.mod(k+1, m);\n        conv = convc[k1];\n        if (conv === 0) {\n          return 1;\n        }\n        d = utils.ddist(vertex[i], vertex[i1]);\n        for (k=k1; k!=j; k=k1) {\n          k1 = utils.mod(k+1, m);\n          k2 = utils.mod(k+2, m);\n          if (convc[k1] != conv) {\n            return 1;\n          }\n          if (utils.sign(utils.cprod(vertex[i], vertex[i1], vertex[k1], vertex[k2])) !=\n              conv) {\n            return 1;\n          }\n          if (utils.iprod1(vertex[i], vertex[i1], vertex[k1], vertex[k2]) <\n              d * utils.ddist(vertex[k1], vertex[k2]) * -0.999847695156) {\n            return 1;\n          }\n        }\n\n        p0 = curve.c[utils.mod(i,m) * 3 + 2].copy();\n        p1 = vertex[utils.mod(i+1,m)].copy();\n        p2 = vertex[utils.mod(j,m)].copy();\n        p3 = curve.c[utils.mod(j,m) * 3 + 2].copy();\n\n        area = areac[j] - areac[i];\n        area -= utils.dpara(vertex[0], curve.c[i * 3 + 2], curve.c[j * 3 + 2])/2;\n        if (i>=j) {\n          area += areac[m];\n        }\n\n        A1 = utils.dpara(p0, p1, p2);\n        A2 = utils.dpara(p0, p1, p3);\n        A3 = utils.dpara(p0, p2, p3);\n\n        A4 = A1+A3-A2;\n\n        if (A2 == A1) {\n          return 1;\n        }\n\n        t = A3/(A3-A4);\n        s = A2/(A2-A1);\n        A = A2 * t / 2.0;\n\n        if (A === 0.0) {\n          return 1;\n        }\n\n        R = area / A;\n        alpha = 2 - Math.sqrt(4 - R / 0.3);\n\n        res.c[0] = utils.interval(t * alpha, p0, p1);\n        res.c[1] = utils.interval(s * alpha, p3, p2);\n        res.alpha = alpha;\n        res.t = t;\n        res.s = s;\n\n        p1 = res.c[0].copy();\n        p2 = res.c[1].copy();\n\n        res.pen = 0;\n\n        for (k=utils.mod(i+1,m); k!=j; k=k1) {\n          k1 = utils.mod(k+1,m);\n          t = utils.tangent(p0, p1, p2, p3, vertex[k], vertex[k1]);\n          if (t<-0.5) {\n            return 1;\n          }\n          pt = utils.bezier(t, p0, p1, p2, p3);\n          d = utils.ddist(vertex[k], vertex[k1]);\n          if (d === 0.0) {\n            return 1;\n          }\n          d1 = utils.dpara(vertex[k], vertex[k1], pt) / d;\n          if (Math.abs(d1) > opttolerance) {\n            return 1;\n          }\n          if (utils.iprod(vertex[k], vertex[k1], pt) < 0 ||\n              utils.iprod(vertex[k1], vertex[k], pt) < 0) {\n            return 1;\n          }\n          res.pen += d1 * d1;\n        }\n\n        for (k=i; k!=j; k=k1) {\n          k1 = utils.mod(k+1,m);\n          t = utils.tangent(p0, p1, p2, p3, curve.c[k * 3 + 2], curve.c[k1 * 3 + 2]);\n          if (t<-0.5) {\n            return 1;\n          }\n          pt = utils.bezier(t, p0, p1, p2, p3);\n          d = utils.ddist(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2]);\n          if (d === 0.0) {\n            return 1;\n          }\n          d1 = utils.dpara(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2], pt) / d;\n          d2 = utils.dpara(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2], vertex[k1]) / d;\n          d2 *= 0.75 * curve.alpha[k1];\n          if (d2 < 0) {\n            d1 = -d1;\n            d2 = -d2;\n          }\n          if (d1 < d2 - opttolerance) {\n            return 1;\n          }\n          if (d1 < d2) {\n            res.pen += (d1 - d2) * (d1 - d2);\n          }\n        }\n\n        return 0;\n      }\n\n      var curve = path.curve, m = curve.n, vert = curve.vertex,\n          pt = new Array(m + 1),\n          pen = new Array(m + 1),\n          len = new Array(m + 1),\n          opt = new Array(m + 1),\n          om, i,j,r,\n          o = new Opti(), p0,\n          i1, area, alpha, ocurve,\n          s, t;\n\n      var convc = new Array(m), areac = new Array(m + 1);\n\n      for (i=0; i<m; i++) {\n        if (curve.tag[i] == \"CURVE\") {\n          convc[i] = utils.sign(utils.dpara(vert[utils.mod(i-1,m)], vert[i], vert[utils.mod(i+1,m)]));\n        } else {\n          convc[i] = 0;\n        }\n      }\n\n      area = 0.0;\n      areac[0] = 0.0;\n      p0 = curve.vertex[0];\n      for (i=0; i<m; i++) {\n        i1 = utils.mod(i+1, m);\n        if (curve.tag[i1] == \"CURVE\") {\n          alpha = curve.alpha[i1];\n          area += 0.3 * alpha * (4-alpha) *\n              utils.dpara(curve.c[i * 3 + 2], vert[i1], curve.c[i1 * 3 + 2])/2;\n          area += utils.dpara(p0, curve.c[i * 3 + 2], curve.c[i1 * 3 + 2])/2;\n        }\n        areac[i+1] = area;\n      }\n\n      pt[0] = -1;\n      pen[0] = 0;\n      len[0] = 0;\n\n\n      for (j=1; j<=m; j++) {\n        pt[j] = j-1;\n        pen[j] = pen[j-1];\n        len[j] = len[j-1]+1;\n\n        for (i=j-2; i>=0; i--) {\n          r = opti_penalty(path, i, utils.mod(j,m), o, self._params.optTolerance, convc,\n              areac);\n          if (r) {\n            break;\n          }\n            if (len[j] > len[i]+1 ||\n                (len[j] == len[i]+1 && pen[j] > pen[i] + o.pen)) {\n              pt[j] = i;\n              pen[j] = pen[i] + o.pen;\n              len[j] = len[i] + 1;\n              opt[j] = o;\n              o = new Opti();\n            }\n        }\n      }\n      om = len[m];\n      ocurve = new Curve(om);\n      s = new Array(om);\n      t = new Array(om);\n\n      j = m;\n      for (i=om-1; i>=0; i--) {\n        if (pt[j]==j-1) {\n          ocurve.tag[i]       = curve.tag[utils.mod(j,m)];\n          ocurve.c[i * 3 + 0] = curve.c[utils.mod(j,m) * 3 + 0];\n          ocurve.c[i * 3 + 1] = curve.c[utils.mod(j,m) * 3 + 1];\n          ocurve.c[i * 3 + 2] = curve.c[utils.mod(j,m) * 3 + 2];\n          ocurve.vertex[i]    = curve.vertex[utils.mod(j,m)];\n          ocurve.alpha[i]     = curve.alpha[utils.mod(j,m)];\n          ocurve.alpha0[i]    = curve.alpha0[utils.mod(j,m)];\n          ocurve.beta[i]      = curve.beta[utils.mod(j,m)];\n          s[i] = t[i] = 1.0;\n        } else {\n          ocurve.tag[i] = \"CURVE\";\n          ocurve.c[i * 3 + 0] = opt[j].c[0];\n          ocurve.c[i * 3 + 1] = opt[j].c[1];\n          ocurve.c[i * 3 + 2] = curve.c[utils.mod(j,m) * 3 + 2];\n          ocurve.vertex[i] = utils.interval(opt[j].s, curve.c[utils.mod(j,m) * 3 + 2],\n                                       vert[utils.mod(j,m)]);\n          ocurve.alpha[i] = opt[j].alpha;\n          ocurve.alpha0[i] = opt[j].alpha;\n          s[i] = opt[j].s;\n          t[i] = opt[j].t;\n        }\n        j = pt[j];\n      }\n\n      for (i=0; i<om; i++) {\n        i1 = utils.mod(i+1,om);\n        ocurve.beta[i] = s[i] / (s[i] + t[i1]);\n      }\n      \n      ocurve.alphaCurve = 1;\n      path.curve = ocurve;\n    }\n\n    for (var i = 0; i < this._pathlist.length; i++) {\n      var path = this._pathlist[i];\n      calcSums(path);\n      calcLon(path);\n      bestPolygon(path);\n      adjustVertices(path);\n\n      if (path.sign === \"-\") {\n        reverse(path);\n      }\n\n      smooth(path);\n\n      if (self._params.optCurve) {\n        optiCurve(path);\n      }\n    }\n  },\n\n  /**\n   * Validates some of parameters\n   * @param params\n   * @private\n   */\n  _validateParameters: function(params) {\n    if (params && params.turnPolicy && SUPPORTED_TURNPOLICY_VALUES.indexOf(params.turnPolicy) === -1) {\n      var goodVals = '\\'' + SUPPORTED_TURNPOLICY_VALUES.join('\\', \\'') + '\\'';\n\n      throw new Error('Bad turnPolicy value. Allowed values are: ' + goodVals);\n    }\n\n    if (params && params.threshold != null && params.threshold !== Potrace.THRESHOLD_AUTO) {\n      if (typeof params.threshold !== 'number' || !utils.between(params.threshold, 0, 255)) {\n        throw new Error('Bad threshold value. Expected to be an integer in range 0..255');\n      }\n    }\n\n    if (params && params.optCurve != null && typeof params.optCurve !== 'boolean') {\n      throw new Error('\\'optCurve\\' must be Boolean');\n    }\n  },\n\n  _processLoadedImage: function(image) {\n    var bitmap = new Bitmap(image.bitmap.width, image.bitmap.height);\n    var pixels = image.bitmap.data;\n\n    image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) {\n      // We want background underneath non-opaque regions to be white\n\n      var opacity = pixels[idx + 3] / 255,\n          r = 255 + (pixels[idx + 0] - 255) * opacity,\n          g = 255 + (pixels[idx + 1] - 255) * opacity,\n          b = 255 + (pixels[idx + 2] - 255) * opacity;\n\n      bitmap.data[idx/4] = utils.luminance(r, g, b);\n    });\n\n    this._luminanceData = bitmap;\n    this._imageLoaded = true;\n  },\n\n  /**\n   * Reads given image. Uses {@link Jimp} under the hood, so target can be whatever Jimp can take\n   *\n   * @param {string|Buffer|Jimp} target Image source. Could be anything that {@link Jimp} can read (buffer, local path or url). Supported formats are: PNG, JPEG or BMP\n   * @param {Function} callback\n   */\n  loadImage: function(target, callback) {\n    var self = this;\n    var jobId = {};\n\n    this._imageLoadingIdentifier = jobId;\n    this._imageLoaded = false;\n\n    if (target instanceof Jimp) {\n      this._imageLoadingIdentifier = null;\n      this._imageLoaded = true;\n      self._processLoadedImage(target);\n      callback.call(self, null);\n    } else {\n      Jimp.read(target, function(err, img) {\n        var sourceChanged = self._imageLoadingIdentifier !== jobId;\n\n        if (sourceChanged) {\n          var error = err ? err : new Error('Another image was loaded instead');\n          return callback.call(self, error);\n        }\n\n        self._imageLoadingIdentifier = null;\n        self._processLoadedImage(img);\n        callback.call(self, null);\n      });\n    }\n  },\n\n  /**\n   * Sets algorithm parameters\n   * @param {Potrace~Options} newParams\n   */\n  setParameters: function(newParams) {\n    var key, tmpOldVal;\n\n    this._validateParameters(newParams);\n\n    for (key in this._params) {\n      if (this._params.hasOwnProperty(key) && newParams.hasOwnProperty(key)) {\n        tmpOldVal = this._params[key];\n        this._params[key] = newParams[key];\n\n        if (tmpOldVal !== this._params[key] && ['color', 'background'].indexOf(key) === -1) {\n          this._processed = false;\n        }\n      }\n    }\n  },\n\n  /**\n   * Generates just <path> tag without rest of the SVG file\n   *\n   * @param {String} [fillColor] - overrides color from parameters\n   * @returns {String}\n   */\n  getPathTag: function(fillColor) {\n    fillColor = arguments.length === 0 ? this._params.color : fillColor;\n\n    if (fillColor === Potrace.COLOR_AUTO) {\n      fillColor = this._params.blackOnWhite ? 'black' : 'white';\n    }\n\n    if (!this._imageLoaded) {\n      throw new Error('Image should be loaded first');\n    }\n\n    if (!this._processed) {\n      this._bmToPathlist();\n      this._processPath();\n      this._processed = true;\n    }\n\n    var tag = '<path d=\"';\n\n    this._pathlist.forEach(function(path) {\n      tag += utils.renderCurve(path.curve, 1);\n    });\n\n    tag += '\" stroke=\"none\" fill=\"' + fillColor + '\" fill-rule=\"evenodd\"/>';\n\n    return tag;\n  },\n\n  /**\n   * Returns <symbol> tag. Always has viewBox specified and comes with no fill color,\n   * so it could be changed with <use> tag\n   *\n   * @param id\n   * @returns {string}\n   */\n  getSymbol: function(id) {\n    return '<symbol ' +\n      'viewBox=\"0 0 ' + this._luminanceData.width + ' ' + this._luminanceData.height + '\" ' +\n      'id=\"' + id + '\">' +\n      this.getPathTag('') +\n      '</symbol>';\n  },\n\n  /**\n   * Generates SVG image\n   * @returns {String}\n   */\n  getSVG: function() {\n    var width = this._luminanceData.width;\n    var height = this._luminanceData.height;\n\n    return '<svg xmlns=\"http://www.w3.org/2000/svg\" ' +\n      'width=\"' + width + '\" ' +\n      'height=\"' + height + '\" ' +\n      'viewBox=\"0 0 ' + width + ' ' + height + '\" ' +\n      'version=\"1.1\">\\n'+\n      (this._params.background !== Potrace.COLOR_TRANSPARENT\n        ? '\\t<rect x=\"0\" y=\"0\" width=\"100%\" height=\"100%\" fill=\"' + this._params.background + '\" />\\n'\n        : '') +\n      '\\t' + this.getPathTag(this._params.color) + '\\n' +\n      '</svg>';\n  }\n};\n\nmodule.exports = Potrace;\n\n/**\n * Potrace options\n *\n * @typedef {Object} Potrace~Options\n * @property {*}       [turnPolicy]   - how to resolve ambiguities in path decomposition (default Potrace.TURNPOLICY_MINORITY)\n * @property {Number}  [turdSize]     - suppress speckles of up to this size (default 2)\n * @property {Number}  [alphaMax]     - corner threshold parameter (default 1)\n * @property {Boolean} [optCurve]     - curve optimization (default true)\n * @property {Number}  [optTolerance] - curve optimization tolerance (default 0.2)\n * @property {Number}  [threshold]    - threshold below which color is considered black (0..255, default Potrace.THRESHOLD_AUTO)\n * @property {Boolean} [blackOnWhite] - specifies colors by which side from threshold should be traced (default true)\n * @property {string}  [color]        - foreground color (default: 'auto' (black or white)) Will be ignored when exporting as <symbol>\n * @property {string}  [background]   - background color (default: 'transparent') Will be ignored when exporting as <symbol>\n */\n\n/**\n * Jimp module\n * @external Jimp\n * @see https://www.npmjs.com/package/jimp\n */"
  },
  {
    "path": "lib/index.js",
    "content": "'use strict';\n\nvar Potrace = require('./Potrace');\nvar Posterizer = require('./Posterizer');\n\n/**\n * Wrapper for Potrace that simplifies use down to one function call\n *\n * @param {string|Buffer|Jimp} file Source image, file path or {@link Jimp} instance\n * @param {Potrace~Options} [options]\n * @param {traceCallback} cb Callback function. Accepts 3 arguments: error, svg content and instance of {@link Potrace} (so it could be reused with different set of parameters)\n */\nfunction trace(file, options, cb) {\n  if (arguments.length === 2) {\n    cb = options;\n    options = {};\n  }\n\n  var potrace = new Potrace(options);\n\n  potrace.loadImage(file, function(err) {\n    if (err) { return cb(err); }\n    cb(null, potrace.getSVG(), potrace);\n  });\n}\n\n/**\n * Wrapper for Potrace that simplifies use down to one function call\n *\n * @param {string|Buffer|Jimp} file Source image, file path or {@link Jimp} instance\n * @param {Posterizer~Options} [options]\n * @param {posterizeCallback} cb Callback function. Accepts 3 arguments: error, svg content and instance of {@link Potrace} (so it could be reused with different set of parameters)\n */\nfunction posterize(file, options, cb) {\n  if (arguments.length === 2) {\n    cb = options;\n    options = {};\n  }\n\n  var posterizer = new Posterizer(options);\n\n  posterizer.loadImage(file, function(err) {\n    if (err) { return cb(err); }\n    cb(null, posterizer.getSVG(), posterizer);\n  });\n}\n\nmodule.exports = {\n  trace: trace,\n  posterize: posterize,\n  Potrace: Potrace,\n  Posterizer: Posterizer\n};\n\n/**\n * Callback for trace method\n * @callback traceCallback\n * @param {Error|null} err\n * @param {string} svg SVG document contents\n * @param {Potrace} [instance] Potrace class instance\n */\n\n/**\n * Callback for posterize method\n * @callback posterizeCallback\n * @param {Error|null} err\n * @param {string} svg SVG document contents\n * @param {Posterizer} [instance] Posterizer class instance\n */"
  },
  {
    "path": "lib/types/Bitmap.js",
    "content": "'use strict';\n\nvar Point = require('./Point');\nvar utils = require('../utils');\nvar Histogram;\n\n/**\n * Represents a bitmap where each pixel can be a number in range of 0..255\n * Used internally to store luminance data.\n *\n * @param {Number} w\n * @param {Number} h\n * @constructor\n */\nfunction Bitmap(w, h) {\n  this._histogram = null;\n\n  this.width = w;\n  this.height = h;\n  this.size = w * h;\n  this.arrayBuffer = new ArrayBuffer(this.size);\n  this.data = new Uint8Array(this.arrayBuffer);\n}\n\nmodule.exports = Bitmap;\nHistogram = require('./Histogram');\n\nBitmap.prototype = {\n  /**\n   * Returns pixel value\n   *\n   * @param {Number|Point} x - index, point or x\n   * @param {Number} [y]\n   */\n  getValueAt: function(x, y) {\n    var index = (typeof x === 'number' && typeof y !== 'number') ? x : this.pointToIndex(x, y);\n    return this.data[index];\n  },\n\n  /**\n   * Converts {@link Point} to index value\n   *\n   * @param {Number} index\n   * @returns {Point}\n   */\n  indexToPoint: function(index) {\n    var point = new Point();\n\n\t  if (utils.between(index, 0, this.size)) {\n      point.y = Math.floor(index / this.width);\n      point.x = index - point.y * this.width;\n    } else {\n      point.x = -1;\n      point.y = -1;\n    }\n\n    return point;\n  },\n\n  /**\n   * Calculates index for point or coordinate pair\n   *\n   * @param {Number|Point} pointOrX\n   * @param {Number} [y]\n   * @returns {Number}\n   */\n  pointToIndex: function(pointOrX, y) {\n    var _x = pointOrX,\n        _y = y;\n\n    if (pointOrX instanceof Point) {\n      _x = pointOrX.x;\n      _y = pointOrX.y;\n    }\n\n    if (!utils.between(_x, 0, this.width) || !utils.between(_y, 0, this.height)) {\n      return -1;\n    }\n\n    return this.width * _y + _x;\n  },\n\n  /**\n   * Makes a copy of current bitmap\n   *\n   * @param {Function} [iterator] optional callback, used for processing pixel value. Accepted arguments: value, index\n   * @returns {Bitmap}\n   */\n  copy: function(iterator) {\n    var bm = new Bitmap(this.width, this.height),\n        iteratorPresent = typeof iterator === 'function',\n        i;\n\n    for (i = 0; i < this.size; i++) {\n      bm.data[i] = iteratorPresent ? iterator(this.data[i], i) : this.data[i];\n    }\n\n    return bm;\n  },\n\n  histogram: function() {\n    var Histogram = require('./Histogram');\n\n    if (this._histogram) {\n      return this._histogram;\n    }\n\n    this._histogram = new Histogram(this);\n    return this._histogram;\n  }\n};"
  },
  {
    "path": "lib/types/Curve.js",
    "content": "'use strict';\n\n/**\n * Curve type\n *\n * @param n\n * @constructor\n * @protected\n */\nfunction Curve(n) {\n  this.n = n;\n  this.tag = new Array(n);\n  this.c = new Array(n * 3);\n  this.alphaCurve = 0;\n  this.vertex = new Array(n);\n  this.alpha = new Array(n);\n  this.alpha0 = new Array(n);\n  this.beta = new Array(n);\n}\n\nmodule.exports = Curve;"
  },
  {
    "path": "lib/types/Histogram.js",
    "content": "\"use strict\";\n\n// Histogram\n\nvar utils = require('../utils');\nvar Jimp = null; try { Jimp = require('jimp'); } catch(e) {}\nvar Bitmap = require('./Bitmap');\n\nvar COLOR_DEPTH = 256;\nvar COLOR_RANGE_END = COLOR_DEPTH - 1;\n\n/**\n * Calculates array index for pair of indexes. We multiple column (x) by 256 and then add row to it,\n * this way `(index(i, j) + 1) === index(i, j + i)` thus we can reuse `index(i, j)` we once calculated\n *\n * Note: this is different from how indexes calculated in {@link Bitmap} class, keep it in mind.\n *\n * @param x\n * @param y\n * @returns {*}\n * @private\n */\nfunction index(x, y) {\n  return COLOR_DEPTH * x + y;\n}\n\nfunction normalizeMinMax(levelMin, levelMax) {\n  /**\n   * Shared parameter normalization for methods 'multilevelThresholding', 'autoThreshold', 'getDominantColor' and 'getStats'\n   *\n   * @param levelMin\n   * @param levelMax\n   * @returns {number[]}\n   * @private\n   */\n  levelMin = typeof levelMin === 'number' ? utils.clamp(Math.round(levelMin), 0, COLOR_RANGE_END) : 0;\n  levelMax = typeof levelMax === 'number' ? utils.clamp(Math.round(levelMax), 0, COLOR_RANGE_END) : COLOR_RANGE_END;\n\n  if (levelMin > levelMax) {\n    throw new Error('Invalid range \"'+ levelMin + '...' + levelMax + '\"');\n  }\n\n  return [levelMin, levelMax];\n}\n\n/**\n * 1D Histogram\n *\n * @param {Number|Bitmap|Jimp} imageSource - Image to collect pixel data from. Or integer to create empty histogram for image of specific size\n * @param [mode] Used only for Jimp images. {@link Bitmap} currently can only store 256 values per pixel, so it's assumed that it contains values we are looking for\n * @constructor\n * @protected\n */\nfunction Histogram(imageSource, mode) {\n  this.data = null;\n  this.pixels = 0;\n  this._sortedIndexes = null;\n  this._cachedStats = {};\n  this._lookupTableH = null;\n\n  if (typeof imageSource === 'number') {\n    this._createArray(imageSource);\n  } else if (imageSource instanceof Bitmap) {\n    this._collectValuesBitmap(imageSource);\n  } else if (Jimp && imageSource instanceof Jimp) {\n    this._collectValuesJimp(imageSource, mode);\n  } else {\n    throw new Error('Unsupported image source');\n  }\n}\n\nHistogram.MODE_LUMINANCE = 'luminance';\nHistogram.MODE_R = 'r';\nHistogram.MODE_G = 'g';\nHistogram.MODE_B = 'b';\n\nHistogram.prototype = {\n  /**\n   * Initializes data array for an image of given pixel size\n   * @param imageSize\n   * @returns {Uint8Array|Uint16Array|Uint32Array}\n   * @private\n   */\n  _createArray: function(imageSize) {\n    var ArrayType = imageSize <= Math.pow(2, 8) ? Uint8Array\n      : imageSize <= Math.pow(2, 16) ? Uint16Array : Uint32Array;\n\n    this.pixels = imageSize;\n    \n    return this.data = new ArrayType(COLOR_DEPTH);\n  },\n\n  /**\n   * Aggregates color data from {@link Jimp} instance\n   * @param {Jimp} source\n   * @param mode\n   * @private\n   */\n  _collectValuesJimp: function(source, mode) {\n    var pixelData = source.bitmap.data;\n    var data = this._createArray(source.bitmap.width * source.bitmap.height);\n\n    source.scan(0, 0, source.bitmap.width, source.bitmap.height, function(x, y, idx) {\n      var val = mode === Histogram.MODE_R ? pixelData[idx]\n        : mode === Histogram.MODE_G ? pixelData[idx + 1]\n        : mode === Histogram.MODE_B ? pixelData[idx + 2]\n        : utils.luminance(pixelData[idx], pixelData[idx + 1], pixelData[idx + 2]);\n\n      data[val]++;\n    });\n  },\n\n  /**\n   * Aggregates color data from {@link Bitmap} instance\n   * @param {Bitmap} source\n   * @private\n   */\n  _collectValuesBitmap: function(source) {\n    var data = this._createArray(source.size);\n    var len = source.data.length;\n    var color;\n\n    for (var i = 0; i < len; i++) {\n      color = source.data[i];\n      data[color]++\n    }\n  },\n\n  /**\n   * Returns array of color indexes in ascending order\n   * @param refresh\n   * @returns {*}\n   * @private\n   */\n  _getSortedIndexes: function(refresh) {\n    if (!refresh && this._sortedIndexes) {\n      return this._sortedIndexes;\n    }\n\n    var data = this.data;\n    var indexes = new Array(COLOR_DEPTH);\n    var i = 0;\n\n    for (i; i < COLOR_DEPTH; i++) {\n      indexes[i] = i;\n    }\n\n    indexes.sort(function(a, b) {\n      return data[a] > data[b] ? 1 : data[a] < data[b] ? -1 : 0;\n    });\n\n    this._sortedIndexes = indexes;\n    return indexes;\n  },\n\n  /**\n   * Builds lookup table H from lookup tables P and S.\n   * see {@link http://www.iis.sinica.edu.tw/page/jise/2001/200109_01.pdf|this paper} for more details\n   *\n   * @returns {Float64Array}\n   * @private\n   */\n  _thresholdingBuildLookupTable: function() {\n    var P = new Float64Array(COLOR_DEPTH * COLOR_DEPTH);\n    var S = new Float64Array(COLOR_DEPTH * COLOR_DEPTH);\n    var H = new Float64Array(COLOR_DEPTH * COLOR_DEPTH);\n    var pixelsTotal = this.pixels;\n    var i, j, idx, tmp;\n\n    // diagonal\n    for (i = 1; i < COLOR_DEPTH; ++i) {\n      idx = index(i, i);\n      tmp = this.data[i] / pixelsTotal;\n\n      P[idx] = tmp;\n      S[idx] = i * tmp;\n    }\n\n    // calculate first row (row 0 is all zero)\n    for (i = 1; i < COLOR_DEPTH - 1; ++i) {\n      tmp = this.data[i + 1] / pixelsTotal;\n      idx = index(1, i);\n\n      P[idx+1] = P[idx] + tmp;\n      S[idx+1] = S[idx] + (i + 1) * tmp;\n    }\n\n    // using row 1 to calculate others\n    for (i = 2; i < COLOR_DEPTH; i++) {\n      for (j=i+1; j < COLOR_DEPTH; j++) {\n        P[index(i, j)] = P[index(1, j)] - P[index(1, i-1)];\n        S[index(i, j)] = S[index(1, j)] - S[index(1, i-1)];\n      }\n    }\n\n    // now calculate H[i][j]\n    for (i = 1; i < COLOR_DEPTH; ++i) {\n      for (j = i + 1; j < COLOR_DEPTH; j++) {\n        idx = index(i, j);\n        H[idx] = P[idx] !== 0 ? S[idx] * S[idx] / P[idx] : 0;\n      }\n    }\n    \n    return this._lookupTableH = H;\n  },\n\n  /**\n   * Implements Algorithm For Multilevel Thresholding\n   * Receives desired number of color stops, returns array of said size. Could be limited to a range levelMin..levelMax\n   *\n   * Regardless of levelMin and levelMax values it still relies on between class variances for the entire histogram\n   *\n   * @param amount - how many thresholds should be calculated\n   * @param [levelMin=0] - histogram segment start\n   * @param [levelMax=255] - histogram segment end\n   * @returns {number[]}\n\t */\n  multilevelThresholding: function (amount, levelMin, levelMax) {\n    levelMin = normalizeMinMax(levelMin, levelMax);\n    levelMax = levelMin[1];\n    levelMin = levelMin[0];\n    amount = Math.min(levelMax - levelMin - 2, ~~amount);\n\n    if (amount < 1) {\n      return [];\n    }\n\n    if (!this._lookupTableH) {\n      this._thresholdingBuildLookupTable();\n    }\n\n    var H = this._lookupTableH;\n    \n    var colorStops = null;\n    var maxSig = 0;\n\n    if (amount > 4) {\n      console.log('[Warning]: Threshold computation for more than 5 levels may take a long time');\n    }\n\n    function iterateRecursive (startingPoint, prevVariance, indexes, previousDepth) {\n      startingPoint = (startingPoint || 0) + 1;\n      prevVariance = prevVariance || 0;\n      indexes = indexes || (new Array(amount));\n      previousDepth = previousDepth || 0;\n\n      var depth = previousDepth + 1; // t\n      var variance;\n\n      for (var i = startingPoint; i < levelMax - amount + previousDepth; i++) {\n        variance = prevVariance + H[index(startingPoint, i)];\n        indexes[depth - 1] = i;\n\n\t      if (depth + 1 < amount + 1) {\n          // we need to go deeper\n          iterateRecursive(i, variance, indexes, depth);\n        } else {\n          // enough, we can compare values now\n          variance += H[index(i + 1, levelMax)];\n\n          if (maxSig < variance) {\n            maxSig = variance;\n            colorStops = indexes.slice();\n          }\n        }\n      }\n    }\n\n    iterateRecursive(levelMin || 0);\n\n    return colorStops ? colorStops : [];\n  },\n\n  /**\n   * Automatically finds threshold value using Algorithm For Multilevel Thresholding\n   *\n   * @param {number} [levelMin]\n   * @param {number} [levelMax]\n   * @returns {null|number}\n   */\n  autoThreshold: function(levelMin, levelMax) {\n    var value = this.multilevelThresholding(1, levelMin, levelMax);\n    return value.length ? value[0] : null;\n  },\n\n  /**\n   * Returns dominant color in given range. Returns -1 if not a single color from the range present on the image\n   *\n   * @param [levelMin=0]\n   * @param [levelMax=255]\n   * @param [tolerance=1]\n   * @returns {number}\n   */\n  getDominantColor: function(levelMin, levelMax, tolerance) {\n    levelMin = normalizeMinMax(levelMin, levelMax);\n    levelMax = levelMin[1];\n    levelMin = levelMin[0];\n    tolerance = tolerance || 1;\n\n    var colors = this.data,\n        dominantIndex = -1,\n        dominantValue = -1,\n        i, j, tmp;\n\n    if (levelMin === levelMax) {\n      return colors[levelMin] ? levelMin : -1;\n    }\n\n    for (i=levelMin; i <= levelMax; i++) {\n      tmp = 0;\n\n      for (j = ~~(tolerance / -2); j < tolerance; j++) {\n        tmp += utils.between(i + j, 0, COLOR_RANGE_END) ? colors[i + j] : 0;\n      }\n\n      var summIsBigger = tmp > dominantValue;\n      var summEqualButMainColorIsBigger = dominantValue === tmp && (dominantIndex < 0 || colors[i] > colors[dominantIndex]);\n\n      if (summIsBigger || summEqualButMainColorIsBigger) {\n        dominantIndex = i;\n        dominantValue = tmp;\n      }\n    }\n\n    return dominantValue <= 0 ? -1 : dominantIndex;\n  },\n\n  /**\n   * Returns stats for histogram or its segment.\n   *\n   * Returned object contains median, mean and standard deviation for pixel values;\n   * peak, mean and median number of pixels per level and few other values\n   *\n   * If no pixels colors from specified range present on the image - most values will be NaN\n   *\n   * @param {Number} [levelMin=0] - histogram segment start\n   * @param {Number} [levelMax=255] - histogram segment end\n   * @param {Boolean} [refresh=false] - if cached result can be returned\n   * @returns {{levels: {mean: (number|*), median: *, stdDev: number, unique: number}, pixelsPerLevel: {mean: (number|*), median: (number|*), peak: number}, pixels: number}}\n   */\n  getStats: function(levelMin, levelMax, refresh) {\n    levelMin = normalizeMinMax(levelMin, levelMax);\n    levelMax = levelMin[1];\n    levelMin = levelMin[0];\n\n    if (!refresh && this._cachedStats[levelMin + '-' + levelMax]) {\n      return this._cachedStats[levelMin + '-' + levelMax];\n    }\n\n    var data = this.data;\n    var sortedIndexes = this._getSortedIndexes();\n\n    var pixelsTotal = 0;\n    var medianValue = null;\n    var meanValue;\n    var medianPixelIndex;\n    var pixelsPerLevelMean;\n    var pixelsPerLevelMedian;\n    var tmpSumOfDeviations = 0;\n    var tmpPixelsIterated = 0;\n    var allPixelValuesCombined = 0;\n    var i, tmpPixels, tmpPixelValue;\n\n    var uniqueValues = 0; // counter for levels that's represented by at least one pixel\n    var mostPixelsPerLevel = 0;\n\n    // Finding number of pixels and mean\n\n    for (i = levelMin; i <= levelMax; i++) {\n      pixelsTotal += data[i];\n      allPixelValuesCombined += data[i] * i;\n\n      uniqueValues += data[i] === 0 ? 0 : 1;\n\n      if (mostPixelsPerLevel < data[i]) {\n        mostPixelsPerLevel = data[i];\n      }\n    }\n\n    meanValue = allPixelValuesCombined / pixelsTotal;\n    pixelsPerLevelMean = pixelsTotal / (levelMax - levelMin);\n    pixelsPerLevelMedian = pixelsTotal / uniqueValues;\n    medianPixelIndex = Math.floor(pixelsTotal / 2);\n\n    // Finding median and standard deviation\n\n    for (i = 0; i < COLOR_DEPTH; i++) {\n      tmpPixelValue = sortedIndexes[i];\n      tmpPixels = data[tmpPixelValue];\n\n      if (tmpPixelValue < levelMin || tmpPixelValue > levelMax) {\n        continue;\n      }\n\n      tmpPixelsIterated += tmpPixels;\n      tmpSumOfDeviations += Math.pow(tmpPixelValue - meanValue, 2) * tmpPixels;\n\n      if (medianValue === null && tmpPixelsIterated >= medianPixelIndex) {\n        medianValue = tmpPixelValue;\n      }\n    }\n\n    return this._cachedStats[levelMin + '-' + levelMax] = {\n      // various pixel counts for levels (0..255)\n\n      levels: {\n        mean: meanValue,\n        median: medianValue,\n        stdDev: Math.sqrt(tmpSumOfDeviations / pixelsTotal),\n        unique: uniqueValues\n      },\n\n      // what's visually represented as bars\n      pixelsPerLevel: {\n        mean: pixelsPerLevelMean,\n        median: pixelsPerLevelMedian,\n        peak: mostPixelsPerLevel\n      },\n\n      pixels: pixelsTotal\n    };\n  }\n};\n\nmodule.exports = Histogram;"
  },
  {
    "path": "lib/types/Opti.js",
    "content": "'use strict';\n\nvar Point = require('./Point');\n\nfunction Opti() {\n  this.pen = 0;\n  this.c = [new Point(), new Point()];\n  this.t = 0;\n  this.s = 0;\n  this.alpha = 0;\n}\n\nmodule.exports = Opti;"
  },
  {
    "path": "lib/types/Path.js",
    "content": "'use strict';\n\nfunction Path() {\n  this.area = 0;\n  this.len = 0;\n  this.curve = {};\n  this.pt = [];\n  this.minX = 100000;\n  this.minY = 100000;\n  this.maxX = -1;\n  this.maxY = -1;\n}\n\nmodule.exports = Path;"
  },
  {
    "path": "lib/types/Point.js",
    "content": "'use strict';\n\nfunction Point(x, y) {\n  this.x = x || 0;\n  this.y = y || 0;\n}\n\nPoint.prototype = {\n  copy: function() {\n    return new Point(this.x, this.y);\n  }\n};\n\nmodule.exports = Point;"
  },
  {
    "path": "lib/types/Quad.js",
    "content": "'use strict';\n\nfunction Quad() {\n  this.data = [0,0,0,0,0,0,0,0,0];\n}\n\nQuad.prototype.at = function(x, y) {\n  return this.data[x * 3 + y];\n};\n\nmodule.exports = Quad;"
  },
  {
    "path": "lib/types/Sum.js",
    "content": "'use strict';\n\nfunction Sum(x, y, xy, x2, y2) {\n  this.x = x;\n  this.y = y;\n  this.xy = xy;\n  this.x2 = x2;\n  this.y2 = y2;\n}\n\nmodule.exports = Sum;"
  },
  {
    "path": "lib/utils.js",
    "content": "'use strict';\n\nvar Point = require('./types/Point');\nvar attrRegexps = {};\n\nfunction getAttrRegexp(attrName) {\n  if (attrRegexps[attrName]) {\n    return attrRegexps[attrName];\n  }\n\n  attrRegexps[attrName] = new RegExp(' ' + attrName + '=\"((?:\\\\\\\\(?=\")\"|[^\"])+)\"', 'i');\n  return attrRegexps[attrName];\n}\n\nfunction setHtmlAttribute(html, attrName, value) {\n  var attr = ' ' + attrName + '=\"' + value + '\"';\n\n  if (html.indexOf(' ' + attrName + '=\"') === -1) {\n    html = html.replace(/<[a-z]+/i, function(beginning) { return beginning + attr; });\n  } else {\n    html = html.replace(getAttrRegexp(attrName), attr);\n  }\n\n  return html;\n}\n\nfunction fixed(number) {\n  return number.toFixed(3).replace('.000', '');\n}\n\nfunction mod(a, n) {\n  return a >= n ? a % n : a>=0 ? a : n-1-(-1-a) % n;\n}\n\nfunction xprod(p1, p2) {\n  return p1.x * p2.y - p1.y * p2.x;\n}\n\nfunction cyclic(a, b, c) {\n  if (a <= c) {\n    return (a <= b && b < c);\n  } else {\n    return (a <= b || b < c);\n  }\n}\n\nfunction sign(i) {\n  return i > 0 ? 1 : i < 0 ? -1 : 0;\n}\n\nfunction quadform(Q, w) {\n  var v = new Array(3), i, j, sum;\n\n  v[0] = w.x;\n  v[1] = w.y;\n  v[2] = 1;\n  sum = 0.0;\n\n  for (i=0; i<3; i++) {\n    for (j=0; j<3; j++) {\n      sum += v[i] * Q.at(i, j) * v[j];\n    }\n  }\n  return sum;\n}\n\nfunction interval(lambda, a, b) {\n  var res = new Point();\n\n  res.x = a.x + lambda * (b.x - a.x);\n  res.y = a.y + lambda * (b.y - a.y);\n  return res;\n}\n\nfunction dorth_infty(p0, p2) {\n  var r = new Point();\n\n  r.y = sign(p2.x - p0.x);\n  r.x = -sign(p2.y - p0.y);\n\n  return r;\n}\n\nfunction ddenom(p0, p2) {\n  var r = dorth_infty(p0, p2);\n\n  return r.y * (p2.x - p0.x) - r.x * (p2.y - p0.y);\n}\n\nfunction dpara(p0, p1, p2) {\n  var x1, y1, x2, y2;\n\n  x1 = p1.x - p0.x;\n  y1 = p1.y - p0.y;\n  x2 = p2.x - p0.x;\n  y2 = p2.y - p0.y;\n\n  return x1 * y2 - x2 * y1;\n}\n\nfunction cprod(p0, p1, p2, p3) {\n  var x1, y1, x2, y2;\n\n  x1 = p1.x - p0.x;\n  y1 = p1.y - p0.y;\n  x2 = p3.x - p2.x;\n  y2 = p3.y - p2.y;\n\n  return x1 * y2 - x2 * y1;\n}\n\nfunction iprod(p0, p1, p2) {\n  var x1, y1, x2, y2;\n\n  x1 = p1.x - p0.x;\n  y1 = p1.y - p0.y;\n  x2 = p2.x - p0.x;\n  y2 = p2.y - p0.y;\n\n  return x1*x2 + y1*y2;\n}\n\nfunction iprod1(p0, p1, p2, p3) {\n  var x1, y1, x2, y2;\n\n  x1 = p1.x - p0.x;\n  y1 = p1.y - p0.y;\n  x2 = p3.x - p2.x;\n  y2 = p3.y - p2.y;\n\n  return x1 * x2 + y1 * y2;\n}\n\nfunction ddist(p, q) {\n  return Math.sqrt((p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y));\n}\n\nmodule.exports = {\n  luminance: function (r, g, b) {\n    return Math.round(0.2126 * r + 0.7153 * g + 0.0721 * b);\n  },\n\n  between: function(val, min, max) {\n    return val >= min && val <= max;\n  },\n\n  clamp: function(val, min, max) {\n    return Math.min(max, Math.max(min, val));\n  },\n  \n  isNumber: function(val) {\n    return typeof val === 'number';\n  },\n\n  setHtmlAttr: setHtmlAttribute,\n\n  /**\n   * Generates path instructions for given curve\n   *\n   * @param {Curve} curve\n   * @param {Number} [scale]\n   * @returns {string}\n   */\n  renderCurve: function(curve, scale) {\n    scale = scale || 1;\n\n    var startingPoint = curve.c[(curve.n - 1) * 3 + 2];\n\n    var path = 'M '\n      + fixed(startingPoint.x * scale) + ' '\n      + fixed(startingPoint.y * scale) + ' ';\n\n    curve.tag.forEach(function(tag, i) {\n      var i3 = i * 3;\n      var p0 = curve.c[i3];\n      var p1 = curve.c[i3 + 1];\n      var p2 = curve.c[i3 + 2];\n\n      if (tag === \"CURVE\") {\n        path += 'C ';\n        path += fixed(p0.x * scale) + ' ' + fixed(p0.y * scale) + ', ';\n        path += fixed(p1.x * scale) + ' ' + fixed(p1.y * scale) + ', ';\n        path += fixed(p2.x * scale) + ' ' + fixed(p2.y * scale) + ' ';\n      } else if (tag === \"CORNER\") {\n        path += 'L ';\n        path += fixed(p1.x * scale) + ' ' + fixed(p1.y * scale) + ' ';\n        path += fixed(p2.x * scale) + ' ' + fixed(p2.y * scale) + ' ';\n      }\n    });\n\n    return path;\n  },\n  \n  bezier: function bezier(t, p0, p1, p2, p3) {\n    var s = 1 - t, res = new Point();\n\n    res.x = s*s*s*p0.x + 3*(s*s*t)*p1.x + 3*(t*t*s)*p2.x + t*t*t*p3.x;\n    res.y = s*s*s*p0.y + 3*(s*s*t)*p1.y + 3*(t*t*s)*p2.y + t*t*t*p3.y;\n\n    return res;\n  },\n\n  tangent: function tangent(p0, p1, p2, p3, q0, q1) {\n    var A, B, C, a, b, c, d, s, r1, r2;\n\n    A = cprod(p0, p1, q0, q1);\n    B = cprod(p1, p2, q0, q1);\n    C = cprod(p2, p3, q0, q1);\n\n    a = A - 2 * B + C;\n    b = -2 * A + 2 * B;\n    c = A;\n\n    d = b * b - 4 * a * c;\n\n    if (a===0 || d<0) {\n      return -1.0;\n    }\n\n    s = Math.sqrt(d);\n\n    r1 = (-b + s) / (2 * a);\n    r2 = (-b - s) / (2 * a);\n\n    if (r1 >= 0 && r1 <= 1) {\n      return r1;\n    } else if (r2 >= 0 && r2 <= 1) {\n      return r2;\n    } else {\n      return -1.0;\n    }\n  },\n\n  mod: mod,\n  xprod: xprod,\n  cyclic: cyclic,\n  sign: sign,\n  quadform: quadform,\n  interval: interval,\n  dorth_infty: dorth_infty,\n  ddenom: ddenom,\n  dpara: dpara,\n  cprod: cprod,\n  iprod: iprod,\n  iprod1: iprod1,\n  ddist: ddist\n};"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"potrace\",\n  \"version\": \"2.1.2\",\n  \"description\": \"Potrace in Javascript, for NodeJS\",\n  \"main\": \"lib/index.js\",\n  \"scripts\": {\n    \"test\": \"cd test && mocha test.js --reporter spec\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/tooolbox/node-potrace.git\"\n  },\n  \"keywords\": [\n    \"potrace\",\n    \"trace\",\n    \"tracing\",\n    \"svg\",\n    \"bitmap\",\n    \"posterization\"\n  ],\n  \"author\": \"mattmc\",\n  \"license\": \"GPL-2.0\",\n  \"bugs\": {\n    \"url\": \"https://github.com/tooolbox/node-potrace/issues\"\n  },\n  \"homepage\": \"https://github.com/tooolbox/node-potrace#readme\",\n  \"dependencies\": {\n    \"jimp\": \"^0.6.4\"\n  },\n  \"devDependencies\": {\n    \"lodash\": \"^4.15.0\",\n    \"mocha\": \"^3.0.2\",\n    \"should\": \"^11.1.0\",\n    \"should-sinon\": \"0.0.5\",\n    \"sinon\": \"^1.17.5\"\n  }\n}\n"
  },
  {
    "path": "test/test.js",
    "content": "'use strict';\n\nvar _ = require('lodash'),\n    assert = require('assert'),\n    should = require('should'),\n    sinon = require('sinon');\n\nrequire('should-sinon');\n\nvar fs = require('fs'),\n    Jimp = require('jimp'),\n    Potrace = require('../lib/Potrace'),\n    Posterizer = require('../lib/Posterizer'),\n    Histogram = require('../lib/types/Histogram'),\n    lib = require('../lib/index');\n\nvar PATH_TO_YAO = './sources/yao.jpg';\nvar PATH_TO_LENNA = './sources/Lenna.png';\nvar PATH_TO_BLACK_AND_WHITE_IMAGE = './sources/clouds.jpg';\n\nvar blackImage = new Jimp(100, 100, 0x000000FF);\nvar whiteImage = new Jimp(100, 100, 0xFFFFFFFF);\n\ndescribe('Histogram class (private, responsible for auto thresholding)', function() {\n  var histogram = null;\n\n  var blackHistogram = new Histogram(blackImage, Histogram.MODE_LUMINANCE);\n  var whiteHistogram = new Histogram(whiteImage, Histogram.MODE_LUMINANCE);\n\n  before(function(done) {\n    this.timeout(10000);\n\n    Jimp.read(PATH_TO_LENNA, function(err, img) {\n      if (err) throw err;\n      histogram = new Histogram(img, Histogram.MODE_LUMINANCE);\n      done();\n    });\n  });\n\n  describe('#getDominantColor', function() {\n    it('gives different results with different tolerance values', function() {\n      assert.equal(histogram.getDominantColor(0, 255), 149);\n      assert.equal(histogram.getDominantColor(0, 255, 10), 143);\n    });\n\n    it('has default argument values of 0, 255 and 1', function() {\n      assert.equal(histogram.getDominantColor(), histogram.getDominantColor(0, 255, 1));\n    });\n\n    it('works for a segment of histogram', function() {\n      assert.equal(41, histogram.getDominantColor(20, 80));\n    });\n\n    it('does not fail when min and max values are the same', function() {\n      assert.equal(histogram.getDominantColor(42, 42), 42);\n    });\n\n    it('returns -1 if colors from the range are not present on image', function() {\n      assert.equal(histogram.getDominantColor(0, 15), -1);\n      assert.equal(histogram.getDominantColor(7, 7, 1), -1);\n    });\n\n    it('throws error if range start is larger than range end', function() {\n      (function() {\n        histogram.getDominantColor(80, 20);\n      }).should.throw();\n    });\n\n    it('behaves predictably in edge cases', function() {\n      blackHistogram.getDominantColor(0, 255).should.be.equal(0);\n      whiteHistogram.getDominantColor(0, 255).should.be.equal(255);\n      whiteHistogram.getDominantColor(25, 235).should.be.equal(-1);\n\n      // Tolerance should not affect returned value\n\n      blackHistogram.getDominantColor(0, 255, 15).should.be.equal(0);\n      whiteHistogram.getDominantColor(0, 255, 15).should.be.equal(255);\n    })\n  });\n\n  describe('#getStats', function() {\n    function toFixedDeep(stats, fractionalDigits) {\n      return _.cloneDeepWith(stats, function(val) {\n        if (_.isNumber(val) && !_.isInteger(val)) {\n          return parseFloat(val.toFixed(fractionalDigits));\n        }\n      });\n    }\n\n    it('produces expected stats object for entire histogram', function() {\n      var expectedValue = {\n        levels: {\n          mean: 116.7673568725586,\n          median: 95,\n          stdDev: 49.42205692905339,\n          unique: 222\n        },\n        pixelsPerLevel: {\n          mean: 1028.0156862745098,\n          median: 1180.8288288288288,\n          peak: 2495\n        },\n        pixels: 262144\n      };\n\n      assert.deepEqual(\n        toFixedDeep(histogram.getStats(), 4),\n        toFixedDeep(expectedValue, 4)\n      );\n    });\n\n    it('produces expected stats object for histogram segment', function() {\n      var expectedValue = {\n        levels: {\n          mean: 121.89677761754915,\n          median: 93,\n          stdDev: 30.2466970087377,\n          unique: 121\n        },\n        pixelsPerLevel: {\n          mean: 1554.4916666666666,\n          median: 1541.6446280991736,\n          peak: 2495\n        },\n        pixels: 186539\n      };\n\n      assert.deepEqual(\n        toFixedDeep(histogram.getStats(60, 180), 4),\n        toFixedDeep(expectedValue, 4)\n      );\n    });\n\n    it('throws error if range start is larger than range end', function() {\n      (function() {\n        histogram.getStats(255, 123);\n      }).should.throw();\n    });\n\n    it('behaves predictably in edge cases', function() {\n      var blackImageStats = blackHistogram.getStats();\n      var whiteImageStats = blackHistogram.getStats();\n\n      blackImageStats.levels.mean.should.be.equal(blackImageStats.levels.median);\n      whiteImageStats.levels.mean.should.be.equal(whiteImageStats.levels.median);\n\n      blackHistogram.getStats(25, 235).should.be.deepEqual(whiteHistogram.getStats(25, 235));\n    });\n  });\n\n  describe('#multilevelThresholding', function() {\n    it('calculates correct thresholds', function() {\n      assert.deepEqual(histogram.multilevelThresholding(1), [111]);\n      assert.deepEqual(histogram.multilevelThresholding(2), [ 92, 154 ]);\n      assert.deepEqual(histogram.multilevelThresholding(3), [ 73, 121, 168 ]);\n    });\n\n    it('works for histogram segment', function() {\n      assert.deepEqual(histogram.multilevelThresholding(2, 60, 180), [ 103, 138 ]);\n    });\n\n    it('calculates as many thresholds as can be fit in given range', function() {\n      assert.deepEqual(histogram.multilevelThresholding(2, 102, 106), [ 103, 104 ]);\n      assert.deepEqual(histogram.multilevelThresholding(2, 103, 106), [ 104 ]);\n    });\n\n    it('returns empty array if no colors from histogram segment is present on the image', function() {\n      assert.deepEqual(histogram.multilevelThresholding(3, 2, 14), []);\n    });\n\n    it('throws error if range start is larger than range end', function() {\n      (function() {\n        histogram.multilevelThresholding(2, 180, 60);\n      }).should.throw();\n    });\n\n  });\n});\n\ndescribe('Potrace class', function() {\n  var jimpInstance = null;\n\n  this.timeout(10000);\n\n  before(function(done) {\n    Jimp.read(PATH_TO_YAO, function(err, img) {\n      if (err) {\n        return done(err);\n      }\n\n      jimpInstance = img;\n      done();\n    });\n  });\n\n  describe('#loadImage', function() {\n    it('instance is being passed to callback function as context', function(done) {\n      var instance = new Potrace();\n\n      instance.loadImage(PATH_TO_YAO, function(err) {\n        this.should.be.an.instanceOf(Potrace).and.be.equal(instance);\n        done(err);\n      });\n    });\n\n    it('supports Jimp instances provided as source image', function(done) {\n      var instance = new Potrace();\n\n      instance.loadImage(jimpInstance, done);\n    });\n\n    it('should throw error if called before previous image was loaded', function(done) {\n      function onImageLoad() {\n        if (firstFinished && secondFinished) {\n          done();\n        }\n      }\n\n      var potraceInstance = new Potrace();\n      var firstFinished = false;\n      var secondFinished = false;\n\n      potraceInstance.loadImage(PATH_TO_LENNA, function(err) {\n        firstFinished = true;\n        should(function() { should.ifError(err); }).throw(/another.*instead/i);\n        onImageLoad();\n      });\n\n      potraceInstance.loadImage(PATH_TO_YAO, function(err) {\n        secondFinished = true;\n        should(function() { should.ifError(err); }).not.throw();\n        onImageLoad();\n      });\n    });\n  });\n\n  describe('#_processPath', function() {\n    var instance = new Potrace();\n    var processingSpy = null;\n\n    before(function() {\n      processingSpy = instance._processPath = sinon.spy(Potrace.prototype._processPath);\n    });\n\n    it('should not execute until path is requested for the first time', function(done) {\n      instance.loadImage(jimpInstance, function() {\n        processingSpy.should.have.callCount(0);\n        this.getSVG();\n        processingSpy.should.have.callCount(1);\n        done();\n      });\n    });\n\n    it('should not execute on repetitive SVG/Symbol export', function() {\n      instance.loadImage(jimpInstance, function() {\n        var initialCallCount = processingSpy.callCount;\n\n        this.getSVG();\n        this.getSVG();\n        this.getPathTag();\n        this.getPathTag('red');\n        this.getSymbol('symbol-id');\n        processingSpy.should.have.callCount(initialCallCount);\n      });\n    });\n\n    it('should not execute after change of foreground/background colors', function() {\n      instance.loadImage(jimpInstance, function() {\n        var initialCallCount = processingSpy.callCount;\n\n        this.setParameters({ color: 'red' });\n        this.getSVG();\n\n        this.setParameters({ background: 'crimson' });\n        this.getSVG();\n\n        processingSpy.should.have.callCount(initialCallCount);\n      });\n    });\n  });\n\n  describe('#getSVG', function() {\n    var instanceYao = new Potrace();\n\n    before(function(done) {\n      instanceYao.loadImage(jimpInstance, done);\n    });\n\n    it('produces expected results with different thresholds', function() {\n      var expected;\n\n      expected = fs.readFileSync('./reference-copies/potrace-bw-threshold-128.svg', { encoding: 'utf8' });\n      instanceYao.setParameters({ threshold: 128 });\n      assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 128 does not match with reference copy');\n\n      expected = fs.readFileSync('./reference-copies/potrace-bw-threshold-65.svg', { encoding: 'utf8' });\n      instanceYao.setParameters({ threshold: 65 });\n      assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 65 does not match with reference copy');\n\n      expected = fs.readFileSync('./reference-copies/potrace-bw-threshold-170.svg', { encoding: 'utf8' });\n      instanceYao.setParameters({ threshold: 170 });\n      assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 170 does not match with reference copy');\n    });\n\n    it('produces expected white on black image with threshold 170', function(done) {\n      var instance = new Potrace({\n        threshold: 128,\n        blackOnWhite: false,\n        color: 'cyan',\n        background: 'darkred'\n      });\n\n      instance.loadImage(PATH_TO_BLACK_AND_WHITE_IMAGE, function(err) {\n        if (err) return done(err);\n\n        var expected = fs.readFileSync('./reference-copies/potrace-wb-threshold-128.svg', { encoding: 'utf8' });\n        var actual = instance.getSVG();\n\n        assert.equal(actual, expected);\n        done();\n      });\n    });\n  });\n\n  describe('#getSymbol', function() {\n    var instanceYao = new Potrace();\n\n    before(function(done) {\n      instanceYao.loadImage(jimpInstance, done);\n    });\n\n    it('should not have fill color or background', function() {\n      instanceYao.setParameters({\n        color: 'red',\n        background: 'cyan'\n      });\n\n      var symbol = instanceYao.getSymbol('whatever');\n\n      symbol.should.not.match(/<rect/i);\n      symbol.should.match(/<path[^>]+(?:fill=\"\\s*\"|fill='\\s*'|)[^>]*>/i);\n    });\n  });\n\n  describe('behaves predictably in edge cases', function() {\n    var instance = new Potrace();\n\n    var bwBlackThreshold0;\n    var bwBlackThreshold255;\n    var bwWhiteThreshold0;\n    var bwWhiteThreshold255;\n    var wbWhiteThreshold0;\n    var wbWhiteThreshold255;\n    var wbBlackThreshold0;\n    var wbBlackThreshold255;\n\n    before(function() {\n      bwBlackThreshold0 = fs.readFileSync('./reference-copies/potrace-bw-black-threshold-0.svg', { encoding: 'utf8' });\n      bwBlackThreshold255 = fs.readFileSync('./reference-copies/potrace-bw-black-threshold-255.svg', { encoding: 'utf8' });\n      bwWhiteThreshold0 = fs.readFileSync('./reference-copies/potrace-bw-white-threshold-0.svg', { encoding: 'utf8' });\n      bwWhiteThreshold255 = fs.readFileSync('./reference-copies/potrace-bw-white-threshold-255.svg', { encoding: 'utf8' });\n\n      wbWhiteThreshold0 = fs.readFileSync('./reference-copies/potrace-wb-white-threshold-0.svg', { encoding: 'utf8' });\n      wbWhiteThreshold255 = fs.readFileSync('./reference-copies/potrace-wb-white-threshold-255.svg', { encoding: 'utf8' });\n      wbBlackThreshold0 = fs.readFileSync('./reference-copies/potrace-wb-black-threshold-0.svg', { encoding: 'utf8' });\n      wbBlackThreshold255 = fs.readFileSync('./reference-copies/potrace-wb-black-threshold-255.svg', { encoding: 'utf8' });\n    });\n\n    it('compares colors against threshold in the same way as original tool', function(done) {\n      instance.loadImage(blackImage, function(err) {\n        if (err) { return done(err); }\n\n        instance.setParameters({ blackOnWhite: true, threshold: 0 });\n        instance.getSVG().should.be.equal(bwBlackThreshold0);\n\n        instance.setParameters({ blackOnWhite: true, threshold: 255 });\n        instance.getSVG().should.be.equal(bwBlackThreshold255);\n\n        instance.loadImage(whiteImage, function() {\n          if (err) { return done(err); }\n\n          instance.setParameters({ blackOnWhite: true, threshold: 0 });\n          instance.getSVG().should.be.equal(bwWhiteThreshold0);\n\n          instance.setParameters({ blackOnWhite: true, threshold: 255 });\n          instance.getSVG().should.be.equal(bwWhiteThreshold255);\n\n          done();\n        });\n      });\n    });\n\n    it('acts in the same way when colors are inverted', function(done) {\n      instance.loadImage(whiteImage, function(err) {\n        if (err) { return done(err); }\n        instance.setParameters({ blackOnWhite: false, threshold: 255 });\n        instance.getSVG().should.be.equal(wbWhiteThreshold255);\n\n        instance.setParameters({ blackOnWhite: false, threshold: 0 });\n        instance.getSVG().should.be.equal(wbWhiteThreshold0);\n\n        instance.loadImage(blackImage, function() {\n          if (err) { return done(err); }\n\n          instance.setParameters({ blackOnWhite: false, threshold: 255 });\n          instance.getSVG().should.be.equal(wbBlackThreshold255);\n\n          instance.setParameters({ blackOnWhite: false, threshold: 0 });\n          instance.getSVG().should.be.equal(wbBlackThreshold0);\n\n          done();\n        });\n      });\n    });\n  });\n});\n\ndescribe('Posterizer class', function() {\n  var jimpInstance = null;\n  var sharedPosterizerInstance = new Posterizer();\n\n  this.timeout(10000);\n\n  before(function(done) {\n    Jimp.read(PATH_TO_YAO, function(err, img) {\n      if (err) {\n        return done(err);\n      }\n\n      jimpInstance = img;\n      done();\n    });\n  });\n  \n  describe('#_getRanges', function() {\n    var posterizer = new Posterizer();\n\n    function getColorStops() {\n      return posterizer._getRanges().map(function(item) {\n        return item.value;\n      });\n    }\n\n    before(function(done) {\n      posterizer.loadImage(PATH_TO_YAO, done);\n    });\n\n    it('returns correctly calculated color stops with \"equally spread\" distribution', function() {\n      posterizer.setParameters({\n        rangeDistribution: Posterizer.RANGES_EQUAL,\n        threshold: 200,\n        steps: 4,\n        blackOnWhite: true\n      });\n\n      getColorStops().should.be.deepEqual([200, 150, 100, 50]);\n\n      posterizer.setParameters({\n        rangeDistribution: Posterizer.RANGES_EQUAL,\n        threshold: 155,\n        steps: 4,\n        blackOnWhite: false\n      });\n\n      getColorStops().should.be.deepEqual([155, 180, 205, 230]);\n\n      posterizer.setParameters({\n        rangeDistribution: Posterizer.RANGES_EQUAL,\n        threshold: Potrace.THRESHOLD_AUTO,\n        steps: 4,\n        blackOnWhite: true\n      });\n\n      getColorStops().should.be.deepEqual([206, 154.5, 103, 51.5]);\n    });\n\n    it('returns correctly calculated color stops with \"auto\" distribution', function() {\n      posterizer.setParameters({\n        rangeDistribution: Posterizer.RANGES_AUTO,\n        threshold: Potrace.THRESHOLD_AUTO,\n        steps: 3,\n        blackOnWhite: true\n      });\n\n      getColorStops().should.be.deepEqual([219, 156, 71]);\n\n      posterizer.setParameters({\n        rangeDistribution: Posterizer.RANGES_AUTO,\n        threshold: Potrace.THRESHOLD_AUTO,\n        steps: 3,\n        blackOnWhite: false\n      });\n\n      getColorStops().should.be.deepEqual([71, 156, 219]);\n\n      // Now with predefined threshold\n\n      posterizer.setParameters({\n        rangeDistribution: Posterizer.RANGES_AUTO,\n        threshold: 128,\n        steps: 4,\n        blackOnWhite: true\n      });\n\n      getColorStops().should.be.deepEqual([128, 97, 62, 24]);\n\n      posterizer.setParameters({\n        rangeDistribution: Posterizer.RANGES_AUTO,\n        threshold: 128,\n        steps: 4,\n        blackOnWhite: false\n      });\n\n      getColorStops().should.be.deepEqual([128, 166, 203, 237]);\n    });\n\n    it('correctly handles predefined array of color stops', function() {\n      posterizer.setParameters({\n        steps: [20, 60, 80, 160],\n        threshold: 120,\n        blackOnWhite: true\n      });\n\n      getColorStops().should.be.deepEqual([160, 80, 60, 20]);\n\n      posterizer.setParameters({\n        steps: [20, 60, 80, 160],\n        threshold: 180,\n        blackOnWhite: true\n      });\n\n      getColorStops().should.be.deepEqual([180, 160, 80, 60, 20]);\n\n      posterizer.setParameters({\n        steps: [20, 60, 80, 160],\n        threshold: 180,\n        blackOnWhite: false\n      });\n\n      getColorStops().should.be.deepEqual([20, 60, 80, 160, 180]);\n\n      posterizer.setParameters({\n        steps: [212, 16, 26, 50, 212, 128, 211],\n        threshold: 180,\n        blackOnWhite: false\n      });\n\n      getColorStops().should.be.deepEqual([16, 26, 50, 128, 211, 212], 'Duplicated items should be present only once');\n\n      posterizer.setParameters({\n        steps: [15, 42, 200, 460, 0, -10],\n        threshold: 180,\n        blackOnWhite: false\n      });\n\n      getColorStops().should.be.deepEqual([0, 15, 42, 200], 'Values out of range should be ignored');\n    });\n  });\n\n  describe('#loadImage', function() {\n    it('instance is being passed to callback function as context', function(done) {\n      sharedPosterizerInstance.loadImage(PATH_TO_YAO, function(err) {\n        this.should.be.an.instanceOf(Posterizer).and.be.equal(sharedPosterizerInstance);\n        done(err);\n      });\n    });\n  });\n\n  describe('#getSVG', function() {\n    var instanceYao = sharedPosterizerInstance;\n\n    it('produces expected results with different thresholds', function() {\n      var expected;\n\n      instanceYao.setParameters({ threshold: 128 });\n      expected = fs.readFileSync('./reference-copies/posterized-yao-black-threshold-128.svg', { encoding: 'utf8' });\n      assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 128 does not match with reference copy');\n\n      instanceYao.setParameters({ threshold: 65 });\n      expected = fs.readFileSync('./reference-copies/posterized-yao-black-threshold-65.svg', { encoding: 'utf8' });\n      assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 65 does not match with reference copy');\n\n      instanceYao.setParameters({ threshold: 170 });\n      expected = fs.readFileSync('./reference-copies/posterized-yao-black-threshold-170.svg', { encoding: 'utf8' });\n      assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 170 does not match with reference copy');\n    });\n\n    it('produces expected white on black image with threshold 170', function(done) {\n      var instance = new Posterizer({\n        threshold: 40,\n        blackOnWhite: false,\n        steps: 3,\n        color: 'beige',\n        background: '#222'\n      });\n\n      instance.loadImage('sources/clouds.jpg', function(err) {\n        if (err) return done(err);\n\n        var expected = fs.readFileSync('./reference-copies/posterized-clouds-white-40.svg', { encoding: 'utf8' });\n        var actual = instance.getSVG();\n\n        assert.equal(actual, expected);\n        done();\n      });\n    });\n  });\n\n  describe('#getSymbol', function() {\n    var instanceYao = new Posterizer();\n\n    before(function(done) {\n      instanceYao.loadImage(jimpInstance, done);\n    });\n\n    it('should not have fill color or background', function() {\n      instanceYao.setParameters({\n        color: 'red',\n        background: 'cyan',\n        steps: 3\n      });\n\n      var symbol = instanceYao.getSymbol('whatever');\n\n      symbol.should.not.match(/<rect/i);\n      symbol.should.match(/<path[^>]+(?:fill=\"\\s*\"|fill='\\s*'|)[^>]*>/i);\n    });\n  });\n\n  describe('edge cases', function() {\n    var instance = new Posterizer();\n\n    it('does not break on images filled with one color', function(done) {\n      instance.loadImage(blackImage, function(err) {\n        if (err) { return done(err); }\n\n        // black image should give us one black layer...\n        instance.setParameters({ blackOnWhite: true, threshold: 128 });\n        instance.getSVG().should.match(/<path fill-opacity=\"1\\.000\"/);\n\n        instance.setParameters({ blackOnWhite: false });\n        instance.getSVG().should.not.match(/<path/);\n\n        instance.loadImage(whiteImage, function() {\n          if (err) { return done(err); }\n\n          instance.setParameters({ blackOnWhite: true });\n          instance.getSVG().should.not.match(/<path/);\n\n          // white image should give us one layer...\n          instance.setParameters({ blackOnWhite: false });\n          instance.getSVG().should.match(/<path fill-opacity=\"1\\.000\"/);\n\n          done();\n        });\n      });\n    });\n\n    it('does not break when no thresholds can be found', function(done) {\n      instance.loadImage(whiteImage, function(err) {\n        if (err) { return done(err); }\n\n        var svg1, svg2, svg3, svg4;\n\n        instance.setParameters({ blackOnWhite: true });\n        svg1 = instance.getSVG();\n        instance.setParameters({ blackOnWhite: true, steps: 3, threshold: 128 });\n        svg2 = instance.getSVG();\n        instance.setParameters({ blackOnWhite: true, steps: [], threshold: 128 });\n        svg3 = instance.getSVG();\n        instance.setParameters({ blackOnWhite: true, steps: [0, 55, 128, 169, 210], threshold: 250 });\n        svg4 = instance.getSVG();\n\n        svg1.should.be.equal(svg2).and.equal(svg3).and.equal(svg4).and.not.match(/<path/);\n\n        instance.loadImage(blackImage, function() {\n          if (err) { return done(err); }\n\n          instance.setParameters({ blackOnWhite: false, threshold: 255 });\n          svg1 = instance.getSVG();\n          instance.setParameters({ blackOnWhite: false, threshold: 0 });\n          svg2 = instance.getSVG();\n\n          svg1.should.equal(svg2).and.not.match(/<path/);\n          \n          done();\n        });\n      });\n    });\n  });\n});\n\ndescribe('Shorthand methods', function() {\n  var jimpInstance = null;\n\n  this.timeout(10000);\n\n  before(function(done) {\n    Jimp.read(PATH_TO_YAO, function(err, img) {\n      if (err) {\n        return done(err);\n      }\n\n      jimpInstance = img;\n      done();\n    });\n  });\n\n  describe('#trace', function() {\n    var instance = null;\n\n    it('works with two arguments', function(done) {\n      lib.trace(jimpInstance, function(err, svgContents, inst) {\n        if (err) {\n          throw err;\n        }\n\n        var expected = fs.readFileSync('./reference-copies/output.svg', { encoding: 'utf8' });\n\n        instance = inst;\n        assert.equal(svgContents, expected);\n        done();\n      });\n    });\n\n    it('works with three arguments', function(done) {\n      lib.trace(jimpInstance, { threshold: 170 }, function(err, svgContents) {\n        if (err) {\n          throw err;\n        }\n\n        var expected = fs.readFileSync('./reference-copies/potrace-bw-threshold-170.svg', { encoding: 'utf8' });\n\n        assert.equal(svgContents, expected);\n        done();\n      });\n    });\n\n    it('returns Potrace instance as third argument', function() {\n      instance.should.be.instanceOf(Potrace);\n    });\n  });\n\n  describe('#posterize', function() {\n    var instance = null;\n\n    it('works with two arguments', function(done) {\n      lib.posterize(jimpInstance, function(err, svgContents, inst) {\n        if (err) {\n          throw err;\n        }\n\n        var expected = fs.readFileSync('./reference-copies/output-posterized.svg', { encoding: 'utf8' });\n\n        instance = inst;\n        assert.equal(svgContents, expected);\n        done();\n      });\n    });\n\n    it('works with three arguments', function(done) {\n      lib.posterize(jimpInstance, { threshold: 170 }, function(err, svgContents) {\n        if (err) {\n          throw err;\n        }\n\n        var expected = fs.readFileSync('./reference-copies/posterized-bw-threshold-170.svg', { encoding: 'utf8' });\n\n        assert.equal(svgContents, expected);\n        done();\n      });\n    });\n\n    it('returns Posterizer instance as third argument', function() {\n      instance.should.be.instanceOf(Posterizer);\n    });\n  });\n});\n\n// lib.trace('./yao.jpg', function(err, svg) {\n//   if (err) { throw err; }\n//   fs.writeFileSync('./output.svg', svg);\n// });\n//\n// lib.posterize('./yao.jpg', function(err, svg) {\n//   if (err) { throw err; }\n//   fs.writeFileSync('./output-posterized.svg', svg);\n// });\n//\n// // Generating example for readme with hand-picked thresholds\n//\n// lib.trace('./yao.jpg', { threshold: 128 }, function(err, svg) {\n//   if (err) { throw err; }\n//   fs.writeFileSync('./example-output.svg', svg);\n// });\n//\n// lib.posterize('./yao.jpg', { steps: [50, 85, 120, 165, 220] }, function(err, svg) {\n//   if (err) { throw err; }\n//   fs.writeFileSync('./example-output-posterized.svg', svg);\n// });"
  }
]