[
  {
    "path": ".gitignore",
    "content": "py/*/\ncpp/*.exe\ncpp/*.a\ncpp/*.dll\ncpp/*.so\ncpp/*.o\ncpp/*.obj\ncpp/*.def\ncpp/*.lib\ncpp/*.exp\nnode_modules\njulia/.vscode/settings.json\ncpp/nanobench.h\ncpp/bench\ncpp/demo\n"
  },
  {
    "path": ".npmignore",
    "content": "# npm sucks and i can only put things under git root\r\n/*\r\n!/js\r\njs/misc\r\n!/doc"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n    \"files.associations\": {\n        \"*.embeddedhtml\": \"html\",\n        \"iostream\": \"cpp\"\n    }\n}"
  },
  {
    "path": "LICENSE.gplv3",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\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 GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  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\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions 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 convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU 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\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\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\nstate 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    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\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 3 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\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program 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, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "PRCoords\n========\n\nPeople's Rectified Coordinates (PRCoords) is a cross-language implementation of \"public secret\" Chinese coordinate obfuscation methods including GCJ-02 and BD-09, along with general deobfuscation methods previously established in [ChinaMapShift][], [eviltransform][], and [geoChina][]. (Referring to the process of replacing straight lines with wavy ones as a \"transform\" is euphemism overdone.)\n\nFor a background on China's geographic obfuscation, see [Restrictions on geographic data in China](https://en.wikipedia.org/wiki/Restrictions_on_geographic_data_in_China#Coordinate_systems) and [中华人民共和国测绘限制](https://zh.wikipedia.org/wiki/中华人民共和国测绘限制) on Wikipedia.\n\n[ChinaMapShift]: https://gist.github.com/anonymous/e7c6f67555099180ce1ae8da4ba2c513\n[geoChina]: https://github.com/caijun/geoChina/blob/master/R/cst.R\n[eviltransform]: https://github.com/googollee/eviltransform\n\nLanguages\n---------\n\n- [x] JavaScript ([`npm install prcoords`](https://www.npmjs.com/package/prcoords)) [![](https://data.jsdelivr.com/v1/package/npm/prcoords/badge)](https://www.jsdelivr.com/package/npm/prcoords)\n  * Web demo: https://artoria2e5.github.io/PRCoords/demo\n  * Now with AMD support and faux `__esModule` interop for Babel and TypeScript!\n- [x] Python ([`pip install prcoords`](https://pypi.org/project/prcoords/))\n- [x] \\(Obj-\\)C/C++ (C ABI)\n  * [x] Makefile with `install`\n- [ ] Ruby\n- [ ] Swift\n- [ ] C#\n- [x] Haskell (GCJ only; data structure incomplete)\n  * need to move googollee/eviltransform#54 here sometime.\n- [ ] Java\n- [x] Matlab/Octave\n- [x] PGSQL\n- [ ] Typed Racket\n  * is it done?\n\n(should I split them into submodules?)\n\nFor languages not yet supported, we recommend you to check for [eviltransform][] (MIT) or [geoChina][] (GPLv3, R) instead.\n\nAPI\n---\n\nPRCoord's APIs operate on, and returns, dedicated structures for coordinates. In API names, we generally refer to WGS-84 as `wgs`, GCJ-02 as `gcj`, and BD-09 (lat-lon) as `bd`. \n\n### Inverse functions\n\nThe obfuscations generally have these properties to maintain basic usefulness:\n\n1. `obfs(coord)` is sort of close to `coord`.\n2. `obfs(a) - obfs(b)` is usually close to `a - b`. (The closer `a` and `b` are\n   to each other, the better it works.)\n\nIn general two approaches of inverting the \"forward\" obfuscations, or working from\n`obfs(coord)` to `coord`, are implemented:\n\n* _Run it backwards_: `obfs(coord)` is never too far from `coord`, so just use\n  `obfs(obfs(coord)) - obfs(coord)` to estimate `obfs(coord) - coord`.\n* _Iterate a bit_: Get a rough `guess` somehow, and just use property 2 to estimate\n  the remaining error as `obfs(guess) - obfs(coord)` and correct the `guess`.\n\nYou can read on the demo page about how well these methods work from the `ΔRoundtrip`\nentry. Unless you are doing archival work, you generally don't have to iterate.\n\n### The \"in China\" sanity check\n\nTypically PRCoords is only supposed to be ran on obfuscated input data, which\nare primarily Chinese coordinates. For this reason, initial implementations\ninclude this [very very rough](https://news.ycombinator.com/item?id=10965506)\nsanity check that spans a rectangular region on a mercator-projected map.\nThis check can be overridden by passing a boolean value, or may be not at all\nimplemented in certain languages if I am not in the right mood for doing\nsilly things.\n\nThere is an \"insane\" sanity check intended to approximate the range of Google\nand Baidu's distortion, intended for use by [IITC](https://iitc.me):\n[`js/insane_is_in_china.js`](https://github.com/Artoria2e5/PRCoords/blob/master/js/insane_is_in_china.js).\nIt is basically a ray-casting polygon check with 70 vertices. You, as the\ncaller, should still be responsible for telling whether a point is part of the\ngov-screwed Chinese data.\n\nFAQ\n---\n\n### Why another wheel?\n\n* Correctness\n* Public Domain\n* Clean API based on pairs of coordinates\n* Need to find a place for this sarcastic name\n\n### Can the systems be described as WKT or proj-strings?\n\nNot directly as a datum, because in both representations a datum is either\n\"sane\" (no non-linearity in 3D, Helmert possible) or a big table of grids.\n\nIt should be possible to describe the two CS with a `PROJECTION` entry as\na `PROJCS`. Since a `PROJCS` cannot be nested in another, the BD\ntransformation must be described using WGS84 and a fuzed GCJ-BD projection.\nThe situation is similar with [Baidu \"Meractor\"](https://github.com/gumblex/cntms/commit/bbde4006adeb92f48da1ff7d1f88da393d382f8a).\n\n<details>\n<summary>Speculative WKT/PROJ4</summary>\n\n```js\nPROJCS[\"Baidu 2009, Pseudo-Mercator\",\n    GEOGCS[\"WGS 84\",\n        DATUM[\"WGS_1984\",\n            SPHEROID[\"WGS 84\",6378137,298.257223563,\n                AUTHORITY[\"EPSG\",\"7030\"]],\n            AUTHORITY[\"EPSG\",\"6326\"]],\n        PRIMEM[\"Greenwich\",0,\n            AUTHORITY[\"EPSG\",\"8901\"]],\n        UNIT[\"degree\",0.0174532925199433,\n            AUTHORITY[\"EPSG\",\"9122\"]],\n        AUTHORITY[\"EPSG\",\"4326\"]],\n    PROJECTION[\"CN_Obfs_Baidu_2009_Mercator\"],\n    AXIS[\"x\",east],\n    AXIS[\"y\",north],\n    UNIT[\"metre\",1,\n      AUTHORITY[\"EPSG\",\"9001\"]],\n    EXTENSION[\"PROJ4\",\"+proj=baidumerc +units=m +nadgrids=@null +wktext +no_defs\"],\n    AUTHORITY[\"EPSG\",\"888002\"]]\n\nPROJCS[\"Chinese BSM 2002, Pseudo-Ellipsoidal\",\n    GEOGCS[\"WGS 84\", AUTHORITY[\"EPSG\",\"4326\"]],\n    PROJECTION[\"CN_Obfs_GCJ_2002_Ellipsoidal\"],\n    AXIS[\"longitude\",east],\n    AXIS[\"latitude\",north],\n    UNIT[\"degree\",0.0174532925199433,\n      AUTHORITY[\"EPSG\",\"9122\"]],\n    EXTENSION[\"PROJ4\",\"+proj=gcjlonglat +units=deg +nadgrids=@null +wktext +no_defs\"],\n    AUTHORITY[\"EPSG\",\"888000\"]]\n```\n</details>\n\nThe good people at proj4js has made their stuff [very easy to extend](https://github.com/proj4js/proj4js/issues/358). Here is [an example](https://runkit.com/artoria2e5/proj4-plugin-prcoords) (backed up in [`docs/proj4_plugin.js`](https://github.com/Artoria2e5/PRCoords/blob/master/docs/proj4_plugin.js) in case RunKit goes down) of how to add PRCoords support to proj4js.\n\n### Should I use fast fp math?\n\nYes. Nobody knows what the original looks like anyways, so what's wrong with letting the compiler recombine a bit more? You can't be more off\nthan the one-meter random error (in \"EMQ\") anyways.\n\nOr tinker with 32-bit floats and fixed-point numbers. Or try approximation tools like [Sollya](http://sollya.gforge.inria.fr/) or [MC++](https://omega-icl.github.io/mcpp/). Really, just search on the Internet for \"\\<language\\> Taylor Chebyshev Model\". You only need less than 1e-6 error on a [not-very-large slice](https://github.com/Artoria2e5/PRCoords/blob/a3a8bb8/js/PRCoords.js#L91) of the Earth anyways.\n\nI threw TaylorModels.jl at GCJ-02, and got ~~decent~~ results out of it. Still too lazy to put it in code though. Check out [approx/approx.ipynb](https://github.com/Artoria2e5/PRCoords/blob/master/approx/approx.ipynb). (Nope, not decent. Gotta do it properly some day, just don't use the notebook and expect it to work!)\n\nI tried another route with the C++ version using a devmaster user Nick's `sinpi()` approximation. It seems to be good enough for 1e-6: check out [cpp/bench_out](https://github.com/Artoria2e5/PRCoords/tree/master/cpp/bench_out) and [cpp/badmath.hh](https://github.com/Artoria2e5/PRCoords/blob/master/cpp/badmath.hh).\n\nPhysical PRCoords\n-----------------\n\nYou can print out a minimal copy of PRCoords with [this PDF file](https://commons.wikimedia.org/wiki/File:PRcoords_Cheatsheet.pdf). I am working on some better options [in issue #2](https://github.com/Artoria2e5/PRCoords/issues/2). A fairly simple tote bag with an older version of the PDF is [available from Teespring](https://teespring.com/miniprcoords-tote-v1).\n\nFeel free to print and sell t-shirts with the PDF file! It is put in the Public Domain, so you don't have to pay me for that. You can always fund my subversive activities on [Patreon](https://www.patreon.com/artoria2e5) though.\n\nLicense\n-------\n\nUnless otherwise mentioned, all files in this package, including this README file,\nare dual-licensed under:\n\n* [CC0 1.0 Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/)\n* [GNU General Public License (version 3 or up)](https://gnu.org/licenses/gpl.html)\n\nGPL is only included for fun here.\n\nSources\n-------\n\n* [Algorithm.Coords.Converter](https://archive.is/20130815104734/emq.googlecode.com/svn/emq/src/Algorithm/Coords/Converter.java) from [EMQ](https://code.google.com/archive/p/emq/) ([GitHub mirror](https://github.com/richardyu-au/emq)) is probably *the* GCJ leak. It is a JSP project \"for demonstrating GIS systems\", probably done by some government contractor.\n  * There is some randomness in the GCJ deltas on both axes: one `sin` invocation and one LCG. Each add a maximum of 1 meter of error.\n* [on4wp7](https://archive.is/20150702191259/https://on4wp7.codeplex.com/SourceControl/changeset/view/21483%23353936) (2013) is the earliest rationalized GCJ (forward) implementation. No randomness is attempted.\n* [ChinaMapShift][] (2014) figured out the quick iterative inverse for GCJ. I learned about it via geoChina first and generalized it here.\n* BD-09 is not very well sourced, but [pycoordtrans](https://github.com/zxteloiv/pycoordtrans) (2014) seems to have it.\n\nSee also\n--------\n\n* [eviltransform][] is among the most popular cross-language soltions to the problem. It borrows its name directly from [EvilTransform.cs](https://github.com/Leask/EvilTransform/blob/master/EvilTransform.cs), an early refactored version of a raw-flesh Java implementation found in \"[emq](https://code.google.com/archive/p/emq/)\", some sort of government contractor GIS demo project.\n  * Since June 2016, eviltransform contains numerous parameter errors that compromise its output, especially for BD-09. See googollee/eviltransform[#43](https://github.com/googollee/eviltransform/issues/43), [#53](https://github.com/googollee/eviltransform/pull/53) and [#44](https://github.com/googollee/eviltransform/issues/44) for corrections. As of June 2019 these problems are not fixed.\n* [geoChina][] by caijun is a clear, concise implementation written in R. It features the iterative method from ChinaMapShift.\n* I am planning on moving some of the comments on the algorithm found in [my initial JavaScript implementation](https://zh.wikipedia.org/wiki/User:Artoria2e5/PRCoords.js) to the [GitHub Wiki](https://github.com/Artoria2e5/PRCoords/wiki). I don't think anyone is going to be interested in copying comments on these idiocy when translating my implementation to other languages.\n  * If you are doing a translation, consider only using the comments from the PDF.\n* [Ishisashi's writeup](https://chaoli.club/index.php/4777/0) on this subject. They wrote a super enhanced version of the demo too.\n\nOh, and finally, here is an official [news report](https://archive.fo/20110804185923/http://cxzy.people.com.cn/GB/196034/14908095.html) on that particular *\\[bleep\\]* who came up with GCJ-02.\n\n\n<a href=\"https://artoria2e5.github.io/PRCoords/demo\">\n  <img src=\"https://Artoria2e5.github.io/PRCoords/Globe%2C_distorted_China.svg\" width=\"100%\" height=\"100\">\n</a>\n"
  },
  {
    "path": "approx/approx.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Approximation\\n\",\n    \"=============\\n\",\n    \"\\n\",\n    \"Scroll down and you should find some approximations of the obfuscation code.\\n\",\n    \"I have no idea what evil forces compelled me to do this, but eh let's roll with it.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"using TaylorModels\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"GCJ-02\\n\",\n    \"------\\n\",\n    \"\\n\",\n    \"The `abs()` makes it impossible to feed into taylor, so I think I will just feed the trigs in. Splitting the x and y too, so we don't get a lot of zero in the coeffs.\\n\",\n    \"\\n\",\n    \"Let's start with... typing the formulae:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": \"e1 (generic function with 1 method)\"\n     },\n     \"execution_count\": 4,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# Not gonna type these pi.\\n\",\n    \"spi(x) = sin(x * pi)\\n\",\n    \"\\n\",\n    \"# Just the core meter-level shite. 1 and 2 are to be fed to taylor.\\n\",\n    \"n0(x, y) = -100 + 0.1x*y + 0.2 * sqrt(abs(x))\\n\",\n    \"n1(x) = 2x + 20 / 3 * (2 * spi(6x) + 2 * spi(2x))\\n\",\n    \"n2(y) = 3y + 0.2y^2 + 20 / 3 * (2 * spi(y) + 4 * spi(y/3) + 16 * spi(y/12) + 32 * spi(y/30))\\n\",\n    \"\\n\",\n    \"e0(x, y) = 300 + 0.1x*y + 0.1 * sqrt(abs(x)) + 2y\\n\",\n    \"e1(x) = x + 0.1x^2 + 20 / 3 * (2 * spi(6x) + 2 * spi(2x) + 2 * spi(x) + 4 * spi(x/3) + 15 * spi(x/12) + 30 * spi(x/30))\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Set up for TaylorModels:\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"n1tm =  [337.103, 337.104] t + [-15434.3, -15434.2] t³ + [265489, 265490] t⁵ + [-4.894e+16, 4.894e+16]\\n\",\n      \"n2tm =  [123.078, 123.079] t + [0.2, 0.200001] t² + [-74.3666, -74.3665] t³ + [34.2831, 34.2832] t⁵ + [-1.74906e+11, 1.74906e+11]\\n\",\n      \"e1tm =  [453.04, 453.041] t + [0.1, 0.100001] t² + [-15508.6, -15508.5] t³ + [265523, 265524] t⁵ + [-4.89402e+16, 4.89402e+16]\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"x_dom = -30..30\\r\\n\",\n    \"y_dom = -30..20\\r\\n\",\n    \"\\r\\n\",\n    \"# 35,105 as the center of China. What can go wrong?\\r\\n\",\n    \"x0 = 0\\r\\n\",\n    \"y0 = 0\\r\\n\",\n    \"\\r\\n\",\n    \"ORDER = 6\\r\\n\",\n    \"\\r\\n\",\n    \"tmx = TaylorModel1(ORDER, interval(x0), x_dom)\\r\\n\",\n    \"tmy = TaylorModel1(ORDER, interval(y0), y_dom)\\r\\n\",\n    \"\\r\\n\",\n    \"n1tm = n1(tmx)\\r\\n\",\n    \"n2tm = n2(tmy)\\r\\n\",\n    \"e1tm = e1(tmx)\\r\\n\",\n    \"\\r\\n\",\n    \"println(\\\"n1tm = \\\", n1tm)\\r\\n\",\n    \"println(\\\"n2tm = \\\", n2tm)\\r\\n\",\n    \"println(\\\"e1tm = \\\", e1tm)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Oh well, the last term is way better than what I expected. Let's export them as usual polynomials then.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"n1t = 337.10321638291134 t - 15434.235503082582 t³ + 265489.0776448309 t⁵ + 𝒪(t⁷)\\n\",\n      \"n2t =  123.07865253720988 t + 0.2 t² - 74.36657685107961 t³ + 34.28315615652991 t⁵ + 𝒪(t⁷)\\n\",\n      \"e1t =  453.0402762665314 t + 0.1 t² - 15508.57959081323 t³ + 265523.36073126463 t⁵ + 𝒪(t⁷)\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"function mid_tm(t::TaylorModel1)\\r\\n\",\n    \"    coeffs = map(x -> mid(x), t.pol.coeffs)\\r\\n\",\n    \"    order = t.pol.order\\r\\n\",\n    \"    return Taylor1(coeffs, order)\\r\\n\",\n    \"end\\r\\n\",\n    \"n1t = mid_tm(n1tm)\\r\\n\",\n    \"n2t = mid_tm(n2tm)\\r\\n\",\n    \"e1t = mid_tm(e1tm)\\r\\n\",\n    \"println(\\\"n1t = \\\", n1t)\\r\\n\",\n    \"println(\\\"n2t = \\\", n2t)\\r\\n\",\n    \"println(\\\"e1t = \\\", e1t)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"These should be good enough to just translate into code. If you are allowing the compiler to reassoc, there should be no need of manually writing Horner and thinking about pipelines. The reduced number of operations might even make `f32` acceptable. I will eventually put it in the cpp thing and check it.\\r\\n\",\n    \"\\r\\n\",\n    \"The arclen stuff have the same `sqrt` issue, so it's not getting changed here.\\r\\n\",\n    \"\\r\\n\",\n    \"Okay, actually, **no**. The range of numbers means that `t^7` is ridiculously large. I should really throw this at MetaLibm-Lutetia\\r\\n\",\n    \"and ask it to do the argument reduction for me...\\r\\n\",\n    \"\\r\\n\",\n    \"BD-09\\r\\n\",\n    \"----\\r\\n\",\n    \"We have a `sqrt` in `hypot`, so no. We can't fuze any operations here anyways.\\r\\n\",\n    \"\\r\\n\",\n    \"\\r\\n\",\n    \"Plotting session\\r\\n\",\n    \"----------------\\r\\n\",\n    \"Oops UI can't install `Plots`. And I just realized the resulting numbers are\\r\\n\",\n    \"unreasonably large. Oops.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Julia 1.5.0-rc1\",\n   \"language\": \"julia\",\n   \"name\": \"julia-1.5\"\n  },\n  \"language_info\": {\n   \"file_extension\": \".jl\",\n   \"mimetype\": \"application/julia\",\n   \"name\": \"julia\",\n   \"version\": \"1.5.0\"\n  },\n  \"orig_nbformat\": 2\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}"
  },
  {
    "path": "cpp/Makefile",
    "content": "CXXFLAGS = -O3 -funsafe-math-optimizations -fno-math-errno -std=c++0x -Wall -Wextra -fvisibility=hidden -fvisibility-inlines-hidden -DNDEBUG $(XCXXFLAGS)\n\n# \"Cross compile\" shite. In other words MinGW.\n# TARGET is Triplet PLUS THE HYPHEN!\nCC = $(TARGET)gcc\nCXX = $(TARGET)g++\nAR ?= $(TARGET)ar\nDLLTOOL ?= $(TARGET)dlltool\n\n# for clang's llvm bitcode: CCAR=llvm-ar\nCCAR ?= gcc-ar\n\n# Override when using CYGWIN: make [target] LIB=cyg SO=dll\n# Override when using MinGW: make [target] LIB='' SO=dll TARGET=x86_64-w64-mingw32-\nLIB ?= lib\nSO ?= so\n\n# Installation\nDESTDIR ?= \nPREFIX ?= /usr/local\n\n# Path to the Microsoft Library Manager (LIB.exe)\n# Available from https://aka.ms/buildtools\n# Tends to be buried deep, e.g. C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.22.27905\\bin\\Hostx64\\x64\n# I recommend putting a shell script called lib.exe in /usr/local/bin to call it with \"$@\"\n#\n# Mingw-W64 has a genlib.exe for those who dare to try. It generates MSVC-style\n# __IMPORT_DESCRIPTOR_%s. Or maybe the ld -Wl,--out-implib will work with MSVC\n# too with __imp symbols only, who knows.\n#\n# Note that this is only meaningful for MinGW output: Cygwin/MSYS builds have\n# dependency for cygwin1.dll, which triggers address-clashes with MSVC's libs.\n#\n# cl /Fe:demo-cl.exe demo.cc prcoords.lib\nLIBEXE ?= LIB.exe\n# Or /machine:x86.\nLIBFLAGS ?= /machine:x64\n\nall: libprcoords.a $(LIB)prcoords.$(SO) demoso\nprec_sample: demo demof demold\nwindows: all $(LIB)prcoords.lib\n\n# We assume that your copy of \"ar\" supports the \"s\" option,\n# which does some ranlib work itself.\nlibprcoords.a: libprcoords.o\n\t$(AR) rcs libprcoords.a libprcoords.o\n\nlibprcoords-lto.a: libprcoords-lto.o\n\t$(CCAR) rcs libprcoords-lto.a libprcoords-lto.o\n\n$(LIB)prcoords.$(SO): libprcoords.o\n\t$(CC) -shared -o $(LIB)prcoords.$(SO) libprcoords.o\n\nlibprcoords.o: libprcoords.cc badmath.hh\n\t$(CC) $(CXXFLAGS) -fPIC -c -DPRCOORDS_DLL -DPRCOORDS_DLL_EXPORTS libprcoords.cc\n\nlibprcoords-lto.o: libprcoords.cc\n\t$(CC) $(CXXFLAGS) -flto -ffat-lto-objects -c libprcoords.cc -o libprcoords-lto.o\n\n# Import library generation for MSVC users (optional)\n$(LIB)prcoords.def: libprcoords.o\n\t$(DLLTOOL) --dllname $(LIB)prcoords.$(SO) -z $(LIB)prcoords.def --export-all-symbols libprcoords.o\n\n# Also spits out an .exp\n$(LIB)prcoords.lib: $(LIB)prcoords.def\n\t$(LIBEXE) $(LIBFLAGS) /nologo /def:$(LIB)prcoords.def /out:$(LIB)prcoords.lib\n\ndemo: demo.cc libprcoords.cc\n\t$(CXX) $(CXXFLAGS) -DPRCOORDS_DEMO_FORCE_STANDALONE=1 -o demo demo.cc\n\ndemof: demo.cc libprcoords.cc\n\t$(CXX) $(CXXFLAGS) -DPRCOORDS_DEMO_FORCE_STANDALONE=1 -DPRCOORDS_NUM=float -DPRCOORDS_STON=stof -o demof demo.cc\n\ndemold: demo.cc libprcoords.cc\n\t$(CXX) $(CXXFLAGS) -DPRCOORDS_DEMO_FORCE_STANDALONE=1 -DPRCOORDS_NUM='long double' -DPRCOORDS_STON=stold -o demold demo.cc\n\n# Horray! We do not need import libraries.\n# FIXME: COMMAND NOT BUILDING ON MY NIXOS\ndemoso: demo.cc $(LIB)prcoords.$(SO)\n\t$(CXX) $(CXXFLAGS) -L. -l:$(LIB)prcoords.$(SO) -o demoso -DPRCOORDS_DLL demo.cc\n\nnanobench.h:\n\twget -O nanobench.h https://github.com/martinus/nanobench/raw/master/src/include/nanobench.h\n\nbench: libprcoords.o prcoords.h nanobench.h bench.cc\n\t$(CXX) $(CXXFLAGS) -DPRCOORDS_BENCH $(DEFS) -o bench libprcoords.o bench.cc\n\n.PHONY: clean help install uninstall\n\ninstall: all\n\tmkdir -p $(DESTDIR)$(PREFIX)/bin/prcoords-demo\n\tinstall -s demoso -- $(DESTDIR)$(PREFIX)/bin/prcoords-demo\n\tmkdir -p $(DESTDIR)$(PREFIX)/lib\n\tinstall -m 644 -- libprcoords.a $(LIB)prcoords.$(SO) $(DESTDIR)$(PREFIX)/lib\n\nuninstall:\n\trm -f -- $(DESTDIR)$(PREFIX)/bin/prcoords-demo $(DESTDIR)$(PREFIX)/lib/libprcoords.a $(DESTDIR)$(PREFIX)/lib/$(LIB)prcoords.$(SO)\n\nclean:\n\t$(RM) demo demof demold *.exe *.a *.o *.def *.dll *.obj *.lib *.exp *.obj bench\n"
  },
  {
    "path": "cpp/badmath.hh",
    "content": "/**\n * Internal header for implementing \"fast\" sin(x*pi).\n */\n#include <cmath>\n\nnamespace badmath {\n    // what are you gonna do about it? x can't be too big!\n    // this is supposed to turn into FMA where fast, and not invoke the fma() libc function otherwise.\n    // like how Julia's muladd() works, but at the mercy of the compiler.\n    template<typename T>\n    inline T red4(T x) {\n        return -4 * std::nearbyint(x * 0.25) + x;\n    }\n    // devmaster user \"Nick\"'s approximation formula\n    // https://web.archive.org/web/20171228230531/http://forum.devmaster.net/t/fast-and-accurate-sine-cosine/9648\n    template<typename T>\n    inline T sinpi_nick(T x) {\n        x = red4(x * 2); // = 0 to 2pi; nick-magic works on units of 0.5pi\n        T y = x * (2 - std::abs(x));\n        return y * (0.775 + 0.225 * std::abs(y));\n    }\n    template<typename T>\n    inline T sinpi_std(T x) {\n        return std::sin(x * M_PI);\n    }\n    template<typename T>\n    inline T sinpi(T x) {\n#ifndef PRCOORDS_NO_BADMATH\n        return sinpi_nick(x);\n#else\n        return sinpi_std(x);\n#endif\n    }\n    template<typename T>\n    inline T cospi(T x) {\n        return sinpi(x + 0.5);\n    }\n}\n"
  },
  {
    "path": "cpp/bench.cc",
    "content": "#include <iostream>\n#include \"badmath.hh\"\n#include \"prcoords.h\"\n#define ANKERL_NANOBENCH_IMPLEMENT\n#include \"nanobench.h\"\n\ndouble uniform(ankerl::nanobench::Rng& rng, double a, double b){\n    return rng.uniform01() * (b - a) + a;\n}\n\nPRCoords rand_coord(ankerl::nanobench::Rng& rng){\n    return PRCoords{.lat = uniform(rng, -90, 90), .lon = uniform(rng, -180, 180)};\n}\n\nint main(){\n    using namespace badmath;\n    auto rng = ankerl::nanobench::Rng();\n    ankerl::nanobench::Bench().minEpochIterations(10000).run(\n        \"nop\", [&]() {\n            auto coord = rand_coord(rng);\n            ankerl::nanobench::doNotOptimizeAway(coord);\n        }\n    );\n    ankerl::nanobench::Bench().minEpochIterations(10000).run(\n        \"wgs_gcj\", [&]() {\n            auto coord = rand_coord(rng);\n            auto res = prcoords_wgs_gcj(coord);\n            ankerl::nanobench::doNotOptimizeAway(res);\n        }\n    );\n    ankerl::nanobench::Bench().minEpochIterations(10000).run(\n        \"gcj_wgs\", [&]() {\n            auto coord = rand_coord(rng);\n            auto res = prcoords_gcj_wgs(coord);\n            ankerl::nanobench::doNotOptimizeAway(res);\n        }\n    );\n    ankerl::nanobench::Bench().minEpochIterations(10000).run(\n        \"gcj_wgs_bored\", [&]() {\n            auto coord = rand_coord(rng);\n            auto res = prcoords_gcj_wgs_bored(coord);\n            ankerl::nanobench::doNotOptimizeAway(res);\n        }\n    );\n    ankerl::nanobench::Bench().minEpochIterations(10000).run(\n        \"bd_wgs_bored\", [&]() {\n            auto coord = rand_coord(rng);\n            auto res = prcoords_gcj_wgs_bored(coord);\n            ankerl::nanobench::doNotOptimizeAway(res);\n        }\n    );\n    ankerl::nanobench::Bench().minEpochIterations(10000).run(\n        \"gcj_bd\", [&]() {\n            auto coord = rand_coord(rng);\n            auto res = prcoords_gcj_bd(coord);\n            ankerl::nanobench::doNotOptimizeAway(res);\n        }\n    );\n    return 0;\n}\n"
  },
  {
    "path": "cpp/bench4.sh",
    "content": "#!/bin/sh\n\nbench_to_file() {\n    make clean\n    make bench XCXXFLAGS=\"$1\"\n    ./bench > bench_out/$2.md\n}\n\nnative='-march=native'\nstdsin='-DPRCOORDS_NO_BADMATH'\n\nif (( ! KEEP_GOVNOR )); then\n    OL_GOVNOR=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)\n    echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor\nfi\n\n\nbench_to_file \"$native\" 'native_nick'\nbench_to_file \"$native $stdsin\" 'native_stdsin'\nbench_to_file \"\" 'nick'\nbench_to_file \"$stdsin\" 'stdsin'\n\nif [[ -n $OL_GOVNOR ]]; then\n    echo $OL_GOVNOR | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor\nfi\n"
  },
  {
    "path": "cpp/bench_out/README.md",
    "content": "# bench_out\n\nAll four files are made by nanobench; just do `./bench4.sh`.\n\n* `nick` is the version with Nick's fast sinpi.\n* `std` is the version with sinpi implemented by `std::sin(M_PI * x)`.\n* The ones with `native_` in front are built with `-march=native`.\n\nAll the other flags are per Makefile: unsafe math optimizations, no math errno,\nyou know the drill.\n\nThe native versions are just 10% faster. The real win comes from using Nick's\napproximation, which quarters the runtime.\n\nThere seems to be no real damage to the output.  I mean, nick is at most 1e-3\noff.  That's appropriate when we are working in how many meters to shift a\npoint.\n\n* Compiler: GCC 13.2.0\n* CPU: Ryzen 5 3600\n* OS: NixOS 24.05pre, Linux 6.6.28\n\n## Update: more agressive nicking\n\nI also applied Nick's approximation to the `arclen` calculation in GCJ.  As\nexpected of a more important divisor, some visible damage to the output is\nseen, but the magnitude remians in the 1e-6 range. I consider that acceptable\ngiven the performance gain (see the files!); it's now the default.\n\n\\[That does make the `bored` conversion a bit pointless. Hmm, idk.\\]\n\n`bd` calculation also now uses nick. It also gets benched.\nGoing native seems to cause a 15% regression on `bd`, std or nick.\nMight be a good idea to look into that, or at least see what clang does.\n\nAnyone wishing to turn off nick can use the `-DPRCOORDS_NO_BADMATH` define.\nThere *might* be a point in turning off nick for specific parts of the\ncalculation, but I don't want to spend time on that.\n"
  },
  {
    "path": "cpp/bench_out/native_nick.md",
    "content": "Warning, results might be unstable:\n* CPU frequency scaling enabled: CPU 0 between 550.0 and 4,208.0 MHz\n\nRecommendations\n* Use 'pyperf system tune' before benchmarking. See https://github.com/psf/pyperf\n\n|               ns/op |                op/s |    err% |          ins/op |          cyc/op |    IPC |         bra/op |   miss% |     total | benchmark\n|--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:----------\n|                4.12 |      242,648,826.64 |    0.4% |           22.00 |           16.60 |  1.325 |           0.00 |    0.0% |      0.01 | `nop`\n|               30.80 |       32,472,208.69 |    3.6% |          223.00 |          121.17 |  1.840 |           2.00 |    0.0% |      0.01 | `wgs_gcj`\n|               37.95 |       26,349,634.73 |    0.2% |          238.00 |          149.56 |  1.591 |           4.00 |    0.0% |      0.01 | `gcj_wgs`\n|              157.44 |        6,351,722.84 |    2.1% |          683.36 |          622.28 |  1.098 |          13.03 |    2.3% |      0.02 | `gcj_wgs_bored`\n|              154.01 |        6,493,059.75 |    1.3% |          683.44 |          613.84 |  1.113 |          13.03 |    2.3% |      0.02 | `bd_wgs_bored`\n|               70.30 |       14,224,263.54 |    3.0% |          360.39 |          274.90 |  1.311 |          49.20 |    3.0% |      0.01 | `gcj_bd`\n"
  },
  {
    "path": "cpp/bench_out/native_stdsin.md",
    "content": "Warning, results might be unstable:\n* CPU frequency scaling enabled: CPU 0 between 550.0 and 4,208.0 MHz\n\nRecommendations\n* Use 'pyperf system tune' before benchmarking. See https://github.com/psf/pyperf\n\n|               ns/op |                op/s |    err% |          ins/op |          cyc/op |    IPC |         bra/op |   miss% |     total | benchmark\n|--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:----------\n|                4.09 |      244,330,932.16 |    0.5% |           22.00 |           16.60 |  1.325 |           0.00 |    0.0% |      0.01 | `nop`\n|              196.22 |        5,096,191.73 |    0.3% |        1,279.11 |          780.29 |  1.639 |         160.01 |    7.2% |      0.02 | `wgs_gcj`\n|              197.34 |        5,067,445.81 |    0.3% |        1,294.41 |          782.36 |  1.655 |         162.02 |    7.0% |      0.02 | `gcj_wgs`\n|              623.01 |        1,605,113.03 |    0.6% |        3,861.91 |        2,462.12 |  1.569 |         489.22 |    5.6% |      0.07 | `gcj_wgs_bored`\n|              622.11 |        1,607,439.62 |    0.4% |        3,856.47 |        2,461.61 |  1.567 |         488.46 |    5.6% |      0.08 | `bd_wgs_bored`\n|               89.76 |       11,141,416.00 |    0.3% |          540.45 |          356.74 |  1.515 |          77.21 |    5.5% |      0.01 | `gcj_bd`\n"
  },
  {
    "path": "cpp/bench_out/nick.md",
    "content": "Warning, results might be unstable:\n* CPU frequency scaling enabled: CPU 0 between 550.0 and 4,208.0 MHz\n\nRecommendations\n* Use 'pyperf system tune' before benchmarking. See https://github.com/psf/pyperf\n\n|               ns/op |                op/s |    err% |          ins/op |          cyc/op |    IPC |         bra/op |   miss% |     total | benchmark\n|--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:----------\n|                3.25 |      307,628,660.33 |    0.4% |           22.00 |           12.97 |  1.696 |           0.00 |    0.0% |      0.01 | `nop`\n|               45.60 |       21,931,100.65 |    0.8% |          448.00 |          179.13 |  2.501 |          38.00 |    0.0% |      0.01 | `wgs_gcj`\n|               59.09 |       16,922,136.13 |    2.1% |          465.00 |          231.72 |  2.007 |          40.00 |    0.0% |      0.01 | `gcj_wgs`\n|              198.70 |        5,032,812.17 |    0.6% |        1,365.35 |          779.44 |  1.752 |         121.13 |    0.3% |      0.02 | `gcj_wgs_bored`\n|              197.66 |        5,059,121.12 |    0.5% |        1,364.69 |          774.35 |  1.762 |         121.07 |    0.2% |      0.02 | `bd_wgs_bored`\n|               58.40 |       17,123,351.22 |    0.4% |          391.40 |          227.11 |  1.723 |          55.21 |    2.7% |      0.01 | `gcj_bd`\n"
  },
  {
    "path": "cpp/bench_out/stdsin.md",
    "content": "Warning, results might be unstable:\n* CPU frequency scaling enabled: CPU 0 between 550.0 and 4,208.0 MHz\n\nRecommendations\n* Use 'pyperf system tune' before benchmarking. See https://github.com/psf/pyperf\n\n|               ns/op |                op/s |    err% |          ins/op |          cyc/op |    IPC |         bra/op |   miss% |     total | benchmark\n|--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:----------\n|                3.24 |      308,253,800.28 |    0.2% |           22.00 |           12.97 |  1.696 |           0.00 |    0.0% |      0.01 | `nop`\n|              216.41 |        4,620,855.79 |    6.9% |        1,315.38 |          853.91 |  1.540 |         160.04 |    7.2% |      0.03 | :wavy_dash: `wgs_gcj` (Unstable with ~10,854.4 iters. Increase `minEpochIterations` to e.g. 108544)\n|              206.03 |        4,853,603.19 |    1.4% |        1,332.00 |          811.94 |  1.641 |         162.03 |    7.0% |      0.03 | `gcj_wgs`\n|              653.44 |        1,530,359.50 |    1.0% |        3,973.24 |        2,546.70 |  1.560 |         488.60 |    5.6% |      0.08 | `gcj_wgs_bored`\n|              653.92 |        1,529,245.44 |    0.6% |        3,976.15 |        2,533.60 |  1.569 |         488.87 |    5.6% |      0.08 | `bd_wgs_bored`\n|               93.34 |       10,713,089.73 |    0.4% |          543.42 |          361.83 |  1.502 |          77.21 |    5.5% |      0.01 | `gcj_bd`\n"
  },
  {
    "path": "cpp/demo.cc",
    "content": "/**\r\n * People's Rectified Coordinates, C++ demo.\r\n */\r\n\r\n#if PRCOORDS_DEMO_FORCE_STANDALONE\r\n#include \"libprcoords.cc\"\r\n#else\r\n#include \"prcoords.h\"\r\n#endif\r\n\r\n#include <iostream>\r\n#include <sstream>\r\n#include <iomanip>\r\n#include <string>\r\nusing namespace std;\r\n\r\n#ifndef PRCOORDS_STON\r\n#define PRCOORDS_STON stod\r\n#endif\r\n\r\nstd::string show_coord(PRCoords v) {\r\n    std::stringstream stream;\r\n    stream << std::fixed << std::setprecision(8) << v.lat << \", \" << v.lon;\r\n    return stream.str();\r\n}\r\n\r\nPRCoords parse_coord(const string& s) {\r\n    int cut = s.find(\", \");\r\n    return PRCoords{\r\n        PRCOORDS_STON(s.substr(0, cut)),\r\n        PRCOORDS_STON(s.substr(cut + 1))\r\n    };\r\n}\r\n\r\nint main(void) {\r\n    string input;\r\n\r\n    while (getline(cin, input))\r\n    {\r\n        PRCoords v = std::move(parse_coord(input));\r\n        cout\r\n            << \"w2g\\t\" << show_coord(prcoords_wgs_gcj(v)) << endl\r\n            << \"w2b\\t\" << show_coord(prcoords_wgs_bd(v)) << endl\r\n            << \"g2b\\t\" << show_coord(prcoords_gcj_bd(v)) << endl\r\n            << \"g2wQ\\t\" << show_coord(prcoords_gcj_wgs(v)) << endl\r\n            << \"b2wQ\\t\" << show_coord(prcoords_bd_wgs(v)) << endl\r\n            << \"b2gQ\\t\" << show_coord(prcoords_bd_gcj(v)) << endl\r\n            << \"g2wP\\t\" << show_coord(prcoords_gcj_wgs_bored(v)) << endl\r\n            << \"b2wP\\t\" << show_coord(prcoords_bd_wgs_bored(v)) << endl\r\n            << \"b2gP\\t\" << show_coord(prcoords_bd_gcj_bored(v)) << endl\r\n            << endl;\r\n    }\r\n}\r\n"
  },
  {
    "path": "cpp/libprcoords.cc",
    "content": "/**\r\n * People's Rectified Coordinates, C++11 implementation\r\n * Should yield a C-compatible ABI.\r\n */\r\n#include \"prcoords.h\"\r\n#include <cmath>\r\n#include <functional>\r\n#include <cassert>\r\n#include \"badmath.hh\"\r\n\r\n#ifndef M_PI\r\n#define M_PI ((PRCOORDS_NUM) (3.14159265358979323846L))\r\n#endif\r\n\r\n// Assume\r\n#ifndef __has_builtin\r\n# define __has_builtin(x) 0\r\n#endif\r\n\r\n#ifndef NDEBUG\r\n#define assume(R) assert(R)\r\n#elif __has_builtin(__builtin_assume)\r\n#define assume(R) __builtin_assume(R)\r\n#elif __has_builtin(__builtin_unreachable)\r\n#define assume(R) ((R) ? (void) 0 : __builtin_unreachable ())\r\n#elif 1200 <= _MSC_VER\r\n#define assume(R) __assume(R)\r\n#else\r\n#define assume(R) ((void) 0)\r\n#endif\r\n\r\n#define assume_angle(x, a) assume(x >= -a && x <= a)\r\n#define assume_coord(c) do { \\\r\n\tassume_angle(c.lat, 90); \\\r\n\tassume_angle(c.lon, 180);\\\r\n} while(0)\r\n\r\n// enforces PRCOORDS_NUM\r\nusing std::sin;\r\nusing std::cos;\r\nusing std::sqrt;\r\nusing std::atan2;\r\nusing std::pow;\r\nusing std::fabs;\r\n\r\nusing badmath::sinpi;\r\nusing badmath::cospi;\r\n\r\n/// Krasovsky 1940 ellipsoid\r\n/// @const\r\nconst static PRCOORDS_NUM GCJ_A = 6378245;\r\nconst static PRCOORDS_NUM GCJ_EE = 0.00669342162296594323;  // f = 1/298.3; e^2 = 2*f - f**2\r\nconst static PRCOORDS_NUM BD_DLAT = 0.0060;\r\nconst static PRCOORDS_NUM BD_DLON = 0.0065;\r\n\r\n/// Epsilon to use for \"exact\" iterations.\r\n/// Wanna troll? Use Number.EPSILON. 1e-13 in 15 calls for gcj.\r\n/// @const\r\nconst static PRCOORDS_NUM PRCOORDS_EPS = 1e-5;\r\n\r\ntypedef PRCoords (*PRCOp)(PRCoords);\r\n/// These conversions are for bored people: too accurate to be useful\r\n/// given pseudo-random noises added to GCJ.\r\n///\r\n/// Should we implement a 2-iter version?\r\n/// Just \"wgs = wgs - (fwd(wgs) - bad);\", repeated twice.\r\ntemplate<PRCOp fwd, PRCOp rev>\r\nPRCOORDS_LOCAL static PRCoords bored_reverse_conversion(PRCoords bad) {\r\n\tassume_coord(bad);\r\n\tPRCoords wgs = rev(bad);\r\n\tPRCoords diff{INFINITY, INFINITY};\r\n\t\r\n\tint i = 0;\r\n\twhile ((fabs(diff.lat) + fabs(diff.lon)) > PRCOORDS_EPS && i++ < 10) {\r\n\t\tdiff = fwd(wgs) - bad;\r\n\t\twgs = wgs - diff;\r\n\t}\r\n\treturn wgs;\r\n}\r\n\r\nextern \"C\" {\r\nPRCoords prcoords_wgs_gcj(PRCoords wgs) {\r\n\tassume_coord(wgs);\r\n\tPRCOORDS_NUM x = wgs.lon - 105, y = wgs.lat - 35;\r\n\r\n\t// These distortion functions accept (x = lon - 105, y = lat - 35).\r\n\t// They return distortions in terms of arc lengths, in meters.\r\n\t//\r\n\t// In other words, you can pretty much figure out how much you will be off\r\n\t// from WGS-84 just through evaulating them...\r\n\t// \r\n\t// For example, at the (mapped) center of China (105E, 35N), you get a\r\n\t// default deviation of <300, -100> meters.\r\n#ifndef APPROX\r\n\tPRCOORDS_NUM dLat_m = -100 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y\r\n\t\t+ 0.2 * sqrt(fabs(x)) + (\r\n\t\t\t2 * sinpi(x * 6) + 2 * sinpi(x * 2)\r\n\t\t\t+ 2 * sinpi(y) + 4 * sinpi(y / 3)\r\n\t\t\t+ 16 * sinpi(y / 12) + 32 * sinpi(y / 30)\r\n\t\t) * 20 / 3;\r\n\tPRCOORDS_NUM dLon_m = 300 + x + 2 * y + 0.1 * x * x + 0.1 * x * y\r\n\t\t+ 0.1 * sqrt(fabs(x)) + (\r\n\t\t\t2 * sinpi(x * 6) + 2 * sinpi(x * 2)\r\n\t\t\t+ 2 * sinpi(x) + 4 * sinpi(x / 3)\r\n\t\t\t+ 15 * sinpi(x / 12) + 30 * sinpi(x / 30)\r\n\t\t) * 20 / 3;\r\n#else\r\n\t// Approximation code from julia side. I should probably\r\n\t// extract the xy-to-ne thing, but that would mean making the whole\r\n\t// program templates. Not today.\r\n\t// FIXME: The coefficients are giving me ridiculously large numbers!\r\n\tPRCOORDS_NUM dLat_m = 0;\r\n\tPRCOORDS_NUM dLon_m = 0;\r\n#endif\r\n\r\n\t// NOTE: Using sinpi_nick causes the results to be off by 1e-6.\r\n\t// That's acceptable casualty.\r\n\t// Don't like it? Use PRCOORDS_NO_BADMATH.\r\n\tPRCOORDS_NUM radLat = wgs.lat / 180;\r\n\tPRCOORDS_NUM magic = 1 - GCJ_EE * pow(sinpi(radLat), 2); // just a common expr\r\n\r\n\t// [[:en:Latitude#Length_of_a_degree_of_latitude]]\r\n\tPRCOORDS_NUM lat_deg_arclen = (M_PI / 180) * (GCJ_A * (1 - GCJ_EE)) / pow(magic, 1.5);\r\n\t// [[:en:Longitude#Length_of_a_degree_of_longitude]]\r\n\tPRCOORDS_NUM lon_deg_arclen = (M_PI / 180) * (GCJ_A * cospi(radLat) / sqrt(magic));\r\n\t\r\n\t// The screwers pack their deviations into degrees and disappear.\r\n\t// Note how they are mixing WGS-84 and Krasovsky 1940 ellipsoids here...\r\n\treturn PRCoords{\r\n\t\twgs.lat + (dLat_m / lat_deg_arclen),\r\n\t\twgs.lon + (dLon_m / lon_deg_arclen),\r\n\t};\r\n}\r\n\r\nPRCoords prcoords_gcj_wgs(PRCoords gcj) {\r\n\tassume_coord(gcj);\r\n\treturn gcj - (prcoords_wgs_gcj(gcj) - gcj);\r\n}\r\n\r\nPRCoords prcoords_gcj_bd(PRCoords gcj) {\r\n\tassume_coord(gcj);\r\n\tPRCOORDS_NUM x = gcj.lon;\r\n\tPRCOORDS_NUM y = gcj.lat;\r\n\t\r\n\t// trivia: pycoordtrans actually describes how these values are calculated\r\n\tPRCOORDS_NUM r = sqrt(x * x + y * y) + 0.00002 * sinpi(y * 3000 / 180);\r\n\tPRCOORDS_NUM t = atan2(y, x) + 0.000003 * cospi(x * 3000 / 180);\r\n\t\r\n\t// Hard-coded default deviations again!\r\n\treturn PRCoords{\r\n\t\tr * sin(t) + BD_DLAT,\r\n\t\tr * cos(t) + BD_DLON,\r\n\t};\r\n}\r\n\r\nPRCoords prcoords_bd_gcj(PRCoords bd) {\r\n\tassume_coord(bd);\r\n\tPRCOORDS_NUM x = bd.lon - BD_DLON;\r\n\tPRCOORDS_NUM y = bd.lat - BD_DLAT;\r\n\t\r\n\tPRCOORDS_NUM r = sqrt(x * x + y * y) - 0.00002 * sinpi(y * 3000 / 180);\r\n\tPRCOORDS_NUM t = atan2(y, x) - 0.000003 * cospi(x * 3000 / 180);\r\n\t\r\n\treturn PRCoords{\r\n\t\tr * sin(t),\r\n\t\tr * cos(t),\r\n\t};\r\n}\r\n\r\nPRCoords prcoords_wgs_bd(PRCoords wgs) {\r\n\treturn prcoords_gcj_bd(prcoords_wgs_gcj(wgs));\r\n}\r\n\r\nPRCoords prcoords_bd_wgs(PRCoords bd) {\r\n\treturn prcoords_gcj_wgs(prcoords_bd_gcj(bd));\r\n}\r\n\r\nPRCoords prcoords_gcj_wgs_bored(PRCoords gcj) {\r\n\treturn bored_reverse_conversion<prcoords_wgs_gcj, prcoords_gcj_wgs>(gcj);\r\n}\r\nPRCoords prcoords_bd_gcj_bored(PRCoords bd) {\r\n\treturn bored_reverse_conversion<prcoords_gcj_bd, prcoords_bd_gcj>(bd);\r\n}\r\nPRCoords prcoords_bd_wgs_bored(PRCoords bd) {\r\n\treturn bored_reverse_conversion<prcoords_wgs_bd, prcoords_bd_wgs>(bd);\r\n}\r\n}\r\n\r\n#if PRCOORDS_TEST\r\n#include <iostream>\r\n#include <type_traits>\r\n\r\nstd::string show_coord(PRCoords v) {\r\n\treturn std::to_string(v.lat) + \", \" + std::to_string(v.lon);\r\n}\r\nint main(void) {\r\n\tstd::cout << std::is_pod<PRCoords>::value << std::endl\r\n\t\t\t  << show_coord(prcoords_wgs_gcj(PRCoords{35, 105})) << std::endl\r\n\t\t\t  << show_coord(prcoords_wgs_bd(PRCoords{35, 105})) << std::endl\r\n\t\t\t  << show_coord(prcoords_wgs_gcj(PRCoords{34, 106})) << std::endl\r\n\t\t\t  << show_coord(prcoords_wgs_bd(PRCoords{34, 106})) << std::endl;\r\n}\r\n#endif\r\n"
  },
  {
    "path": "cpp/prcoords.h",
    "content": "/**\r\n * People's Rectified Coordinates, C/C++ Header.\r\n */\r\n#ifndef PRCOORDS_H\r\n#define PRCOORDS_H\r\n\r\n/** May be changed to \"long double\" for bored folks\r\n  * (need an \"L\" suffix on literals for the seriously bored)\r\n  * \"float\" is not recommended\r\n  */\r\n#ifndef PRCOORDS_NUM\r\n#define PRCOORDS_NUM double\r\n#endif\r\n\r\n// Generic helper definitions for shared library support\r\n#if defined _WIN32 || defined __CYGWIN__\r\n  #define PRCOORDS_HELPER_DLL_IMPORT __declspec(dllimport)\r\n  #define PRCOORDS_HELPER_DLL_EXPORT __declspec(dllexport)\r\n  #define PRCOORDS_HELPER_DLL_LOCAL\r\n#else\r\n  #if __GNUC__ >= 4 // works on clang lmao\r\n    #define PRCOORDS_HELPER_DLL_IMPORT __attribute__ ((visibility (\"default\")))\r\n    #define PRCOORDS_HELPER_DLL_EXPORT __attribute__ ((visibility (\"default\")))\r\n    #define PRCOORDS_HELPER_DLL_LOCAL  __attribute__ ((visibility (\"hidden\")))\r\n  #else\r\n    #define PRCOORDS_HELPER_DLL_IMPORT\r\n    #define PRCOORDS_HELPER_DLL_EXPORT\r\n    #define PRCOORDS_HELPER_DLL_LOCAL\r\n  #endif\r\n#endif\r\n\r\n#ifdef PRCOORDS_DLL // defined if PRCOORDS is compiled as a DLL\r\n  #ifdef PRCOORDS_DLL_EXPORTS // defined if we are building the PRCOORDS DLL (instead of using it)\r\n    #define PRCOORDS_API PRCOORDS_HELPER_DLL_EXPORT\r\n  #else\r\n    #define PRCOORDS_API PRCOORDS_HELPER_DLL_IMPORT\r\n  #endif // PRCOORDS_DLL_EXPORTS\r\n  #define PRCOORDS_LOCAL PRCOORDS_HELPER_DLL_LOCAL\r\n#else // PRCOORDS_DLL is not defined: this means PRCOORDS is a static lib.\r\n  #define PRCOORDS_API\r\n  #define PRCOORDS_LOCAL\r\n#endif // PRCOORDS_DLL\r\n\r\n#ifdef __cplusplus\r\n#define PRCOORDS_CONSTEXPR constexpr\r\n\r\n#if __cplusplus >= 201300L\r\n#define PRCOORDS_CONSTEXPR14 constexpr\r\n#else\r\n#define PRCOORDS_CONSTEXPR14 inline\r\n#endif // c++14, including 1y\r\n\r\nextern \"C\" {\r\n#else\r\n#include <stdbool.h>\r\n#define PRCOORDS_CONSTEXPR inline\r\n#endif\r\n\r\ntypedef struct PRCoords {\r\n    PRCOORDS_NUM lat, lon;\r\n} PRCoords;\r\n\r\n// make them pure\r\n\r\n/// GCJ APIs should all probably turn on china-checks.\r\n/// But we should allow some override.... Damn C.\r\nPRCOORDS_API PRCoords prcoords_wgs_gcj(PRCoords);\r\nPRCOORDS_API PRCoords prcoords_gcj_wgs(PRCoords);\r\nPRCOORDS_API PRCoords prcoords_gcj_bd(PRCoords);\r\nPRCOORDS_API PRCoords prcoords_bd_gcj(PRCoords);\r\nPRCOORDS_API PRCoords prcoords_wgs_bd(PRCoords);\r\nPRCOORDS_API PRCoords prcoords_bd_wgs(PRCoords);\r\n\r\nPRCOORDS_API PRCoords prcoords_gcj_wgs_bored(PRCoords);\r\nPRCOORDS_API PRCoords prcoords_bd_gcj_bored(PRCoords);\r\nPRCOORDS_API PRCoords prcoords_bd_wgs_bored(PRCoords);\r\n\r\nPRCOORDS_LOCAL static PRCOORDS_CONSTEXPR bool prcoords_in_china(const PRCoords& a) {\r\n    // cut out some \r\n    return a.lat >= 16.7414 && a.lon >= 72.004 && a.lat <= 55.8271 && a.lon <= 137.8347;\r\n}\r\n\r\n#ifdef __cplusplus\r\n}\r\n\r\n\r\nPRCOORDS_LOCAL inline PRCoords operator- (const PRCoords& a, const PRCoords& b) {\r\n    return PRCoords {\r\n        a.lat - b.lat,\r\n        a.lon - b.lon\r\n    };\r\n}\r\n\r\n// for sorting\r\n//   lat\r\n//    |\r\n// -<-o---lon (quadrants III, IV and x < 0)\r\n//  < | <\r\nPRCOORDS_LOCAL inline bool operator< (const PRCoords& a, const PRCoords& b) {\r\n    return a.lat < b.lat || (a.lat == b.lat && a.lon < b.lon);\r\n}\r\nPRCOORDS_LOCAL inline bool operator> (const PRCoords& a, const PRCoords& b) { return b < a; }\r\nPRCOORDS_LOCAL inline bool operator<=(const PRCoords& a, const PRCoords& b) { return !(a > b); }\r\nPRCOORDS_LOCAL inline bool operator>=(const PRCoords& a, const PRCoords& b) { return !(a < b); }\r\n\r\nPRCOORDS_LOCAL inline bool operator==(const PRCoords& a, const PRCoords& b) {\r\n    return a.lat == b.lat && a.lon == b.lon;\r\n}\r\nPRCOORDS_LOCAL inline bool operator!=(const PRCoords& a, const PRCoords& b) { return !(a == b); }\r\n#endif // __cplusplus\r\n#endif // header\r\n"
  },
  {
    "path": "docs/demo.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n<!--\nSnapshot from http://jsbin.com/zonafut/37/edit\n-->\n  <meta name=\"viewport\" content=\"width=device-width\">\n  <meta name=\"author\" content=\"Mingye Wang\">\n  <meta name=\"description\" content=\"A Public Domain GCJ-02/BD-09 to WGS-84 Deobfscator (not eviltransform, but PRCoords)\">\n  <link href=\"https://Artoria2e5.github.io/PRCoords/Globe%2C_distorted_China.svg\" type=\"image/svg+xml\" rel=\"icon\">\n  <link rel=\"schema.DCTERMS\" href=\"http://purl.org/dc/terms/\">\n  <title>People Rectify Coordinates</title>\n<style id=\"jsbin-css\">\nbody {\n  font-family: sans-serif;\n  margin: 0 auto;\n  max-width: 50em;\n  padding: 0 1em;\n}\n\n@media print {\n  body {\n    max-width: none;\n    padding: 0;\n  }\n}\n\nh1, h2, h3, h4, h5, h6 {\n  font-family: serif;\n}\n\ndt {\n  font-weight: bold;\n}\n\nh1, h2, h3 {\n  border-bottom: 1px solid #a2a9b1;\n}\n\ninput[type='number'].dnum {\n  -moz-appearance:textfield;\n}\n\ninput[type='number'].dnum::-webkit-outer-spin-button,\ninput[type='number'].dnum::-webkit-inner-spin-button {\n  -webkit-appearance: none;\n}\n\ninput[type='number'] {\n  width: 4em;\n}\n\ninput[type='number'][name^=s] {\n  width: 6em\n}\n\n#deg-in input[type='number'] {\n  width: 8em\n}\n\n#output > table {\n  width: 100%\n}\n\nimg.logo {\n  position: absolute;\n  top: 1em;\n  right: 1em;\n  border: none;\n}\n\nfooter {\n  font-size: smaller;\n}\n\ntable {\n  border-collapse: collapse;\n}\n\ntd {\n  border: thin solid #a2a9b1;\n  padding: 0.2em 0.4em;\n}\n\ntbody td:nth-child(n+2) {\n  font-family: monospace;\n}\n\n#egcj td:nth-child(1), #ebd td:nth-child(1), #bbd td:nth-child(1) {\n  background: LightSalmon;\n}\n#dgcj td:nth-child(1), #dbd td:nth-child(1), #bgcj td:nth-child(1) {\n  background: PaleGreen;\n}\n#cgcj td:nth-child(1), #cbd td:nth-child(1), #bcgcj td:nth-child(1) {\n  background: Aquamarine;\n}\n\n</style>\n</head>\n<body onload=\"from_query()\">\n  <h1>People Rectify Coordinates</h1>\n  <div style=\"margin-top: -1em\"><small>With <a href=\"https://en.wikipedia.org/wiki/GCJ-02\">restrictions</a> from the People’s Republic of China</small></div>\n  <a href=\"https://commons.wikimedia.org/wiki/File:Globe,_distorted_China.svg\">\n  <img class=\"logo\" src=\"https://Artoria2e5.github.io/PRCoords/Globe%2C_distorted_China.svg\" width=\"100\" height=\"100\" alt=\"logo: China? Where?\"></a>\n  <article>\n    <section>\n      <h2>Input</h2>\n      <form id=\"inputc\" onsubmit=\"return false\"><!-- also make edge happy -->\n        <ul>\n        <li><label>Degrees:</label><ul id=\"deg-in\">\n          <li><label>lat=</label> <input type=\"number\" class=\"dnum\" name=\"lat\" value=\"35\" step=\"any\" min=\"-90\" max=\"90\">;\n          <li><label>lon=</label> <input type=\"number\" class=\"dnum\" name=\"lon\" value=\"105\" step=\"any\" min=\"-180\" max=\"180\">.</ul>\n        <li><label>Or dms:</label><ul id=\"dms-in\">\n          <li><label>lat=</label>\n              <input type=\"number\" name=\"dlat\" min=\"0\" max=\"90\" step=\"1\" value=\"35\">°\n              <input type=\"number\" name=\"mlat\" min=\"0\" max=\"59\" step=\"1\" value=\"0\">′\n              <input type=\"number\" name=\"slat\" min=\"0\" max=\"60\" value=\"0\" step=any>″\n              <select name=\"hlat\"><option>N</option><option>S</option></select>;\n          <li><label>lon=</label>\n              <input type=\"number\" name=\"dlon\" min=\"0\" max=\"180\" step=\"1\" value=\"105\">°\n              <input type=\"number\" name=\"mlon\" min=\"0\" max=\"59\" step=\"1\" value=\"0\">′\n              <input type=\"number\" name=\"slon\" min=\"0\" max=\"69\" value=\"0\" step=any>″\n              <select name=\"hlon\"><option>E</option><option>W</option></select>.</ul></ul>\n        <button onclick=\"return fill_output() && false\">Screw that!</button>\n      </form>\n      <script src=\"https://cdn.jsdelivr.net/npm/prcoords@1/js/PRCoords.min.js\" onerror=\"this.src='../js/PRCoords.js'\"></script>\n\n      <h2>Results</h2>\n      <table id=\"output\">\n        <tr>\n          <th>Operation\n          <th>Result\n          <th title=\"How wrong have I been?\">ΔObfs/m\n          <th title=\"How precise is this operation?\">ΔRoundtrip/m</tr>\n        <tr id=\"egcj\"><td>WGS → GCJ<td><td><td>\n        <tr id=\"ebd\"><td>WGS → BD<td><td><td>\n        <tr id=\"dgcj\"><td>GCJ → WGS<td><td><td>\n        <tr id=\"dbd\"><td>BD → WGS<td><td><td>\n        <tr id=\"cgcj\"><td>GCJ →<sup>cai</sup> WGS<td><td><td>\n        <tr id=\"cbd\"><td>BD →<sup>cai</sup> WGS<td><td><td>\n        <tr id=\"bbd\"><td>GCJ → BD<td><td><td>\n        <tr id=\"bgcj\"><td>BD → GCJ<td><td><td>\n        <tr id=\"bcgcj\"><td>BD →<sup>cai</sup> GCJ<td><td><td>\n      </table>\n      <p><a id=\"permalink\" href=\"https://artoria2e5.github.io/PRCoords/demo\">Permalink to this result</a>.\n      Toggle sections: <a href=\"javascript:toggle('notes')\">Notes</a>, <a href=\"javascript:toggle('faq')\">FAQ</a>, <a href=\"javascript:toggle('footer')\">footer</a>.\n      And <a href=\"javascript:window.print()\">print</a>.\n    </section>\n    <section id=\"notes\">\n      <h2>Notes</h2>\n      <ol>\n        <li>Caijun’s iterative method is included for precise decoding.\n            It's most useful for bored folks whose GPS data is pretty accurate\n            and GCJ-02 obfuscation not tainted by the original\n            <abbr title=\"linear congruential pseudo-random number generator\">LCPRNG</abbr>.\n            <p>If you are doing Wikipedia or any kind of archival work, use it to avoid introducing extra error.\n        <li>BD is defined in terms of GCJ, hence the last three functions.\n        <li>This demo omits the “in China” sanity check. Data regarding\n            Baidu’s behavior with overseas maps is needed for further\n            decisions. Observations:<ul>\n            <li>Unlike Google Maps, Baidu's map in Hong Kong is fully subject to\n                BD-09&nbsp;∘&nbsp;GCJ-02 chained distortions.\n            <li>Coordinates in Russia, outside of the sanity check rectangle, uses WGS-84 or and/or friends.\n            <li>TODO: check along the boundary.\n            </ul>\n      </ol>\n    </section>\n    <section id=\"faq\">\n      <h2>FAQ</h2>\n      <dl>\n        <dt id=\"what\">What is this all about?</dt>\n        <dd>The PRC government requires all local map services to use an\n            obfuscated, <a href=\"https://github.com/Artoria2e5/PRCoords/blob/1ea97f2/js/PRCoords.js#L102-L109\">\n            deviation-orienated</a> coordinate system.\n            Click on the “restriction” link to read the full Wikipedia article.</dd>\n        <dt id=\"why\">Why should I care?</dt>\n        <dd>With half a kilometer of deviation, GCJ-02 and friends fucks up your\n            <a href=\"https://github.com/iitc-project/ingress-intel-total-conversion/blob/75a517b/plugins/fix-googlemap-china-offset.user.js\">Ingress games</a>,\n            causes <a href=\"https://www.zhihu.com/question/29806566/answer/46099380\">crazy errors</a>\n            in elevation profiles along cycle routes, and cheerfully leads you\n            into roadside ditches plus a bone fracture.</dd>\n        <dt id=\"google\">Why doesn’t Google/Bing correct its Chinese data served to global users?</dt>\n        <dd><a href=\"https://productforums.google.com/forum/#!topic/maps/NunCUpRwLA0\">I don’t know</a>.\n            Perhaps they are afraid of getting fined or further kicked out of China.\n            Maybe try <a href=\"https://openstreetmap.org\">OpenStreetMap</a> next time?</dd>\n        <dt id=\"wheel\">Why are you writing another implementation?</dt>\n        <dd><a href=\"https://github.com/Artoria2e5/PRCoords#why-another-wheel\">Because I got bored</a>.</dd>\n        <dt id=\"caijun\">How does Caijun’s iterative method work?</dt>\n        <dd>Cai has explained the method in full in his\n            <a href=\"https://github.com/caijun/geoChina/blob/5c6284b/R/cst.R#L101-L107\"> R implementation</a>. Go read it, or read Wikipedia.\n      </dl>\n    </section>\n  </article>\n  <footer id=\"footer\">\n    <hr>\n    Powered by <a href=\"https://github.com/Artoria2e5/PRCoords\">PRCoords</a>. Try playing with <code>window.PRCoords</code> in your console!\n\n    <p>\n      <a rel=\"license\"\n        href=\"http://creativecommons.org/publicdomain/zero/1.0/\">\n        <img src=\"https://licensebuttons.net/p/zero/1.0/88x31.png\" style=\"border-style: none;\" alt=\"CC0\"></a>\n        <br>\n        To the extent possible under law,\n      <a rel=\"DCTERMS.publisher\"\n        href=\"https://zh.wikipedia.org/wiki/User:Artoria2e5\">\n        <span property=\"DCTERMS.title\">Mingye Wang</span></a>\n      has waived all copyright and related or neighboring rights to\n      <span property=\"DCTERMS.title\">People Rectify Coordinates</span>.\n      This work is published from:\n      <span property=\"geo.country\"\n          content=\"US\" about=\"https://artoria2e5.github.io/PRCoords/demo\">\n      United States</span>.</p>\n    </footer>\n<script>\n\"use strict\";\n\n// dms/deg\nvar coordInfo = {\n\t'N': [+1, 'lat'],\n\t'S': [-1, 'lat'],\n\t'E': [+1, 'lon'],\n\t'W': [-1, 'lon'],\n}\n\nvar coordBack = {\n\t'+lat': 'N',\n\t'-lat': 'S',\n\t'+lon': 'E',\n\t'-lon': 'W',\n}\n\nfunction dmsToDec(d, m, s, hemisphere = 'N', type = '') {\n\tif (type !== '') {\n\t\tif (coordInfo[hemisphere][1] !== type) {\n\t\t\tthrow new RangeError('' + hemisphere + ' ' + type)\n\t\t}\n\t}\n\treturn coordInfo[hemisphere][0] * Math.round(((+d) + (+m)/60 + (+s)/3600)*1e8)/1e8\n}\n\nfunction decToDms(dec, type) {\n\tvar sign = (+dec) >= 0 ? 1 : -1\n\tvar hemi = coordBack[(sign == -1 ? '-' : '+') + type]\n\n\tdec *= sign\n\tvar d = Math.floor(dec)\n\tvar m = Math.floor((dec-d)*60)\n\tvar s = Math.round((dec-d-m/60)*3600*1e4)/1e4\n\n\treturn [d, m, s, hemi]\n}\n\n// TODO refactor\n// link back to the referrer if we can recognize it\nvar relink = function(lat, lon, ref) {\n  try {\n    var uref = new URL(ref)\n  } catch (e) {\n    return\n  }\n\n  if (uref.hostname == \"tools.wmflabs.org\" &&\n      uref.pathname.startsWith(\"/geohack\")) {\n    var uparams = new URLSearchParams(uref.search.slice(1))\n    var uparam = uparams.get(\"params\").split('_')\n    uparam[0] = Math.abs(lat)\n    uparam[1] = coordBack[(+lat < 0 ? '-' : '+') + 'lat']\n    uparam[2] = Math.abs(lon)\n    uparam[3] = coordBack[(+lon < 0 ? '-' : '+') + 'lon']\n    uparams.set(\"params\", uparam.join('_'))\n    uref.search = uparams.toString()\n    return uref\n  }\n}\n\n// hooks\nvar inputs = document.getElementById('inputc')\nfunction updFromDeg (ev) {\n  if (ev.target.value === '')\n    return;\n  var type = ev.target.name\n  var dmsh = [\n    inputs['d'+type],\n    inputs['m'+type],\n    inputs['s'+type],\n    inputs['h'+type],\n  ]\n  ;[\n    dmsh[0].value,\n    dmsh[1].value,\n    dmsh[2].value,\n    dmsh[3].value,\n  ] = decToDms(+ev.target.value, type)\n}\nfunction updFromDms (ev) {\n  if (ev.target.value === '')\n    return;\n  var type = ev.target.name.substring(1)\n  inputs[type].value = dmsToDec(\n    inputs['d'+type].value,\n    inputs['m'+type].value,\n    inputs['s'+type].value,\n    inputs['h'+type].value,\n    type\n  )\n}; // <- happy edge\n\n// note: make edge happy:\n// * make an array for a iterator in Edge\n// * Don't use spread or Edge freaks out\nfor (let i of Array.from(inputs.querySelectorAll('#deg-in input')))\n  i.onchange = updFromDeg\n\nfor (let i of Array.from(inputs.querySelectorAll('#dms-in input, #dms-in select')))\n  i.onchange = updFromDms\n\n// handler..\nvar a_perm = document.getElementById('permalink')\nvar baseurl = a_perm.href\nfunction fill_output() {\n  // Edge shit\n  a_perm = a_perm || document.getElementById('permalink')\n  baseurl = baseurl || a_perm.href\n  // end Edge\n  var get_inverse = function (fname) {\n    var comp = fname.split('_')\n    return comp[1] + '_' + comp[0]/* +\n          (bored &&\n           comp[0] !== 'wgs'  &&\n           !(comp[0] === 'gcj' && comp[1] === 'bd')) ?\n          '_bored' : ''*/\n  }\n  var fnames = {\n    dgcj: 'gcj_wgs',\n    dbd: 'bd_wgs',\n    egcj: 'wgs_gcj',\n    ebd: 'wgs_bd',\n    cgcj: 'gcj_wgs_bored',\n    cbd: 'bd_wgs_bored',\n    bgcj: 'bd_gcj',\n    bbd: 'gcj_bd',\n    bcgcj: 'bd_gcj_bored',\n  }\n  var incoords = {\n    lat: +inputs.lat.value,\n    lon: +inputs.lon.value,\n  }\n  console.log(incoords)\n\n  var coordToHtml = function(c) {\n    var lat = c.lat.toFixed(8)\n    var lon = c.lon.toFixed(8)\n    var ret = '(' + lat + ', ' + lon + ')'\n    var relinked = relink(lat, lon, document.referrer)\n    if (relinked) {\n      var a_boi = document.createElement(\"a\")\n      a_boi.innerText = ret\n      a_boi.href = relinked\n      ret = a_boi.outerHTML\n    }\n    ret += '<br/>'\n\n    var dms = decToDms(lat, 'lat')\n    ret += dms[0] + '°' + dms[1] + '′' + dms[2] + '″&nbsp;' + dms[3] + ', '\n    dms = decToDms(lon, 'lon')\n    return ret + dms[0] + '°' + dms[1] + '′' + dms[2] + '″ ' + dms[3]\n  }\n\n  for (var i in fnames) {\n    var row = document.getElementById(i)\n    var fun = PRCoords[fnames[i]]\n    var inv = PRCoords[get_inverse(fnames[i])]\n    var out = Array.from(row.childNodes).slice(1)\n\n    var res = fun(incoords, false)\n    var dObfs = PRCoords.distance(res, incoords)\n    var dRoundtrip = PRCoords.distance(inv(res, false), incoords)\n    out[0].innerHTML = coordToHtml(res)\n    out[1].innerText = dObfs.toExponential()\n    out[2].innerText = dRoundtrip.toExponential()\n  }\n  a_perm.href = baseurl + '?lat=' + incoords.lat + '&lon=' + incoords.lon // + '#output'\n  return false\n}\n\n/// *** polyfill handling *** ///\n\n// https://philipwalton.com/articles/loading-polyfills-only-when-needed/\nfunction loadScript(src, done) {\n  var js = document.createElement('script')\n  js.src = src\n  js.onload = function() {\n    done()\n  }\n  js.onerror = function() {\n    done(new Error('Failed to load script ' + src))\n  }\n  document.head.appendChild(js)\n}\n/// ^^^ polyfill handling ^^^ ///\n\nfunction __from_query() {\n  function qe(s, d) {\n    return s ? s : d\n  }\n  try {\n    let params = new URLSearchParams(location.search.slice(1))\n    inputs.lat.value = qe(params.get('lat'), inputs.lat.value)\n    inputs.lon.value = qe(params.get('lon'), inputs.lon.value)\n    // trigger a dms update\n    var event = new Event(\"change\")\n    for (let i of  Array.from(inputs.querySelectorAll('#deg-in input')))\n      i.dispatchEvent(event)\n  }\n  catch (e) {\n    console.error(e)\n  }\n  return fill_output()\n}\n\nfunction from_query() {\n  if (typeof URLSearchParams !== 'undefined') {\n    return __from_query()\n  } else {\n  // https://github.com/WebReflection/url-search-params\n    loadScript(\"https://cdn.rawgit.com/WebReflection/url-search-params/774ee42/build/url-search-params.js\", __from_query)\n  }\n}\n\nfunction toggle(id) {\n  var el = document.getElementById(id)\n  if (el.style.display !== 'none')\n    el.style.display = 'none'\n  else\n    el.style.display = ''\n}\nconsole.log('syntax looks right')\n</script>\n\n</body>\n</html>\n"
  },
  {
    "path": "docs/index.md",
    "content": "<script>window.location.replace('https://github.com/Artoria2e5/PRCoords/')</script>\n<script>window.location.href = 'https://github.com/Artoria2e5/PRCoords/'</script>\nJust go to the <a href=\"https://github.com/Artoria2e5/PRCoords\">GitHub repo</a>.\n"
  },
  {
    "path": "docs/proj4_plugin.js",
    "content": "// mirror of https://runkit.com/artoria2e5/proj4-plugin-prcoords\nconst proj4 = require(\"proj4\")\nconst prcoords = require(\"prcoords\")\nconst noop = Function.prototype\nconst DEG = Math.PI / 180\n\nfunction xy_to_ll(p) {\n  return { lon: p.x / DEG, lat: p.y / DEG }\n}\nfunction ll_to_xy(p) {\n  return { x: p.lon * DEG, y: p.lat * DEG }\n}\nfunction xy_rename_ll(p) {\n  return { lon: p.x, lat: p.y }\n}\nfunction ll_rename_xy(p) {\n  return { x: p.lon, y: p.lat }\n}\n\nfunction wrap(f, ...args) {\n  return (p) => ll_to_xy(f(xy_to_ll(p), ...args))\n}\n\n// We lie our way to Baidu \"Mercator\".\nproj4.defs([\n  [\n    \"_CLARK_MC\",\n    \"+proj=merc +a=6378206.4 +b=6356583.8 +lat_ts=0.0 +lon_0=0.0 +x_0=0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs\",\n  ],\n  [\"_CLARK_LL\", \"+proj=longlat +a=6378206.4 +b=6356583.8\"],\n])\n\nproj4.Proj.projections.add({\n  init: noop,\n  forward: wrap(prcoords.wgs_gcj),\n  inverse: wrap(prcoords.gcj_wgs_bored),\n  names: [\"gcj\", \"gcj02\", \"CN_Obfs_GCJ_2002_Ellipsoidal\"],\n})\n\nproj4.Proj.projections.add({\n  init: noop,\n  forward: wrap(prcoords.wgs_bd),\n  inverse: wrap(prcoords.bd_wgs_bored),\n  names: [\"baidu\", \"bd09\", \"CN_Obfs_Baidu_2009_Ellipsoidal\"],\n})\n\nproj4.Proj.projections.add({\n  init: noop,\n  forward: (p) =>\n    proj4(\"_CLARK_LL\", \"_CLARK_MC\", ll_rename_xy(prcoords.wgs_bd(xy_to_ll(p)))),\n  inverse: (p) =>\n    ll_to_xy(\n      prcoords.bd_wgs_bored(xy_rename_ll(proj4(\"_CLARK_MC\", \"_CLARK_LL\", p))),\n    ),\n  names: [\"baidu\", \"bd09mc\", \"CN_Obfs_Baidu_2009_Mercator\"],\n})\n\nproj4.defs([\n  // Why isn't units=degrees working... work around with wrap() now.\n  [\"GCJ02\", \"+title=GCJ 02 (long/lat) +proj=gcj02 +units=degrees\"],\n  [\"BD09\", \"+title=Baidu 2009 (long/lat) +proj=bd09 +units=degrees\"],\n  [\"BD09MC\", \"+title=Baidu 2009 (Mercator) +proj=bd09mc +units=m\"],\n])\n\nconsole.log([\n  // should be the same as https://artoria2e5.github.io/PRCoords/demo\n  xy_to_ll(proj4(\"WGS84\", \"BD09\", { x: 105, y: 35 })),\n  xy_to_ll(proj4(\"WGS84\", \"GCJ02\", { x: 105, y: 35 })),\n])\n\nconsole.log([\n  // should be very close to the original\n  proj4(\n    \"BD09\",\n    \"WGS84\",\n    ll_to_xy({ lat: 35.005403668456964, lon: 105.00966682831948 }),\n  ),\n  proj4(\n    \"GCJ02\",\n    \"WGS84\",\n    ll_to_xy({ lat: 34.99909863223526, lon: 105.00328624145706 }),\n  ),\n])\n\nconsole.log([\n  proj4(\"WGS84\", \"BD09MC\", { x: 105, y: 35 }),\n  proj4(\"BD09MC\", \"WGS84\", { x: 11689750, y: 4139877 }),\n])\n"
  },
  {
    "path": "haskell/PRCoords.cabal",
    "content": "-- Initial prcoords.cabal generated by cabal init.  For further \n-- documentation, see http://haskell.org/cabal/users-guide/\n\n-- The name of the package.\nname:                PRCoords\n\n-- The package version.  See the Haskell package versioning policy (PVP) \n-- for standards guiding when and how versions should be incremented.\n-- http://www.haskell.org/haskellwiki/Package_versioning_policy\n-- PVP summary:      +-+------- breaking API changes\n--                   | | +----- non-breaking API additions\n--                   | | | +--- code changes with no API change\nversion:             0.1.0.0\n\n-- A short (one-line) description of the package.\nsynopsis:            Library for GCJ-02 and BD-09 (de)obfuscation from/to WGS-84. May trigger mental episodes.\n\ndescription:         People's Rectified Coordinates (PRCoords) is a cross-language implementation of \"public secret\" Chinese coordinate obfuscation methods including GCJ-02 and BD-09, along with general deobfuscation methods previously established in pycoordtrans, eviltransform, and geoChina.\n\n-- URL for the project homepage or repository.\nhomepage:            https://github.com/Artoria2e5/PRCoords\n\n-- The license under which the package is released.\nlicense:             PublicDomain\n\n-- The file containing the license text.\n-- license-file:        LICENSE\n\n-- The package author(s).\nauthor:              Mingye Wang\n\n-- An email address to which users can send suggestions, bug reports, and \n-- patches.\nmaintainer:          arthur200126@gmail.com\n\n-- A copyright notice.\n-- copyright:           \n\ncategory:            Geography\n\nbuild-type:          Simple\n\n-- Extra files to be distributed with the package, such as examples or a \n-- README.\n-- extra-source-files:  \n\n-- Constraint on the version of Cabal needed to build this package.\ncabal-version:       >=1.10\n\n\nlibrary\n  -- Modules exported by the library.\n  exposed-modules: PRCoords \n  \n  -- Modules included in this library but not exported.\n  -- other-modules:       \n  \n  -- LANGUAGE extensions used by modules in this package.\n  other-extensions: BangPatterns\n  \n  -- Other library packages from which modules are imported.\n  build-depends:\n    base -- >=4.8 && <4.9\n    -- AC-Angle\n  \n  -- Directories containing source files.\n  -- hs-source-dirs:      \n  \n  -- Base language which the package is written in.\n  default-language:    Haskell2010\n  \n"
  },
  {
    "path": "haskell/PRCoords.hs",
    "content": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -fexcess-precision #-}\n{-# OPTIONS_GHC -optc-ffast-math -optllc--enable-unsafe-fp-math -optllc--enable-no-nans-fp-math -optllc--enable-no-infs-fp-math #-}\n\n--- | This module contains functions for generating People's Rectified Coordinates.\n--- Jeez, my naming is awful.\nmodule PRCoords where -- (wgsGcj, gcjBd, wgsBd, gcjWgs, bdGcj, bdWgsC, gcjWgsC, bdGcjC, bdWgsC, caijun)\n    -- import Data.Angle\n    -- import Numeric.FastMath\n    \n    data PCoords = PCoords { !lat :: Double\n                           , !lon :: Double } deriving (Eq, Ord, Show)\n    \n    subtractPCoords :: PCoords -> PCoords -> PCoords\n    subtractPCoords a b = PCoords (lat a - lat b) (lon a - lon b)\n    \n    wgsGcj :: PCoords -> PCoords\n    wgsGcj (PCoords lat lon) = PCoords (lat + dLat / arclenLat) (lon + dLon / arclenLon) where\n        gcj_a  = 6378245.0              -- <_ Krasovsky 1940\n        gcj_ee = 0.00669342162296594323 -- f = 1/2983; e^2 = 2*f - f**2\n        magic  = 1 - gcj_ee * ((sin (pi * lat / 180)) ** 2) -- common expr\n        arclenLat = (pi / 180) * (gcj_a * (1 - gcj_ee)) / (magic ** 1.5)\n        arclenLon = (pi / 180) * (gcj_a * (cos (pi * lat / 180)) / (sqrt magic))\n        x = lon - 105 -- Here goes the deviation\n        y = lat - 35\n        gcjTerm !v !f !n = n * (sin f * v * pi)\n        -- check operator stuff later\n        dLat = -100 + 2 * x + 3 * y + 0.2 * y ** 2 + 0.1 * x * y + 0.2 * (sqrt (abs x)) + (*) (20/3) (\n               gcjTerm x 6 2 + gcjTerm x 2 2 + gcjTerm y 1 2 + gcjTerm y (1/3) 4 +\n               gcjTerm y (1/12) 16 + gcjTerm y (1/30) 32)\n        dLon = 300 + 1 * x + 2 * y + 0.1 * x ** 2 + 0.1 * x * y + 0.1 * (sqrt (abs x)) + (*) (20/3) (\n              gcjTerm x 6 2 + gcjTerm x 2 2 + gcjTerm x 1 2 + gcjTerm x (1/3) 4 +\n              gcjTerm x (1/12) 15 + gcjTerm y (1/30) 30)\n    \n    gcjWgs :: PCoords -> PCoords\n    gcjWgs a = subtractPCoords a (subtractPCoords ga a) where\n        ga = wgsGcj a\n    \n    caiFix :: (PCoords -> PCoords) -> PCoords -> PCoords -> Int -> PCoords\n    caiFix fwd guess fwd_result iter\n        | iter > 5 = better\n        | (abs $ lon diff) + (abs $ lat diff) < 1E-5 = better\n        | otherwise = caiFix fwd better fwd_result (iter+1)\n        where fwd_guess = fwd guess\n              diff = subtractPCoords fwd_guess fwd_result\n              better = subtractPCoords guess diff\n    \n    caijun :: (PCoords -> PCoords) -> (PCoords -> PCoords) -> (PCoords -> PCoords)\n    caijun fwd rev = (\\x -> caiFix fwd (rev x) x 0)\n    \n    gcjWgsC :: PCoords -> PCoords\n    gcjWgsC = caijun wgsGcj gcjWgs\n    \n    -- next: baidu\n"
  },
  {
    "path": "haskell/Setup.hs",
    "content": "import Distribution.Simple\nmain = defaultMain\n"
  },
  {
    "path": "js/.npmignore",
    "content": "misc\n"
  },
  {
    "path": "js/PRCoords.d.ts",
    "content": "// Type definitions for PRCoords\r\n// Project: PRCoords\r\n\r\nexport as namespace PRCoords\r\n\r\nexport interface PRCoord {\r\n\tlat: number\r\n\tlon: number\r\n}\r\nexport type PRCoordOp = (c: PRCoord, checkChina?: boolean) => PRCoord\r\n\r\nexport function distance(a: PRCoord, b: PRCoord): number\r\n\r\n// We do not use the PRCO type to make it a bit more transparent on the IDE\r\nexport function gcj_wgs(c: PRCoord, checkChina?: boolean): PRCoord\r\nexport function wgs_gcj(c: PRCoord, checkChina?: boolean): PRCoord\r\nexport function wgs_gcj_bored(c: PRCoord, checkChina?: boolean): PRCoord\r\nexport function gcj_bd(c: PRCoord, __dummy__?: boolean): PRCoord\r\nexport function bd_gcj(c: PRCoord, __dummy__?: boolean): PRCoord\r\nexport function bd_gcj_bored(c: PRCoord, __dummy__?: boolean): PRCoord\r\nexport function wgs_bd(c: PRCoord, checkChina?: boolean): PRCoord\r\nexport function bd_wgs(c: PRCoord, checkChina?: boolean): PRCoord\r\nexport function bd_wgs_bored(c: PRCoord, checkChina?: boolean): PRCoord\r\nexport function __bored__(fwd: PRCoordOp, rev: PRCoordOp): PRCoordOp\r\n"
  },
  {
    "path": "js/PRCoords.js",
    "content": ";(function (factory, scope) {\n\t\"use strict\"\n\tvar res = factory()\n\tif (typeof module === 'object') {\n\t\tmodule.exports = res\n\t} else {\n\t\tif (typeof define === 'function' && define.amd)\n\t\t\tdefine('prcoords', function() { return res })\n\t\ttry {\n\t\t\t// Global can be undefined\n\t\t\tscope.PRCoords = res\n\t\t} catch(e) {}\n    }\n})((function (){\n\"use strict\"\n// <nowiki>\n/**\n * People's Rectified Coordinates\n * @file Utils for inserting valid WGS-84 coords from GCJ-02/BD-09 input\n * @author User:Artoria2e5\n * @url https://github.com/Artoria2e5/PRCoords\n * \n * @see [[:en:GCJ-02]]\n * @see https://en.wikipedia.org/wiki/User:Artoria2e5/coord-notice\n * @see https://github.com/caijun/geoChina (GPLv3)\n * @see https://github.com/googollee/eviltransform (MIT)\n * @see https://on4wp7.codeplex.com/SourceControl/changeset/view/21483#353936 (Anonymous)\n * @see https://github.com/zxteloiv/pycoordtrans (BSD-3)\n * \n * @license CC0\n * To the greatest extent possible, this implementation of obfuscations designed\n * in hope that they will screw y'all up is dedicated into the public domain\n * under CC0 1.0 <https://creativecommons.org/publicdomain/zero/1.0/>.\n *\n * Happy geotagging/ingressing/whatever.\n * \n * To make my FSF membership shine brighter, this conversion implementation is\n * additionally licensed under GPLv3+:\n * @license GPLv3+\n * @copyright 2016 Mingye Wang (User:Artoria2e5)\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 3 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\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n/// Krasovsky 1940 ellipsoid\n/// @const\nvar GCJ_A = 6378245\nvar GCJ_EE = 0.00669342162296594323 // f = 1/298.3; e^2 = 2*f - f**2\n\n/// Epsilon to use for \"exact\" iterations.\n/// Wanna troll? Use Number.EPSILON. 1e-13 in 15 calls for gcj.\n/// @const\nvar PRC_EPS = 1e-5\n\n/// Baidu's artificial deviations\n/// @const\nvar BD_DLAT = 0.0060\nvar BD_DLON = 0.0065\n\n/// Mean Earth Radius\n/// @const\nvar EARTH_R = 6371000\n\n/// Distance for haversine method; suitable over short distances like\n/// conversion deviation checking\nfunction distance(a, b) {\n\tfunction hav(θ) {\n\t\treturn Math.pow(Math.sin(θ/2), 2)\n\t}\n\t\n\tvar Δ = _coord_diff(a, b)\n\treturn 2 * EARTH_R * Math.asin(Math.sqrt(\n\t\thav(Δ.lat * Math.PI / 180) +\n\t\t\tMath.cos(a.lat * Math.PI / 180) *\n\t\t\tMath.cos(b.lat * Math.PI / 180) *\n\t\t\thav(Δ.lon  * Math.PI / 180)\n\t))\n}\n\nfunction sanity_in_china_p(coords) {\n\treturn coords.lat >= 0.8293 && coords.lat <= 55.8271 &&\n           coords.lon >= 72.004 && coords.lon <= 137.8347\n}\n\nfunction _coord_diff(a, b) {\n\treturn {\n\t\tlat: a.lat - b.lat,\n\t\tlon: a.lon - b.lon,\n\t}\n}\n\nfunction _stringify(c) {\n\treturn \"(\" + c.lat + \", \" + c.lon + \")\"\n}\n\nfunction wgs_gcj(wgs, checkChina) {\n\tif ((checkChina === undefined || checkChina) && !sanity_in_china_p(wgs)) {\n\t\tconsole.warn(\"Non-Chinese coords found, returning as-is: \" +\n\t\t\t\t\t _stringify(wgs))\n\t\treturn wgs\n\t}\n\t\n\tvar x = wgs.lon - 105, y = wgs.lat - 35\n\t\n\t// These distortion functions accept (x = lon - 105, y = lat - 35).\n\t// They return distortions in terms of arc lengths, in meters.\n\t//\n\t// In other words, you can pretty much figure out how much you will be off\n\t// from WGS-84 just through evaulating them...\n\t//\n\t// For example, at the (mapped) center of China (105E, 35N), you get a\n\t// default deviation of <300, -100> meters.\n\tvar dLat_m = -100 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y +\n\t\t0.2 * Math.sqrt(Math.abs(x)) + (\n\t        2 * Math.sin(x * 6 * Math.PI) + 2 * Math.sin(x * 2 * Math.PI) +\n\t        2 * Math.sin(y * Math.PI) + 4 * Math.sin(y / 3 * Math.PI) +\n\t        16 * Math.sin(y / 12 * Math.PI) + 32 * Math.sin(y / 30 * Math.PI)\n        ) * 20 / 3\n\tvar dLon_m = 300 + x + 2 * y + 0.1 * x * x + 0.1 * x * y +\n\t\t0.1 * Math.sqrt(Math.abs(x)) + (\n        \t2 * Math.sin(x * 6 * Math.PI) + 2 * Math.sin(x * 2 * Math.PI) +\n\t        2 * Math.sin(x * Math.PI) + 4 * Math.sin(x / 3 * Math.PI) +\n\t        15 * Math.sin(x / 12 * Math.PI) + 30 * Math.sin(x / 30 * Math.PI)\n        ) * 20 / 3\n    \n    \n    var radLat = wgs.lat / 180 * Math.PI\n    var magic = 1 - GCJ_EE * Math.pow(Math.sin(radLat), 2) // just a common expr\n    \n    // [[:en:Latitude#Length_of_a_degree_of_latitude]]\n    var lat_deg_arclen = (Math.PI / 180) * (GCJ_A * (1 - GCJ_EE)) / Math.pow(magic, 1.5)\n    // [[:en:Longitude#Length_of_a_degree_of_longitude]]\n    var lon_deg_arclen = (Math.PI / 180) * (GCJ_A * Math.cos(radLat) / Math.sqrt(magic))\n    \n    // The screwers pack their deviations into degrees and disappear.\n    // Note how they are mixing WGS-84 and Krasovsky 1940 ellipsoids here...\n    return {\n    \tlat: wgs.lat + (dLat_m / lat_deg_arclen),\n    \tlon: wgs.lon + (dLon_m / lon_deg_arclen),\n    }\n}\n\n// rev_transform_rough; accuracy ~2e-6 deg (meter-level)\nfunction gcj_wgs(gcj, checkChina) {\n\treturn _coord_diff(gcj, _coord_diff(wgs_gcj(gcj, checkChina), gcj))\n}\n\nfunction gcj_bd(gcj, __dummy__) {\n\tvar x = gcj.lon\n\tvar y = gcj.lat\n\n\t// trivia: pycoordtrans actually describes how these values are calculated\n\tvar r = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI * 3000 / 180)\n\tvar θ = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI * 3000 / 180)\n\t\n\t// Hard-coded default deviations again!\n\treturn {\n\t\tlat: r * Math.sin(θ) + BD_DLAT,\n\t\tlon: r * Math.cos(θ) + BD_DLON,\n\t}\n}\n\n// Yes, we can implement a \"precise\" one too.\n// accuracy ~1e-7 deg (decimeter-level; exceeds usual data accuracy)\nfunction bd_gcj(bd, __dummy__) {\n\tvar x = bd.lon - BD_DLON\n\tvar y = bd.lat - BD_DLAT\n\t\n\t// trivia: pycoordtrans actually describes how these values are calculated\n\tvar r = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI * 3000 / 180)\n\tvar θ = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI * 3000 / 180)\n\t\n\treturn {\n\t\tlat: r * Math.sin(θ),\n\t\tlon: r * Math.cos(θ),\n\t}\n}\n\nfunction bd_wgs(bd, checkChina) {\n\treturn gcj_wgs(bd_gcj(bd), checkChina)\n}\n\nfunction wgs_bd(bd, checkChina) {\n\treturn gcj_bd(wgs_gcj(bd, checkChina))\n}\n\n// generic \"bored function\" factory, Caijun 2014\n// gcj: 4 calls to wgs_gcj; ~0.1mm acc\nfunction __bored__(fwd, rev) {\n\treturn function rev_bored(heck, checkChina) {\n\t\tif (checkChina === undefined) checkChina = true\n\t\tvar curr = rev(heck, checkChina)\n\t\tvar diff = {lat: Infinity, lon: Infinity}\n\n\t\t// Wait till we hit fixed point or get bored\n\t\tvar i = 0\n\t\twhile (Math.max(Math.abs(diff.lat), Math.abs(diff.lon)) > PRC_EPS && i++ < 10) {\n\t\t\tdiff = _coord_diff(fwd(curr, checkChina), heck)\n\t\t\tcurr = _coord_diff(curr, diff)\n\t\t}\n\t\t\n\t\treturn curr\n\t}\n}\n\nvar exports = {\n\tdistance: distance,\n\twgs_gcj: wgs_gcj,\n\tgcj_wgs: gcj_wgs,\n\tgcj_bd: gcj_bd,\n\tbd_gcj: bd_gcj,\n\twgs_bd: wgs_bd,\n\tbd_wgs: bd_wgs,\n\t\n\t// Precise functions using caijun 2014 method\n\t//\n\t// Why \"bored\"? Because they usually exceed source data accuracy -- the\n\t// original GCJ implementation contains noise from a linear-modulo PRNG,\n\t// and Baidu seems to do similar things with their API too.\n\t__bored__: __bored__,\n\tgcj_wgs_bored: __bored__(wgs_gcj, gcj_wgs),\n\tbd_gcj_bored: __bored__(gcj_bd, bd_gcj),\n\tbd_wgs_bored: __bored__(wgs_bd, bd_wgs),\n}\n// We can stub this out too if we are aiming for ES3, but then there are no\n// trailing commas\nObject.defineProperty(exports, '__esModule', { value: true })\n\nreturn exports\n}), typeof self !== 'undefined' ? self : typeof this !== undefined ? this : globalThis)\n"
  },
  {
    "path": "js/misc/insane_is_in_china.js",
    "content": "(function(){\n\"use strict\"\n// Insane version of the \"is in China\" check (70 points. I tried.)\n//\n// Dedicated to the Public Domain under CC0, except for pnpoly by\n// Wm. Randolph Franklin (BSD3)\n//\n// Incorrect use of this polygon can lead to adverse geopolitical issues.\n// This set of points is only intended to approximate the scope of a type of distortion,\n// and has nothing to do with any political entities.\n//\n// Also, screw geodetics. The Earth is flat according to this approximation.\n\n/// *** pnpoly *** ///\n// Copyright (c) 1970-2003, Wm. Randolph Franklin\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n//   1. Redistributions of source code must retain the above copyright\n//      notice, this list of conditions and the following disclaimers.\n//   2. Redistributions in binary form must reproduce the above\n//      copyright notice in the documentation and/or other materials\n//      provided with the distribution.\n//   3. The name of W. Randolph Franklin may not be used to endorse or\n//      promote products derived from this Software without specific\n//      prior written permission. \n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\nfunction pnpoly(xs, ys, x, y) {\n  if (! (xs.length === ys.length))\n    throw new Error(\"pnpoly: assert(xs.length === ys.length)\")\n  var inside = 0\n  // j records previous value. Also handles wrapping around.\n  for (let i = 0, j = xs.length - 1; i < xs.length; j = i++)\n    inside ^= (((ys[i] > y) !== (ys[j] > y)) &&\n              (x < (xs[j] - xs[i]) * (y - ys[i]) / (ys[j] - ys[i]) + xs[i]))\n  // Let's make js as magical as C. Yay.\n  return !!inside\n}\n/// ^^^ pnpoly ^^^ ///\n\n// We will need to filter out these points for Baidu.\n// (We will need South China Sea too.)\nvar is_near_hkmo = function (lat, lon) {\n  return 22 <= lat && lat <= 22.7 && 113.5 <= lon && lon <= 114.5\n}\n// Well we now have indices for HK/MO.\nvar HK_LENGTH = 12\n\n// lon, lat\nvar POINTS = [\n  // start hkmo\n  114.433722, 22.064310,\n  114.009458, 22.182105,\n  113.599275, 22.121763,\n  113.583463, 22.176002,\n  113.530900, 22.175318,\n  113.529542, 22.210608,\n  113.613377, 22.227435,\n  113.938514, 22.483714,\n  114.043449, 22.500274,\n  114.138506, 22.550640,\n  114.222984, 22.550960,\n  114.366803, 22.524255,\n  // end hkmo\n  115.254019, 20.235733,\n  121.456316, 26.504442,\n  123.417261, 30.355685,\n  124.289197, 39.761103,\n  126.880509, 41.774504,\n  127.887261, 41.370015,\n  128.214602, 41.965359,\n  129.698745, 42.452788,\n  130.766139, 42.668534,\n  131.282487, 45.037051,\n  133.142361, 44.842986,\n  134.882453, 48.370596,\n  132.235531, 47.785403,\n  130.980075, 47.804860,\n  130.659026, 48.968383,\n  127.860252, 50.043973,\n  125.284310, 53.667091,\n  120.619316, 53.100485,\n  119.403751, 50.105903,\n  117.070862, 49.690388,\n  115.586019, 47.995542,\n  118.599613, 47.927785,\n  118.260771, 46.707335,\n  113.534759, 44.735134,\n  112.093739, 45.001999,\n  111.431259, 43.489381,\n  105.206324, 41.809510,\n  96.485703, 42.778692,\n  94.167961, 44.991668,\n  91.130430, 45.192938,\n  90.694601, 47.754437,\n  87.356293, 49.232005,\n  85.375791, 48.263928,\n  85.876055, 47.109272,\n  82.935423, 47.285727,\n  81.929808, 45.506317,\n  79.919457, 45.108122,\n  79.841455, 42.178752,\n  73.334917, 40.076332,\n  73.241805, 39.062331,\n  79.031902, 34.206413,\n  78.738395, 31.578004,\n  80.715812, 30.453822,\n  81.821692, 30.585965,\n  85.501663, 28.208463,\n  92.096061, 27.754241,\n  94.699781, 29.357171,\n  96.079442, 29.429559,\n  98.910308, 27.140660,\n  97.404057, 24.494701,\n  99.400021, 23.168966,\n  100.697449, 21.475914,\n  102.976870, 22.616482,\n  105.476997, 23.244292,\n  108.565621, 20.907735,\n  107.730505, 18.193406,\n  110.669856, 17.754550,\n]\n\nvar lats = POINTS.filter((ditch, i) => i % 2 == 1)\nvar lons = POINTS.filter((ditch, i) => i % 2 == 0)\nPOINTS = null // no need\n\nvar bdlats = lats.slice(HK_LENGTH)\nvar bdlons = lons.slice(HK_LENGTH)\n\nfunction isInGoogle(lat, lon) {\n  // Yank out South China Sea\n  if (lat <= 17.75455)\n    return false;\n  return pnpoly(lats, lons, lat, lon)\n}\n\nfunction isInBaidu(lat, lon) {\n  // Yank out South China Sea, as:\n  // 1. Nobody wants Baidu's crap Sansha data\n  // 2. I am too lazy to add like four points\n  if (lat <= 17.75455)\n    return false;\n  return pnpoly(bdlats, bdlons, lat, lon)\n}\n\nexports = {isInBaidu: isInBaidu, isInGoogle: isInGoogle}\n\nif (typeof module === \"object\" && module.exports) {\n\tmodule.exports = exports\n} else if (typeof window !== \"undefined\") {\n\twindow.PRCoords = exports\n}\n})()\n"
  },
  {
    "path": "js/misc/package.json",
    "content": "{\n    \"name\": \"insane-in-china\",\n    \"version\": \"0.0.1\",\n    \"description\": \"Routine for deciding whether one coordiate might be affected by Chinese obfuscation.\",\n    \"main\": \"insane_is_in_china.js\",\n    \"repository\": {\n        \"type\": \"git\",\n        \"url\": \"https://github.com/Artoria2e5/PRCoords.git\",\n        \"directory\": \"js/misc\"\n    },\n    \"keywords\": [\n        \"gcj\", \"wgs\", \"bd\", \"baidu\", \"coordinates\", \"pnpoly\"\n    ],\n    \"author\": \"Mingye Wang (Artoria2e5) <arthur200126@gmail.com>\",\n    \"license\": \"BSD-3-Clause\",\n    \"bugs\": {\n        \"url\": \"https://github.com/Artoria2e5/PRCoords/issues\"\n    }\n}\n"
  },
  {
    "path": "js/package.json",
    "content": "{\n    \"name\": \"prcoords\",\n    \"version\": \"1.0.3-rc1\",\n    \"description\": \"Chinese coordinate obfuscation methods (GCJ-02, BD-09) and inverses.\",\n    \"main\": \"PRCoords.js\",\n    \"repository\": {\n        \"type\": \"git\",\n        \"url\": \"https://github.com/Artoria2e5/PRCoords.git\",\n        \"directory\": \"js\",\n        \"//note\": \"Unused before I figure out what to do with docs and readme.\"\n    },\n    \"keywords\": [\n        \"gcj\",\n        \"wgs\",\n        \"bd\",\n        \"baidu\",\n        \"coordinates\"\n    ],\n    \"author\": \"Mingye Wang (Artoria2e5) <arthur200126@gmail.com>\",\n    \"license\": \"CC0-1.0\",\n    \"bugs\": {\n        \"url\": \"https://github.com/Artoria2e5/PRCoords/issues\"\n    },\n    \"dependencies\": {}\n}\n"
  },
  {
    "path": "julia/Project.toml",
    "content": "name = \"PRCoords\"\nuuid = \"0c59880a-3f55-4b0d-8a02-bd83932d11da\"\nauthors = [\"Mingye Wang <arthur2e5@aosc.io>\"]\nversion = \"0.1.0\"\n"
  },
  {
    "path": "julia/src/PRCoords.jl",
    "content": "module PRCoords\n\nstruct Coords\n    lat::Float64\n    lon::Float64\nend\n\nend # module\n"
  },
  {
    "path": "lua/PRCoords.lua",
    "content": "-- People's Rectified Coordinates\n-- https://github.com/Artoria2e5/PRCoords\n--\n-- Dedicated to the Public Domain under CC0\n-- Artoria2e5, 2017.\n\nPRCoords = {\n    [\"EARTH_R\"] = 6371000\n}\n\n-- Ray-casting polygon\nfunction PRCoords._in_poly(xs, ys, x, y)\n\tassert(#xs == #ys, \"poly length don't match\")\n\tlocal inside = false\n\t\n\tfor i=1,#xs do\n\t\tif (ys[i] > y) ~= (ys[j] > y) and\n\t\t   (x < (xs[j] - xs[i]) * (y - ys[i]) / (ys[j] - ys[i]) + xs[i]) then\n\t\t\tinside = (not inside)\n\t\tend\n\tend\n\treturn inside\nend\n\nlocal function bind_poly(xs, ys)\n\treturn function(x, y)\n\t\treturn PRCoords._in_poly(xs, ys, x, y)\n\tend\nend\n\nfunction PRCoords.cdiff(a_lat, a_lon, b_lat, b_lon)\n\treturn a_lat - b_lat, a_lon - b_lon\nend\n\nlocal function cerr(lat, lon)\n\treturn abs(lat) + abs(lon)\nend\n\nfunction PRCoords.cdist(a_lat, a_lon, b_lat, b_lon)\n\tlocal function hav(theta)\n\t\treturn math.sin(theta/2) ^ 2\n\tend\n\t\n\tlocal delta_lat = a_lat - b_lat\n\tlocal delta_lon = a_lon - b_lon\n\t\n\treturn 2 * PRCoords.EARTH_R * math.asin(math.sqrt(\n\t\thav(delta_lat * math.pi / 180) +\n\t\tmath.cos(a.lat * math.pi / 180) *\n\t\tmath.cos(b.lat * math.pi / 180) *\n\t\thav(delta_lon  * math.pi / 180)))\nend\n\nfunction PRCoords.caijun(forward, reverse)\n\treturn function(bad_lat, bad_lon)\n\t\tlocal guess_lat, guess_lon = reverse(bad_lat, bad_lon)\n\t\tlocal iter = 0\n\t\tlocal diff_lat, diff_lon, tlat, tlon\n\t\t\n\t\trepeat\n\t\t\ttlat, tlon = forward(guess_lat, guess_lon)\n\t\t\tdiff_lat, diff_lon = PRCoords.cdiff(tlat, tlon, bad_lat, bad_lon)\n\t\t\tguess_lat -= diff_lat\n\t\t\tguess_lon -= diff_lon\n\t\t\titer += 1\n\t\tuntil cerr(diff_lat, diff_lon) <= 1e-5 or iter >= 10\n\tend\nend\n\t\nfunction PRCoords.wgs_gcj(wlat, wlon)\n\tlocal y, x = wlon - 105, wlat - 35\n\t\nend\n"
  },
  {
    "path": "matlab/PRCoords.m",
    "content": "function v = PRCoords()\r\n  %% People's Rectified Coordinates: Chinese geographic obfuscations\r\n  %% Dedicated to the Public Domain under CC0.\r\n  %% Mingye Wang (Artoria2e5), 2017, 2025.\r\n  %% @url https://github.com/Artoria2e5/PRCoords\r\n  v = \"1.2.0\";\r\nend\r\n"
  },
  {
    "path": "matlab/bd_gcj.m",
    "content": "function g = bd_gcj (b)\r\n  % Reverse the BD-09 distortion to GCJ-02 coordinates.\r\n  x = b (2) - 0.0065;\r\n  y = b (1) - 0.006;\r\n\r\n  r = sqrt (x .* x + y .* y) - 0.00002 * sin (y * pi * 3000 / 180);\r\n  theta = atan2 (y, x) - 0.000003 * cos (x * pi * 3000 / 180);\r\n\r\n  gcj_lon = r .* cos (theta);\r\n  gcj_lat = r .* sin (theta);\r\n  g = [gcj_lat, gcj_lon];\r\nendfunction\r\n"
  },
  {
    "path": "matlab/bd_gcj_precise.m",
    "content": "function g = bd_gcj_precise (b, tol, maxn)\r\n  % Reverse the BD-09 distortion to GCJ-02 coordinates in a precise way.\r\n  if nargin < 2\r\n    tol = 1e-13;\r\n  end\r\n  if nargin < 3\r\n    maxn = 10;\r\n  end\r\n  fun = caijun_precise (@gcj_bd, @bd_gcj);\r\n  g = fun (b, tol, maxn);\r\nendfunction"
  },
  {
    "path": "matlab/bd_wgs.m",
    "content": "function w = bd_wgs (b)\r\n  % Reverse the BD-09 distortion to WGS-84 coordinates.\r\n  g = bd_gcj (b);\r\n  w = gcj_wgs (g);\r\nendfunction"
  },
  {
    "path": "matlab/bd_wgs_precise.m",
    "content": "function w = bd_wgs_precise (b, tol, maxn)\r\n  % Reverse the BD-09 distortion to WGS-84 coordinates in a precise way.\r\n  if nargin < 2\r\n    tol = 1e-13;\r\n  end\r\n  if nargin < 3\r\n    maxn = 10;\r\n  end\r\n  fun = caijun_precise (@wgs_bd, @bd_wgs);\r\n  w = fun (b, tol, maxn);\r\nendfunction\r\n"
  },
  {
    "path": "matlab/caijun_precise.m",
    "content": "function fun = caijun_precise (fwd, rev, o, tol, maxn)\r\n  % usage: fun = caijun_precise (@fwd, @rev)\r\n  %\r\n  % With a precise forward obfuscation and a rough deobfuscation\r\n  % function, construct a precise iterative deobfuscation function.\r\n  %\r\n  % A custom tolilon for \"fixed point\" detection can be specified\r\n  % with the \"tol\" operand. The default value is 1e-4 degrees.\r\n  % \r\n  % A custon max iteration limit can be specified with the \"maxn\"\r\n  % operand. The default value is 10 iterations.\r\n  %\r\n  % (caijun/geoChina; 2014)\r\n\r\n  function c = rectify (o, tol, maxn)\r\n    % Given obfuscated coords,\r\n    % return something that appears much less wrong to us.\r\n    c = rev (o);\r\n    d = c - o;\r\n    \r\n    for i = 1:maxn\r\n      if (max(abs(d (1))) + max(abs(d (2))) <= tol)\r\n        break;\r\n      end\r\n      d = fwd(c) - o;\r\n      c -= d;\r\n    end\r\n  endfunction\r\n  fun = @rectify;\r\nendfunction\r\n"
  },
  {
    "path": "matlab/gcj_bd.m",
    "content": "function b = gcj_bd (g)\r\n  % Apply the BD-09 distortion to GCJ-02 coordinates.\r\n  x = g (2);\r\n  y = g (1);\r\n\r\n  r = sqrt (x .* x + y .* y) + 0.00002 * sin (y * pi * 3000 / 180);\r\n  theta = atan2 (y, x) + 0.000003 * cos (x * pi * 3000 / 180);\r\n\r\n  bd_lon = r .* cos (theta) + 0.0065;\r\n  bd_lat = r .* sin (theta) + 0.006;\r\n  b = [bd_lat, bd_lon];\r\nendfunction\r\n"
  },
  {
    "path": "matlab/gcj_wgs.m",
    "content": "function w = gcj_wgs (g)\r\n  % Reverse the GCJ-02 distortion in a rough way.\r\n  gg = wgs_gcj (g);\r\n  w = g * 2 - gg;\r\nendfunction\r\n"
  },
  {
    "path": "matlab/gcj_wgs_precise.m",
    "content": "function w = gcj_wgs_precise (g, tol, maxn)\r\n  if nargin < 2\r\n    tol = 1e-13;\r\n  end\r\n  if nargin < 3\r\n    maxn = 10;\r\n  end\r\n  fun = caijun_precise (@wgs_gcj, @gcj_wgs);\r\n  w = fun (g, tol, maxn);\r\nendfunction\r\n"
  },
  {
    "path": "matlab/wgs_bd.m",
    "content": "function b = wgs_bd (w)\r\n  % Apply the BD-09 distortion to WGS-84 coordinates.\r\n  g = wgs_gcj (w);\r\n  b = gcj_bd (g);\r\nendfunction"
  },
  {
    "path": "matlab/wgs_gcj.m",
    "content": "function r = wgs_gcj (w)\r\n  % Apply the GCJ-02 distortion to WGS-84 coordinates.\r\n  wlat = w (1); wlon = w (2);\r\n\r\n  % Krasovsky 1940 ellipsoid\r\n  GCJ_A = 6378245;\r\n  GCJ_EE = 0.00669342162296594323; % f = 1./298.3; e^2 = 2.*f - f.*.*2\r\n\r\n  % Deviation computation in meters, inlined.\r\n  % [x, y] are relative coords from a common mapped \"center\" of China.\r\n  x = wlat - 35;\r\n  y = wlon - 105;\r\n  dlat = -100 + 2 .* x + 3 .* y + 0.2 .* y .* y + 0.1 .* x .* y + ...\r\n      0.2 .* sqrt(abs(x)) + (2 .* sin(x .* 6 .* pi) + ...\r\n      2 .* sin(x .* 2 .* pi) + 2 .* sin(y .* pi) + 4 .* sin(y ./ 3 .* pi) + ...\r\n      16 .* sin(y ./ 12 .* pi) + 32 .* sin(y ./ 30 .* pi)) .* 20 ./ 3;\r\n  dlon = 300 + x + 2 .* y + 0.1 .* x .* x + 0.1 .* x .* y + ...\r\n      0.1 .* sqrt(abs(x)) + (2 .* sin(x .* 6 .* pi) + ...\r\n      2 .* sin(x .* 2 .* pi) + 2 .* sin(x .* pi) + 4 .* sin(x ./ 3 .* pi) + ...\r\n      15 .* sin(x ./ 12 .* pi) + 30 .* sin(x ./ 30 .* pi)) .* 20 ./ 3;\r\n\r\n  % Arc lengths for one degree on the wrong ellipsoid\r\n  magic = 1 - GCJ_EE .* (sind(wlat) .^ 2); % A common expression\r\n  arclen_1lat = pi / 180 .* (GCJ_A .* (1 - GCJ_EE)) ./ magic .^ 1.5;\r\n  arclen_1lon = pi / 180 .*  GCJ_A .* cosd(wlat) ./ magic .^ 0.5;\r\n\r\n  % Pack deviations into degrees\r\n  glat = wlat + dlat ./ arclen_1lat;\r\n  glon = wlon + dlon ./ arclen_1lon;\r\n  r = [glat, glon];\r\nendfunction\r\n"
  },
  {
    "path": "package.json",
    "content": "{\n    \"name\": \"prcoords\",\n    \"version\": \"1.0.5\",\n    \"description\": \"Chinese coordinate obfuscation methods (GCJ-02, BD-09) and inverses.\",\n    \"main\": \"js/PRCoords.js\",\n    \"//\": \"Will this work with the repo? https://github.com/npm/npm/issues/2974\",\n    \"repository\": \"github:Artoria2e5/PRCoords\",\n    \"keywords\": [\n        \"gcj\",\n        \"wgs\",\n        \"bd\",\n        \"baidu\",\n        \"coordinates\"\n    ],\n    \"author\": \"Mingye Wang (Artoria2e5) <arthur200126@gmail.com>\",\n    \"license\": \"CC0-1.0\",\n    \"bugs\": {\n        \"url\": \"https://github.com/Artoria2e5/PRCoords/issues\"\n    },\n    \"dependencies\": {}\n}\n"
  },
  {
    "path": "pgsql/distance_agg.sql",
    "content": "CREATE TYPE _geodistance_agg_state AS\n(distance double precision, lat double precision, lon double precision);\n\nCREATE FUNCTION public._geodistance_agg_sfunc\n(state _geodistance_agg_state, lat double precision, lon double precision)\nRETURNS _geodistance_agg_state AS $$\nSELECT\n  (CASE WHEN $1 IS NULL THEN 0\n   ELSE $1.distance+geodistance($1.lat, $1.lon, $2, $3) END),\n  $2, $3\nAS nextstate;\n$$ LANGUAGE SQL IMMUTABLE;\n\nCREATE FUNCTION public._geodistance_agg_ffunc (state _geodistance_agg_state)\nRETURNS double precision AS $$\nSELECT $1.distance AS result;\n$$ LANGUAGE SQL IMMUTABLE;\n\nCREATE AGGREGATE geodistance_agg (double precision, double precision) (\n  SFUNC = _geodistance_agg_sfunc,\n  STYPE = _geodistance_agg_state,\n  FINALFUNC = _geodistance_agg_ffunc\n);\n"
  },
  {
    "path": "pgsql/prcoords.sql",
    "content": "CREATE OR REPLACE FUNCTION public.geodistance\n(alat double precision, alng double precision, blat double precision, blng double precision)\nRETURNS double precision AS $$\nSELECT 2 * 6371000 * asin(\n  sqrt(\n    sin(radians($3-$1)/2)^2 +\n    sin(radians($4-$2)/2)^2 * cos(radians($1)) * cos(radians($3))\n  )\n) AS distance;\n$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE COST 100;\n\nCREATE OR REPLACE FUNCTION public.geodistance (a point, b point)\nRETURNS double precision AS $$\nSELECT 2 * 6371000 * asin(\n  sqrt(\n    sin(radians($2[0]-$1[0])/2)^2 +\n    sin(radians($2[1]-$1[1])/2)^2 * cos(radians($1[0])) * cos(radians($2[0]))\n  )\n) AS distance;\n$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE COST 100;\n\nCREATE OR REPLACE FUNCTION public.wgs_gcj (wgs point) RETURNS point AS\n$$\nDECLARE\n  GCJ_A CONSTANT double precision := 6378245;\n  GCJ_EE CONSTANT double precision := 0.00669342162296594323;\n  x double precision;\n  y double precision;\n  dLat_m double precision;\n  dLon_m double precision;\n  radLat double precision;\n  magic double precision;\n  lat_deg_arclen double precision;\n  lon_deg_arclen double precision;\nBEGIN\n  x := wgs[1] - 105;\n  y := wgs[0] - 35;\n  dLat_m := (-100 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y +\n    0.2 * sqrt(abs(x)) + (\n        2 * sin(x * 6 * pi()) + 2 * sin(x * 2 * pi()) +\n        2 * sin(y * pi()) + 4 * sin(y / 3 * pi()) +\n        16 * sin(y / 12 * pi()) + 32 * sin(y / 30 * pi())\n    ) * 20 / 3);\n  dLon_m := (300 + x + 2 * y + 0.1 * x * x + 0.1 * x * y +\n      0.1 * sqrt(abs(x)) + (\n          2 * sin(x * 6 * pi()) + 2 * sin(x * 2 * pi()) +\n          2 * sin(x * pi()) + 4 * sin(x / 3 * pi()) +\n          15 * sin(x / 12 * pi()) + 30 * sin(x / 30 * pi())\n      ) * 20 / 3);\n\n  radLat := radians(wgs[0]);\n  magic := 1 - GCJ_EE * power(sin(radLat), 2);\n\n  lat_deg_arclen := radians((GCJ_A * (1 - GCJ_EE)) / power(magic, 1.5));\n  lon_deg_arclen = radians(GCJ_A * cos(radLat) / sqrt(magic));\n\n  RETURN (wgs[0] + (dLat_m / lat_deg_arclen),\n          wgs[1] + (dLon_m / lon_deg_arclen));\nEND;\n$$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE COST 150;\n\nCREATE OR REPLACE FUNCTION public.gcj_wgs (gcj point) RETURNS point AS $$\nSELECT $1 - (wgs_gcj($1) - $1) AS wgs\n$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE COST 150;\n\nCREATE OR REPLACE FUNCTION public.gcj_wgs_bored (gcj point) RETURNS point AS\n$$\nDECLARE\n  MAXITER CONSTANT double precision := 10;\n  PRC_EPS CONSTANT double precision := 1e-5;\n  wgs point;\n  old point;\n  diff point;\n  i smallint;\nBEGIN\n  wgs = gcj_wgs(gcj);\n  LOOP\n    diff := (wgs - old);\n    IF i < MAXITER AND (abs(diff[0]) > PRC_EPS OR abs(diff[1]) > PRC_EPS) THEN\n      old := wgs;\n      wgs := wgs - (wgs_gcj(wgs) - gcj);\n      i := i + 1;\n    ELSE\n      RETURN wgs;\n    END IF;\n  END LOOP;\nEND;\n$$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE COST 450;\n\nCREATE OR REPLACE FUNCTION public.gcj_bd (gcj point) RETURNS point AS\n$$\nDECLARE\n  r double precision;\n  t double precision;\nBEGIN\n  r := sqrt(gcj[0] * gcj[0] + gcj[1] * gcj[1]) + 2e-5 * sin(3000 * radians(gcj[0]));\n  t := atan2(gcj[0], gcj[1]) + 3e-6 * cos(3000 * radians(gcj[1]));\n  RETURN point(r * sin(t) + 0.0060, r * cos(t) + 0.0065);\nEND;\n$$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE COST 100;\n"
  },
  {
    "path": "pgsql/prcoords_postgis.sql",
    "content": "-- Depends on PostGIS and prcoords.sql\n\nCREATE OR REPLACE FUNCTION public._latlng2geometry (p point)\nRETURNS geometry AS $$\nSELECT ST_SetSRID(ST_MakePoint(p[1], p[0]), 4326);\n$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE;\n\nCREATE OR REPLACE FUNCTION public._geometry2latlng (p geometry)\nRETURNS point AS $$\nBEGIN\n  IF GeometryType(p) != 'POINT' THEN\n    RAISE EXCEPTION 'Input geom must be a point. Currently is: %', GeometryType(p);\n  ELSIF ST_SRID(p) != 4326 THEN\n    RAISE EXCEPTION 'SRID of the input geom must be 4326. Currently is: %', ST_SRID(p);\n  END IF;\n  RETURN point(ST_Y($1), ST_X($1));\nEND;\n$$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE;\n\nCREATE OR REPLACE FUNCTION public.wgs_gcj (wgs geometry)\nRETURNS geometry AS $$\nSELECT _latlng2geometry(wgs_gcj(_geometry2latlng($1)))\n$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE;\n\nCREATE OR REPLACE FUNCTION public.gcj_wgs (gcj geometry)\nRETURNS geometry AS $$\nSELECT _latlng2geometry(gcj_wgs(_geometry2latlng($1)))\n$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE;\n\nCREATE OR REPLACE FUNCTION public.gcj_bd (gcj geometry)\nRETURNS geometry AS $$\nSELECT _latlng2geometry(gcj_bd(_geometry2latlng($1)))\n$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE;\n"
  },
  {
    "path": "py/prcoords.py",
    "content": "'''\nPeople's Rectified [[T:Coord|Coordinates]]\n@file Utils for inserting valid WGS-84 coords from GCJ-02/BD-09 input\n@author User:Artoria2e5\n@url https://github.com/Artoria2e5/PRCoords\n\n@see [[:en:GCJ-02]]\n@see https://github.com/caijun/geoChina (GPLv3)\n@see https://github.com/googollee/eviltransform (MIT)\n@see https://on4wp7.codeplex.com/SourceControl/changeset/view/21483#353936 (Anonymous)\n@see https://github.com/zxteloiv/pycoordtrans (BSD-3)\n\n@license CC0\nTo the greatest extent possible, this implementation of obfuscations designed\nin hope that they will screw y'all up is dedicated into the public domain\nunder CC0 1.0 <https://creativecommons.org/publicdomain/zero/1.0/>.\n\nHappy geotagging/ingressing/whatever.\n\nTo make my FSF membership shine brighter, this conversion implementation is\nadditionally licensed under GPLv3+:\n@license GPLv3+\n@copyright 2016 Mingye Wang (User:Artoria2e5)\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <http://www.gnu.org/licenses/>.\n'''\n\nimport math\nimport warnings\nimport collections\n\n# Krasovsky 1940 ellipsoid\n# @const\nGCJ_A = 6378245\nGCJ_EE = 0.00669342162296594323 # f = 1/298.3; e^2 = 2*f - f**2\n\n# Epsilon to use for \"exact\" iterations.\n# Wanna troll? Use Number.EPSILON. 1e-13 in 15 calls for gcj.\n# @const\nPRC_EPS = 1e-5\n\n# Baidu's artificial deviations\n# @const\nBD_DLAT = 0.0060\nBD_DLON = 0.0065\n\n# Mean Earth Radius\n# @const\nEARTH_R = 6371000\n\nclass Coords(collections.namedtuple('Coords', 'lat lon')):\n    def __add__(self, other):\n        return Coords(self.lat + other.lat, self.lon + other.lon)\n\n    def __sub__(self, other):\n        return Coords(self.lat - other.lat, self.lon - other.lon)\n\n    def __abs__(self):\n        return math.hypot(*self)\n\n    def distance(self, other):\n        '''\n        Distance for haversine method; suitable over short distances like\n        conversion deviation checking\n        '''\n        hav = lambda theta: math.sin(theta / 2) ** 2\n\n        delta = self - other\n        return 2 * EARTH_R * math.asin(math.sqrt(\n            hav(math.radians(delta.lat)) +\n            math.cos(math.radians(self.lat)) *\n            math.cos(math.radians(other.lat)) *\n            hav(math.radians(delta.lon))\n        ))\n\ndef sanity_in_china_p(coords):\n    return (0.8293 <= coords.lat <= 55.8271 and\n            72.004 <= coords.lon <= 137.8347)\n\ndef wgs_gcj(wgs, check_china=True):\n    wgs = Coords(*wgs)\n    if check_china and not sanity_in_china_p(wgs):\n        warnings.warn('Non-Chinese coords found, returning as-is: %r' % (wgs,))\n        return wgs\n\n    x, y = wgs.lon - 105, wgs.lat - 35\n\n    # These distortion functions accept (x = lon - 105, y = lat - 35).\n    # They return distortions in terms of arc lengths, in meters.\n\n    # In other words, you can pretty much figure out how much you will be off\n    # from WGS-84 just through evaulating them...\n    #\n    # For example, at the (mapped) center of China (105E, 35N), you get a\n    # default deviation of <300, -100> meters.\n    dLat_m = (-100 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y +\n        0.2 * math.sqrt(abs(x)) + (\n            2 * math.sin(x * 6 * math.pi) + 2 * math.sin(x * 2 * math.pi) +\n            2 * math.sin(y * math.pi) + 4 * math.sin(y / 3 * math.pi) +\n            16 * math.sin(y / 12 * math.pi) + 32 * math.sin(y / 30 * math.pi)\n        ) * 20 / 3)\n    dLon_m = (300 + x + 2 * y + 0.1 * x * x + 0.1 * x * y +\n        0.1 * math.sqrt(abs(x)) + (\n            2 * math.sin(x * 6 * math.pi) + 2 * math.sin(x * 2 * math.pi) +\n            2 * math.sin(x * math.pi) + 4 * math.sin(x / 3 * math.pi) +\n            15 * math.sin(x / 12 * math.pi) + 30 * math.sin(x / 30 * math.pi)\n        ) * 20 / 3)\n\n    radLat = math.radians(wgs.lat)\n    magic = 1 - GCJ_EE * math.pow(math.sin(radLat), 2) # just a common expr\n\n    # [[:en:Latitude#Length_of_a_degree_of_latitude]]\n    lat_deg_arclen = math.radians((GCJ_A * (1 - GCJ_EE)) / math.pow(magic, 1.5))\n    # [[:en:Longitude#Length_of_a_degree_of_longitude]]\n    lon_deg_arclen = math.radians(GCJ_A * math.cos(radLat) / math.sqrt(magic))\n\n    # The screwers pack their deviations into degrees and disappear.\n    # Note how they are mixing WGS-84 and Krasovsky 1940 ellipsoids here...\n    return Coords(wgs.lat + (dLat_m / lat_deg_arclen),\n                  wgs.lon + (dLon_m / lon_deg_arclen))\n\ndef gcj_wgs(gcj, check_china=True):\n    '''rev_transform_rough; accuracy ~2e-6 deg (meter-level)'''\n    gcj = Coords(*gcj)\n    return gcj - (wgs_gcj(gcj, check_china) - gcj)\n\ndef gcj_bd(gcj, _dummy=False):\n    y, x = gcj\n\n    # trivia: pycoordtrans actually describes how these values are calculated\n    r = math.sqrt(x * x + y * y) + 0.00002 * math.sin(math.radians(y) * 3000)\n    theta = math.atan2(y, x) + 0.000003 * math.cos(math.radians(x) * 3000)\n\n    # Hard-coded default deviations again!\n    return Coords(r * math.sin(theta) + BD_DLAT, r * math.cos(theta) + BD_DLON)\n\n# Yes, we can implement a \"precise\" one too.\ndef bd_gcj(bd, _dummy=False):\n    '''accuracy ~1e-7 deg (decimeter-level; exceeds usual data accuracy)'''\n    bd = Coords(*bd)\n    x = bd.lon - BD_DLON\n    y = bd.lat - BD_DLAT\n\n    # trivia: pycoordtrans actually describes how these values are calculated\n    r = math.sqrt(x * x + y * y) - 0.00002 * math.sin(math.radians(y) * 3000)\n    theta = math.atan2(y, x) - 0.000003 * math.cos(math.radians(x) * 3000)\n\n    return Coords(r * math.sin(theta), r * math.cos(theta))\n\ndef bd_wgs(bd, check_china=True):\n    return gcj_wgs(bd_gcj(bd), check_china)\n\ndef wgs_bd(bd, check_china=True):\n    return gcj_bd(wgs_gcj(bd, check_china))\n\ndef _bored(fwd, rev):\n    '''\n    generic \"bored function\" factory, Caijun 2014\n    gcj: 4 calls to wgs_gcj; ~0.1mm acc\n    '''\n    def rev_bored(bad, check_china=True):\n        wgs = rev(bad)\n        bad = Coords(*bad)\n        diff = Coords(99, 99) # canary\n\n        # Wait till we hit fixed point or get bored\n        i = 0\n        while i < 10 and abs(diff) > PRC_EPS:\n            diff = fwd(wgs, False) - bad\n            wgs = wgs - diff\n            i += 1\n\n        return wgs\n\n    return rev_bored\n\n# Precise functions using caijun 2014 method\n# \n# Why \"bored\"? Because they usually exceed source data accuracy -- the\n# original GCJ implementation contains noise from a linear-modulo PRNG,\n# and Baidu seems to do similar things with their API too.\n\ngcj_wgs_bored = _bored(wgs_gcj, gcj_wgs)\nbd_gcj_bored = _bored(gcj_bd, bd_gcj)\nbd_wgs_bored = _bored(wgs_bd, bd_wgs)\n"
  },
  {
    "path": "py/setup.py",
    "content": "# This file is a part of PRCoords, a public-domain library\r\nfrom __future__ import with_statement\r\nfrom setuptools import setup\r\n\r\ndescription=\"Public Domain library for rectifying Chinese coordinates (gcj-02/bd-09)\"\r\n\r\ntry:\r\n    with open(\"../README.md\", \"r\") as f:\r\n        long_description = f.read()\r\nexcept:\r\n    # Will only happen with non-wheel archives and never on pypi\r\n    long_description = description\r\n\r\nsetup(\r\n    name=\"prcoords\",\r\n    version=\"1.0.2\",\r\n    author=\"Mingye Wang\",\r\n    author_email=\"arthur200126@gmail.com\",\r\n    description=description,\r\n    long_description=long_description,\r\n    long_description_content_type=\"text/markdown\",\r\n    url=\"https://github.com/Artoria2e5/PRCoords\",\r\n    py_modules=[\"prcoords\"],\r\n    classifiers=[\r\n        \"Programming Language :: Python :: 2\",\r\n        \"Programming Language :: Python :: 3\",\r\n        \"Development Status :: 5 - Production/Stable\",\r\n        \"License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication\",\r\n        \"Operating System :: OS Independent\",\r\n        \"Topic :: Scientific/Engineering :: GIS\",\r\n    ],\r\n)\r\n"
  },
  {
    "path": "racket/prcoords.rkt",
    "content": ";; People's Rectified Coordinates\n;; Dedicated to the Public Domain under CC0\n\n;; No idea about the module stuff.\n;; Will it handle my awful, collision-prone naming?\n\n;;(module prcoords typed/racket\n;;  (provide latlon latlon-lat latlon-lon latlon? ;; Do I have to say these all?\n\n\n;; I figured that before writing one for F#/Haskell/OCaml,\n;; Writing one in parentheses first might be a good idea.\n\n;; This sounds fun.\n#lang typed/racket\n\n;; I could have added some more restrictions, but whatever.\n(struct latlon ([lat : Float] [lon : Float]))\n;; I hear that those people in Haskell land use types to encode\n;; more information. Should I do that?\n\n;; These creepy x/y people...\n(define (latlon-from-complex [c : Float-Complex]) : latlon\n  (latlon (imag-part c) (real-part c)))\n(define (latlon-to-complex [a : latlon]) : Float-Complex\n  (make-rectangular (latlon-lon a) (latlon-lat a)))\n\n;; This one is a little sloppy...\n(: dcoord (-> latlon latlon\n              latlon))\n(define (dcoord a b)\n  (latlon\n   (- (latlon-lat a) (latlon-lat b))\n   (- (latlon-lon a) (latlon-lon b))))\n\n;; For looking into errors\n(: dcoord-abs (-> latlon latlon\n                  Float))\n(define (dcoord-abs a b)\n  (max\n   (abs (latlon-lat (dcoord a b)))\n   (abs (latlon-lon (dcoord a b)))))\n\n;; For estimating deviations\n(define\n  (dist [a : latlon] [b : latlon]) : Float\n  (let\n      ([a-lat (degrees->radians (latlon-lat a))]\n       [a-lon (degrees->radians (latlon-lon a))]\n       [b-lat (degrees->radians (latlon-lat b))]\n       [b-lon (degrees->radians (latlon-lon b))]\n       [d-lat (degrees->radians (latlon-lat (dcoord a b)))]\n       [d-lon (degrees->radians (latlon-lon (dcoord a b)))]\n       [R 6371000.]\n       [hav : (-> Float Float)\n            (λ (theta)\n              (* (sin (/ 2 theta)) (sin (/ 2 theta))))])\n    (* 2. R (cast (asin (sqrt (+ (hav d-lat)\n                                 (*\n                                  (hav d-lon)\n                                  (cos a-lat)\n                                  (cos b-lat))))) Float))))\n\n;; What, you want a polygon check? Not now.\n(: probably-bad (-> latlon\n                    Boolean))\n(define (probably-bad a)\n  (and\n   #t ;; TODO\n   #t\n   #t\n   #t))\n\n;; For your sanity, no functions will be defined with the\n;; rough \"sanity\" check on by default.\n(: sanity-wrap (-> (-> latlon latlon) (-> latlon Boolean)\n                   (-> latlon latlon)))\n(define (sanity-wrap conv check)\n  (λ ([a : latlon])\n    (if (check a)\n        (conv a)\n        a)))\n\n;; Sometimes people are like...\n(: sanity-wrap-backward (-> (-> latlon latlon) (-> latlon Boolean)\n                            (-> latlon latlon)))\n(define (sanity-wrap-backward conv check)\n  (λ ([a : latlon])\n    (let ([c (conv a)])\n      (if (check c)\n          c\n          a))))\n\n\n;; Finally a conversion. I understand that you have been\n;; cursing for all these poorly-written BS.\n(: wgs-gcj (-> latlon\n               latlon))\n(define (wgs-gcj wgs)\n  ; For (human) laziness\n  (let* ([gcj-ee 0.00669342162296594323]  ;; Krasovsky 1940, Not What You Use With WGS-84(TM)\n         [gcj-a 6378245.]\n         [x (- (latlon-lon wgs) 105.)]    ;; Deviation params\n         [y (- (latlon-lat wgs) 35.)]\n         [dlat 0.] ;; Yay, huge expressions, not today\n         [dlon 0.]\n         [rlat (degrees->radians (latlon-lat wgs))]\n         ;; This type checker is unhappy with...\n         [mm (cast (- 1 (* gcj-ee (sin rlat) (sin rlat))) Positive-Flonum)]\n         [arclat (exact->inexact (* (/ pi 180.) gcj-a (- 1 gcj-ee) (expt mm -1.5)))]\n         [arclon (exact->inexact (* (/ pi 180.) gcj-a (cos rlat) (sqrt mm)))])\n    (latlon\n     (+ (latlon-lat wgs) (/ dlat arclat))\n     (+ (latlon-lon wgs) (/ dlon arclon))))) ;; Do you really think I am gonna finish this?\n\n;; A rough reverse function.\n(: gcj-wgs-rough (-> latlon\n                     latlon))\n(define (gcj-wgs-rough gcj)\n  (dcoord gcj\n          (dcoord (wgs-gcj gcj)\n                  gcj)))\n\n;; Cai's iteration.\n;; Not now. Chill, it's just carrying four accumulators around and stuff.\n(define\n  (caijun-iterate [fwd : (-> latlon latlon)]\n                  [rough-rev : (-> latlon latlon)]\n                  #:eps [eps : Float 1e-4]\n                  #:maxn [maxn : Integer 10])\n  (λ \n      ([bad : latlon]) : latlon\n    (letrec\n        ([improve : (-> latlon latlon Integer\n                        latlon)\n                  (λ\n                    (curr prev i)\n                    ;; Fixing a sloppy part in js, etc.:\n                    ;; what happens if rough-rev is just an `id`?\n                    (if (or (and (< i maxn) (< (dcoord-abs curr prev) eps)) (= i 0))\n                        (improve\n                         (dcoord curr\n                                 (dcoord (fwd curr)\n                                         bad))\n                         curr\n                         (+ 1 i))\n                        curr))])\n      (improve bad (rough-rev bad) 0))))\n\n(define gcj-wgs : (-> latlon latlon)\n  (caijun-iterate wgs-gcj gcj-wgs-rough))\n\n;; Baudu's Obfuscation.\n(define\n  (gcj-bd [a : latlon]) : latlon\n  (let\n      ([bd-delta 0.0060+0.0065i]\n       [c1 (latlon-to-complex a)]\n       [lat (latlon-lat a)]\n       [lon (latlon-lon a)])\n    (latlon-from-complex\n     (+\n      (make-polar\n       (+ (magnitude c1) (* 0.00002 (sin (* 3000. (degrees->radians lat)))))\n       (+ (angle c1) (* 0.000003 (cos (* 3000. (degrees->radians lon))))))\n      bd-delta))))\n\n(define\n  (bd-gcj-rough [a : latlon]) : latlon\n  (let*\n      ([bd-delta 0.0060+0.0065i]\n       [c1 (- (latlon-to-complex a) bd-delta)]\n       [lat (imag-part c1)]\n       [lon (real-part c1)])\n    (latlon-from-complex\n     (make-polar\n      (- (magnitude c1) (* 0.00002 (sin (* 3000. (degrees->radians lat)))))\n      (- (angle c1) (* 0.000003 (cos (* 3000. (degrees->radians lon)))))))))\n\n(define bd-gcj : (-> latlon latlon)\n  (caijun-iterate gcj-bd bd-gcj-rough))\n\n(define (wgs-bd [a : latlon]) : latlon\n  (gcj-bd (wgs-gcj a)))\n(define (bd-wgs-rough [a : latlon]) : latlon\n  (gcj-wgs-rough (bd-gcj-rough a)))        \n(define bd-wgs : (-> latlon latlon)\n  (caijun-iterate wgs-bd bd-wgs-rough))\n\n;; Yay!\n"
  }
]