diff --git a/LICENSE b/LICENSE
new file mode 100644
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,675 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+
diff --git a/Setup.hs b/Setup.hs
new file mode 100644
--- /dev/null
+++ b/Setup.hs
@@ -0,0 +1,3 @@
+#!/usr/bin/env runhaskell
+import Distribution.Simple
+main = defaultMain
diff --git a/apelsin.cabal b/apelsin.cabal
new file mode 100644
--- /dev/null
+++ b/apelsin.cabal
@@ -0,0 +1,74 @@
+Name:                   apelsin
+Version:                1.0
+Author:                 Christoffer Öjeling
+Maintainer:             christoffer@ojeling.net
+License:                GPL-3
+License-File:           LICENSE
+Category:               Network
+Synopsis:               Server and community browser for the game Tremulous
+Description:            A gtk2hs server and clan browser for the open source game Tremulous <http://tremulous.net>.
+                        Both Tremulous 1.1 and GPP are supported.
+			.
+                        Features filtering, player search, a list of online clan members, a clan list and basic perferences.
+
+Cabal-Version:          >= 1.10
+Build-Type:             Simple
+Data-Dir:               share
+Data-Files:             icons/hicolor/128x128/apps/apelsin.png
+                        icons/hicolor/256x256/apps/apelsin.png
+                        icons/hicolor/16x16/apps/apelsin.png
+                        icons/hicolor/32x32/apps/apelsin.png
+                        icons/hicolor/22x22/apps/apelsin.png
+                        icons/hicolor/48x48/apps/apelsin.png
+                        icons/hicolor/24x24/apps/apelsin.png
+                        icons/hicolor/64x64/apps/apelsin.png
+
+Tested-With:            GHC==7.0.3
+
+
+Flag relativePath
+  description: Use relative paths for data files instead of cabal defaults
+  default:     False
+
+Executable apelsin
+  Default-Language:     Haskell2010
+  Default-Extensions:   BangPatterns NamedFieldPuns RecordWildCards
+                        ScopedTypeVariables OverloadedStrings
+  Other-Extensions:     CPP
+  Build-Depends:        base>=4.3&&<5, array, mtl, stm, containers, transformers,
+                        bytestring, directory, filepath, HTTP, network,
+                        tremulous-query, gtk, glib, process
+  Hs-Source-Dirs:       src
+  Main-is:              Apelsin.hs
+  Other-Modules:        System.Environment.XDG.BaseDir
+                        About
+                        ClanFetcher
+                        Clanlist
+                        Config
+                        Constants
+                        FilterBar
+                        FindPlayers
+                        GtkUtils
+                        InfoBox
+                        List2
+                        Preferences
+                        ServerBrowser
+                        ServerInfo
+                        STM2
+                        Toolbar
+                        TremFormatting
+                        Types
+                        Paths_apelsin
+
+  Ghc-Options:          -Wall -threaded -fno-warn-unused-do-bind -funbox-strict-fields
+
+  if !flag(relativePath)
+    cpp-options:        -DCABAL_PATH
+
+  if os(windows)
+    ld-options:         -mwindows
+
+Source-Repository head
+  Type:                 git
+  Location:             git://github.com/Cadynum/Apelsin.git
+
diff --git a/share/icons/hicolor/128x128/apps/apelsin.png b/share/icons/hicolor/128x128/apps/apelsin.png
new file mode 100644
Binary files /dev/null and b/share/icons/hicolor/128x128/apps/apelsin.png differ
diff --git a/share/icons/hicolor/16x16/apps/apelsin.png b/share/icons/hicolor/16x16/apps/apelsin.png
new file mode 100644
Binary files /dev/null and b/share/icons/hicolor/16x16/apps/apelsin.png differ
diff --git a/share/icons/hicolor/22x22/apps/apelsin.png b/share/icons/hicolor/22x22/apps/apelsin.png
new file mode 100644
Binary files /dev/null and b/share/icons/hicolor/22x22/apps/apelsin.png differ
diff --git a/share/icons/hicolor/24x24/apps/apelsin.png b/share/icons/hicolor/24x24/apps/apelsin.png
new file mode 100644
Binary files /dev/null and b/share/icons/hicolor/24x24/apps/apelsin.png differ
diff --git a/share/icons/hicolor/256x256/apps/apelsin.png b/share/icons/hicolor/256x256/apps/apelsin.png
new file mode 100644
Binary files /dev/null and b/share/icons/hicolor/256x256/apps/apelsin.png differ
diff --git a/share/icons/hicolor/32x32/apps/apelsin.png b/share/icons/hicolor/32x32/apps/apelsin.png
new file mode 100644
Binary files /dev/null and b/share/icons/hicolor/32x32/apps/apelsin.png differ
diff --git a/share/icons/hicolor/48x48/apps/apelsin.png b/share/icons/hicolor/48x48/apps/apelsin.png
new file mode 100644
Binary files /dev/null and b/share/icons/hicolor/48x48/apps/apelsin.png differ
diff --git a/share/icons/hicolor/64x64/apps/apelsin.png b/share/icons/hicolor/64x64/apps/apelsin.png
new file mode 100644
Binary files /dev/null and b/share/icons/hicolor/64x64/apps/apelsin.png differ
diff --git a/src/About.hs b/src/About.hs
new file mode 100644
--- /dev/null
+++ b/src/About.hs
@@ -0,0 +1,18 @@
+module About where
+import Graphics.UI.Gtk
+import Constants
+
+newAbout :: WindowClass w => w -> IO ()
+newAbout win = do
+	about <- aboutDialogNew
+	set about [
+		  windowWindowPosition := WinPosCenterOnParent
+		, windowTransientFor	:= win
+		, aboutDialogProgramName:= programName
+		, aboutDialogVersion	:= "1.0"
+		, aboutDialogCopyright	:= "Copyright © 2011\nChristoffer Öjeling <christoffer@ojeling.net>"
+		, aboutDialogComments	:= "A tremulous server and community browser\nLicense: GPLv3"
+		, aboutDialogWebsite	:= "http://ojeling.net"
+		]
+	dialogRun about
+	widgetDestroy about
diff --git a/src/Apelsin.hs b/src/Apelsin.hs
new file mode 100644
--- /dev/null
+++ b/src/Apelsin.hs
@@ -0,0 +1,115 @@
+import Graphics.UI.Gtk
+import System.Glib.GError
+
+import Control.Applicative
+import Control.Monad.IO.Class
+import Control.Exception
+import Control.Monad
+import qualified Data.Set as S
+import Network.Socket
+import Network.Tremulous.Protocol
+import System.FilePath (joinPath)
+
+import Types
+import Constants
+import GtkUtils
+import ServerInfo
+import ServerBrowser
+import FindPlayers
+import Clanlist
+import ClanFetcher
+import Preferences
+import Config
+import Toolbar
+
+main :: IO ()
+main = withSocketsDo $ do
+	unsafeInitGUIForThreadedRTS
+	win		<- windowNew
+	config		<- configFromFile
+	cacheclans	<- clanListFromCache
+	bundle		<- atomically $ Bundle
+				<$> newTMVar (PollResult [] 0 0 S.empty)
+				<*> newTMVar config
+				<*> newTMVar cacheclans
+				<*> pure win
+
+	(currentInfo, currentUpdate, currentSet)<- newServerInfo bundle
+	(browser, browserUpdate)		<- newServerBrowser bundle currentSet
+	(findPlayers, findUpdate)		<- newFindPlayers bundle currentSet
+	(clanlist, clanlistUpdate)		<- newClanList bundle
+	(onlineclans, onlineclansUpdate)	<- newOnlineClans bundle currentSet
+
+	preferences				<- newPreferences bundle
+
+	toolbar <- newToolbar bundle
+		(clanlistUpdate >> onlineclansUpdate)
+		(browserUpdate >> findUpdate >> currentUpdate >> onlineclansUpdate)
+
+	-- /// Layout ////////////////////////////////////////////////////////////////////////////
+
+	book <- notebookNew
+	notebookAppendMnemonic book browser	"_1: Browser"
+	notebookAppendMnemonic book findPlayers	"_2: Find players"
+	notebookAppendMnemonic book onlineclans	"_3: Online clans"
+	notebookAppendMnemonic book clanlist	"_4: Clan list"
+	notebookAppendMnemonic book preferences	"_5: Preferences"
+	leftView <- vBoxNew False 0
+	boxPackStart leftView toolbar PackNatural 0
+	boxPackStart leftView book PackGrow 0
+
+
+	pane <- hPanedNew
+	panedPack1 pane leftView True False
+	panedPack2 pane currentInfo  False True
+
+
+	-- save the current window size and pane positon on exit
+	on win deleteEvent $ tryEvent $ liftIO $ do
+		Config {autoGeometry} <- atomically $ readTMVar (mconfig bundle)
+		when autoGeometry $ do
+			file		<- inCacheDir "windowsize"
+			(winw, winh)	<- windowGetSize win
+			ppos		<- panedGetPosition pane
+			writeFile file $ show (winw, winh, ppos)
+		mainQuit
+
+	ddir <- getDataDir
+	handleGError (const $ trace $ "Window icon not found: " ++ ddir) $ do
+		let list = map
+			(\x -> joinPath [ddir, "icons", "hicolor", x ++ "x" ++ x, "apps", "apelsin.png"])
+			["16", "32", "48", "64"]
+		icons <- mapM pixbufNewFromFile list
+		set win [ windowIconList := icons]
+	
+	-- Without allowshrink the window may change size back and forth when selecting new servers
+	set win [ containerChild	:= pane
+		, windowTitle		:= fullProgramName
+		, windowAllowShrink	:= True
+		]
+
+	--Showing it to get size requests
+	widgetShowAll leftView
+
+	-- Restore the window size and pane position
+	when (autoGeometry config) $ handle ignoreIOException $ do
+		file	<- inCacheDir "windowsize"
+		fx	<- readFile file
+		whenJust (mread fx) $ \(winw::Int, winh, ppos::Int) -> do
+			Requisition  _ minh	<- widgetSizeRequest leftView
+			Requisition minw _	<- widgetSizeRequest leftView
+			let panebuf = 15 -- size we assume the panehandle is at most
+			panedSetPosition pane (if minw+panebuf > winw then ppos+panebuf else ppos)
+			set win [ widgetHeightRequest	:= max minh winh
+				, widgetWidthRequest	:= max (minw+panebuf) winw ]
+	widgetShowAll win
+
+
+
+	mainGUI
+
+
+ignoreIOException :: IOException -> IO ()
+ignoreIOException _ = return ()
+
+
diff --git a/src/ClanFetcher.hs b/src/ClanFetcher.hs
new file mode 100644
--- /dev/null
+++ b/src/ClanFetcher.hs
@@ -0,0 +1,106 @@
+module ClanFetcher( 
+	Clan(..), TagExpr, matchTagExpr, getClanList, clanListFromCache
+) where
+
+import Prelude as P hiding (catch)
+import Control.Exception
+import Control.Applicative
+import Control.Monad
+import Data.ByteString.Char8 as B
+import Data.ByteString.Lazy.Char8 as L
+import Data.Char (intToDigit, toLower)
+import Data.Maybe
+import Network.HTTP
+import Network.URI
+import Network.Tremulous.NameInsensitive
+
+import Constants
+
+data TagExpr =
+	  TagPrefix !B.ByteString
+	| TagSuffix !B.ByteString
+	| TagInfix !B.ByteString
+	| TagContained !B.ByteString !B.ByteString
+	| TagError
+
+data Clan = Clan {
+	  clanid	:: !B.ByteString
+	, name
+	, tag		:: !TI
+	, website
+	, irc		:: !B.ByteString
+	, tagexpr	:: !TagExpr
+	}
+
+mkTagExpr :: B.ByteString -> TagExpr
+mkTagExpr str
+	| B.length str > 0 = case x of
+	'<' -> TagPrefix xs
+	'>' -> TagSuffix xs
+	'^' -> TagInfix xs
+	'%' -> let (a, b) = B.break (=='%') xs in TagContained a (B.drop 1 b)
+	_   -> TagError
+	| otherwise = TagError
+	where	(x, xs)	= (B.head str, B.map toLower (B.tail str))
+
+matchTagExpr :: TagExpr -> TI -> Bool
+matchTagExpr expr raw = case expr of
+	TagPrefix xs		-> xs `B.isPrefixOf` str
+	TagSuffix xs		-> xs `B.isSuffixOf` str
+	TagInfix xs		-> xs `B.isInfixOf` str
+	TagContained xs ys	-> xs `B.isPrefixOf` str && ys `B.isSuffixOf` str
+	TagError		-> False
+	where str = cleanedCase raw
+
+
+rawToClan :: L.ByteString -> Maybe [Clan]
+rawToClan = mapM (f . B.split '\t' . lazyToStrict) . P.filter (not . L.null) . L.split '\n' where 
+	f [clanid, rname, rtag, website, irc, rexpr, _] =
+		Just Clan	{ name = mkAlphaNum rname
+				, tag = mk rtag
+				, tagexpr = mkTagExpr rexpr
+				, .. }
+	f _	= Nothing
+
+getClanList :: String -> IO (Maybe [Clan])
+getClanList url = do
+	cont <- get url
+	case cont of
+		Right _ -> return Nothing
+		Left raw -> do
+			file	<- inCacheDir "clans"
+			let clans = rawToClan raw
+			when (isJust clans) $
+				L.writeFile file raw
+
+			return clans
+			
+
+clanListFromCache :: IO [Clan]
+clanListFromCache = handle err $ do
+	file	<- inCacheDir "clans"
+	fromMaybe [] . rawToClan <$> L.readFile file
+	where
+	err (_::IOError) = return [] 
+	
+
+lazyToStrict :: L.ByteString -> B.ByteString		
+lazyToStrict = B.concat . toChunks
+
+
+-- I blame this on buggy Network.HTTP
+get :: HStream ty => String -> IO (Either ty String)
+get url = case parseURI url of
+		Nothing -> return $ Right "Error in URL"
+		Just uri -> do
+			resp <- catch (getRight `fmap` simpleHTTP (mkRequest GET uri)) err
+			return $ case resp of
+				Left msg				-> Right $ show msg
+				Right (Response (2,0,0) _  _ body)	-> Left body
+				Right (Response code reason _ _)	-> Right $ showRspCode code  ++ " " ++ reason
+	where
+	showRspCode (a,b,c) = P.map intToDigit [a,b,c]
+	getRight (Right a) = Right a
+	getRight (Left _) = error ""
+	err :: IOException -> IO (Either String a )
+	err = return . Left . show
diff --git a/src/Clanlist.hs b/src/Clanlist.hs
new file mode 100644
--- /dev/null
+++ b/src/Clanlist.hs
@@ -0,0 +1,185 @@
+module Clanlist where
+
+import Graphics.UI.Gtk
+
+import Control.Concurrent
+import Control.Concurrent.STM
+import qualified Data.ByteString.Char8 as B
+import Data.Ord
+import Data.Tree
+import Data.Maybe
+import Data.List (sortBy)
+import Data.IORef
+import Network.Tremulous.NameInsensitive
+import Network.Tremulous.ByteStringUtils
+import qualified Network.Tremulous.Protocol as P
+import Network.Tremulous.Util
+
+import Types
+import ClanFetcher
+import Constants
+import Config
+import FilterBar
+import InfoBox
+import GtkUtils
+import TremFormatting
+
+
+newClanList :: Bundle -> IO (VBox, IO ())
+newClanList Bundle{..} = do
+	raw			<- listStoreNew []
+	filtered		<- treeModelFilterNew raw []
+	sorted			<- treeModelSortNewWithModel filtered
+	view			<- treeViewNewWithModel sorted
+	scrollview		<- scrollIt view PolicyAutomatic PolicyAlways
+
+	(infobox, statNow, statTot) <- newInfobox "clans"
+
+	(filterbar, current)	<- newFilterBar filtered statNow ""
+
+	let updateF = do
+		new <- atomically $ readTMVar mclans
+		listStoreClear raw
+		treeViewColumnsAutosize view
+		mapM_ (listStoreAppend raw) new
+		treeModelFilterRefilter filtered
+		set statTot [ labelText := show (length new) ]
+		n <- treeModelIterNChildren filtered Nothing
+		set statNow [ labelText := show n ]
+
+	addColumnsFilterSort raw filtered sorted view (Just (comparing name)) [
+		  ("_Name"	, 0 , False	, True	, False	, unpackorig . name	, Just (comparing name))
+		, ("_Tag"	, 0 , False	, True	, False	, unpackorig . tag	, Just (comparing tag))
+		, ("Website"	, 0 , False	, True	, False	, B.unpack . showURL . website	, Nothing)
+		, ("IRC"	, 0 , False	, True	, False	, B.unpack . irc	, Nothing)
+		]
+
+	treeModelFilterSetVisibleFunc filtered $ \iter -> do
+		Clan{..}	<- treeModelGetRow raw iter
+		s		<- readIORef current
+		let cmplist	= [ cleanedCase name, cleanedCase tag ]
+		return $ B.null s || smartFilter s cmplist
+
+	box <- vBoxNew False 0
+
+	boxPackStart box filterbar PackNatural spacing
+	boxPackStart box scrollview PackGrow 0
+	boxPackStart box infobox PackNatural 0
+
+	updateF
+
+	return (box, updateF)
+	where showURL x = fromMaybe x (stripPrefix "http://" x)
+
+
+newOnlineClans :: Bundle-> (Bool -> P.GameServer -> IO ()) -> IO (ScrolledWindow, IO ())
+newOnlineClans Bundle{..} setServer = do
+	Config {colors} <- atomically $ readTMVar mconfig
+
+	let showName c =  case c of
+		Left Clan{..}		-> "<b>" ++ htmlEscape (unpackorig name) ++ "</b>"
+		Right (P.Player{..}, _)	-> pangoPretty colors name
+
+	let showServer c =  case c of
+		Left _ -> ""
+		Right (_, P.GameServer{hostname}) -> pangoPretty colors hostname
+
+	raw	<- treeStoreNew []
+	view	<- treeViewNewWithModel raw
+
+
+	treeViewExpandAll view
+	addColumns raw view [
+		  ("Name"	, 0	, True	, True	, True	, showName )
+		, ("Server"	, 0	, True	, True	, True	, showServer )
+		]
+
+	let updateF = do
+		P.PollResult{..}	<- atomically $ readTMVar mpolled
+		clans			<- atomically $ readTMVar mclans
+		let players = buildTree $ sortByPlayers $
+			associatePlayerToClans (makePlayerList polled) clans
+		treeStoreClear raw
+		treeViewColumnsAutosize view
+		mapM_ (treeStoreInsertTree raw [] 0) players
+		treeViewExpandAll view
+
+	onCursorChanged view $ do
+		(x, _)		<- treeViewGetCursor view
+		Just iter	<- treeModelGetIter raw x
+		item		<- treeModelGetRow raw iter
+		case item of
+			Left _ -> return ()
+			Right (_, a) -> setServer False a
+
+	onRowActivated view $ \path _ -> do
+		Just vIter	<- treeModelGetIter raw path
+		gs	<- treeModelGetRow raw vIter
+		case gs of
+			Left _ -> return ()
+			Right (_, gameserver) -> setServer True gameserver
+
+	scroll <- scrollIt view PolicyAutomatic PolicyAutomatic
+
+
+	return (scroll, updateF)
+
+
+
+
+
+-- /// Utility functions ///////////////////////////////////////////////////////////////////////////
+
+type PlayerList = [(P.Player, P.GameServer)]
+
+type OnlineView = Forest (Either Clan (P.Player, P.GameServer))
+
+associatePlayerToClans :: PlayerList -> [Clan] -> [(Clan, PlayerList)]
+associatePlayerToClans players clans = map f clans
+	where
+	f c@Clan{tagexpr} = (c, filter (cmp tagexpr) players)
+	cmp e = matchTagExpr e . P.name . fst
+
+buildTree :: [(Clan, PlayerList)] -> OnlineView
+buildTree = filter notEmpty . foldr f [] where
+	f (clan, pls) xs = Node (Left clan) (map rightNode pls) : xs
+	rightNode x = Node (Right x) []
+	notEmpty (Node _ [])	= False
+	notEmpty _		= True
+--f tag x =
+
+sortByPlayers :: [(a, [b])] -> [(a, [b])]
+sortByPlayers = sortBy (comparing (length . snd))
+
+newClanSync :: Bundle -> IO () -> IO (HBox, IO ())
+newClanSync Bundle{..} updateF = do
+	button	<- buttonNewWithMnemonic "_Sync clan list"
+	img	<- imageNewFromStock stockSave IconSizeButton
+	set button 	[ buttonImage := img
+			, buttonRelief := ReliefNone
+			, buttonFocusOnClick := False ]
+
+	box	<- hBoxNew False 0
+	boxPackStart box button PackRepel 0
+
+
+	let doSync = do
+		set button [ widgetSensitive := False ]
+		Config {clanSyncURL} <- atomically $ readTMVar mconfig
+		forkIO $ do
+			new <- getClanList clanSyncURL
+			case new of
+				Nothing	-> postGUISync $ do
+					gtkError "Unable to download clanlist"
+					set button [ widgetSensitive := True ]
+				Just a	-> do
+					atomically $
+						swapTMVar mclans a
+					postGUISync $ do
+						updateF
+						set button [ widgetSensitive := True ]
+		return ()
+
+	on button buttonActivated doSync
+
+	return (box, doSync)
diff --git a/src/Config.hs b/src/Config.hs
new file mode 100644
--- /dev/null
+++ b/src/Config.hs
@@ -0,0 +1,74 @@
+module Config where
+
+import Data.Array
+import Control.Exception
+import Network.Tremulous.Protocol
+
+import Constants
+import GtkUtils
+import TremFormatting
+
+
+type ColorTheme = Array Int TremFmt
+
+data Config = Config {
+	  configVersion	:: !Int
+	, masterServers :: ![(String, Int, Int)]
+	, clanSyncURL	:: !String
+	, tremPath
+	, tremGppPath	:: !String
+	, autoMaster
+	, autoClan
+	, autoGeometry	:: !Bool
+	, filterBrowser
+	, filterPlayers	:: !String
+	, filterEmpty	:: !Bool
+	, delays	:: !Delay
+	, colors	:: !ColorTheme
+	} deriving (Show, Read)
+
+defaultConfig :: Config
+defaultConfig = Config {
+	  configVersion	= 1
+	, masterServers = [("master.tremulous.net", 30710, 69), ("master.tremulous.net", 30700, 70)]
+	, clanSyncURL	= "http://ddos-tremulous.eu/cw/api/clanlist"
+	, tremPath	= defaultTremulousPath
+	, tremGppPath	= defaultTremulousGPPPath
+	, autoMaster	= True
+	, autoClan	= True
+	, autoGeometry	= True
+	, filterBrowser	= ""
+	, filterPlayers	= ""
+	, filterEmpty	= True
+	, delays	= defaultDelay
+	, colors	= makeColorsFromList $
+		TFNone : map TFColor ["#d60503", "#25c200", "#eab93d", "#0021fe", "#04c9c9", "#e700d7"] ++ [TFNone]
+	} 
+makeColorsFromList :: [e] -> Array Int e
+makeColorsFromList = listArray (0,7)
+
+configToFile :: Config -> IO ()
+configToFile config = handle err $ do
+	file	<- inConfDir "config"
+	writeFile file (show config)
+	where
+	err (_::IOError) = gtkWarn "Error saving config file"
+
+
+configFromFile :: IO Config
+configFromFile = handle err $ do
+	file	<- inConfDir "config"
+	cont	<- readFile file
+	case mread cont of
+		Nothing -> do
+			gtkWarn $ "Errors in " ++ file ++ "!\nUsing default"
+			return defaultConfig
+		Just a -> return a
+	where
+	err (_::IOError) = return defaultConfig
+
+mread :: (Read a) => String -> Maybe a
+mread x = case reads x of
+	[(a, _)]	-> Just a
+	_		-> Nothing
+
diff --git a/src/Constants.hs b/src/Constants.hs
new file mode 100644
--- /dev/null
+++ b/src/Constants.hs
@@ -0,0 +1,55 @@
+{-# LANGUAGE CPP #-}
+module Constants where
+import Data.String
+import System.Environment.XDG.BaseDir
+import System.FilePath
+import System.Directory
+import System.IO
+
+#ifdef CABAL_PATH
+import Paths_apelsin
+#endif
+
+configName, programName, fullProgramName :: IsString s => s
+configName = "apelsin"
+programName = "Apelsin"
+fullProgramName = "Apelsin Tremulous Browser"
+
+inCacheDir, inConfDir :: FilePath -> IO FilePath
+
+inCacheDir x = do
+	dir <- getUserCacheDir configName
+	createDirectoryIfMissing True dir
+	return (dir </> x)
+
+inConfDir x = do
+	dir <- getUserConfigDir configName
+	createDirectoryIfMissing True dir
+	return (dir </> x)
+
+
+getDataDir :: IO FilePath 
+#ifdef CABAL_PATH
+getDataDir = dropTrailingPathSeparator `fmap` getDataFileName ""
+#else
+getDataDir = getCurrentDirectory
+#endif
+
+trace :: String -> IO ()
+defaultTremulousPath, defaultTremulousGPPPath :: FilePath
+#if defined(mingw32_HOST_OS) || defined(__MINGW32__)
+defaultTremulousPath	= "C:\\Program Files\\Tremulous\\tremulous.exe"
+defaultTremulousGPPPath	= "C:\\Program Files\\Tremulous\\tremulous-gpp.exe"
+trace _			= return ()
+#else
+defaultTremulousPath	= "tremulous"
+defaultTremulousGPPPath	= "tremulous-gpp"
+trace 			= hPutStrLn stderr
+#endif
+
+
+spacing, spacingHalf, spacingBig :: Integral i => i
+spacing		= 4
+spacingHalf	= 2
+spacingBig	= 8
+
diff --git a/src/FilterBar.hs b/src/FilterBar.hs
new file mode 100644
--- /dev/null
+++ b/src/FilterBar.hs
@@ -0,0 +1,61 @@
+module FilterBar (newFilterBar, smartFilter) where
+
+import Graphics.UI.Gtk
+import Data.IORef
+import qualified Data.ByteString.Char8 as B
+import Data.ByteString.Char8 (ByteString)
+import Data.Char
+import Network.Tremulous.ByteStringUtils as B
+
+import Constants
+
+
+newFilterBar :: (TreeModelClass self, TreeModelFilterClass self) => self -> Label -> String
+	-> IO (HBox, IORef ByteString)
+newFilterBar filtered stat initial  = do
+	current <- newIORef ""
+	
+	-- Filterbar
+	ent <- entryNew
+	set ent [ widgetHasFocus	:= True
+		, widgetIsFocus		:= True
+		, widgetCanDefault	:= True
+		, entryText		:= initial ]
+	lbl <- labelNewWithMnemonic "_Filter:"
+	set lbl [ labelMnemonicWidget := ent ]
+	
+	findbar <- hBoxNew False spacing
+	boxPackStart findbar lbl PackNatural 0
+	boxPackStart findbar ent PackGrow 0
+	
+	let f = do
+		rawstr <- entryGetText ent
+		let str = B.pack $ map toLower rawstr
+		writeIORef current str
+		treeModelFilterRefilter filtered
+		n <- treeModelIterNChildren filtered Nothing
+		set stat [ labelText := show n ]
+		return True
+	f 
+	onKeyRelease ent (const f) 
+		
+	return (findbar, current)
+
+	
+data Expr = Is !ByteString | Not !ByteString
+
+mkExpr :: ByteString -> Expr
+mkExpr ss = case (B.head ss, B.tail ss) of
+	('-', xs) | B.length xs > 0	-> Not (B.tail ss)
+                  | otherwise		-> Is xs                 
+	_				-> Is ss
+
+matchExpr :: Expr -> [ByteString] -> Bool
+matchExpr (Is xs)  = any (xs `B.isInfixOf`)
+matchExpr (Not xs) = all (not . (xs `B.isInfixOf`))
+
+smartFilter :: ByteString -> [ByteString] -> Bool
+smartFilter raw xs = all (`matchExpr` xs) search 
+	where
+	search	= map mkExpr (B.splitfilter ' ' raw)
+	
diff --git a/src/FindPlayers.hs b/src/FindPlayers.hs
new file mode 100644
--- /dev/null
+++ b/src/FindPlayers.hs
@@ -0,0 +1,69 @@
+module FindPlayers where
+import Graphics.UI.Gtk
+
+import Data.IORef
+import qualified Data.ByteString.Char8 as B
+import Network.Tremulous.Protocol
+import Network.Tremulous.Util
+
+import Types
+import GtkUtils
+import TremFormatting
+import FilterBar
+import InfoBox
+import Constants
+import Config
+
+newFindPlayers :: Bundle -> (Bool -> GameServer -> IO ()) -> IO (VBox, IO ())
+newFindPlayers Bundle{..} setServer = do
+	Config {colors} <- atomically $ readTMVar mconfig
+	rawmodel	<- listStoreNew []
+	model		<- treeModelFilterNew rawmodel []
+	view		<- treeViewNewWithModel model
+	
+	addColumnsFilter rawmodel model view [
+		  ("Name", True, pangoPretty colors . fst)
+		, ("Server", True, pangoPretty colors . hostname . snd) 
+		]
+
+	(infobox, statNow, statTot) <- newInfobox "players"
+	Config {filterPlayers} <- atomically $ readTMVar mconfig
+	(filterbar, current)	<- newFilterBar model statNow filterPlayers
+	
+	treeModelFilterSetVisibleFunc model $ \iter -> do
+		(item,_) <- treeModelGetRow rawmodel iter
+		s <- readIORef current
+		return $ B.null s || s `B.isInfixOf` cleanedCase item
+		
+	let updateFilter = do
+		PollResult{..} <- atomically $ readTMVar mpolled
+		listStoreClear rawmodel
+		let plist = makePlayerNameList polled
+		mapM_ (listStoreAppend rawmodel) plist
+		treeModelFilterRefilter model
+		set statTot [ labelText := show (length plist) ]
+		n <- treeModelIterNChildren model Nothing
+		set statNow [ labelText := show n ]
+						
+	onCursorChanged view $ do
+		(x, _) <- treeViewGetCursor view
+		Just vIter <- treeModelGetIter model x
+		iter	<-treeModelFilterConvertIterToChildIter model vIter
+		gameserver <- treeModelGetRow rawmodel iter
+		setServer False (snd gameserver)
+		return ()
+
+	onRowActivated view $ \path _ -> do
+		Just vIter	<- treeModelGetIter model path
+		fIter		<- treeModelFilterConvertIterToChildIter model vIter
+		gameserver	<- treeModelGetRow rawmodel fIter
+		setServer True (snd gameserver)
+	
+	scroll <- scrollIt view PolicyAutomatic PolicyAlways
+	
+	box <- vBoxNew False 0
+	boxPackStart box filterbar PackNatural spacing
+	boxPackStart box scroll PackGrow 0
+	boxPackStart box infobox PackNatural 0
+	
+	return (box, updateFilter)
diff --git a/src/GtkUtils.hs b/src/GtkUtils.hs
new file mode 100644
--- /dev/null
+++ b/src/GtkUtils.hs
@@ -0,0 +1,162 @@
+module GtkUtils where
+import Graphics.UI.Gtk
+import Control.Monad 
+
+whenJust :: Monad m => Maybe a -> (a -> m ()) -> m ()
+whenJust x f = case x of
+	Nothing	-> return ()
+	Just a	-> f a 
+	
+			
+scrollIt, scrollItV :: WidgetClass widget => widget -> PolicyType -> PolicyType -> IO ScrolledWindow
+scrollIt widget pol1 pol2 = do
+	scroll <- scrolledWindowNew Nothing Nothing
+	scrolledWindowSetPolicy scroll pol1 pol2
+	containerAdd scroll widget
+	return scroll
+	
+scrollItV widget pol1 pol2 = do
+	scroll <- scrolledWindowNew Nothing Nothing
+	scrolledWindowSetPolicy scroll pol1 pol2
+	scrolledWindowAddWithViewport scroll widget
+	--set scroll [ scrolledWindowShadowType := ShadowNone ]
+	Just vp <- binGetChild scroll
+	set (castToViewport vp) [ viewportShadowType  := ShadowNone ]
+	return scroll
+	
+
+simpleListView :: [(String, Bool, a -> String)] -> IO (ListStore a, TreeView)
+simpleListView headers = do
+	model <- listStoreNew []
+	view <- treeViewNewWithModel model
+	select <- treeViewGetSelection view
+	treeSelectionSetMode select SelectionNone
+	addColumns model view $
+		map (\(title, isName, f) -> (title, if isName then 0 else 1, isName, isName, isName, f)) headers
+	return (model, view)
+	
+	
+
+newLabeledFrame :: String -> IO Frame
+newLabeledFrame lbl = do
+	frame <- frameNew
+	frameSetLabel frame lbl
+	return frame
+	
+	
+notebookAppendMnemonic :: (NotebookClass self, WidgetClass child) => self -> child -> String -> IO Int
+notebookAppendMnemonic nb child txt = do
+	n <- notebookAppendPage nb child ""
+	lbl <- labelNewWithMnemonic txt
+	notebookSetTabLabel nb child lbl
+	return n
+
+addColumns :: (TreeViewClass view, TreeModelClass (model row), TypedTreeModelClass model) =>
+	model row -> view -> [(String, Float, Bool, Bool, Bool, row -> String)] -> IO ()
+addColumns model view xs = mapM_ g xs where
+	g (title, align, format, expand, ellipsize, f) = do
+		col <- treeViewColumnNew
+		set col	[ treeViewColumnTitle := title
+			, treeViewColumnExpand := expand ]
+		rend <- cellRendererTextNew
+		set rend [ cellXAlign := align]
+		when ellipsize $
+			set rend [ cellTextEllipsizeSet := True, cellTextEllipsize := EllipsizeEnd]
+		cellLayoutPackStart col rend True
+		cellLayoutSetAttributes col rend model $ \row -> if format
+			then [ cellTextMarkup := Just (f row) ]
+			else [ cellText := f row ]
+		treeViewAppendColumn view col
+		
+{-
+addColumnsSort raw model view xs = sequence_ $ zipWith f (iterate (+1) 0) xs where
+	f n (title, format, expand, showf,  sortf) = do
+		col <- treeViewColumnNew
+		set col	[ treeViewColumnTitle := title
+			, treeViewColumnExpand := expand ]
+		rend <- cellRendererTextNew
+		cellLayoutPackStart col rend True
+		cellLayoutSetAttributeFunc col rend model $ \iter -> do
+			cIter	<- treeModelSortConvertIterToChildIter model iter
+			item	<- treeModelGetRow raw cIter
+			set rend $ if format 
+				then [ cellTextMarkup := Just (showf item) ]
+				else [ cellText := showf item ]
+		treeViewAppendColumn view col
+		case sortf of
+			Nothing	-> return ()
+			Just g	-> do
+				col `treeViewColumnSetSortColumnId` n
+				treeSortableSetSortFunc model n (xort raw g)
+-}
+addColumnsFilter :: (TreeViewClass self1, TreeModelFilterClass self, TreeModelClass self, TypedTreeModelClass model) =>
+	model t -> self -> self1 -> [(String, Bool, t -> String)] -> IO ()
+addColumnsFilter raw model view xs = mapM_ f xs where
+	f (title, expand, showf) = do
+		col <- treeViewColumnNew
+		set col	[ treeViewColumnTitle := title
+			, treeViewColumnExpand := expand ]
+		rend <- cellRendererTextNew
+		when expand $
+			set rend [ cellTextEllipsize := EllipsizeEnd]
+		cellLayoutPackStart col rend True
+		cellLayoutSetAttributeFunc col rend model $ \iter -> do
+			cIter	<- treeModelFilterConvertIterToChildIter model iter
+			item	<- treeModelGetRow raw cIter
+			set rend [ cellTextMarkup := Just (showf item) ]
+		treeViewAppendColumn view col
+
+addColumnsFilterSort :: (TreeViewClass self, TreeSortableClass self1, TreeModelSortClass self1,
+	TreeModelFilterClass self2, TreeModelClass self1, TypedTreeModelClass model) =>
+	model t -> self2 -> self1 -> self -> Maybe (t -> t -> Ordering)
+	-> [(String, Float, Bool, Bool, Bool, t -> String, Maybe (t -> t -> Ordering))]
+	-> IO ()
+addColumnsFilterSort raw filtered sorted view defaultSort xs = zipWithM_ f [0..] xs where
+	f n (title, align, format, expand, ellipsize, showf,  sortf) = do
+		col <- treeViewColumnNew
+		set col	[ treeViewColumnTitle := title
+			, treeViewColumnExpand := expand ]
+		rend <- cellRendererTextNew
+		when ellipsize $
+			set rend [ cellTextEllipsizeSet := True, cellTextEllipsize := EllipsizeEnd]
+		set rend [ cellXAlign := align]
+		cellLayoutPackStart col rend True
+		cellLayoutSetAttributeFunc col rend sorted $ \iter -> do
+			cIter	<- treeModelSortConvertIterToChildIter sorted iter
+			rcIter	<- treeModelFilterConvertIterToChildIter filtered cIter
+			item	<- treeModelGetRow raw rcIter
+			set rend $ if format 
+				then [ cellTextMarkup := Just (showf item) ]
+				else [ cellText := showf item ] 
+		treeViewAppendColumn view col
+		case sortf of
+			Nothing	-> return ()
+			Just g	-> do
+				col `treeViewColumnSetSortColumnId` n
+				treeSortableSetSortFunc sorted n $ \it1 it2 -> do
+					rit1	<- treeModelFilterConvertIterToChildIter filtered it1
+					rit2	<- treeModelFilterConvertIterToChildIter filtered it2
+					xort raw g rit1 rit2
+		whenJust defaultSort $ \a -> treeSortableSetDefaultSortFunc sorted $ Just $ \it1 it2 -> do
+				rit1	<- treeModelFilterConvertIterToChildIter filtered it1
+				rit2	<- treeModelFilterConvertIterToChildIter filtered it2
+				xort raw a rit1 rit2
+				
+gtkPopup :: MessageType -> String -> IO ()
+gtkPopup what str = do
+	a <- messageDialogNew Nothing [DialogDestroyWithParent, DialogModal]
+		what ButtonsOk str
+	set a [ windowWindowPosition := WinPosCenter]
+	dialogRun a
+	widgetDestroy a
+
+gtkWarn, gtkError :: String -> IO ()
+gtkWarn = gtkPopup MessageWarning
+gtkError = gtkPopup MessageError
+
+xort :: TypedTreeModelClass model => model t -> (t -> t -> b) -> TreeIter -> TreeIter -> IO b
+xort model g it1 it2 = do
+a <- treeModelGetRow model it1 
+b <- treeModelGetRow model  it2
+return $ g a b
+
diff --git a/src/InfoBox.hs b/src/InfoBox.hs
new file mode 100644
--- /dev/null
+++ b/src/InfoBox.hs
@@ -0,0 +1,38 @@
+module InfoBox (newInfobox, newInfoboxBrowser) where
+import Graphics.UI.Gtk
+
+
+newInfobox :: String -> IO (VBox, Label, Label)
+newInfobox what= do
+	lst <- mapM (labelNew . Just)
+		["Showing", "0", " out of", "0", ' ' : what]
+		
+	let (_:a:_:b:_) = lst
+	mapM_ (\x -> set x [ labelWidthChars := 4 ] >> miscSetAlignment x 1 0) [a,b]
+	
+	bar <- mkStatusBar lst
+	return (bar, a, b)
+
+newInfoboxBrowser :: IO (VBox, Label, Label, Label)
+newInfoboxBrowser = do
+	lst <- mapM (labelNew . Just)
+		["Showing", "0", " out of", "0", " servers, with", "0", " not responding" ]
+
+	let (_:a:_:b:_:c:_) = lst
+	mapM_ (\x -> set x [ labelWidthChars := 4 ] >> miscSetAlignment x 1 0) [a,b,c]
+	set c [ labelWidthChars := 3 ]
+	
+	bar <- mkStatusBar lst
+	return (bar, a, b, c)
+
+mkStatusBar :: WidgetClass child => [child] -> IO VBox
+mkStatusBar xs = do
+	box <- hBoxNew False 0
+	mapM_ (\x -> boxPackStart box x PackNatural 0) xs
+	vb <- vBoxNew False 0
+	sep <- hSeparatorNew
+	boxPackStart vb sep PackNatural 0
+	boxPackStart vb box PackNatural 0
+	return vb
+	
+	
diff --git a/src/List2.hs b/src/List2.hs
new file mode 100644
--- /dev/null
+++ b/src/List2.hs
@@ -0,0 +1,14 @@
+module List2 (stripw, intmean) where
+import Prelude hiding (foldr, foldl, foldr1, foldl1)
+import Data.Char
+import Data.Foldable
+
+stripw :: String -> String
+stripw = dropWhileRev isSpace . dropWhile isSpace
+
+dropWhileRev :: (a -> Bool) -> [a] -> [a]
+dropWhileRev p = foldr (\x xs -> if p x && null xs then [] else x:xs) []
+
+intmean :: (Integral i, Foldable f) => f i -> i
+intmean l = if len == 0 then 0 else lsum `div` len where
+	(len, lsum) = foldl' (\(!n, !s) elm -> (n+1, s+elm)) (0, 0) l
diff --git a/src/Preferences.hs b/src/Preferences.hs
new file mode 100644
--- /dev/null
+++ b/src/Preferences.hs
@@ -0,0 +1,273 @@
+module Preferences where
+import Graphics.UI.Gtk
+import Control.Monad
+import Control.Applicative hiding (empty)
+import Control.Concurrent.STM
+import Data.Char
+import Data.Array
+import Text.Printf
+import Network.Tremulous.Protocol
+
+import Types
+import Config
+import Constants
+import GtkUtils
+import TremFormatting
+
+
+newPreferences :: Bundle -> IO ScrolledWindow
+newPreferences Bundle{..} = do
+	-- Default filters
+	
+	(tbl, [filterBrowser', filterPlayers'], filterEmpty') <-
+		configTable ["_Browser:", "Find _players:"]
+	filters <- newLabeledFrame "Default filters"
+	set filters [ containerChild := tbl]
+
+
+	-- Tremulous path
+	(pathstbl, [tremPath', tremGppPath']) <- pathTable parent ["_Tremulous 1.1:", "Tremulous _GPP:"]
+	paths <- newLabeledFrame "Tremulous path or command"
+	set paths [ containerChild := pathstbl]
+
+	-- Startup
+
+	startupMaster	<- checkButtonNewWithMnemonic "Re_fresh all servers"
+	startupClan	<- checkButtonNewWithMnemonic "S_ync clan list"
+	startupGeometry	<- checkButtonNewWithMnemonic "Restore _window geometry from previous session"
+	
+	(startup, startupBox) <- framedVBox ("On startup")
+	boxPackStartDefaults startupBox startupMaster	
+	boxPackStartDefaults startupBox startupClan
+	boxPackStartDefaults startupBox startupGeometry
+			
+
+	-- Colors
+
+	(colorTbl, colorList)	<- numberedColors 
+	(colors', colorBox)	<- framedVBox "Color theme"
+	colorWarning		<- labelNew (Just "Note: Requires a restart to take effect")
+	
+	miscSetAlignment colorWarning 0 0
+	boxPackStart colorBox colorTbl PackNatural 0
+	boxPackStart colorBox colorWarning PackNatural 0
+
+
+	-- Internals
+	(itbl, [itimeout, iresend, ibuf]) <- mkInternals 
+	(internals, ibox) <- framedVBox "Polling Internals"
+	ilbl <- labelNew $ Just "Tip: Hover the cursor over each option for a description"
+	miscSetAlignment ilbl 0 0
+	--labelSetLineWrap ilbl True
+	boxPackStart ibox itbl PackNatural 0
+	boxPackStart ibox ilbl PackNatural 0
+
+
+	-- Apply
+	
+	apply	<- buttonNewFromStock stockApply
+	bbox	<- hBoxNew False 0
+	boxPackStartDefaults bbox apply
+	balign	<- alignmentNew 0.5 1 0 0
+	set balign [ containerChild := bbox ]
+
+	on apply buttonActivated $ do
+		filterBrowser	<- get filterBrowser' entryText
+		filterPlayers	<- get filterPlayers' entryText
+		filterEmpty	<- get filterEmpty' toggleButtonActive
+		tremPath	<- get tremPath' entryText
+		tremGppPath	<- get tremGppPath' entryText
+		autoMaster	<- get startupMaster toggleButtonActive
+		autoClan	<- get startupClan toggleButtonActive
+		autoGeometry	<- get startupGeometry toggleButtonActive
+		packetTimeout	<- (*1000) <$> spinButtonGetValueAsInt itimeout
+		packetDuplication	<- spinButtonGetValueAsInt iresend
+		throughputDelay	<- (*1000) <$> spinButtonGetValueAsInt ibuf
+		
+		rawcolors	<- forM colorList $ \(colb, cb) -> do
+					bool <- get cb toggleButtonActive
+					if bool then
+						TFColor . colorToHex <$> colorButtonGetColor colb
+					else
+						return TFNone
+		old		<- atomically $ takeTMVar mconfig
+		let new		= old {filterBrowser, filterPlayers, autoMaster
+				, autoClan, autoGeometry, tremPath, tremGppPath
+				, colors = makeColorsFromList rawcolors
+				, delays = Delay{..}, filterEmpty}
+		atomically $ putTMVar mconfig new
+		configToFile new
+		return ()
+	
+	-- Main box
+
+	box <- vBoxNew False spacing
+	set box [ containerBorderWidth := spacingBig ]
+	boxPackStart box filters PackNatural 0
+	boxPackStart box paths PackNatural 0
+	boxPackStart box startup PackNatural 0
+	boxPackStart box colors' PackNatural 0
+	boxPackStart box internals PackNatural 0
+	boxPackStart box balign PackGrow 0
+
+
+	-- Set values from Config
+	let updateF = do
+		Config {..} 		<- atomically $ readTMVar mconfig
+		set filterBrowser'	[ entryText := filterBrowser ]
+		set filterPlayers'	[ entryText := filterPlayers ]
+		set filterEmpty'	[ toggleButtonActive := filterEmpty]
+		set tremPath'		[ entryText := tremPath ]
+		set tremGppPath'	[ entryText := tremGppPath ]
+		set startupMaster	[ toggleButtonActive := autoMaster ]
+		set startupClan		[ toggleButtonActive := autoClan ]
+		set startupGeometry	[ toggleButtonActive := autoGeometry ]
+		set itimeout		[ spinButtonValue := fromIntegral (packetTimeout delays `div` 1000) ]
+		set iresend		[ spinButtonValue := fromIntegral (packetDuplication delays) ]
+		set ibuf		[ spinButtonValue := fromIntegral (throughputDelay delays `div` 1000) ]
+		sequence_ $ zipWith f colorList (elems colors)
+		where	f (a, b) (TFColor c) = do
+				colorButtonSetColor a (hexToColor c)
+				toggleButtonSetActive b True
+			f (_,b) _ = do
+				toggleButtonSetActive b False
+				-- Apparently this is needed too
+				toggleButtonToggled b
+	updateF
+		
+	scrollItV box PolicyNever PolicyAutomatic
+
+configTable :: [String] -> IO (Table, [Entry], CheckButton)
+configTable ys = do
+	tbl <- tableNew 0 0 False
+	empty <- checkButtonNewWithMnemonic "_empty"
+	let easyAttach pos lbl  = do
+		a <- labelNewWithMnemonic lbl
+		b <- entryNew
+		set a [ labelMnemonicWidget := b ]
+		miscSetAlignment a 0 0.5
+		tableAttach tbl a 0 1 pos (pos+1) [Fill] [] spacing spacingHalf
+		tableAttach tbl b 1 2 pos (pos+1) [Expand, Fill] [] spacing spacingHalf
+		when (pos == 0) $ 
+			tableAttach tbl empty 2 3 pos (pos+1) [Fill] [] spacing spacingHalf
+				
+		return b
+		
+	let mkTable xs = mapM (uncurry easyAttach) (zip [0..] xs)
+	rt	<- mkTable ys
+	return (tbl, rt, empty)
+
+pathTable :: Window -> [String] -> IO (Table, [Entry])
+pathTable parent ys = do
+	tbl <- tableNew 0 0 False
+	let easyAttach pos lbl  = do
+		a <- labelNewWithMnemonic lbl
+		(box, ent) <- pathSelectionEntryNew parent
+		set a [ labelMnemonicWidget := ent ]
+		miscSetAlignment a 0 0.5
+		tableAttach tbl a 0 1 pos (pos+1) [Fill] [] spacing spacingHalf
+		tableAttach tbl box 1 2 pos (pos+1) [Expand, Fill] [] spacing spacingHalf
+		return ent
+		
+	let mkTable xs = mapM (uncurry easyAttach) (zip [0..] xs)
+	rt	<- mkTable ys
+	return (tbl, rt)
+
+mkInternals :: IO (Table, [SpinButton])
+mkInternals = do
+	tbl <- tableNew 0 0 False
+	tips <- tooltipsNew
+
+	let easyAttach pos (lbl, lblafter, tip)  = do
+		a <- labelNewWithMnemonic lbl
+		tooltipsSetTip tips a tip ""
+		b <- spinButtonNewWithRange 0 10000 1
+		c <- labelNew (Just lblafter)
+		set a [ labelMnemonicWidget := b ]
+		miscSetAlignment a 0 0.5
+		miscSetAlignment c 0 0
+		tableAttach tbl a 0 1 pos (pos+1) [Fill] [] spacing spacingHalf
+		tableAttach tbl b 1 2 pos (pos+1) [Fill] [] spacing spacingHalf
+		tableAttach tbl c 2 3 pos (pos+1) [Fill] [] spacing spacingHalf
+		return b
+		
+	let mkTable xs = mapM (uncurry easyAttach) (zip [0..] xs)
+	rt <- mkTable	[ ("Respo_nse Timeout:", "ms", "How long Apelsin should wait before sending a new request to a server possibly not responding")
+			, ("Maximum packet _duplication:", "times", "Maximum number of extra requests to send beoynd the initial one if a server does not respond" )
+			, ("Throughput _limit:", "ms", "Should be set as low as possible as long as pings from \"Refresh all servers\" remains the same as \"Refresh current\"") ]
+	return (tbl, rt)
+
+
+framedVBox :: String -> IO (Frame, VBox)
+framedVBox title = do
+	box	<- vBoxNew False 0
+	frame	<- newLabeledFrame title
+	set box [ containerBorderWidth := spacing ]
+	set frame	[ containerChild := box ]
+	return (frame, box)
+	
+numberedColors :: IO (Table, [(ColorButton, CheckButton)])
+numberedColors = do
+	tbl <- tableNew 0 0 False
+	let easyAttach pos lbl  = do
+		a <- labelNew (Just lbl)
+		b <- colorButtonNew
+		c <- checkButtonNew
+		on c toggled $ do
+			bool <- get c toggleButtonActive
+			set b [ widgetSensitive := if bool then True else False ]
+		miscSetAlignment a 0.5 0
+		tableAttach tbl a pos (pos+1) 0 1 [Fill] [] spacingHalf spacingHalf
+		tableAttach tbl b pos (pos+1) 1 2 [Fill] [] spacingHalf spacingHalf
+		tableAttach tbl c pos (pos+1) 2 3 [] [] spacingHalf spacingHalf
+		return (b, c)
+	let mkTable xs = mapM (uncurry easyAttach) (zip (iterate (+1) 0) xs)
+
+	xs <- mkTable ["^0", "^1", "^2", "^3", "^4", "^5", "^6", "^7"]
+	return (tbl, xs)
+
+
+-- Gtk fails yet again and doesn't offer something like this by default
+pathSelectionEntryNew :: Window -> IO (HBox, Entry)
+pathSelectionEntryNew parent = do
+	box	<- hBoxNew False 0
+	img	<- imageNewFromStock stockOpen (IconSizeUser 1)
+	button	<- buttonNew
+	set button [ buttonImage := img ]
+	ent	<- entryNew
+
+	boxPackStart box ent PackGrow 0
+	boxPackStart box button PackNatural 0
+	
+		
+	on button buttonActivated $ do
+		fc	<- fileChooserDialogNew (Just "Select path") (Just parent) FileChooserActionOpen
+			[ (stockCancel, ResponseCancel)
+			, (stockOpen, ResponseAccept) ]
+		widgetShow fc
+		resp <- dialogRun fc
+		case resp of
+			ResponseAccept -> do
+					tst <- fileChooserGetFilename fc
+					whenJust tst $ \path ->
+						set ent [ entryText := path ]
+			_-> return ()
+		widgetDestroy fc
+		
+	
+	return (box, ent)
+
+
+-- And more fail by gtk to not include something like this by default
+
+colorToHex :: Color -> String
+colorToHex (Color a b c) = printf "#%02x%02x%02x" (f a) (f b) (f c)
+	where f = (`div` 0x100)
+
+
+hexToColor :: String -> Color
+hexToColor ('#':a:b:c:d:e:g:_)	= Color (f a b) (f c d) (f e g)
+	where f x y = fromIntegral $ (digitToInt x * 0x10 + digitToInt y) * 0x100
+hexToColor ('#':a:b:c:_)	= Color (f a) (f b) (f c)
+	where f x = fromIntegral $ digitToInt x * 0x1000
+hexToColor _			= Color 0 0 0
diff --git a/src/STM2.hs b/src/STM2.hs
new file mode 100644
--- /dev/null
+++ b/src/STM2.hs
@@ -0,0 +1,32 @@
+module STM2(
+	module Control.Concurrent, module Control.Concurrent.STM
+	, tryReadTMVar, withTMVar, clearTMVar, replaceTMVar
+) where
+
+import Control.Concurrent
+import Control.Concurrent.STM
+import Control.Monad
+
+tryReadTMVar :: TMVar a -> STM (Maybe a)
+tryReadTMVar v = do 
+	x <- tryTakeTMVar v
+	case x of
+		Just a	-> putTMVar v a >> return (Just a)
+		Nothing	-> return Nothing
+
+withTMVar :: TMVar a -> (a -> IO ()) -> IO ()
+withTMVar mvar f = do
+	tst <- atomically $ tryReadTMVar mvar
+	case tst of
+		Nothing	-> return ()
+		Just a	-> f a
+		
+clearTMVar :: TMVar a -> STM ()		
+clearTMVar mvar = do
+	t <- isEmptyTMVar mvar
+	unless t $ do
+		takeTMVar mvar
+		return ()
+
+replaceTMVar :: TMVar a -> a -> STM ()
+replaceTMVar t x = clearTMVar t >> putTMVar t x
diff --git a/src/ServerBrowser.hs b/src/ServerBrowser.hs
new file mode 100644
--- /dev/null
+++ b/src/ServerBrowser.hs
@@ -0,0 +1,98 @@
+module ServerBrowser where
+import Graphics.UI.Gtk
+import Control.Concurrent.STM
+import Data.IORef
+import qualified Data.ByteString.Char8 as B
+import Data.Ord
+import Network.Tremulous.Protocol
+import Text.Printf
+
+import Types
+import GtkUtils
+import FilterBar
+import InfoBox
+import TremFormatting
+import Constants
+import Config
+
+newServerBrowser :: Bundle -> (Bool -> GameServer -> IO ()) -> IO (VBox, IO ())
+newServerBrowser Bundle{..} setServer = do
+	Config {colors} <- atomically $ readTMVar mconfig
+	rawmodel	<- listStoreNew []
+	filtered	<- treeModelFilterNew rawmodel []
+	model		<- treeModelSortNewWithModel filtered	
+	view		<- treeViewNewWithModel model
+	
+	addColumnsFilterSort rawmodel filtered model view (Just (comparing gameping)) [
+		  ("_Game"	, 0	, False	, False	, False	, showGame , Just (comparing (\x -> (protocol x, gamemod x))))
+		, ("_Name"	, 0	, True	, True	, True	, pangoPretty colors . hostname	, Just (comparing hostname))
+		, ("_Map"	, 0	, True	, False	, False	, take 16 . unpackorig . mapname	, Just (comparing mapname))
+		, ("P_ing"	, 1	, False	, False , False	, show . gameping	, Just (comparing gameping))
+		, ("_Players"	, 1	, False	, False , False	, showPlayers		, Just (comparing nplayers))
+		]
+
+	(infobox, statNow, statTot, statRequested) <- newInfoboxBrowser
+	
+	Config {filterBrowser, filterEmpty} <- atomically $ readTMVar mconfig
+	(filterbar, current) <- newFilterBar filtered statNow filterBrowser
+	empty <- checkButtonNewWithMnemonic "_empty"
+	set empty [ toggleButtonActive := filterEmpty ]
+	boxPackStart filterbar empty PackNatural 0
+	on empty toggled $ do
+		treeModelFilterRefilter filtered
+		n <- treeModelIterNChildren filtered Nothing
+		set statNow [ labelText := show n ]
+
+
+	treeModelFilterSetVisibleFunc filtered $ \iter -> do
+		GameServer{..}	<- treeModelGetRow rawmodel iter
+		s		<- readIORef current
+		showEmpty	<- toggleButtonGetActive empty
+		return $ (showEmpty || not (null players)) && (B.null s ||
+			smartFilter s [
+				  cleanedCase hostname
+				, cleanedCase mapname
+				, proto2string protocol
+				, maybe "" cleanedCase gamemod
+				])
+			
+	onCursorChanged view $ do
+		(x, _)		<- treeViewGetCursor view
+		Just vIter	<- treeModelGetIter model x
+		sIter		<- treeModelSortConvertIterToChildIter model vIter
+		fIter		<- treeModelFilterConvertIterToChildIter filtered sIter
+		gameserver	<- treeModelGetRow rawmodel fIter
+		setServer False gameserver
+
+	onRowActivated view $ \path _ -> do
+		Just vIter	<- treeModelGetIter model path
+		sIter		<- treeModelSortConvertIterToChildIter model vIter
+		fIter		<- treeModelFilterConvertIterToChildIter filtered sIter
+		gameserver	<- treeModelGetRow rawmodel fIter
+		setServer True gameserver
+		
+	
+	scrollview <- scrolledWindowNew Nothing Nothing
+	scrolledWindowSetPolicy scrollview PolicyNever PolicyAlways
+	containerAdd scrollview view
+	
+	let updateF = do
+		PollResult{..} <- atomically $ readTMVar mpolled
+		listStoreClear rawmodel
+		treeViewColumnsAutosize view
+		mapM_ (listStoreAppend rawmodel) polled
+		treeModelFilterRefilter filtered
+		set statTot		[ labelText := show serversResponded ]
+		set statRequested	[ labelText := show (serversRequested-serversResponded) ]
+		n <- treeModelIterNChildren filtered Nothing
+		set statNow [ labelText := show n ]
+		
+	box <- vBoxNew False 0
+	boxPackStart box filterbar PackNatural spacing
+	boxPackStart box scrollview PackGrow 0
+	boxPackStart box infobox PackNatural 0
+	
+	return (box, updateF)
+	where
+	showGame GameServer{..} = proto2string protocol ++ maybe "" (("-"++) . htmlEscape . unpackorig) gamemod
+	showPlayers GameServer{..} = printf "%d / %2d" nplayers slots
diff --git a/src/ServerInfo.hs b/src/ServerInfo.hs
new file mode 100644
--- /dev/null
+++ b/src/ServerInfo.hs
@@ -0,0 +1,189 @@
+module ServerInfo where
+import Graphics.UI.Gtk
+
+import Prelude hiding (catch)
+import Control.Monad hiding (join)
+import Control.Exception
+import Data.Ord
+import Data.List (sortBy)
+import System.Process
+
+import Network.Tremulous.Protocol
+import Network.Tremulous.Polling
+import Network.Tremulous.Util
+
+import Types
+import STM2
+import List2
+import TremFormatting
+import GtkUtils
+import Constants
+import Config
+
+newServerInfo :: Bundle -> IO (VBox, IO (), Bool -> GameServer -> IO ())
+newServerInfo Bundle{..} = do
+	Config {colors} <- atomically $ readTMVar mconfig
+	current		<- atomically newEmptyTMVar
+	running		<- atomically newEmptyTMVar
+	
+	-- Host name
+	hostnamex <- labelNew Nothing
+	hostnamex `labelSetMarkup` "<b><big>Server</big></b>"
+	set hostnamex [
+		  labelWrap	:= True
+		, labelJustify	:= JustifyCenter
+		, labelSelectable := True
+		-- failgtk exception..
+		--, labelWrapMode := WrapPartialWords
+		]
+	
+	-- Pretty Cvar table
+	tbl <- tableNew 5 2 True
+	let easyAttach pos lbl  = do
+		a <- labelNew (Just lbl)
+		b <- labelNew Nothing
+		miscSetAlignment a 1 0.5
+		miscSetAlignment b 0 0.5
+		tableAttach tbl a 0 1 pos (pos+1) [Expand, Fill] [Expand, Fill] 8 2
+		tableAttach tbl b 1 2 pos (pos+1) [Expand, Fill] [Expand, Fill] 8 2 
+		return b
+		
+	let mkTable xs = mapM (uncurry easyAttach) (zip [0..] xs)
+	datta <- mkTable ["IP:Port", "Game (mod)", "Map", "Password protected"
+			, "Slots (+private)", "Ping (server average)"]
+	set (head datta) [ labelSelectable := True ]
+	
+	
+	-- Players
+	allplayers <- vBoxNew False 4
+	--allplayersscroll <- scrollItV allplayers PolicyNever PolicyAutomatic
+		
+	alienshumans <- hBoxNew True 4
+	
+	let playerView x = simpleListView [(x, True, pangoPretty colors . name)
+					, ("Score", False, show . kills)
+					, ("Ping", False, show . ping)
+					]
+	(amodel, aview) <- playerView "Aliens"
+	(hmodel, hview) <- playerView "Humans"
+	(smodel, sview) <- simpleListView [("Spectators", True, pangoPretty colors . name)
+					, ("Ping", False, show . ping)]
+	
+	ascroll <- scrollIt aview PolicyNever PolicyAutomatic
+	hscroll <- scrollIt hview PolicyNever PolicyAutomatic
+	boxPackStart alienshumans ascroll PackGrow 0
+	boxPackStart alienshumans hscroll PackGrow 0
+
+
+	boxPackStart allplayers alienshumans PackGrow 0
+	specscroll <- scrollIt sview PolicyNever PolicyAutomatic
+	boxPackStart allplayers specscroll PackNatural 0
+
+	-- Action buttons
+	
+	join	<- buttonNewWithMnemonic "_Join Server"
+	refresh	<- buttonNewWithMnemonic "Refresh _current"
+	jimg	<- imageNewFromStock stockConnect IconSizeButton
+	rimg	<- imageNewFromStock stockRefresh IconSizeButton
+	set join 	[ buttonImage := jimg
+			, widgetSensitive := False ]
+	set refresh	[ buttonImage := rimg
+			, widgetSensitive := False ]
+	
+	serverbuttons <- hBoxNew False 0
+	boxPackStart serverbuttons join PackRepel 0
+	boxPackStart serverbuttons refresh PackRepel 0
+	
+	-- Packing
+	rightpane <- vBoxNew False spacing
+	set rightpane  [ containerBorderWidth := spacing ]
+	boxPackStart rightpane hostnamex PackNatural 1
+	boxPackStart rightpane tbl PackNatural 0
+	boxPackStart rightpane allplayers PackGrow 0
+	boxPackStart rightpane serverbuttons PackNatural 2
+
+
+	let launchTremulous = withTMVar current $ \GameServer{..} -> do
+		tst <- atomically $ tryTakeTMVar running
+		whenJust tst $ \a -> catch (terminateProcess a) (\(_ :: IOError) -> return ())
+		Config {tremPath, tremGppPath} <- atomically $ readTMVar mconfig
+		let binary = case protocol of
+			69 -> tremPath
+			70 -> tremGppPath
+			_  -> ""
+
+		set join [ widgetSensitive := False ]
+		(_,_,_,p) <- createProcess $ (proc (stripw binary) ["+connect", show address])
+			{close_fds = True, std_in = Inherit, std_out = Inherit, std_err = Inherit}
+		atomically $ putTMVar running p
+		forkIO $ do
+			threadDelay 1000000
+			postGUISync $ set join [ widgetSensitive := True ]
+			return ()
+		return ()
+
+	on join buttonActivated launchTremulous
+		
+	let setF boolJoin gs@GameServer{..} = do
+		let (a:b:d:e:f:g:_) = datta
+		hostnamex `labelSetMarkup` showHostname colors hostname
+		a `labelSetMarkup` show address
+		b `labelSetMarkup` (proto2string protocol ++ (case gamemod of
+					Nothing	-> ""
+					Just z	-> " (" ++ unpackorig z ++ ")"))
+		d `labelSetMarkup` unpackorig mapname
+		e `labelSetMarkup` if protected then "Yes" else "No"
+		f `labelSetMarkup` (show slots ++ " (+" ++ show privslots ++ ")")
+		labelSetMarkup g $ show gameping ++ 
+			" (" ++ (show . intmean . filter validping . map ping) players ++ ")"
+		
+		listStoreClear amodel
+		listStoreClear hmodel
+		listStoreClear smodel
+		
+		let (s', a', h', _) = partitionTeams (scoreSort players)
+		mapM_ (listStoreAppend amodel) a'
+		mapM_ (listStoreAppend hmodel) h'
+		mapM_ (listStoreAppend smodel) s'
+		treeViewColumnsAutosize aview
+		treeViewColumnsAutosize hview
+		treeViewColumnsAutosize sview
+		Requisition _ sReq <- widgetSizeRequest sview
+		set specscroll [ widgetHeightRequest := sReq ]
+		
+		atomically $ clearTMVar current >> putTMVar current gs
+		
+		set join [ widgetSensitive := True ]
+		set refresh [ widgetSensitive := True ]
+
+		when boolJoin launchTremulous
+		return ()
+
+		
+	let updateF = withTMVar mpolled $ \PollResult{..} ->
+		withTMVar current $ \GameServer{address} ->
+			case serverByAddress address polled of
+				Nothing -> return ()
+				Just a	-> setF False a
+			
+	
+	on refresh buttonActivated $ withTMVar current $ \x -> do
+		set refresh [ widgetSensitive := False ]
+		Config {delays} <- atomically $ readTMVar mconfig
+		forkIO $ do
+			new <- pollOne delays (address x)
+			postGUISync $ do
+				whenJust new (setF False)
+				set refresh [ widgetSensitive := True ]
+		return ()
+		
+	return (rightpane, updateF, setF)
+	where
+	validping x = x > 0 && x < 999
+	scoreSort = sortBy (flip (comparing kills))
+	showHostname colors x = "<b><big>" ++
+		(case pangoPretty colors x of
+			"" -> "<i>Invalid name</i>"
+			a -> a)
+		++ "</big></b>"
+		
diff --git a/src/System/Environment/XDG/BaseDir.hs b/src/System/Environment/XDG/BaseDir.hs
new file mode 100644
--- /dev/null
+++ b/src/System/Environment/XDG/BaseDir.hs
@@ -0,0 +1,103 @@
+{-# LANGUAGE CPP #-}
+
+module System.Environment.XDG.BaseDir
+    ( getUserDataDir
+    , getUserDataFile
+    , getUserConfigDir
+    , getUserConfigFile
+    , getUserCacheDir
+    , getUserCacheFile
+    , getSystemDataDirs
+    , getSystemDataFiles
+    , getSystemConfigDirs
+    , getSystemConfigFiles
+    , getAllDataDirs
+    , getAllDataFiles
+    , getAllConfigDirs
+    , getAllConfigFiles
+    ) where
+
+import System.FilePath    ( (</>), splitSearchPath )
+import System.Environment
+import System.Directory   ( getHomeDirectory )
+import Control.Monad      ( liftM2 )
+
+getDefault :: String -> IO FilePath
+#if defined(mingw32_HOST_OS) || defined(__MINGW32__)
+
+getDefault "XDG_DATA_HOME"   = getEnv "AppData"
+getDefault "XDG_CONFIG_HOME" = userRelative $ "Local Settings"
+getDefault "XDG_CACHE_HOME"  = userRelative $ "Local Settings" </> "Cache"
+getDefault "XDG_DATA_DIRS"   = getEnv "ProgramFiles"
+getDefault "XDG_CONFIG_DIRS" = getEnv "ProgramFiles"
+getDefault _                 = return ""
+
+#else
+
+getDefault "XDG_DATA_HOME"   = userRelative $ ".local" </> "share"
+getDefault "XDG_CONFIG_HOME" = userRelative $ ".config"
+getDefault "XDG_CACHE_HOME"  = userRelative $ ".cache"
+getDefault "XDG_DATA_DIRS"   = return $ "/usr/local/share:/usr/share"
+getDefault "XDG_CONFIG_DIRS" = return $ "/etc/xdg"
+getDefault _                 = return $ ""
+
+#endif
+
+-- | Get the directory for user-specific data files.
+getUserDataDir      :: String -> IO FilePath
+getUserDataDir      = singleDir "XDG_DATA_HOME"
+-- | Get the directory for user-specific configuration files.
+getUserConfigDir    :: String -> IO FilePath
+getUserConfigDir    = singleDir "XDG_CONFIG_HOME"
+-- | Get the directory for user-specific cache files.
+getUserCacheDir     :: String -> IO FilePath
+getUserCacheDir     = singleDir "XDG_CACHE_HOME"
+-- | Get a list of the system-wide data directories.
+getSystemDataDirs   :: String -> IO [FilePath]
+getSystemDataDirs   = multiDirs "XDG_DATA_DIRS"
+-- | Get a list of the system-wide configuration directories.
+getSystemConfigDirs :: String -> IO [FilePath]
+getSystemConfigDirs = multiDirs "XDG_CONFIG_DIRS"
+-- | Get a list of all data directories.
+getAllDataDirs      :: String -> IO [FilePath]
+getAllDataDirs a    = liftM2 (:) (getUserDataDir a) (getSystemDataDirs a)
+-- | Get a list of all configuration directories.
+getAllConfigDirs    :: String -> IO [FilePath]
+getAllConfigDirs a  = liftM2 (:) (getUserConfigDir a) (getSystemConfigDirs a)
+-- | Get the path to a specific user data file.
+getUserDataFile          :: String -> String -> IO FilePath
+getUserDataFile a f      = fmap (</> f) $ getUserDataDir a
+-- | Get the path to a specific user configuration file.
+getUserConfigFile        :: String -> String -> IO FilePath
+getUserConfigFile a f    = fmap (</> f) $ getUserConfigDir a
+-- | Get the path to a specific user cache file.
+getUserCacheFile         :: String -> String -> IO FilePath
+getUserCacheFile a f     = fmap (</> f) $ getUserCacheDir a
+-- | Get a list of all paths for a specific system data file.
+getSystemDataFiles       :: String -> String -> IO [FilePath]
+getSystemDataFiles a f   = fmap (map (</> f)) $ getSystemDataDirs a
+-- | Get a list of all paths for a specific system configuration file.
+getSystemConfigFiles     :: String -> String -> IO [FilePath]
+getSystemConfigFiles a f = fmap (map (</> f)) $ getSystemConfigDirs a
+-- | Get a list of all paths for a specific data file.
+getAllDataFiles          :: String -> String -> IO [FilePath]
+getAllDataFiles a f      = fmap (map (</> f)) $ getAllDataDirs a
+-- | Get a list of all paths for a specific configuration file.
+getAllConfigFiles        :: String -> String -> IO [FilePath]
+getAllConfigFiles a f    = fmap (map (</> f)) $ getAllConfigDirs a
+
+singleDir :: String -> String -> IO FilePath
+singleDir key app = envLookup key >>= return . (</> app)
+
+multiDirs :: String -> String -> IO [FilePath]
+multiDirs key app = envLookup key >>= return . map (</> app) . splitSearchPath
+
+envLookup :: String -> IO String
+envLookup key = do env <- getEnvironment
+                   case lookup key env of
+                        Just val -> return val
+                        Nothing  -> getDefault key
+
+userRelative :: FilePath -> IO FilePath
+userRelative p = getHomeDirectory >>= return . (</> p)
+
diff --git a/src/Toolbar.hs b/src/Toolbar.hs
new file mode 100644
--- /dev/null
+++ b/src/Toolbar.hs
@@ -0,0 +1,114 @@
+module Toolbar where
+
+import Graphics.UI.Gtk
+
+import Control.Applicative
+import Control.Exception
+import Control.Monad
+import Data.Maybe
+
+import Network.Socket 
+import Network.Tremulous.Protocol
+import Network.Tremulous.Polling
+import Network.Tremulous.Scheduler (getMicroTime)
+
+import Types
+import Constants
+import STM2
+
+import Config
+import About
+import Clanlist
+
+getDNS :: String -> String -> IO (Maybe SockAddr)
+getDNS host port = handle (\(_::IOException) -> return Nothing) $ do
+	AddrInfo _ _ _ _ addr _ <- Prelude.head `liftM` getAddrInfo Nothing (Just host) (Just port)
+	return $ Just addr
+
+	
+whileTrue :: Monad m => m Bool -> m ()
+whileTrue f = f >>= \t -> when t (whileTrue f)
+
+newToolbar :: Bundle -> IO () -> IO () -> IO HBox
+newToolbar bundle@Bundle{..} clanHook polledHook = do	
+	pbrbox		<- hBoxNew False spacing
+		
+	pb		<- progressBarNew
+	set pb		[ widgetNoShowAll := True ]
+	
+	refresh	<- buttonNewWithMnemonic "_Refresh all servers"
+	rimg		<- imageNewFromStock stockRefresh IconSizeButton
+	set refresh	[ buttonImage := rimg 
+			, buttonRelief := ReliefNone 
+			, buttonFocusOnClick := False ]
+			
+	about		<- buttonNewFromStock stockAbout
+	set about	[ buttonRelief		:= ReliefNone 
+			, buttonFocusOnClick	:= False ]
+
+	on about buttonActivated $ newAbout parent
+			
+	(clanSync, doSync) <- newClanSync bundle clanHook
+	
+	align		<- alignmentNew 0 0 0 0
+	alignbox	<- hBoxNew False spacing
+	set align [ containerChild := alignbox ]
+	
+	boxPackStartDefaults alignbox refresh
+	boxPackStartDefaults alignbox clanSync
+	boxPackStartDefaults alignbox about
+			
+	
+	set pbrbox [ containerBorderWidth := spacing ]
+	boxPackStart pbrbox align PackNatural 0
+	boxPackStart pbrbox pb PackGrow 0
+	
+	
+	let serverRefresh = do
+		progressBarSetFraction pb 0
+		widgetShow pb
+		refresh `set` [ widgetSensitive := False ]
+		Config {masterServers, delays=Delay{..}}	<- atomically $ readTMVar mconfig
+		
+		start <- getMicroTime
+
+		-- This is a stupid guess based on that about 110 servers will respond and the master
+		-- will take about 200ms to respond
+		PollResult { serversResponded } <- atomically $ readTMVar mpolled
+		let serversGuess = if serversResponded == 0 then 110 else serversResponded
+		let tremTime = (packetDuplication + 1) * packetTimeout
+			+ serversGuess * throughputDelay + 200 * 1000
+		
+		pbth <- forkIO $ whileTrue $ do
+			threadDelay 10000 --10 ms, 100 fps
+			now <- getMicroTime
+			let diff = now - start
+			if now-start > fromIntegral tremTime then do
+				postGUISync $ progressBarSetFraction pb 1
+				return False
+			else do
+				postGUISync $ progressBarSetFraction pb
+					(fromIntegral diff / fromIntegral tremTime)
+				return True
+			
+		forkIO $ do
+			Config {delays} <- atomically $ readTMVar mconfig
+			hosts <- catMaybes <$> mapM
+				(\(host, port, proto) -> fmap (`MasterServer` proto) <$> getDNS host (show port))
+				masterServers
+			result <- pollMasters delays hosts
+
+			atomically $ replaceTMVar mpolled result
+			killThread pbth
+			postGUISync $ do
+				polledHook
+				refresh `set` [ widgetSensitive := True ]
+				widgetHide pb
+		return ()
+	on refresh buttonActivated serverRefresh
+
+	Config {..} <- atomically $ readTMVar mconfig
+	when autoMaster serverRefresh
+	when autoClan doSync
+	return pbrbox
+	
diff --git a/src/TremFormatting.hs b/src/TremFormatting.hs
new file mode 100644
--- /dev/null
+++ b/src/TremFormatting.hs
@@ -0,0 +1,33 @@
+module TremFormatting where
+import Data.Array
+import Data.Char
+import Network.Tremulous.NameInsensitive
+
+data TremFmt = TFColor !String | TFNone
+	deriving (Show, Read)
+
+type ColorArray = Array Int TremFmt
+
+htmlEscape :: String -> String
+htmlEscape = foldr f [] where
+	f x xs = case x of 
+		'<' -> "&lt;" ++ xs
+		'>' -> "&gt;" ++ xs
+		'&' -> "&amp;" ++ xs
+		_   -> x : xs 
+	
+pangoColors :: ColorArray -> String -> String
+pangoColors arr = f False where
+	f n ('^':x:xs) | isAlphaNum x = case arr ! (a `mod` 8) of
+		TFColor color	-> close n ++ "<span color=\"" ++ color ++ "\">" ++ f True xs
+		TFNone		-> close n ++ f False xs
+		where a = ord x - ord '0'
+			  
+			
+	f n (x:xs)	= x:f n xs
+	f n []		= close n
+	
+	close n = if n then "</span>" else ""
+
+pangoPretty :: ColorArray-> TI -> String
+pangoPretty arr = pangoColors arr . htmlEscape . unpackorig
diff --git a/src/Types.hs b/src/Types.hs
new file mode 100644
--- /dev/null
+++ b/src/Types.hs
@@ -0,0 +1,16 @@
+module Types (
+	module Control.Concurrent.STM
+	, Bundle(..)
+) where
+import Graphics.UI.Gtk
+import Config
+import ClanFetcher
+import Control.Concurrent.STM
+import Network.Tremulous.Protocol
+
+data Bundle = Bundle {
+	  mpolled	:: !(TMVar PollResult)
+	, mconfig	:: !(TMVar Config)
+	, mclans	:: !(TMVar [Clan])
+	, parent	:: !Window
+	}
