diff --git a/LICENSE b/LICENSE
new file mode 100644
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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
+<https://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
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/README.org b/README.org
new file mode 100644
--- /dev/null
+++ b/README.org
@@ -0,0 +1,139 @@
+* HamLog
+** User manual for the hamlog program
+   This can be found here: [[file:doc/user_manual.org]]
+** Introduction
+This is the attempt to make a console based logging application
+for Ham Radio contacts.
+It is meant to be simple and fast to use,
+but additional useful features may be added in the future.
+There are two parts:
+1. The Ham library, providing functions for creating and modifying
+   contact lists.
+2. The hamlog user facing application.
+The two parts are separate, and most of the actual functionality is
+kept in the library, so other applications using the library can easily be built
+without having to replicate the functionalities that have nothing
+to do with user interfaces.
+
+* State of Development
+This is not really mature, but
+it is being used by some on a daily basis.
+
+* Compiling
+Get GHC and Cabal using e.g. [[https://www.haskell.org/ghcup/]].
+Run
+#+begin_src shell
+cabal configure
+cabal build
+#+end_src
+This should technically build on any system that supports all the
+needed libraries, which probably include macOS and Windows along with Linux.
+This has only been tried on Linux and macOS.
+
+* Library Usage
+The HamLog monad is meant as an easy to use back end to
+manipulate log lists.
+A usage example would be:
+#+begin_src haskell
+runHamLog defaultConfig emptyLogState $ do
+   readLog
+   q <- newQsoNow
+   updateQso 0 $ q { _qsoFreqency = MHz 146.52,
+                     _qsoNotes    = "Nice contact!" }
+   writeLog
+#+end_src
+Note that some things in this library are subject to change still.
+See the source for details.
+
+* CAT Interface
+There is a CAT (computer aided transceiver) interface included.
+Currently, the Yaesu FT-891 and the Elecraft K3/KX2/KX3 are supported.
+
+** Adding support for another radio
+Basically, the steps you need to do to support a new radio are simple:
+See the module Ham.CAT.SerialCAT; you need to add a set of functions in a SerialCAT structure.
+Check out the ones in Ham.CAT.YaesuFT891 and Ham.CAT.ElecraftKX2 for examples.
+It is currently assumed that the radio is connected using a serial interface, e.g. via USB.
+Note this interface may change in the future.
+Steps for adding a radio:
+- Add a SerialCAT interface and put it in a module in Ham.CAT, just like the existing radios.
+- Add a constructor for the new radio in Ham.CAT.Radios.Radio.
+- Add the SerialCAT interface to serialInterface in Ham.CAT.Radios.
+
+Each of these steps is really not much to do, the most work is probably the first one.
+
+The terminal UI supports reading the frequency and the current communications mode when
+creating a new contact.
+This functionality can be accessed in the `HamLog` monad also via the `cat` action.
+
+* Todo List
+** TODO Minimal ADIF export to support LOTW
+** TODO ADIF import?
+** TODO Add versioning for files and data structures. Support converting from older versions.
+   - Note taken on [2020-09-05 Sat 13:22] \\
+     Works for hamlog.config. Need to add some error reporting if something fails.
+     Need to add support for versioning the log file.
+** DONE Integrate getting values for new QSOs via CAT into HamLog.
+   Currently that is done in the Brick UI.
+** DONE Connection to radio
+   - Note taken on [2020-09-05 Sat 13:21] \\
+     Works so far SerialCAT implemented for FT891 and KX2/K3/KX3
+   - Note taken on [2020-08-15 Sat 23:01]
+     Support for Yaesu FT891 works, everything compiled in so far.
+*** DONE Add error handling to CAT
+*** DONE Separate the serial interface for particular radios from CAT.hs
+*** DONE Write / read configuration from disk.
+    Currently it's compiled in.
+** DONE Hand Writer [Text] result to the UI for the Info window.
+** DONE [#A] Make the Info window scrollable and fixed height.
+   It messes up the UI if there are many messages.
+** TODO Compute distances between locations
+** TODO Add Cabrillo output to Contest typeclass.
+** TODO Update QSO time while typing QSO.
+   Update the UTC time with e.g. CTRL-T.
+** TODO End time optional
+** TODO Add an ID to each QSO
+   This would help to find duplicates. Until then, use everything, including date/time,
+   to find actual duplicates, minus the one we are searching for.
+** TODO Fix callsign lookup
+** TODO Search QSOs.
+** TODO For searching and dupe checks, add hash table?
+** TODO Tags, grouping by tags.
+** TODO Multiple selection?
+** TODO Scrollable notes, if necessary.
+** TODO Application hangs when radio is not connected.
+   - Note taken on [2020-09-06 Sun 23:06] \\
+     Mitigation implemented. Not very pretty, but at least it happens only once per session at maximum.
+   - Note taken on [2020-09-06 Sun 14:06] \\
+     closeSerial blocks after writing / reading when the serial device exists
+     but is not connected.
+     There is no immediate way to get around that.
+     Mitigation: add error reporting to CAT and after first failure,
+     turn CAT off and let the user know.
+   Add error checks!
+   This happens when the serial port is configured to the wrong file node.
+** [#B] Multiple log files?
+   - Note taken on [2018-07-28 Sat 23:06] \\
+     This is simply possible by keeping log files in separate directories, along with configurations.
+** DONE Sanitize QSOs when updating / creating.
+   Remove leading and trailing whitespaces, possibly toUpper, etc.
+** DONE Point calculation NAQP
+   Add instance for Contest typeclass.
+** DONE Dupe check
+   - Note taken on [2020-07-07 Tue 00:21] \\
+     More or less done.
+** DONE Mode should stay the same for new contacts
+** DONE Point calculation FieldDay
+   - Note taken on [2020-06-30 Tue 23:03] \\
+     Done.
+** DONE [#A] Export to Cabrillo, configurable.
+   - Note taken on [2020-06-30 Tue 23:00] \\
+     Sort of works.
+** DONE Values for exchanges at contests.
+   CLOSED: [2018-07-28 Sat 23:05]
+   - Note taken on [2018-07-28 Sat 23:05] \\
+     Default values have been added to the config structure.
+     See QsoDefaults. FixedValue means the UI does not display the value,
+     DefaultValue means the UI displays it but pre-populates with the given value
+     in the config file.
+     This way the application can be configured to work better in contests.
diff --git a/app/Main.hs b/app/Main.hs
new file mode 100644
--- /dev/null
+++ b/app/Main.hs
@@ -0,0 +1,119 @@
+{-# LANGUAGE OverloadedStrings, RankNTypes, BangPatterns, DataKinds, DeriveGeneric, TypeOperators, FlexibleInstances, ScopedTypeVariables, StandaloneDeriving #-}
+
+
+module Main where
+
+import Control.Monad.IO.Class (liftIO)
+import Ham.Log as HL
+import Ham.Cabrillo
+import Ham.CabrilloTypes
+import Ham.UI.Brick
+import Data.List as L
+import Brick.Main
+import qualified Graphics.Vty as V
+import Ham.Fcc
+
+import Ham.Contest
+import Data.Proxy
+
+import System.Exit
+import System.Posix.Files (fileExist)
+import System.Console.GetOpt
+import System.Environment (getArgs)
+
+import GHC.Generics
+import Options.Generic
+
+data Options w = Options { cabrillo :: w ::: Maybe String <?> "Export to cabrillo; argument one of {naqp, fieldday}"
+                         , outfile :: w ::: Maybe String <?> "Output file for cabrillo export."
+                         , config :: w ::: Maybe FilePath <?> "hamlog.config file to use"
+                         , points :: w ::: Maybe String <?> "Points for a contest, one of {fieldday, naqpcw, naqpssb}" } deriving  Generic
+
+instance ParseRecord (Options Wrapped)
+deriving instance Show (Options Unwrapped)
+
+
+main :: IO ()
+main = do
+  opts :: Options Unwrapped <- unwrapRecord "hamlog"
+
+  let
+      configfilename = maybe "hamlog.config" id $ config opts
+      mcabrillo = cabrillo opts
+      moutfile = outfile opts
+      callsign = ""
+      location = ""
+      name = ""
+
+
+
+  let buildVty = do
+          v <- V.mkVty =<< V.standardIOConfig
+          V.setMode (V.outputIface v) V.Mouse True
+          return v
+
+  fe <- fileExist configfilename
+  mcfg <- if fe then configFromFile configfilename else return (Just defaultConfig)
+  maybe (putStrLn "Could not read config file. Please check the file hamlog.config" >> exitFailure) (const $ putStrLn "Config file read successfully.") mcfg
+
+  let appState' = emptyAppState
+  let appState = appState' { logConfig = cfg }
+      !cfg = maybe defaultConfig id mcfg
+
+
+  case points opts of
+    Nothing -> return ()
+    Just contest -> case contest of
+                      "fieldday" ->
+                        do
+                          let conf = ConfigFieldDay { fdEmergencyPower = True,
+                                                      fdPower = FD150W,
+                                                      fdMediaPublicity = False,
+                                                      fdPublicLocation = False,
+                                                      fdPublicInfoTable = False,
+                                                      fdFormalMessages = 0,
+                                                      fdAlternatePower = False,
+                                                      fdOtherBonusPoints = 0 }
+                          (p, _) <- evalHamLog cfg emptyLogState $ do { readLog; computePoints (Proxy :: Proxy FieldDay) conf }
+                          putStrLn $ "Points total: " ++ show p
+                          exitSuccess
+                      "naqpcw" ->
+                        do
+                          (p, _) <- evalHamLog cfg emptyLogState $ do { readLog; computePoints (Proxy :: Proxy NAQPCW) () }
+                          putStrLn $ "Points total: " ++ show p
+                          exitSuccess
+                      "naqpssb" ->
+                        do
+                          (p, _) <- evalHamLog cfg emptyLogState $ do { readLog; computePoints (Proxy :: Proxy NAQPSSB) () }
+                          putStrLn $ "Points total: " ++ show p
+                          exitSuccess
+                      _ -> putStrLn "Unknown contest for points. Choices are: fieldday, naqpcw, naqpssb" >> exitFailure
+
+
+
+  case mcabrillo of
+    Nothing -> return ()
+    Just cabname -> do
+
+      let mh = mcab >>= \cab -> return (do { readLog; makeCabrillo cab })
+          mcab = name_to_cab cabname
+          name_to_cab cn = case cn of
+            "naqp" -> Just $ naqp callsign location name
+            "fieldday" -> Just $ field_day callsign location name
+            _ -> Nothing
+
+      case mh of
+        Nothing -> print ("Unknown cabrillo type " ++ cabname) >> exitFailure
+        Just h -> do
+          (c, _) <- evalHamLog cfg emptyLogState h
+          maybe (putStrLn $ show c) (\a -> writeFile a $ show c) moutfile
+          putStrLn $ unlines [
+            "Please edit the Cabrillo output file to add your callsign, name,"
+            ,"and edit your points, and any other changes you may want to make."]
+          exitSuccess
+
+
+  initialVty <- buildVty
+  s' <- customMain initialVty buildVty Nothing app $ appState
+  configToFile (logConfig s') configfilename
+  return ()
diff --git a/ham.cabal b/ham.cabal
new file mode 100644
--- /dev/null
+++ b/ham.cabal
@@ -0,0 +1,115 @@
+-- This file has been generated from package.yaml by hpack version 0.20.0.
+--
+-- see: https://github.com/sol/hpack
+--
+-- hash: e3e1e1bdbc72322eb45a75e72a2a47e5776a46a0084febd38d074bbc684803d0
+
+name:           ham
+version:        0.1.0.0
+description:    Please see README.org
+homepage:       https://github.com/km6thj/hamlog
+bug-reports:
+author:         KM6THJ
+maintainer:     km6thj@goschs.de
+copyright:      2018-2020
+license:        GPL
+license-file:   LICENSE
+build-type:     Simple
+cabal-version:  >= 1.10
+
+extra-source-files:
+    README.org
+
+source-repository head
+  type: git
+  location: https://github.com/km6thj/hamlog
+
+library
+  hs-source-dirs:
+      src
+  build-depends:
+                base >=4.7 && <5,
+                text -any,
+                time >= 1.8
+              , aeson -any
+              , containers >= 0.5.10
+              , aeson-pretty -any
+              , bytestring -any
+              , transformers -any
+              , vector -any
+              , microlens-th -any
+              , microlens -any
+              , brick >= 0.36.1
+              , vty -any
+              , HTTP >= 4000.3
+              , unordered-containers >= 0.2
+              , array -any
+              , unix >= 2.7.2
+              , serialport >= 0.4.7
+              , attoparsec >= 0.13
+  exposed-modules:
+                  Ham.Log
+                  Ham.Qso
+                  Ham.Fcc
+                  Ham.Data
+                  Ham.UI.Brick
+                  Ham.Cabrillo
+                  Ham.CabrilloTypes
+                  Ham.Contest
+                  Ham.CAT
+                  Ham.CAT.SerialCAT
+                  Ham.CAT.YaesuFT891
+                  Ham.CAT.ElecraftKX2
+                  Ham.CAT.Radios
+                  Ham.CAT.Parser
+  other-modules:
+                Paths_ham
+                Ham.Internal.Qso
+                Ham.Internal.Log
+                Ham.Internal.Fcc
+                Ham.Internal.Data
+                Ham.Internal.Contest
+                Ham.Internal.CAT
+                Ham.Internal.Log.Log
+                Ham.Internal.Log.Config
+                Ham.Internal.Log.V1
+                Ham.Internal.Log.V2
+                Ham.Internal.Log.V3
+                Ham.Internal.FixedSequence
+  default-language: Haskell2010
+
+executable hamlog
+  main-is: Main.hs
+  hs-source-dirs:
+      app
+  ghc-options: -threaded -rtsopts -with-rtsopts=-N
+  build-depends:
+                base >=4.7 && <5
+              , ham
+              , time >= 1.8
+              , text -any
+              , brick >= 0.36.1
+              , vty -any
+              , containers >= 0.5.10
+              , vector -any
+              , microlens -any
+              , unix >= 2.7.2
+              , optparse-generic >= 1.3.1
+  -- allow-newer: true
+  other-modules:
+      Paths_ham
+  default-language: Haskell2010
+
+test-suite ham-test
+  type: exitcode-stdio-1.0
+  main-is: Spec.hs
+  hs-source-dirs:
+      test
+  ghc-options: -threaded -rtsopts -with-rtsopts=-N
+  build-depends:
+      base >=4.7 && <5
+    , ham
+    , bytestring >= 0.10
+  other-modules:
+      Paths_ham
+  default-language: Haskell2010
diff --git a/src/Ham/CAT.hs b/src/Ham/CAT.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/CAT.hs
@@ -0,0 +1,9 @@
+module Ham.CAT ( module Ham.Internal.CAT
+               , module Ham.CAT.SerialCAT
+               , module Ham.CAT.YaesuFT891
+               , module Ham.CAT.ElecraftKX2 ) where
+
+import Ham.Internal.CAT
+import Ham.CAT.SerialCAT
+import Ham.CAT.YaesuFT891
+import Ham.CAT.ElecraftKX2
diff --git a/src/Ham/CAT/ElecraftKX2.hs b/src/Ham/CAT/ElecraftKX2.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/CAT/ElecraftKX2.hs
@@ -0,0 +1,50 @@
+module Ham.CAT.ElecraftKX2 (elecraftKX2) where
+
+import Ham.CAT.SerialCAT
+import Ham.CAT.Parser
+import Ham.Internal.Data
+
+import qualified Data.ByteString.Char8 as B
+import System.Hardware.Serialport
+import Data.Attoparsec.ByteString.Char8
+import Text.Printf
+
+
+----------------------------------------------------------------------------------
+-- K3/KX2/KX3 stuff below this line.
+
+-- | Interface for the Elecraft radios K3, KX2, KX3.
+elecraftKX2 :: SerialCAT
+elecraftKX2 = SerialCAT {
+    serialGetFrequency = \s -> serialGet s "FA" frequencyFromAnswer
+  , serialGetMode      = \s -> serialGet s "MD" modeFromAnswer
+  , serialGetPowerSSB = \s -> serialGet s "PC" intFromAnswer
+  , serialSetPowerSSB = \s p -> serialSend s (printf "PC%.3d;" p)
+  , serialIdentify = identify_kx2
+  }
+
+
+identify_kx2 :: SerialPort -> IO Bool
+identify_kx2 s = do
+  mi <- serialGet s "K3" intFromAnswer
+  case mi of
+    Just _ -> return True
+    _ -> return False
+
+
+modeFromAnswer :: B.ByteString
+               -> Parser QsoMode
+modeFromAnswer prefix = do
+  string prefix
+  c <- anyChar
+  char ';'
+  return $ case c of
+             '1' -> PH
+             '2' -> PH
+             '3' -> CW
+             '4' -> FM
+             '5' -> PH
+             '6' -> DATA
+             '7' -> CW
+             '9' -> DATA
+             _ -> PH
diff --git a/src/Ham/CAT/Parser.hs b/src/Ham/CAT/Parser.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/CAT/Parser.hs
@@ -0,0 +1,34 @@
+module Ham.CAT.Parser where
+
+import Ham.Internal.Data
+
+import qualified Data.ByteString.Char8 as B
+import Data.Attoparsec.ByteString.Char8
+
+
+parseFrequency :: B.ByteString -> Maybe Frequency
+parseFrequency a = case r of
+                     Done s r' -> Just $ MHz $ realToFrac $ r' * 1e-6 -- Assuming the number returned is in Hertz.
+                     _         -> Nothing
+  where r = parse (doubleFromAnswer (B.pack "FA")) a
+
+
+frequencyFromAnswer :: B.ByteString
+                    -> Parser Frequency
+frequencyFromAnswer prefix = do
+  string prefix
+  v <- double
+  char ';'
+  return $ MHz $ realToFrac $ v * 1e-6 -- Assuming the number returned is in Hertz.
+
+
+-- | Parse a double from an answer from the radio given the prefix.
+doubleFromAnswer :: B.ByteString  -- Prefix to ignore from the answer.
+                 -> Parser Double
+doubleFromAnswer prefix = string prefix *> double <* char ';'
+
+
+-- | Parse an integer from an answer from the radio given the prefix.
+intFromAnswer :: B.ByteString -- Prefix to ignore from the answer.
+              -> Parser Int
+intFromAnswer prefix = string prefix *> decimal <* char ';'
diff --git a/src/Ham/CAT/Radios.hs b/src/Ham/CAT/Radios.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/CAT/Radios.hs
@@ -0,0 +1,29 @@
+{-# LANGUAGE DeriveGeneric #-}
+
+{-| Definitions for supported radios. -}
+module Ham.CAT.Radios (Radio(..)
+                      ,serialInterface
+                      ,module Ham.CAT.YaesuFT891
+                      ,module Ham.CAT.ElecraftKX2) where
+
+
+import Data.Map
+import Ham.CAT.YaesuFT891
+import Ham.CAT.ElecraftKX2
+import Ham.CAT.SerialCAT
+import GHC.Generics
+
+
+-- | Identifier for each of the supported radios.
+-- The names are more or less self-explanatory.
+data Radio = YaesuFT891
+           | ElecraftK3 -- ^ This includes K3, KX2, KX3.
+           deriving (Show, Generic, Ord, Eq)
+
+
+-- | Map from radio identifiers to serial interfaces.
+-- This is used e.g. when reading a radio identifier from a configuration file,
+-- to instantiate the correct `SerialCAT'.
+serialInterface :: Map Radio SerialCAT
+serialInterface = fromList [(YaesuFT891, yaesuFT891)
+                           ,(ElecraftK3, elecraftKX2)]
diff --git a/src/Ham/CAT/SerialCAT.hs b/src/Ham/CAT/SerialCAT.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/CAT/SerialCAT.hs
@@ -0,0 +1,52 @@
+module Ham.CAT.SerialCAT (SerialCAT(..)
+                         ,serialGet
+                         ,serialSend) where
+
+import Ham.Internal.Data
+import System.Hardware.Serialport
+import Data.Attoparsec.ByteString.Char8
+import qualified Data.ByteString.Char8 as B
+import Control.Concurrent (threadDelay)
+
+
+-- | Interface for radios that are communicating via serial interface.
+data SerialCAT = SerialCAT {
+    serialGetFrequency :: SerialPort -> IO (Maybe Frequency)
+  , serialGetMode      :: SerialPort -> IO (Maybe QsoMode)
+  , serialSetPowerSSB  :: SerialPort -> Int -> IO ()
+  , serialGetPowerSSB  :: SerialPort -> IO (Maybe Int)
+  , serialIdentify     :: SerialPort -> IO Bool
+}
+
+
+-- | Get a value from a radio connected to a serial port.
+-- This uses a format that seems to be used by more than one manufacturer, such as Yaesu and Elecraft.
+-- The command format is "XY;" for getting something, where XY is a string. XY is given as second argument to this function.
+serialGet :: SerialPort
+         -> String                     -- ^ Command; e.g. FA for getting frequency of VFO A.
+         -> (B.ByteString -> Parser a) -- ^ Decoder for the resulting answer from the radio.
+         -> IO (Maybe a)
+serialGet s cmd parser = do
+  let cmd' = B.pack cmd <> B.pack ";"
+  send s cmd'
+  -- Wait for 100ms to give the transceiver some time to answer;
+  -- I have not found a better way to do this at the moment with the serialport library.
+  -- It seems to set all operations to non-blocking.
+  -- Set the radio's CAT TOT to 10msec (minimum).
+  threadDelay 100000
+  a <- recv s 100
+  -- putStrLn $ B.unpack a
+
+  return $
+      let r = parse (parser $ B.pack cmd) a
+      in maybeResult r
+
+
+-- | Send a string to the radio.
+serialSend :: SerialPort -> String -> IO ()
+serialSend s value =  do
+    send s $ B.pack value
+    threadDelay 100000
+    _ <- recv s 100
+    return ()
+    -- putStrLn $ B.unpack a
diff --git a/src/Ham/CAT/YaesuFT891.hs b/src/Ham/CAT/YaesuFT891.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/CAT/YaesuFT891.hs
@@ -0,0 +1,89 @@
+module Ham.CAT.YaesuFT891 (yaesuFT891) where
+
+import Ham.CAT.SerialCAT
+import Ham.CAT.Parser
+import Ham.Internal.Data
+
+import Control.Concurrent (threadDelay)
+import qualified Data.ByteString.Char8 as B
+import System.Hardware.Serialport
+import Data.Attoparsec.ByteString.Char8
+import Text.Printf
+
+
+----------------------------------------------------------------------------------
+-- Yaesu FT891 stuff below this line.
+
+-- | Interface for the Yaesu FT-891
+yaesuFT891 :: SerialCAT
+yaesuFT891 = SerialCAT {
+    serialGetFrequency = \s -> serialGet s "FA" frequencyFromAnswer
+  , serialGetMode      = \s -> serialGet s "MD0" modeFromAnswer
+  , serialGetPowerSSB = \s -> ft891GetMenu s "1601" intFromAnswer
+  , serialSetPowerSSB = \s p -> ft891SetMenu s "1601" (printf "%.3d" p)
+  , serialIdentify = identify_ft891
+  }
+
+
+
+identify_ft891 :: SerialPort -> IO Bool
+identify_ft891 s = do
+  mi <- serialGet s "ID" intFromAnswer
+  case mi of
+    Just 650 -> return True
+    _ -> return False
+
+
+
+-- | Menu command ("EX")
+ft891Menu :: B.ByteString       -- Menu entry, P1 in the radio's CAT documentation
+          -> Maybe B.ByteString -- OPtional value to set, P2 in the radio's CAT documentation
+          -> B.ByteString       -- Resulting command to send to the radio.
+ft891Menu p1 p2 = B.pack "EX" <> p1 <> (maybe mempty id p2)
+
+
+ft891GetMenu :: SerialPort -> String -> (B.ByteString -> Parser a) -> IO (Maybe a)
+ft891GetMenu s menuName valueParser =  do
+    let menu = ft891Menu (B.pack menuName) Nothing
+    send s $ (menu <> B.pack ";")
+    threadDelay 100000
+    a <- recv s 100
+    return $
+      let r = parse (valueParser menu) a
+      in maybeResult r
+      -- in case r of
+      --   Done _ r' -> Just r'
+      --   _         -> Nothing
+
+
+ft891SetMenu :: SerialPort -> String -> String -> IO ()
+ft891SetMenu s menuName value =  do
+    let menu = ft891Menu (B.pack menuName) (Just $ B.pack value)
+    send s $ (menu <> B.pack ";")
+    -- putStrLn $ B.unpack menu
+    threadDelay 100000
+    _ <- recv s 100
+    return ()
+    -- putStrLn $ B.unpack a
+
+modeFromAnswer :: B.ByteString
+               -> Parser QsoMode
+modeFromAnswer prefix = do
+  string prefix
+  c <- anyChar
+  char ';'
+  return $ case c of
+             '1' -> PH
+             '2' -> PH
+             '3' -> CW
+             '4' -> FM
+             '5' -> PH
+             '6' -> RY
+             '7' -> CW
+             '8' -> DATA
+             '9' -> RY
+             'A' -> DATA
+             'B' -> PH
+             'C' -> DATA
+             'D' -> PH
+             _ -> PH
diff --git a/src/Ham/Cabrillo.hs b/src/Ham/Cabrillo.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Cabrillo.hs
@@ -0,0 +1,221 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+module Ham.Cabrillo
+ where
+
+import Data.Maybe (isJust, fromJust)
+import Data.Text as T
+import Data.Text (unpack)
+import Data.List as L
+import Data.Time.Clock
+import Data.Time.Calendar
+import Data.Time.LocalTime
+import Data.Time.Format
+import Ham.Data
+
+data VersionNumber = VersionNumber Int Int
+instance Show VersionNumber where
+    showsPrec _ (VersionNumber a b) s = L.concat [show a, ".", show b] ++ s
+
+data CategoryAssisted = Assisted | NonAssisted
+instance Show CategoryAssisted where
+    show Assisted = "ASSISTED"
+    show NonAssisted = "NON-ASSISTED"
+
+data CategoryMode = CMCW | CMDIGI | CMFM | CMRTTY | CMSSB | CMMIXED
+instance Show CategoryMode where
+    show CMCW = "CW"
+    show CMDIGI = "DIGI"
+    show CMFM = "FM"
+    show CMRTTY = "RTTY"
+    show CMSSB = "SSB"
+    show CMMIXED = "MIXED"
+
+data CategoryOperator = SINGLE_OP | MULTI_OP | CHECKLOG
+instance Show CategoryOperator where
+    show SINGLE_OP = "SINGLE-OP"
+    show MULTI_OP = "MULTI-OP"
+    show CHECKLOG = "CHECKLOG"
+
+data CategoryPower = HIGH | LOW | QRP deriving (Show, Read)
+
+data CategoryStation = FIXED | MOBILE | PORTABLE | ROVER 
+                     | ROVER_LIMITED | ROVER_UNLIMITED | EXPEDITION | HQ | SCHOOL
+instance Show CategoryStation where
+    show FIXED = "FIXED"
+    show MOBILE = "MOBILE"
+    show PORTABLE = "PORTABLE"
+    show ROVER = "ROVER"
+    show ROVER_LIMITED = "ROVER-LIMITED"
+    show ROVER_UNLIMITED = "ROVER-UNLIMITED"
+    show EXPEDITION = "EXPEDITION"
+    show HQ = "HQ"
+    show SCHOOL = "SCHOOL"
+
+data CategoryTime = HOURS_6 | HOURS_12 | HOURS_24
+instance Show CategoryTime where
+    show HOURS_6 = "6-HOURS"
+    show HOURS_12 = "12-HOURS"
+    show HOURS_24 = "24-HOURS"
+
+data CategoryTransmitter = ONE | TWO | LIMITED | UNLIMITED | SWL deriving (Show, Read)
+data CategoryOverlay = CLASSIC | ROOKIE | TB_WIRES | NOVICE_TECH | OVER_50
+instance Show CategoryOverlay where
+    show CLASSIC = "CLASSIC"
+    show ROOKIE = "ROOKIE"
+    show TB_WIRES = "TB-WIRES"
+    show NOVICE_TECH = "NOVICE-TECH"
+    show OVER_50 = "OVER-50"
+
+
+data YesNo = YES | NO deriving (Show, Read)
+
+data Cabrillo = Cabrillo
+            { 
+                version :: VersionNumber
+            , callsign :: Maybe Text
+            , contest :: Maybe Text
+            , category_assisted :: Maybe CategoryAssisted
+            , category_band :: Maybe Text
+            , category_mode :: Maybe CategoryMode
+            , category_operator :: Maybe CategoryOperator
+            , category_power :: Maybe CategoryPower
+            , category_station :: Maybe CategoryStation
+            , category_time :: Maybe CategoryTime
+            , category_transmitter :: Maybe CategoryTransmitter
+            , category_overlay :: Maybe CategoryOverlay
+            , certificate :: Maybe YesNo
+            , claimed_score :: Maybe Integer
+            , club :: Maybe Text
+            , created_by :: Maybe Text
+            , email :: Maybe Text
+            , grid_locator :: Maybe Text
+            , location :: Maybe Text -- Note: This is restricted depending on the contest. See http://wwrof.org/cabrillo/cabrillo-specification-v3/
+            , name :: Maybe Text
+            , address_city :: Maybe Text
+            , address_state_province :: Maybe Text
+            , address_postalcode :: Maybe Text
+            , address_country :: Maybe Text
+            , operators :: Maybe [Text]
+            }
+
+defaultCabrillo = Cabrillo (VersionNumber 3 0)
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+                    Nothing
+
+
+
+showtext d f a = fmap (\b -> L.concat [a, unpack b]) $ f d 
+showother d f a = fmap (\b -> L.concat [a, show b]) $ f d
+showlist :: d -> (d -> Maybe [Text]) -> String -> Maybe String
+showlist d f a = fmap (\b -> a ++ L.unwords (L.map unpack b)) $ f d
+
+instance Show Cabrillo where
+    show c = L.unlines $ L.map fromJust $ L.filter isJust [
+         showtext  c callsign "CALLSIGN: "
+        ,showtext  c contest "CONTEST: "
+        ,showother c category_assisted "CATEGORY-ASSISTED: "
+        ,showtext  c category_band "CATEGORY-BAND: "
+        ,showother c category_mode "CATEGORY-MODE: "
+        ,showother c category_operator "CATEGORY-OPERATOR: "
+        ,showother c category_power "CATEGORY-POWER: "
+        ,showother c category_station "CATEGORY-STATION: "
+        ,showother c category_time "CATEGORY-TIME: "
+        ,showother c category_transmitter "CATEGORY-TRANSMITTER: "
+        ,showother c category_overlay "CATEGORY-OVERLAY: "
+        ,showother c certificate "CERTIFICATE: "
+        ,showother c claimed_score "CLAIMED-SCORE: "
+        ,showtext  c club "CLUB: "
+        ,showtext  c created_by "CREATED-BY: "
+        ,showtext  c email "EMAIL: "
+        ,showtext  c grid_locator "GRID-LOCATOR: "
+        ,showtext  c location "LOCATION: "
+        ,showtext  c name "NAME: "
+        ,showtext  c address_city "ADDRESS-CITY: "
+        ,showtext  c address_state_province "ADDRESS-STATE-PROVINCE: "
+        ,showtext  c address_postalcode "ADDRESS-POSTALCODE: "
+        ,showtext  c address_country "ADDRESS-COUNTRY: "
+        ,showlist  c operators "OPERATORS: "]
+
+
+
+
+
+data CabrilloLine = CLSoapbox Text | CLQso CabrilloQso 
+                  | CLX Text Text | CLXQso CabrilloQso
+
+instance Show CabrilloLine where
+    show (CLSoapbox t) = "SOAPBOX: " ++ unpack t
+    show (CLQso a) = "QSO: " ++ show a
+    show (CLX a b) = "X-" ++ unpack a ++ ": " ++ unpack b
+    show (CLXQso a) = "X-QSO: " ++ show a
+
+-- Note: OffTime is missing.
+data CabrilloQso = CabrilloQso 
+                        Frequency Mode UTCTime 
+                        CabrilloInfoSent CabrilloInfoReceived 
+                        (Maybe TransmitterNumber)
+
+data CabrilloInfo = CabrilloInfo Callsign Exchange
+
+instance Show CabrilloInfo where
+    show (CabrilloInfo cs exchg) = L.unwords [cs, exchg]
+
+type Exchange = String
+type Callsign = String
+type Location = String
+type CabrilloInfoSent = CabrilloInfo
+type CabrilloInfoReceived = CabrilloInfo
+type TransmitterNumber = Int
+data Mode = CW | PH | FM | RY | DG deriving (Show, Read)
+
+instance Show CabrilloQso where
+    show (CabrilloQso (MHz f) m t s r mn) = L.unwords $ 
+        [
+         show $ round (f * 1000)
+        ,show m
+        ,date
+        ,tm
+        ,show s
+        ,show r
+        ,maybe [] show mn
+        ]
+        where date = formatTime defaultTimeLocale "%F" t
+              tm   = formatTime defaultTimeLocale "%H%M" t
+
+
+data CabrilloLog = CabrilloLog Cabrillo [CabrilloLine]
+
+instance Show CabrilloLog where
+    show (CabrilloLog c ls) = 
+        L.unlines $ [
+            "START-OF-LOG: 3.0"
+            ,show c
+            ,L.unlines (L.map show ls)
+            ,"END-OF-LOG:"]
+
+
+class ToCabrillo a where
+    toCabrillo :: a -> [CabrilloLine]
diff --git a/src/Ham/CabrilloTypes.hs b/src/Ham/CabrilloTypes.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/CabrilloTypes.hs
@@ -0,0 +1,41 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+module Ham.CabrilloTypes where
+
+import Ham.Cabrillo
+import Data.Text (pack)
+
+naqp :: Callsign  -- ^ My callsign
+     -> Location  -- ^ My location
+     -> String    -- ^ My name
+     -> Cabrillo
+naqp cs loc nm = defaultCabrillo { contest = Just "NAQP-SSB"
+                               ,location = Just $ pack loc
+                               ,callsign = Just $ pack cs
+                               ,category_operator = Just SINGLE_OP
+                               ,category_transmitter = Just ONE
+                               ,category_assisted = Just NonAssisted
+                               ,category_band = Just "ALL"
+                               ,category_power = Just LOW
+                               ,category_mode = Just CMSSB
+                               ,category_station = Just FIXED
+                               ,claimed_score = Just 0
+                               ,name = Just $ pack nm}
+
+
+field_day :: Callsign  -- ^ My callsign
+          -> Location  -- ^ My location
+          -> String    -- ^ My name
+          -> Cabrillo
+field_day cs loc nm = defaultCabrillo { contest = Just "ARRL-FIELDDAY"
+                                      ,location = Just $ pack loc
+                                      ,callsign = Just $ pack cs
+                                      ,category_operator = Just SINGLE_OP
+                                      ,category_transmitter = Just ONE
+                                      ,category_assisted = Just NonAssisted
+                                      ,category_band = Just "ALL"
+                                      ,category_power = Just LOW
+                                      ,category_mode = Just CMMIXED
+                                      ,category_station = Just FIXED
+                                      ,claimed_score = Just 0
+                                      ,name = Just $ pack nm}
diff --git a/src/Ham/Contest.hs b/src/Ham/Contest.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Contest.hs
@@ -0,0 +1,15 @@
+-- | Contest related things.
+-- Functions to compute points, so far.
+
+module Ham.Contest
+  (
+    -- * ARRL Field Day
+    FieldDayPoints(..)
+  , FieldDay
+  , NAQPCW
+  , NAQPSSB
+  , Contest(..)
+  , ConfigFieldDay(..)
+  , FieldDayPower(..)) where
+
+import Ham.Internal.Contest
diff --git a/src/Ham/Data.hs b/src/Ham/Data.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Data.hs
@@ -0,0 +1,12 @@
+{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
+
+module Ham.Data
+    (RST(..),
+     Frequency(..),
+     wavelength,
+     Band(..),
+     band,
+     QsoMode(..))
+where
+
+import Ham.Internal.Data
diff --git a/src/Ham/Fcc.hs b/src/Ham/Fcc.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Fcc.hs
@@ -0,0 +1,80 @@
+{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
+
+module Ham.Fcc
+  (fccLookup',
+   fccLookup,
+   fccLookupName,
+   fccLicenseFromResult,
+   FccResult,
+   FccLicense(..),
+   FccLicenses,
+   licenses
+  ) where
+
+import Network.HTTP
+import Data.Aeson
+import Data.Aeson.TH
+import Data.Array
+import Data.Char (toLower)
+import Data.Maybe (listToMaybe)
+import qualified Data.Text as T
+import Data.Text (Text)
+import qualified Data.ByteString.Lazy as B
+import qualified Data.HashMap.Strict as H
+
+import Ham.Internal.Fcc
+
+type Address = String
+type Name = String
+
+-- $(deriveJSON (defaultOptions { fieldLabelModifier = resultLabelMod, constructorTagModifier = resultConstructorMod }) ''FccResult)
+$(deriveJSON defaultOptions ''FccLicense)
+
+instance FromJSON FccResult where
+  parseJSON (Object v) = FccResult
+    <$> v .: "status"
+    <*> v .: "Licenses"
+
+instance FromJSON FccLicenses where
+  parseJSON (Object v) = FccLicenses
+    <$> v .: "lastUpdate"
+    <*> v .: "page"
+    <*> v .: "totalRows"
+    <*> v .: "License"
+    <*> v .: "rowPerPage"
+
+
+-- | Lookup an entry for a callsign in the FCC online database.
+-- If an entry can be found, it is returned.
+fccLookup' :: Text  -- ^ The callsign to search for.
+           -> IO (Maybe FccResult)
+fccLookup' callsign = do
+  let rq_string = "http://data.fcc.gov/api/license-view/basicSearch/getLicenses?searchValue=" ++ T.unpack callsign ++ "&format=json"
+  r <- simpleHTTP $ getRequest rq_string
+  case r of
+    Left err -> return Nothing
+    Right response -> do
+      let o = decode (B.pack $ map (fromIntegral . fromEnum) $ rspBody response) :: Maybe Object
+      let eo2 = eitherDecode (B.pack $ map (fromIntegral . fromEnum) $ rspBody response) :: Either String FccResult
+      case eo2 of
+        Right a -> return $ Just a
+        Left s -> putStrLn s >> return Nothing
+
+
+-- | Look up the first active license given a callsign.
+fccLookup :: Text -> IO (Maybe FccLicense)
+fccLookup cs = do { a <- fccLookup' cs; return $ a >>= fccLicenseFromResult }
+
+
+-- | Look up the operator's name from the first active license given a callsign.
+fccLookupName :: Text -> IO Text
+fccLookupName cs = do
+  a <- fccLookup' cs
+  maybe (return "") (return . T.pack . licName) (a >>= fccLicenseFromResult)
+
+
+
+fccLicenseFromResult :: FccResult -> Maybe FccLicense
+fccLicenseFromResult r = listToMaybe ls
+  where ls = license $ licenses r
+        active_ls = filter (( == "active") . map toLower . statusDesc) ls
diff --git a/src/Ham/Internal/CAT.hs b/src/Ham/Internal/CAT.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/CAT.hs
@@ -0,0 +1,205 @@
+{-# LANGUAGE DeriveAnyClass, FlexibleInstances, ScopedTypeVariables, DeriveGeneric, StandaloneDeriving, OverloadedStrings #-}
+
+{-| Computer Aided Transceiver interface.
+This provides a monad that allows to talk to serially connected transceivers.
+To support a transceiver, there must be a `SerialCAT' provided for it.
+-}
+module Ham.Internal.CAT where
+
+import Control.Monad (when)
+import Control.Monad.Trans.RWS
+import Control.Monad.Trans.Except
+import Control.Monad.Trans.Class (lift)
+import Control.Monad.IO.Class
+import Control.Exception
+import Data.Aeson
+import qualified Data.ByteString.Char8 as B
+import Data.Maybe (isJust)
+import qualified Data.Text as T
+import Data.Text (Text)
+import GHC.Generics
+import Ham.CAT.SerialCAT
+import Ham.CAT.Radios
+import Ham.Internal.Data
+import System.Hardware.Serialport
+
+
+
+-- | Configuration for the CAT monad.
+data CATConfig = CATConfig { catPort :: String  -- ^ Serial port the radio is connected to. In Linux e.g. "/dev/ttyUSB0".
+                           , catRadio :: Radio  -- ^ Radio identifier.
+                           , catSerialSettings :: SerialPortSettings  -- ^ Serial settings for the connection. Note the radio must have the same settings.
+                           } deriving (Generic, Show)
+
+-- Automatically derive Show instance. That's not inclded in the serialport library.
+deriving instance Show SerialPortSettings
+deriving instance Generic SerialPortSettings
+deriving instance Generic CommSpeed
+deriving instance Generic FlowControl
+deriving instance Generic StopBits
+deriving instance Generic Parity
+
+instance FromJSON SerialPortSettings
+instance ToJSON SerialPortSettings
+instance FromJSON CommSpeed
+instance ToJSON CommSpeed
+instance FromJSON FlowControl
+instance ToJSON FlowControl
+
+instance FromJSON StopBits
+instance ToJSON StopBits
+instance FromJSON Parity
+instance ToJSON Parity
+
+instance FromJSON CATConfig
+instance ToJSON CATConfig
+
+instance FromJSON Radio
+instance ToJSON Radio
+
+
+-- | Default configuration. Note this assumes port and radio, so you will want to adjust it.
+defaultConfig :: CATConfig
+defaultConfig = CATConfig { catPort = "/dev/ttyUSB0"
+                          , catRadio = YaesuFT891
+                          , catSerialSettings = defaultSerialSettings { commSpeed = CS4800
+                                                                      , bitsPerWord = fromIntegral 8
+                                                                      , stopb = One
+                                                                      , parity = NoParity
+                                                                      , flowControl = NoFlowControl
+                                                                      , timeout = 2 } }
+
+-- | State type for the CAT monad.
+data CATState = CATState { statePort :: Maybe SerialPort  -- ^ Serial port, if one is open.
+                         , stateInterface :: SerialCAT    -- ^ SerialCAT implementation for the radio.
+                         }
+
+
+-- | Default state. Note that this sets the SerialCAT to a default implementation. You will want to change that.
+defaultState :: CATState
+defaultState = CATState { statePort = Nothing
+                        , stateInterface = yaesuFT891 }
+
+
+data CATError = CATError CATErrorType Text deriving Show
+data CATErrorType = CATErrorGeneric
+                  | CATErrorIdentify
+  deriving Show
+
+
+-- | The computer aided transceiver monad.
+newtype CAT m a = CAT { unCAT :: RWST CATConfig [Text] CATState (ExceptT CATError m) a }
+
+instance Monad m => Functor (CAT m) where
+  fmap f a = CAT $ fmap f (unCAT a)
+
+instance Monad m => Applicative (CAT m) where
+  pure = CAT . pure
+  a <*> b = CAT $ unCAT a <*> unCAT b
+
+instance Monad m => Monad (CAT m) where
+  a >>= b = CAT $ unCAT a >>= (unCAT . b)
+
+
+-- | Throw an exception in the `Overpass' monad.
+throwCAT :: Monad m => CATError -> CAT m a
+throwCAT = CAT . lift . throwE
+
+
+-- | Catching exceptions in the `Overpass' monad.
+catchCAT :: Monad m => CAT m a -> (CATError -> CAT m a) -> CAT m a
+catchCAT act c = CAT $ liftCatch catchE (unCAT act) (unCAT . c)
+
+
+-- | Run an action in the CAT monad.
+runCAT :: MonadIO m => CATConfig
+       -> CATState -- ^ State to start with.
+       -> CAT m a
+       -> m (Either CATError (a, [Text]))
+runCAT config state act = runExceptT $ evalRWST (unCAT act') config state
+  where
+    act' = do
+      result <- catchCAT (catInit >> act) $ \e -> catDeinit >> throwCAT e
+      catDeinit
+      return result
+
+
+
+
+-- | FIXME: Add error handling. What if the radio can not be opened?
+catInit :: MonadIO m => CAT m ()
+catInit = do
+  result <- CAT $ do
+     portName <- asks catPort
+     serialSettings <- asks catSerialSettings
+
+     ms <- liftIO $ catch
+           (do { s <- openSerial portName serialSettings; return (Just s) })
+           (\(e :: SomeException) -> {- putStrLn (show e) >> -} return Nothing)
+     get >>= \a -> put (a { statePort = ms })
+     case ms of
+       Just s -> do
+         ident <- serialIdentify <$> gets stateInterface
+         a <- liftIO $ ident s
+         tell $ ["Identifying configured radio: " <> T.pack (show a)]
+         if a
+           then return Nothing
+           else return $ Just $ CATError CATErrorIdentify "Radio was not identified as the configured one."
+       _ -> return $ Just (CATError CATErrorGeneric "Could not open serial port.")
+  case result of
+    Just e -> throwCAT e
+    _ -> return ()
+
+
+-- | Close everything down.
+catDeinit :: MonadIO m => CAT m ()
+catDeinit = CAT $ do
+  ms <- gets statePort
+  maybe (return ()) (\s -> liftIO $ closeSerial s) ms
+  get >>= \a -> put (a { statePort = Nothing })
+
+
+-- | Get the current frequency from the transceiver.
+catFrequency :: MonadIO m => CAT m (Maybe Frequency)
+catFrequency = CAT $ do
+  ms <- gets statePort
+  i <- gets stateInterface
+  maybe
+    (tell ["Could not get frequency from radio"] >> return Nothing)
+    (\s -> do
+        f <- liftIO $ serialGetFrequency i s
+        tell ["Got frequency " <> T.pack (show f)]
+        return f
+    )
+    ms
+
+
+-- | Get the current mode from the transceiver.
+catMode :: MonadIO m => CAT m (Maybe QsoMode)
+catMode = CAT $ do
+  ms <- gets statePort
+  i <- gets stateInterface
+  maybe
+    (tell ["Could not get mode from radio."] >> return Nothing)
+    (\s -> do
+        a <- liftIO $ serialGetMode i s
+        tell ["Got mode " <> T.pack (show a)]
+        return a
+    )
+    ms
+
+
+-- | Get the SSB power setting in watts.
+catPowerSSB :: MonadIO m => CAT m (Maybe Int)
+catPowerSSB = CAT $ do
+  ms <- gets statePort
+  i <- gets stateInterface
+  maybe (return Nothing) (\s -> liftIO $ serialGetPowerSSB i s) ms
+
+
+-- | Set the SSB power in watts.
+catSetPowerSSB :: MonadIO m => Int -> CAT m ()
+catSetPowerSSB power = CAT $ do
+  ms <- gets statePort
+  i <- gets stateInterface
+  maybe (return ()) (\s -> liftIO $ serialSetPowerSSB i s power) ms
diff --git a/src/Ham/Internal/Contest.hs b/src/Ham/Internal/Contest.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/Contest.hs
@@ -0,0 +1,159 @@
+{-# LANGUAGE EmptyDataDecls, TypeFamilies #-}
+
+module Ham.Internal.Contest where
+
+import Ham.Log
+import Ham.Data (band, Band)
+
+import Data.Sequence as S
+import Data.Char (toUpper)
+import Data.Text as T
+import qualified Data.Map as M
+import Data.Proxy
+import Data.List as L (groupBy, sortBy)
+import Data.Foldable (toList)
+import Prelude as P
+
+
+
+class Contest a where
+  type Points a :: *
+  type Config a :: *
+  computePoints :: Proxy a -> Config a -> HamLog (Points a)
+
+
+data FieldDay
+
+
+data FieldDayPoints = FieldDayPoints { fdpTotal :: Float
+                                     , fdpPowerMult :: Float
+                                     , fdpBonus :: Float
+                                     , fdpQsos :: [(String, [(String, Int)])] } deriving Show
+
+
+instance Contest FieldDay where
+  type Points FieldDay = FieldDayPoints
+  type Config FieldDay = ConfigFieldDay
+  computePoints _ cfg = do
+    s <- getQsoSeq
+    let cw_qsos = S.filter (\a -> _qsoMode a == CW) s
+        ph_qsos = S.filter (\a -> _qsoMode a == PH || _qsoMode a == FM) s
+        data_qsos = S.filter (\a -> _qsoMode a == DATA || _qsoMode a == RY) s
+        cw_points = 2 * fromIntegral (S.length cw_qsos)
+        ph_points = 1 * fromIntegral (S.length ph_qsos)
+        data_points = 2 * fromIntegral (S.length data_qsos)
+        total = (cw_points + ph_points + data_points) * powerMult + bonus
+        powerMult = fieldDayPowerMultiplier cfg
+        bonus = fieldDayBonus cfg
+    return $ FieldDayPoints total powerMult bonus [("CW", qsosByBand' cw_qsos),
+                                                   ("PH", qsosByBand'  ph_qsos),
+                                                   ("DATA", qsosByBand' data_qsos)]
+
+
+qsosByBand' :: Seq Qso -> [(String, Int)]
+qsosByBand' qsos = P.map f $ qsosByBand qsos
+  where
+    f as@(a:_) = ((show $ band $ _qsoFrequency a), P.length as)
+
+
+-- | Group QSOs by band
+qsosByBand :: Seq Qso -> [[Qso]]
+qsosByBand qsos = groups
+  where groups = L.groupBy (\a b -> band (_qsoFrequency a) == band (_qsoFrequency b)) sortedQsos
+        sortedQsos = L.sortBy (\a b -> compare (_qsoFrequency a) (_qsoFrequency b)) $ toList qsos
+
+
+qsosByBand'' :: Seq Qso -> [(Band, [Qso])]
+qsosByBand'' qsos = P.map f $ qsosByBand qsos
+  where f as@(a:_) = ((band $ _qsoFrequency a), as)
+
+
+fieldDayBonus :: ConfigFieldDay -> Float
+fieldDayBonus c = sum [c1,c2,c3,c4,c5,c6,fdOtherBonusPoints c]
+  where c1 | fdMediaPublicity c = 100
+           | otherwise = 0
+        c2 | fdPublicLocation c = 100
+           | otherwise = 0
+        c3 | fdPublicInfoTable c = 100
+           | otherwise = 0
+        c4 = (fromIntegral $ fdFormalMessages c) * 10
+        c5 | fdEmergencyPower c = 100
+           | otherwise = 0
+        c6 | fdAlternatePower c = 100
+           | otherwise = 0
+
+
+fieldDayPowerMultiplier :: ConfigFieldDay -> Float
+fieldDayPowerMultiplier c =
+  case fdPower c of
+    FD5W -> 5
+    FD150W -> 2
+    FDHighPower -> 1
+
+
+
+data FieldDayPower = FD5W | FD150W | FDHighPower
+
+data ConfigFieldDay = ConfigFieldDay { fdEmergencyPower :: Bool  -- ^ Whether we are 100% on emergency power
+                                     , fdPower :: FieldDayPower  -- ^ Whether we are <= 5 Watts for all contacts
+                                     , fdMediaPublicity :: Bool  -- ^ Whether media publicity was done. Must provide proof.
+                                     , fdPublicLocation :: Bool  -- ^ Whether we operate in a public location.
+                                     , fdPublicInfoTable :: Bool -- ^ Whether there is an information table for people to stop by.
+                                     , fdFormalMessages :: Int   -- ^ Number of formal messages relayed.
+                                     , fdAlternatePower :: Bool  -- ^ Whether all batteries were charging from alternate power (no mains or gas).
+                                     , fdOtherBonusPoints :: Float
+                                     }
+
+
+{--------------------------------------------------------------------------------}
+{- NAQP CW -}
+
+
+-- Get the state from a QSO exchange field, used for NAQP and possibly others.
+-- The assumption is that the exchange is <something> and then the state as one word
+-- as the last word, separated by whitespaces.
+state qso = s
+   where ex = _qsoExchange qso
+         ws = T.words ex
+         s | P.length ws >= 2 = T.toUpper $ P.last ws
+           | otherwise = mempty
+
+-- Counts the states in a list of QSOs. Used for NAQP to determine the state multiplier.
+countStates qsos = M.size $ M.fromListWith (+) $ P.zip (P.map state qsos) (repeat 1)
+
+naqpPoints :: QsoMode -> HamLog PointsNAQP
+naqpPoints mode = do
+    s <- getQsoSeq
+    let mode_qsos = S.filter (\a -> _qsoMode a == mode)
+        qsos_by_band = qsosByBand'' $ mode_qsos s
+        multipliers_and_qso_count = P.map f qsos_by_band
+          where f (bd, qsos) =
+                  -- (band, multiplier, qso count)
+                  (bd, fromIntegral $ countStates qsos, fromIntegral $ P.length qsos)
+
+        -- Points per band
+        mode_points = P.map (\(bd, mult, n) -> (bd, mult * n)) multipliers_and_qso_count
+        mode_points_total = P.foldr ((+) . snd) 0 mode_points
+    return $ PointsNAQP multipliers_and_qso_count mode_points_total
+
+
+data PointsNAQP = PointsNAQP { pnaqpPointsPerBand :: [(Band, Float, Float)],
+                               pnaqpTotalPoints :: Float } deriving Show
+
+
+data NAQPCW
+
+
+instance Contest NAQPCW where
+  type Points NAQPCW = PointsNAQP
+  type Config NAQPCW = ()
+  computePoints _ cfg = naqpPoints CW
+
+
+data NAQPSSB
+
+
+instance Contest NAQPSSB where
+  type Points NAQPSSB = PointsNAQP
+  type Config NAQPSSB = ()
+  computePoints _ cfg = naqpPoints PH
diff --git a/src/Ham/Internal/Data.hs b/src/Ham/Internal/Data.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/Data.hs
@@ -0,0 +1,98 @@
+{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
+
+module Ham.Internal.Data where
+
+import Data.Aeson
+import Data.Aeson.TH
+import Data.List
+import Data.Char (isDigit, digitToInt)
+
+-- | Frequency in MHz.
+newtype Frequency = MHz Float
+                  deriving (Show, Read, Eq, Ord)
+
+
+-- | Wavelength in metres.
+wavelength :: Frequency -> Float
+wavelength (MHz f) = c / (f * 1e6)
+  where c = 299792458 -- m / s
+
+-- | Commmon bands in meters.
+bands = [160, 80, 60, 40, 30, 20, 17, 15, 12, 10, 6, 2, 1.25, 0.7, 0.33, 0.23]
+
+band_name :: Float -> String
+band_name a | (fromIntegral $ round a) == a = show (round a) <> "m"
+            | a > 1.0 = show a <> "m"
+            | otherwise = show (round $ a * 100) <> "cm"
+
+data Band = M Float     -- ^ Band in metres
+          | Microwave   -- ^ Anything 15% shorter than about 23cm.
+          deriving Eq
+
+instance Show Band where
+  show (M b) = band_name b
+  show Microwave = "Microwave"
+
+
+-- | Find canonical band name for frequency.
+band :: Frequency -> Band
+band f = case m of
+           (0.23, d) -> if (d / 0.23) > 0.15 then Microwave else M 0.23
+           (a, _) -> M a
+  where l = wavelength f
+        diffs = map (\a -> (a, abs (l - a))) bands
+        m = minimumBy (\a b -> compare (snd a) (snd b)) diffs
+
+
+
+-- | Modes for a QSO.
+-- TODO: This is following Cabrillo; this should go into the Cabrillo module and this type here should have many more entries.
+data QsoMode = CW  -- ^ Morse code.
+             | PH  -- ^ Voice.
+             | FM  -- ^ FM voice.
+             | RY  -- ^ RTTY or other teletype mode.
+             | DATA
+             deriving (Show, Read, Eq)
+
+
+-- | RST report.
+data RST = RST Int Int Int  -- ^ Readability, signal strength, tone.
+         | RS Int Int       -- ^ Readability, signal strength
+         | NoRST deriving (Eq, Ord)
+
+
+
+rstReadability :: RST -> Int
+rstReadability (RST r _ _) = r
+rstReadability (RS r _)    = r
+rstReadability _           = 0
+
+rstStrength :: RST -> Int
+rstStrength (RST _ s _) = s
+rstStrength (RS _ s)    = s
+rstStrength _           = 0
+
+rstTone :: RST -> Int
+rstTone (RST _ _ t) = t
+rstTone (RS _ _)    = 0
+rstTone _           = 0
+
+
+instance Show RST where
+    show (RST r s t) = show r ++ show s ++ show t
+    show (RS r s)    = show r ++ show s
+    show _           = ""
+
+instance Read RST where
+    readsPrec _ ss@(r:s:t:rest) = if Data.List.all isDigit (r:s:t:[]) then
+                                    [(RST (digitToInt r) (digitToInt s) (digitToInt t), rest)] else
+                                    [(NoRST, ss)]
+    readsPrec _ ss@(r:s:rest)   = if Data.List.all isDigit (r:s:[]) then
+                                    [(RS (digitToInt r) (digitToInt s), rest)] else
+                                    [(NoRST, ss)]
+    readsPrec _ ss              = [(NoRST, ss)]
+
+
+$(deriveJSON defaultOptions ''Frequency)
+$(deriveJSON defaultOptions ''RST)
+$(deriveJSON defaultOptions ''QsoMode)
diff --git a/src/Ham/Internal/Fcc.hs b/src/Ham/Internal/Fcc.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/Fcc.hs
@@ -0,0 +1,43 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+module Ham.Internal.Fcc where
+
+import Data.Aeson
+
+
+-- | Result received from a FCC database query.
+data FccResult = FccResult
+  {
+    status :: String         -- ^ Status code of the licenses.
+  , licenses :: FccLicenses  -- ^ The actual licenses.
+   } deriving (Read, Show)
+
+data FccLicenses = FccLicenses
+  { lastUpdate :: String
+  , page :: String
+  , totalRows :: String
+  , license :: [FccLicense]
+  , rowPerPage :: String
+  } deriving (Read, Show)
+
+data FccLicense = FccLicense
+  { frn :: String
+  , licName :: String
+  , serviceDesc :: String
+  , licDetailURL :: String
+  , statusDesc :: String
+  , expiredDate :: String
+  , licenseID :: String
+  , callsign :: String
+  , categoryDesc :: String } deriving (Read, Show)
+
+resultLabelMod :: String -> String
+resultLabelMod "licenses" = "Licenses"
+resultLabelMod "license" = "License"
+resultLabelMod a = a
+
+resultConstructorMod :: String -> String
+resultConstructorMod "licenses" = "Licenses"
+resultConstructorMod "license" = "License"
+resultConstructorMod a = a
+
diff --git a/src/Ham/Internal/FixedSequence.hs b/src/Ham/Internal/FixedSequence.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/FixedSequence.hs
@@ -0,0 +1,26 @@
+{-| Not very efficient, simple implementation of a max. size buffer.
+This is used to hold the text logs from HamLog actions in the Brick UI. -}
+
+module Ham.Internal.FixedSequence
+  (FixedSequence
+  ,addElement
+  ,toList
+  ,emptyFS)
+where
+
+import qualified Data.Sequence as S
+import qualified Data.Foldable as F (toList)
+
+data FixedSequence a = FixedSequence Int (S.Seq a)
+
+addElement :: a -> FixedSequence a -> FixedSequence a
+addElement a (FixedSequence n s) = result
+  where l = S.length s
+        result | l < n = FixedSequence n (a S.<| s)
+               | otherwise = FixedSequence n (a S.<| s')
+        s' = S.take (n - 1) s
+
+toList :: FixedSequence a -> [a]
+toList (FixedSequence n s) = F.toList s
+
+emptyFS n = FixedSequence n S.empty
diff --git a/src/Ham/Internal/Log.hs b/src/Ham/Internal/Log.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/Log.hs
@@ -0,0 +1,8 @@
+{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
+
+module Ham.Internal.Log
+  (module Ham.Internal.Log.Config
+  ,module Ham.Internal.Log.Log) where
+
+import Ham.Internal.Log.Config
+import Ham.Internal.Log.Log
diff --git a/src/Ham/Internal/Log/Config.hs b/src/Ham/Internal/Log/Config.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/Log/Config.hs
@@ -0,0 +1,97 @@
+{-# LANGUAGE MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}
+
+module Ham.Internal.Log.Config (LogConfig
+                               ,ToLogConfig
+                               ,defaultConfig
+                               ,configFromFile
+                               ,configToFile
+--                               ,module V1
+--                               ,module V2
+                               ,module Ham.Internal.Log.V3)
+
+  where
+
+import Control.Exception
+import Control.Monad (liftM)
+import Data.Aeson
+import Data.Aeson.Encode.Pretty
+import Data.Maybe (listToMaybe, catMaybes)
+import Data.Proxy
+import qualified Data.ByteString.Lazy as B
+import Ham.Internal.Qso
+import qualified Ham.Internal.Log.V1 as V1
+import qualified Ham.Internal.Log.V2 as V2
+import qualified Ham.Internal.Log.V3 as V3
+import Ham.Internal.Log.V3
+import Ham.Qso
+import qualified Ham.CAT as CAT
+
+
+type LogConfig = V3.LogConfigV3
+
+
+class ToLogConfig a b where
+  toLogConfig :: a -> b
+
+
+instance ToLogConfig V1.LogConfigV1 V2.LogConfigV2 where
+  toLogConfig (V1.LogConfigV1 logfile qsodefaults) = V2.LogConfigV2 { V2._configLogFile = logfile,
+                                                                      V2._configQsoDefaults = qsodefaults,
+                                                                      V2._configCat = CAT.defaultConfig }
+
+instance ToLogConfig V1.LogConfigV1 V3.LogConfigV3 where
+  toLogConfig a = toLogConfig b
+    where b = toLogConfig a :: V2.LogConfigV2
+
+
+instance ToLogConfig V2.LogConfigV2 V2.LogConfigV2 where
+  toLogConfig = id
+
+
+instance ToLogConfig V2.LogConfigV2 V3.LogConfigV3 where
+  toLogConfig (V2.LogConfigV2 logfile qsodefaults catconf) = V3.LogConfigV3 { V3._configLogFile = logfile,
+                                                                              V3._configQsoDefaults = qsodefaults,
+                                                                              V3._configUseCat = False,
+                                                                              V3._configCat = CAT.defaultConfig }
+
+instance ToLogConfig V3.LogConfigV3 V3.LogConfigV3 where
+  toLogConfig = id
+
+
+defaultConfig :: LogConfig
+defaultConfig = V3.LogConfigV3 { V3._configLogFile = "hamlog.json" -- This is the name of the log database file.
+                               , V3._configQsoDefaults = emptyQsoDefaults
+                               , V3._configUseCat = False
+                               , V3._configCat = CAT.defaultConfig
+                               }
+
+
+-- | Read the log configuration from a text file.
+configFromFile :: FilePath -> IO (Maybe LogConfig)
+configFromFile fp = do
+  let p1 :: Proxy V1.LogConfigV1
+      p1 = Proxy
+      p2 :: Proxy V2.LogConfigV2
+      p2 = Proxy
+      p3 = Proxy :: Proxy V3.LogConfigV3
+  let a = sequence [configFromFile' fp p3, configFromFile' fp p2, configFromFile' fp p1]
+  result <- (liftM $ listToMaybe . catMaybes) a
+  return result
+
+--configFromFile :: FilePath -> IO (Maybe LogConfig)
+--configFromFile fp = (decode <$> B.readFile fp)
+--      `catch` \(SomeException e) -> return Nothing
+
+
+configFromFile' :: forall a. (ToLogConfig a LogConfig, FromJSON a) => FilePath -> Proxy a -> IO (Maybe LogConfig)
+configFromFile' fp _ =
+  (do
+    ma <- (decode <$> B.readFile fp) :: IO (Maybe a)
+    return $ fmap toLogConfig ma)
+  `catch` \(SomeException e) -> return Nothing
+
+
+-- | Write the log configuration to a text file.
+configToFile :: LogConfig -> FilePath -> IO ()
+configToFile c fp =
+  B.writeFile fp $ encodePretty c
diff --git a/src/Ham/Internal/Log/Log.hs b/src/Ham/Internal/Log/Log.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/Log/Log.hs
@@ -0,0 +1,25 @@
+{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
+
+module Ham.Internal.Log.Log
+  where
+
+import Ham.Internal.Qso
+import Ham.Qso
+import Data.Sequence
+
+import Data.Aeson
+import Data.Aeson.TH
+
+import Lens.Micro.TH
+
+
+-- | A log.
+-- A log contains a set of 'Qso's
+data Log = Log {
+  _logQsos :: Seq Qso  -- ^ The set of QSOs contained in this log.
+  } deriving Show
+
+
+$(deriveJSON defaultOptions ''Log)
+
+makeLenses ''Log
diff --git a/src/Ham/Internal/Log/V1.hs b/src/Ham/Internal/Log/V1.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/Log/V1.hs
@@ -0,0 +1,28 @@
+{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
+
+module Ham.Internal.Log.V1
+  where
+
+import Ham.Internal.Qso
+import Ham.Qso
+import Data.Text
+import Data.Time.Calendar
+import Data.Time.Clock
+import Data.Sequence
+
+import Data.Aeson
+import Data.Aeson.TH
+
+import Lens.Micro.TH
+
+
+
+-- | Configuration for a log, version 1.
+data LogConfigV1 = LogConfigV1 {
+  _configLogFile :: FilePath       -- ^ File to store the logged Qsos in.
+  , _configQsoDefaults :: QsoDefaults -- ^ Default values, if any, for Qsos.
+  } deriving Show
+
+
+
+$(deriveJSON defaultOptions ''LogConfigV1)
diff --git a/src/Ham/Internal/Log/V2.hs b/src/Ham/Internal/Log/V2.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/Log/V2.hs
@@ -0,0 +1,30 @@
+{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
+
+module Ham.Internal.Log.V2
+  where
+
+import Ham.Internal.Qso
+import Ham.Qso
+import qualified Ham.CAT as CAT
+import Data.Text
+import Data.Time.Calendar
+import Data.Time.Clock
+import Data.Sequence
+
+import Data.Aeson
+import Data.Aeson.TH
+
+import Lens.Micro.TH
+
+
+-- | Configuration for a log, version 2.
+data LogConfigV2 = LogConfigV2 {
+  _configLogFile :: FilePath          -- ^ File to store the logged Qsos in.
+  , _configQsoDefaults :: QsoDefaults -- ^ Default values, if any, for Qsos.
+  , _configCat :: CAT.CATConfig       -- ^ CAT configuration.
+  } deriving Show
+
+
+$(deriveJSON defaultOptions ''LogConfigV2)
+
+makeLenses ''LogConfigV2
diff --git a/src/Ham/Internal/Log/V3.hs b/src/Ham/Internal/Log/V3.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/Log/V3.hs
@@ -0,0 +1,31 @@
+{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
+
+module Ham.Internal.Log.V3
+  where
+
+import Ham.Internal.Qso
+import Ham.Qso
+import qualified Ham.CAT as CAT
+import Data.Text
+import Data.Time.Calendar
+import Data.Time.Clock
+import Data.Sequence
+
+import Data.Aeson
+import Data.Aeson.TH
+
+import Lens.Micro.TH
+
+
+-- | Configuration for a log, version 2.
+data LogConfigV3 = LogConfigV3 {
+  _configLogFile :: FilePath          -- ^ File to store the logged Qsos in.
+  , _configQsoDefaults :: QsoDefaults -- ^ Default values, if any, for Qsos.
+  , _configUseCat :: Bool             -- ^ Flag to turn CAT support on or off.
+  , _configCat :: CAT.CATConfig       -- ^ CAT configuration.
+  } deriving Show
+
+
+$(deriveJSON defaultOptions ''LogConfigV3)
+
+makeLenses ''LogConfigV3
diff --git a/src/Ham/Internal/Qso.hs b/src/Ham/Internal/Qso.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Internal/Qso.hs
@@ -0,0 +1,80 @@
+{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
+
+module Ham.Internal.Qso
+  where
+
+import Data.Char (isDigit, digitToInt)
+import Data.List (all)
+import Data.Text
+import Data.Time.Clock
+import Data.Time.Calendar
+import Data.Time.LocalTime
+
+import Data.Aeson
+import Data.Aeson.TH
+
+import Lens.Micro.TH
+
+import Ham.Internal.Data
+
+
+-- | Contains information about a ham radio contact.
+data Qso = Qso {
+      _qsoTimeStart    :: UTCTime
+    , _qsoTimeEnd      :: UTCTime
+    , _qsoFrequency    :: Frequency
+    , _qsoMode         :: QsoMode
+    , _qsoCallsign     :: Text
+    , _qsoLocation     :: Text
+    , _qsoRST          :: RST
+    , _qsoExchange     :: Text
+    , _qsoSentCallsign :: Text
+    , _qsoSentLocation :: Text
+    , _qsoSentRST      :: RST
+    , _qsoSentExchange :: Text
+    , _qsoNotes        :: Text
+    } deriving (Show, Eq)
+
+
+
+-- | Sanitizing a Qso.
+-- Strips leading and trailing whitespace and converts to upper case.
+sanitizeQso :: Qso -> Qso
+sanitizeQso q = q { _qsoCallsign = toUpper $ strip $ _qsoCallsign q }
+
+
+data DefaultValue a = FixedValue a | DefaultValue a deriving (Show, Read)
+defaultValueGet :: DefaultValue a -> a
+defaultValueGet (FixedValue a) = a
+defaultValueGet (DefaultValue a) = a
+
+--instance Show a => Show (DefaultValue a)
+--instance Read a => Read (DefaultValue a)
+
+-- | Default values to fill in to a 'Qso'.
+-- These are kept in the configuration.
+-- For each entry in 'Qso', there is one default that either marks one
+-- as fixed value, or changeable value.
+data QsoDefaults = QsoDefaults {
+      _qsoDefaultTimeStart    :: DefaultValue UTCTime
+    , _qsoDefaultTimeEnd      :: DefaultValue UTCTime
+    , _qsoDefaultFrequency    :: DefaultValue Frequency
+    , _qsoDefaultMode         :: DefaultValue QsoMode
+    , _qsoDefaultCallsign     :: DefaultValue Text
+    , _qsoDefaultLocation     :: DefaultValue Text
+    , _qsoDefaultRST          :: DefaultValue RST
+    , _qsoDefaultExchange     :: DefaultValue Text
+    , _qsoDefaultSentCallsign :: DefaultValue Text
+    , _qsoDefaultSentLocation :: DefaultValue Text
+    , _qsoDefaultSentRST      :: DefaultValue RST
+    , _qsoDefaultSentExchange :: DefaultValue Text
+    , _qsoDefaultNotes        :: DefaultValue Text
+    } deriving (Show, Read)
+
+
+makeLenses ''Qso
+
+
+$(deriveJSON defaultOptions ''Qso)
+$(deriveJSON defaultOptions ''DefaultValue)
+$(deriveJSON defaultOptions ''QsoDefaults)
diff --git a/src/Ham/Log.hs b/src/Ham/Log.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Log.hs
@@ -0,0 +1,394 @@
+{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
+
+{-| Ham radio logging and other operations.
+This module provides a monad that abstracts some of the work
+necessary for logging ham radio contacts, as well as doing related
+tasks.
+-}
+module Ham.Log
+    (module Ham.Qso,
+     -- * Reading and writing log and configuration.
+     logToFile,
+     logFromFile,
+     configToFile,
+     configFromFile,
+     -- * The HamLog monad.
+     HamLog,
+     LogState(..),
+     emptyLogState,
+     -- ** Configuration
+     LogConfigV3(..),
+     LogConfig(..),
+     configLogFile,
+     configQsoDefaults,
+     defaultConfig,
+     -- ** Running the monad
+     evalHamLog,
+     execHamLog,
+     runHamLog,
+     -- ** Reading and writing logs
+     readLog,
+     writeLog,
+     -- ** Manipulating QSOs.
+     addQso,
+     newQsoNow,
+     fillFromCAT,
+     updateQso,
+     deleteQso,
+     sortLog,
+     -- ** Helpers
+     currentUtcTime,
+     -- ** Queries
+     filterCallsign,
+     isDuplicate,
+     findQsos,
+     findDuplicateQsos,
+     Duplicate(..),
+     getQsoList,
+     getQsoSeq,
+     asks,
+     -- ** Interacting with a radio via CAT
+     cat,
+     -- ** Getting information from the FCC database.
+     lookupFcc,
+     lookupFccName,
+     -- * The Log
+     Log(..),
+     addQsoToLog,
+     sortLog_,
+     emptyLog,
+     -- * Exporting
+     makeCabrillo
+) where
+
+
+import Data.Foldable
+import qualified Data.Sequence as S
+import Data.Sequence (Seq)
+import Data.Time.Calendar
+import Data.Time.Clock
+import Data.Time.LocalTime
+
+import Data.Text as T
+import Data.Sequence
+import qualified Data.ByteString.Lazy as B
+import Data.Aeson.Encode.Pretty
+import Data.Aeson
+import Data.Maybe (isJust, fromJust)
+import qualified Data.Map as M
+import Control.Applicative ((<|>))
+import Control.Monad (when)
+import Control.Monad.Trans.RWS.Strict
+import Control.Monad.IO.Class
+import Control.Exception
+
+import Ham.Internal.Log
+import Ham.Internal.Log.Config
+import Ham.Fcc
+import Ham.Cabrillo
+import Ham.Qso
+import Ham.Data
+import qualified Ham.CAT as CAT
+import Ham.CAT.Radios
+
+import Lens.Micro.TH
+
+
+-- | An empty log.
+emptyLog :: Log
+emptyLog = Log mempty
+
+
+-- | Add a QSO to the beginning of the log list.
+addQsoToLog :: Log -> Qso -> Log
+addQsoToLog l q = l { _logQsos = m }
+  where m = q <| _logQsos l
+
+
+sortLog_ :: Ord a => Log -> (Qso -> a) -> Log
+sortLog_ l g = l { _logQsos = sortBy f (_logQsos l) }
+  where f a b = compare (g a) (g b)
+
+
+-- | Write a log to a file in JSON format.
+logToFile :: Log -> FilePath -> IO ()
+logToFile l fp = B.writeFile fp $ encodePretty l
+
+
+-- | Read a log from a file in JSON format.
+logFromFile :: FilePath -> IO (Maybe Log)
+logFromFile fp =
+  (decode <$> B.readFile fp)
+    `catch` \(SomeException e) -> return Nothing
+
+
+
+--------------------------------------------------------------------------------
+-- Log monad.
+
+{-| Log monad.
+You would normally run the monad for example with 'evalHamLog',
+and use the monadic actions such as 'readLog', 'newQsoNow', 'writeLog', etc.
+to modify the log and QSOs. -}
+type HamLog = RWST LogConfig [Text] LogState IO
+
+data LogState = LogState { _stateLog :: Log
+                         , _stateUseCat :: Bool   -- ^ Mirroring the configuration in _configCat in the LogConfig to be able to turn it off after a failed action.
+                         , _stateSerialCAT :: Maybe CAT.SerialCAT }
+
+makeLenses ''LogState
+
+
+emptyLogState :: LogState
+emptyLogState = LogState emptyLog True Nothing
+
+
+initState :: HamLog ()
+initState = do
+  catconf <- asks _configCat
+  -- Set the serial radio interface if there is one.
+  let mserial = M.lookup (CAT.catRadio catconf) serialInterface
+  s <- get
+  c <- asks _configUseCat
+  put s { _stateSerialCAT = mserial
+        , _stateUseCat = c }
+  -- maybe (return ()) (\serial -> do { s <- get; put s { _stateSerialCAT = Just serial } }) mserial
+
+
+
+
+-- | Run a 'HamLog' action and return the result and potential logging text.
+evalHamLog :: LogConfig -> LogState -> HamLog a -> IO (a, [Text])
+evalHamLog cfg s act = evalRWST (initState >> act) cfg s
+
+
+-- | Run a 'HamLog' action and return the final state and potential logging text.
+execHamLog :: LogConfig -> LogState -> HamLog a -> IO (LogState, [Text])
+execHamLog cfg s act = execRWST (initState >> act) cfg s
+
+
+-- | Run a 'HamLog' action and return the result, final state, and potential logging text.
+runHamLog :: LogConfig -> LogState -> HamLog a -> IO (a, LogState, [Text])
+runHamLog cfg s act = runRWST (initState >> act) cfg s
+
+
+-- | Read the log database from the file set in '_configLogFile' entry of the 'LogConfig'.
+-- The log is then set to the '_stateLog' entry of the current 'LogState'.
+readLog :: HamLog ()
+readLog = do
+  f <- asks _configLogFile
+  ml <- liftIO $ logFromFile f `catch` \(SomeException a) -> return Nothing
+  maybe (return ()) (\l -> do { s <- get; put $ s { _stateLog = l } }) ml
+
+
+-- | Write the log database to the file set in '_configLogFile' entry of the 'LogConfig'.
+writeLog :: HamLog ()
+writeLog = do
+  f <- asks _configLogFile
+  l <- gets _stateLog
+
+  liftIO $ logToFile l f
+
+
+-- | Add the given QSO at the front of the current log.
+addQso :: Qso -> HamLog ()
+addQso q = do
+  l <- gets _stateLog
+  let l' = addQsoToLog l $ sanitizeQso q
+  modify $ \s -> s { _stateLog = l' }
+
+
+-- | Get the current UTC time up to seconds.
+currentUtcTime :: HamLog UTCTime
+currentUtcTime = liftIO $ do
+    t <- getCurrentTime
+    let tod = utctDayTime t
+        -- Remove anything that is more accurate than one second. We assume that is enough for
+        -- our purpose.
+        tod' = (picosecondsToDiffTime . (\a -> a - a `rem` (10^12)) . diffTimeToPicoseconds) tod
+    return $ t { utctDayTime = tod' }
+
+
+-- | Create a new QSO with the current UTC time as reported by the operating system,
+-- and set the default values from the '_configQsoDefaults' values.
+-- uses `fillFromCAT` to fill some values from a connected radio, if any.
+newQsoNow :: HamLog Qso
+newQsoNow = do
+  now <- currentUtcTime
+  defaults <- asks _configQsoDefaults
+  let q = (qsoWithDefaults defaults)
+            { _qsoTimeStart = now
+            , _qsoTimeEnd = (fromIntegral 60) `addUTCTime` now
+            }
+  q' <- fillFromCAT q
+  addQso q'
+  return q'
+
+
+-- | Try to get a few values from a CAT connected radio.
+-- If the function is turned off (_stateUseCat is False), then the input is going to be
+-- returned unchanged. The same is true if there is an error while retrieving
+-- data from the radio.
+-- Note that when the functionality is turned on and there is an error, it may take a few seconds
+-- for the function to return. A message will be set in the Writer layer of HamLog,
+-- so that you can get the messages back with `evalHamLog`, `execHamLog`, or `runHamLog`.
+fillFromCAT :: Qso -> HamLog Qso
+fillFromCAT qso = do
+  result <- cat $ do
+    f <- CAT.catFrequency
+    m <- CAT.catMode
+    return (f,m)
+  case result of
+    Left (CAT.CATError t s) -> tell [s] >> return qso
+    Right ((mf, mm), _) -> return $ qso { _qsoFrequency = maybe (_qsoFrequency qso) id mf,
+                                          _qsoMode = maybe (_qsoMode qso) id mm }
+
+
+
+-- | Update the QSO at the given position in the log with the given QSO.
+updateQso :: Int -> Qso -> HamLog ()
+updateQso i q = do
+  l <- gets _stateLog
+  let q' = update i (sanitizeQso q) $ _logQsos l
+  modify $ \s -> s { _stateLog = l { _logQsos = q' } }
+  return ()
+
+
+-- | Delete the QSO at the given position in the log.
+deleteQso :: Int -> HamLog ()
+deleteQso i = do
+  l <- gets _stateLog
+  let q' = deleteAt i $ _logQsos l
+  modify $ \s -> s { _stateLog = l { _logQsos = q' } }
+
+
+-- | Sort the log according to the given key.
+sortLog :: Ord a => (Qso -> a) -> HamLog ()
+sortLog g = do
+  l <- gets _stateLog
+  let l' = sortLog_ l g
+  modify $ \s -> s { _stateLog = l' }
+
+
+-- | Get a list of QSOs. Use qsoSeq for better performance.
+getQsoList :: HamLog [Qso]
+getQsoList = do
+  l <- _logQsos <$> gets _stateLog
+  return $ Data.Foldable.foldr (:) [] l
+
+
+-- | Get the sequence of stored QSOs.
+getQsoSeq :: HamLog (Seq Qso)
+getQsoSeq = _logQsos <$> gets _stateLog
+
+
+-- | Return a sequence of all QSOs with a given callsign.
+filterCallsign :: Text             -- ^ The Callsign to find.
+               -> HamLog (Seq Qso) -- ^ Returns a sequence of Qsos.
+filterCallsign callsign = do
+  l <- getQsoSeq
+  let f q = let cs = T.toUpper $ _qsoCallsign q
+                cs' = T.strip $ T.toUpper callsign
+            in cs == cs'
+  return (S.filter f l)
+
+
+-- | Checks if there is already at least one entry with the given callsign.
+-- DEPRECATED. Use findDuplicateQsos.
+isDuplicate :: Text        -- ^ The Callsign to find.
+            -> HamLog Bool
+isDuplicate callsign = do
+  s <- filterCallsign callsign
+  case s of
+    Empty -> return False
+    _ -> return True
+
+
+
+-- | Find qsos containing the given information.
+findQsos :: Text -- ^ The callsign to find.
+         -> Maybe Band -- ^ Band to check for
+         -> Maybe QsoMode -- ^ Mode to check for
+         -> HamLog (Seq Qso)
+findQsos callsign mband mmode = do
+  s <- filterCallsign callsign
+  let msb = maybe Nothing (\a -> Just $ S.filter (\qso -> band (_qsoFrequency qso) == a) s) mband
+      Just s2 = msb <|> Just s
+      msm = maybe Nothing (\a -> Just $ S.filter (\qso -> _qsoMode qso == a) s2) mmode
+      Just s3 = msm <|> Just s2
+
+  return s3
+
+
+data Duplicate = Duplicate { duplicateBand :: Bool -- ^ Indicates whether band matches
+                           , duplicateMode :: Bool -- ^ Indicates whether mode matches
+                           , duplicateQso :: Qso   -- ^ The potential duplicate QSO
+                           }
+
+
+instance Show Duplicate where
+  show d = "Met " ++ c ++ " on " ++ show b ++ " using " ++ show m ++ " at " ++ show (_qsoTimeStart q)
+    where b = band $ _qsoFrequency q
+          m = _qsoMode q
+          q = duplicateQso d
+          c = T.unpack $ _qsoCallsign q
+
+
+findDuplicateQsos :: Qso
+                  -> HamLog (Seq Duplicate)
+findDuplicateQsos qso = do
+  let qso' = sanitizeQso qso
+      b = band $ _qsoFrequency qso'
+      c = _qsoCallsign qso'
+      m = _qsoMode qso'
+      f a = if _qsoCallsign a == c && (a /= qso') -- Do not return the same QSO itself. FIXME: It may be necessary to use IDs for this.
+            then Just (Duplicate { duplicateBand = band (_qsoFrequency a) == b,
+                                   duplicateMode = _qsoMode a == m,
+                                   duplicateQso = a })
+            else Nothing
+      catM :: S.Seq (Maybe a) -> S.Seq a
+      catM s = fmap fromJust $ S.filter isJust s
+
+  qsos <- getQsoSeq
+  return $ catM $ fmap f qsos
+
+
+-- | Get the FCC information for a given callsign.
+lookupFcc :: Text -> HamLog (Maybe FccResult)
+lookupFcc a = liftIO $ fccLookup' a
+
+
+-- | Get the operator's name for a given callsign from the FCC.
+lookupFccName :: Text -> HamLog Text
+lookupFccName a = liftIO $ fccLookupName a
+
+
+-- | Make a cabrillo log from the current log, given a cabrillo configuration.
+makeCabrillo :: Cabrillo -> HamLog CabrilloLog
+makeCabrillo cab = do
+    l <- getQsoList
+    myCall <- _qsoDefaultCallsign <$> asks _configQsoDefaults
+    let l' = Prelude.concatMap toCabrillo l
+    return $ CabrilloLog cab l'
+
+
+-- | Run a CAT action.
+cat :: CAT.CAT IO a -> HamLog (Either CAT.CATError (a, [Text]))
+cat act = do
+  -- FIXME: fromJust may be somewhat dangerous. As it currently is used,
+  -- it wil always be set, but that is not guaranteed to remain this way.
+  usecat <- gets _stateUseCat
+  if usecat
+    then do
+      radio_interface <- fromJust <$> gets _stateSerialCAT
+      conf <- asks _configCat
+      let catstate = CAT.defaultState { CAT.stateInterface = radio_interface }
+      result <- liftIO $ CAT.runCAT conf catstate act
+      case result of
+        Left (CAT.CATError t s) -> do
+          tell $ ["CAT failed: " <> s <> " - turning off CAT for now."]
+          s <- get
+          put  $ s { _stateUseCat = False }
+        Right a -> tell $ snd a
+      return result
+    else  return $ Left $ (CAT.CATError CAT.CATErrorGeneric "CAT is turned off.")
diff --git a/src/Ham/Qso.hs b/src/Ham/Qso.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/Qso.hs
@@ -0,0 +1,80 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+module Ham.Qso
+  (
+    QsoMode(..),
+    Qso(..),
+    QsoDefaults(..), DefaultValue(..),
+    emptyQso, qsoWithDefaults, emptyQsoDefaults, Frequency(..),
+    sanitizeQso,
+    qsoTimeStart,
+    qsoTimeEnd,
+    qsoFrequency,
+    qsoMode,
+    qsoCallsign,
+    qsoLocation,
+    qsoRST,
+    qsoExchange,
+    qsoSentCallsign,
+    qsoSentLocation,
+    qsoSentRST,
+    qsoSentExchange,
+    qsoNotes,
+    module Data.Time.Clock,
+    module Data.Time.Calendar,
+    module Data.Time.LocalTime
+  ) where
+
+
+import Ham.Internal.Qso
+import qualified Ham.Cabrillo as C
+import Ham.Cabrillo (ToCabrillo)
+import Ham.Data as D
+import Data.Time.Clock
+import Data.Time.Calendar
+import Data.Time.LocalTime
+import Data.Text (unpack)
+
+
+
+defaultQsoTime = UTCTime (fromGregorian 2018 01 22) (timeOfDayToTime $ TimeOfDay 00 00 00)
+emptyQso = qsoWithDefaults emptyQsoDefaults -- Qso defaultQsoTime defaultQsoTime (MHz 0) PH mempty mempty (RST 0 0 0) mempty mempty mempty (RST 0 0 0) mempty mempty
+
+emptyQsoDefaults = QsoDefaults (DefaultValue defaultQsoTime) (DefaultValue defaultQsoTime) (DefaultValue (MHz 0)) (DefaultValue PH) (DefaultValue mempty) (DefaultValue mempty) (DefaultValue (RST 0 0 0)) (DefaultValue mempty) (DefaultValue mempty) (DefaultValue mempty) (DefaultValue (RST 0 0 0)) (DefaultValue mempty) (DefaultValue mempty)
+
+qsoWithDefaults :: QsoDefaults -> Qso
+qsoWithDefaults d = q
+  where q = Qso {
+                  _qsoTimeStart    = f _qsoDefaultTimeStart
+                , _qsoTimeEnd      = f _qsoDefaultTimeEnd
+                , _qsoFrequency    = f _qsoDefaultFrequency
+                , _qsoMode         = f _qsoDefaultMode
+                , _qsoCallsign     = f _qsoDefaultCallsign
+                , _qsoLocation     = f _qsoDefaultLocation
+                , _qsoRST          = f _qsoDefaultRST
+                , _qsoExchange     = f _qsoDefaultExchange
+                , _qsoSentCallsign = f _qsoDefaultSentCallsign
+                , _qsoSentLocation = f _qsoDefaultSentLocation
+                , _qsoSentRST      = f _qsoDefaultSentRST
+                , _qsoSentExchange = f _qsoDefaultSentExchange
+                , _qsoNotes        = f _qsoDefaultNotes
+                }
+        f a = defaultValueGet $ a d
+
+
+instance ToCabrillo Qso where
+    toCabrillo q = [C.CLQso $ C.CabrilloQso (_qsoFrequency q)
+                                (modeConvert (_qsoMode q))
+                                (_qsoTimeStart q)
+                                s
+                                r
+                                Nothing]
+            where s = C.CabrilloInfo (unpack $ _qsoSentCallsign q) (unpack $ _qsoSentExchange q)
+                  r = C.CabrilloInfo (unpack $ _qsoCallsign q) (unpack $ _qsoExchange q)
+
+modeConvert :: QsoMode -> C.Mode
+modeConvert D.CW = C.CW
+modeConvert D.PH = C.PH
+modeConvert D.FM = C.FM
+modeConvert D.RY = C.RY
+modeConvert D.DATA = C.DG
diff --git a/src/Ham/UI/Brick.hs b/src/Ham/UI/Brick.hs
new file mode 100644
--- /dev/null
+++ b/src/Ham/UI/Brick.hs
@@ -0,0 +1,529 @@
+{-# LANGUAGE OverloadedStrings, RankNTypes, TupleSections #-}
+
+
+module Ham.UI.Brick
+  (
+    emptyAppState
+  , AppMode(..)
+  , AppState(..)
+  , AppResource
+  , app
+  )
+where
+
+import Ham.Log
+import Ham.Data
+import qualified Ham.CAT as CAT
+import Ham.CAT.ElecraftKX2
+import Ham.CAT.YaesuFT891
+import qualified Ham.Internal.FixedSequence as FS
+import Ham.Internal.FixedSequence (FixedSequence)
+
+import Control.Concurrent.MVar
+import Control.Monad
+import Control.Monad.IO.Class
+
+import Data.Monoid ((<>))
+import Data.Time.Clock
+import Data.Time.Calendar
+import Data.Time.LocalTime
+import Data.Time.Format (formatTime, defaultTimeLocale)
+import qualified Data.Text as T
+import Data.Text (Text)
+import Data.Foldable
+import Data.List (foldl')
+import qualified Data.Text as Text
+import qualified Data.Sequence as S
+import qualified Data.Vector as V
+
+import Brick
+import Brick.Forms
+import Brick.Widgets.List
+import Brick.Widgets.Border
+import Brick.Widgets.Dialog
+import qualified Brick.Widgets.Edit as E
+import qualified Brick.Focus as F
+import qualified Brick.Types as T
+import Brick.Main
+
+import qualified Brick.Widgets.Border.Style
+import Graphics.Vty.Attributes (defAttr, blue)
+import Graphics.Vty.Input.Events
+import qualified Graphics.Vty as V
+
+import Lens.Micro
+
+
+-- | Application state for the 'Brick' UI.
+data AppState = AppState {
+  logState :: LogState,             -- ^ State for the Hamlog monad.
+  logConfig :: LogConfig,           -- ^ Configuration for the Hamlog monad.
+  qsoList :: List AppResource Qso,  -- ^ List of contacts to display
+  qsoForm :: Form Qso HamlogEvent AppResource, -- ^ Form to enter new contacts
+  focusRing :: F.FocusRing AppResource, -- ^ Focus ring to use
+  appMode :: AppMode,                   -- ^ Current mode of the app
+  selectedQsoIndex :: Int,              -- ^ Index of the currently selected contact
+  infoText :: FixedSequence Text,       -- ^ Text to display in the info window
+  statusText :: [Text],                 -- ^ Text to display in the status line
+  duplicateQsos :: S.Seq Duplicate      -- ^ Any potential duplicates found.
+  }
+
+
+-- | Default AppState.
+emptyAppState :: AppState
+emptyAppState =
+  AppState { logState = emptyLogState,
+             logConfig = defaultConfig,
+             qsoList = list LogList V.empty 1,
+             qsoForm = newForm [] emptyQso,
+             focusRing = lappDefaultFocusRing,
+             appMode = AppModeList,
+             selectedQsoIndex = 0,
+             infoText = FS.emptyFS 10,
+             statusText = [],
+             duplicateQsos = S.Empty
+           }
+
+
+
+data HamlogEvent
+
+-- | Resource type to index widgets
+data AppResource = LogList |
+                   LogInfo |
+                   LogQso |
+                   LogQsoTimeStart |
+                   LogQsoTimeEnd |
+                   LogQsoFrequency |
+                   LogQsoMode |
+                   LogQsoCallsign |
+                   LogQsoLocation |
+                   LogQsoRST |
+                   LogQsoExchange |
+                   LogQsoMyCallsign |
+                   LogQsoMyLocation |
+                   LogQsoSentRST |
+                   LogQsoSentExchange |
+                   LogQsoNotes
+  deriving (Eq, Ord, Show)
+
+
+-- | Run a 'HamLog' action given the AppState, in the EventM monad.
+hamLog :: AppState -> HamLog a -> EventM AppResource (a, AppState)
+hamLog s act = do
+  (a, ls, logtext) <- liftIO $ runHamLog (logConfig s) (logState s) $ act
+  let s' = s { logState = ls,
+               infoText = fs,
+               logConfig = (logConfig s) { _configUseCat = _stateUseCat ls } } -- Turn CAT on or off depending on the state delivered by HamLog. It could be there was an initialization error, in that case we want to turn off the configured CAT use flag.
+      fs = foldr FS.addElement (infoText s) logtext
+  return (a, s')
+
+
+-- | Default focus ring. Empty.
+lappDefaultFocusRing :: F.FocusRing AppResource
+lappDefaultFocusRing = F.focusRing []
+
+
+-- | Focus ring for the QSO edit widget.
+lappQsoFocusRing :: AppState -> F.FocusRing AppResource
+lappQsoFocusRing s = formFocus $ qsoForm s
+
+
+-- | Add a new QSO at the beginning of the list and go to edit mode immediately.
+lappNewQso :: AppState -> EventM AppResource AppState
+lappNewQso s = do
+  (q, s') <- hamLog s newQsoNow
+  s'' <- lupdateQsoList 0 s' >>= lupdateQsoForm
+
+  -- Edit the new QSO (at index 0)
+  return $ s'' { appMode = AppModeQso, focusRing = lappQsoFocusRing s'', selectedQsoIndex = 0 }
+
+
+
+
+-- | Given a QSO, create a form for editing it.
+mkQsoForm :: Qso -> QsoDefaults -> Form Qso HamlogEvent AppResource
+mkQsoForm q q_def = newForm fieldStates q
+  where
+    timeStart = f _qsoDefaultTimeStart $ label "Start:" @@= editShowableField qsoTimeStart LogQsoTimeStart
+    timeEnd   = f _qsoDefaultTimeEnd   $ label "End:"   @@= editShowableField qsoTimeEnd LogQsoTimeEnd
+    f d s = case d q_def of
+      FixedValue _ -> []
+      DefaultValue _ -> [s]
+    fieldStates = concat [
+                          f _qsoDefaultCallsign     $ label "Callsign:"     @@= editTextField qsoCallsign LogQsoCallsign (Just 1),
+                          f _qsoDefaultLocation     $ label "Location:"     @@= editTextField qsoLocation LogQsoLocation (Just 1),
+                          f _qsoDefaultRST          $ label "RST received:" @@= editShowableField qsoRST LogQsoRST,
+                          f _qsoDefaultExchange     $ label "Exchg recvd:"  @@= editTextField qsoExchange LogQsoExchange (Just 1),
+                          f _qsoDefaultSentRST      $ label "RST sent:"     @@= editShowableField qsoSentRST LogQsoSentRST,
+                          f _qsoDefaultSentExchange $ label "Exchg sent:"   @@= editTextField qsoSentExchange LogQsoSentExchange (Just 1),
+                          f _qsoDefaultFrequency    $ label "Frequency:"    @@= editShowableField qsoFrequency LogQsoFrequency,
+                          f _qsoDefaultMode         $ label "Mode (CW,PH,FM,RY):" @@= editShowableField qsoMode LogQsoMode,
+                          f _qsoDefaultSentCallsign $ label "My callsign:"  @@= editTextField qsoSentCallsign LogQsoMyCallsign (Just 1),
+                          f _qsoDefaultSentLocation $ label "My location:"  @@= editTextField qsoSentLocation LogQsoMyLocation (Just 1),
+                          timeStart,
+                          timeEnd,
+                          f _qsoDefaultNotes        $ label "Notes:"        @@= editTextField qsoNotes LogQsoNotes Nothing]
+    label s w = -- padBottom (Pad 1) $
+                (vLimit 1 $ hLimit 20 $ str s <+> fill ' ') <+> w
+
+
+-- | Create a form for editing the currently selected QSO.
+mkSelectedQsoForm :: AppState -> Form Qso HamlogEvent AppResource
+mkSelectedQsoForm s = qsoForm
+  where
+    q_def   = _configQsoDefaults $ logConfig s
+    qsoForm = mkQsoForm selectedQso q_def
+    selectedQso = maybe emptyQso id $ snd <$> listSelectedElement (qsoList s)
+
+
+-- | Selected QSO. If none is selected, the empty QSO is returned.
+lselectedQso :: AppState -> Qso
+lselectedQso s = maybe emptyQso id $ snd <$> listSelectedElement (qsoList s)
+
+
+-- | Drawing function. Draws depending on current AppMode.
+lappDraw :: AppState -> [Widget AppResource]
+lappDraw s = case (appMode s) of
+  AppModeQuestion _ dlg _ _ -> [ renderDialog dlg $ str "", mainView ]
+  _                         -> [ mainView ]
+  where
+    mainView = ((renderListWidget <=> lappStatusTextWidget s) <+> (qsoWidget <=> lappHelp s <=> appInfoWidget s)) <=> statusWidget
+    renderListWidget = border $ hLimit 30 $ renderList lrenderLogListItem True l
+    l = qsoList s
+    qsoWidget = border $ {-padTop (Pad 0) $-} renderForm $ qsoForm s
+    statusWidget = lappStatusWidget s
+
+
+lappStatusTextWidget :: AppState -> Widget AppResource
+lappStatusTextWidget s = str t
+  where t = unlines $ map T.unpack $ statusText s
+
+
+-- | Information widget. Shows dupes.
+appInfoWidget :: AppState -> Widget AppResource
+appInfoWidget s = info
+  where info = padTop (Pad 1) $ borderWithLabel (str "Info") body
+        body = case (appMode s) of
+          -- AppModeList -> str ""
+          _ -> vLimitPercent 30 $ viewport LogInfo Both $ vBox $ fmap txt (FS.toList $ infoText s) <> toList (fmap f dupes)
+                  where
+                    dupes = duplicateQsos s
+                    dupeToText dupe = T.pack $ show dupe
+                    f dupe = if (duplicateBand dupe) && (duplicateMode dupe)
+                             then withAttr "dupeWarn" $ txt $ dupeToText dupe
+                             else txt $ dupeToText dupe
+
+
+
+-- | Rendering a list item in the log list.
+lrenderLogListItem :: Bool -> Qso -> Widget AppResource
+lrenderLogListItem True  q = withAttr ("qsoList" <> "selected") $ str $ lrenderLogListItem_str q
+lrenderLogListItem False q = withAttr ("qsoList" <> "normal")   $ str $ lrenderLogListItem_str q
+lrenderLogListItem_str :: Qso -> String
+lrenderLogListItem_str q = time_date ++ " " ++ call ++ " " ++ bd ++ " " ++ mode
+  where time_date = formatTime  defaultTimeLocale "%F %R" (_qsoTimeStart q)
+        call      = Text.unpack (_qsoCallsign q)
+        bd        = show $ band $ _qsoFrequency q
+        mode      = show $ _qsoMode q
+
+-- | Update the UI list widget with the current log list in the state.
+lupdateQsoList :: Int -> AppState -> EventM AppResource AppState
+lupdateQsoList qso_index s = return $ s { qsoList = l }
+  where
+    l  = listMoveTo qso_index $ list LogList ll 1
+    ll = V.fromList $ (foldr (:) [] . _logQsos . _stateLog . logState) s
+
+
+-- | Update the QSO widget with the currently selected QSO in the list.
+lupdateQsoForm :: AppState -> EventM AppResource AppState
+lupdateQsoForm s = return $ s { qsoForm = mkSelectedQsoForm s }
+
+
+-- | Handler for AppModeQuestion; this is for asking the user a yes/no question.
+lhandleEvent_question :: AppState -> BrickEvent AppResource HamlogEvent -> EventM AppResource (Next AppState)
+lhandleEvent_question s ev =
+  case appMode s of
+
+    AppModeQuestion prev dlg yes no ->
+
+      case ev of
+
+        VtyEvent (EvKey KEnter []) -> do
+          let msel = dialogSelection dlg
+          let s' = s { appMode = prev }
+          case msel of
+            Just sel -> continue =<< if sel then (yes s') else (no s')
+
+        VtyEvent (EvKey (KChar 'y') []) -> do
+          let s' = s { appMode = prev }
+          continue =<< yes s'
+
+        VtyEvent (EvKey (KChar 'n') []) -> do
+          let s' = s { appMode = prev }
+          continue =<< no s'
+
+        VtyEvent (EvKey KEsc []) -> do
+          let s' = s { appMode = prev }
+          continue =<< no s'
+
+        VtyEvent e -> do
+          dlg' <- handleDialogEvent e dlg
+          let s' = s { appMode = AppModeQuestion prev dlg' yes no }
+          continue s'
+        _ -> continue s
+
+    _ -> continue s
+
+
+-- | List mode. This is the default, main mode of the application.
+lhandleEvent_list :: AppState -> BrickEvent AppResource HamlogEvent -> EventM AppResource (Next AppState)
+lhandleEvent_list s ev =
+  case appMode s of
+
+    AppModeList ->
+      -- This mode is editing the log list.
+
+      case ev of
+
+        VtyEvent (EvKey (KChar 'q') [])  -> do
+          (_, s') <- hamLog s writeLog
+          halt s'
+
+        VtyEvent (EvKey (KChar 'n') [])  -> do
+          let
+            updated_qso_defaults = qso_defaults {
+              _qsoDefaultFrequency = case _qsoDefaultFrequency qso_defaults of
+                                       DefaultValue f -> DefaultValue f
+                                       a              -> a,
+              _qsoDefaultMode = case _qsoDefaultMode qso_defaults of
+                                  DefaultValue m -> DefaultValue m
+                                  a              -> a }
+            --, _qsoDefaultMode = case _qsoDefaultMode qso_defaults of
+            --                      DefaultValue _ -> DefaultValue (_qsoMode f) }
+            qso_defaults         = _configQsoDefaults $ logConfig s
+            updated_config       = (logConfig s) { _configQsoDefaults = updated_qso_defaults }
+            s'                   = s { logConfig = updated_config }
+          continue =<< lappNewQso s'
+
+        VtyEvent (EvKey KBS [])         -> do
+          let dlg = dialog (Just "Delete entry?") (Just (1, [("Yes", True), ("No", False)])) 25
+              s' = s { appMode = AppModeQuestion AppModeList dlg yes no }
+              yes ss = maybe
+                         (return ss)
+                         (\i -> snd <$> hamLog ss (deleteQso i) >>=
+                                        lupdateQsoList i >>=
+                                        lupdateQsoForm >>= \ss' ->
+                                        lcheckDupes (lselectedQso ss') ss')  -- Check for dupes again after deleting an element.
+                         mi
+              no = return
+              mi = listSelected $ qsoList s'
+          continue s'
+
+        VtyEvent (EvKey (KChar 's') []) -> continue $ s { appMode = AppModeSort AppModeList }
+
+        VtyEvent (EvKey (KChar 'w') []) -> snd <$> hamLog s writeLog >>= continue
+
+        VtyEvent (EvKey (KChar '\t') []) -> do
+          let mi = listSelected $ qsoList s
+          case mi of
+            Just i -> continue $ s { appMode = AppModeQso, focusRing = lappQsoFocusRing s, selectedQsoIndex = i }
+            Nothing -> continue s
+        VtyEvent e                       -> do
+          s' <- handleListEvent e (qsoList s) >>= \l -> return (s { qsoList = l })
+          continue =<< lupdateQsoForm s'
+        _ -> continue s
+
+    _ -> continue s
+
+
+lhandleEvent_qso :: AppState -> BrickEvent AppResource HamlogEvent -> EventM AppResource (Next AppState)
+lhandleEvent_qso s ev =
+  case (appMode s) of
+
+    AppModeQso ->
+      -- This mode is editing the current QSO entry.
+
+      case ev of
+
+        VtyEvent (EvKey KUp []) -> do
+          let focusring = lappQsoFocusRing s
+              m_current_focus = F.focusGetCurrent focusring
+
+          case m_current_focus of
+            Just LogQsoNotes ->
+              handleFormEvent ev (qsoForm s) >>= \f ->
+              continue $ s { qsoForm = f, focusRing = lappQsoFocusRing s }
+            Just _ -> lhandleEvent_qso s (VtyEvent (EvKey KBackTab []))
+
+        VtyEvent (EvKey KDown []) -> do
+          let focusring = lappQsoFocusRing s
+              m_current_focus = F.focusGetCurrent focusring
+
+          case m_current_focus of
+            Just LogQsoNotes ->
+              handleFormEvent ev (qsoForm s) >>= \f ->
+              continue $ s { qsoForm = f, focusRing = lappQsoFocusRing s }
+              --return (s { qsoForm = f }) >>= \ss ->
+              --return (ss { focusRing = lappQsoFocusRing ss }) >>= continue
+            Just _ -> lhandleEvent_qso s (VtyEvent (EvKey (KChar '\t') []))
+
+        VtyEvent (EvKey (KChar 'l') [MCtrl]) -> do
+          let f = formState $ qsoForm s
+          let s' = s { statusText = ["[Retrieving...]"] }
+          (name, s') <- hamLog s $ lookupFccName (_qsoCallsign f)
+          continue $ s' { statusText = [name] }
+
+
+        VtyEvent (EvKey (KChar 't') [MCtrl]) -> do
+          let f = formState $ qsoForm s
+              s' = s { statusText = ["Time updated"] }
+              i = selectedQsoIndex s'
+          (mf', s'') <- hamLog s' $ do
+            currentUtcTime >>= \t -> updateQso i (f { _qsoTimeStart = t, _qsoTimeEnd = t })
+            a <- getQsoSeq
+            return (a S.!? i)
+          -- FIXME: I need to update the form entries, not the qso directly.
+
+          lupdateQsoForm s'' >>= continue -- FIXME: The time is not updated in the form, and then set to the old time when the form is left.
+
+
+        VtyEvent (EvKey KEsc []) -> do
+          -- Modify the qso currently under edit and go back to list mode.
+          let f = formState $ qsoForm s
+              i = selectedQsoIndex s
+              -- Also modify the a subset of the configured default values to the ones we set last, if it is not a FixedValue.
+              updated_qso_defaults = qso_defaults { _qsoDefaultFrequency = case _qsoDefaultFrequency qso_defaults of
+                                                                             DefaultValue _ -> DefaultValue (_qsoFrequency f)
+                                                                             a              -> a
+                                                  , _qsoDefaultMode = case _qsoDefaultMode qso_defaults of
+                                                                        DefaultValue _ -> DefaultValue (_qsoMode f) }
+              qso_defaults         = _configQsoDefaults $ logConfig s
+              updated_config       = (logConfig s) { _configQsoDefaults = updated_qso_defaults }
+
+          -- Check for duplicates using a Qso type object.
+          -- FIXME: Add a level of duplicate: Met on another band, on the same band but different mode,
+          -- met on the same band with the same mode.
+          -- (dupes, s') <- hamLog s $ findDuplicateQsos f
+          s' <- (hamLog s $ updateQso i f) >>= lcheckDupes f . snd
+          -- s'' <- lcheckDupes f s'
+
+          let s'' = s' { appMode = AppModeList,
+                         focusRing = lappDefaultFocusRing,
+                         logConfig = updated_config,
+                         selectedQsoIndex = -1 }
+
+          -- FIXME: Do this more efficiently than updating the whole list.
+          continue =<< lupdateQsoList i s''
+
+        _ -> do
+          s' <- handleFormEvent ev (qsoForm s) >>= \f ->
+                --return s { qsoForm = f, focusRing = lappQsoFocusRing s }
+                return (s { qsoForm = f }) >>= \ss ->
+                return (ss { focusRing = lappQsoFocusRing ss }) -- NOTE: This is apparently necessary to get the text cursor to show.
+          continue s'
+    _ -> continue s
+
+
+
+lcheckDupes :: Qso -> AppState -> EventM AppResource AppState
+lcheckDupes qso s = do
+  (dupes, s') <- hamLog s $ findDuplicateQsos qso
+  return $ s' { duplicateQsos = dupes }
+
+
+
+data QsoSortKey = QsoSortTime
+                | QsoSortCallsign
+                | QsoSortLocation
+
+
+lsetAppMode :: AppMode -> AppState -> EventM AppResource AppState
+lsetAppMode m s = return $ s { appMode = m }
+
+
+lhandleEvent_sortQsos :: AppState -> BrickEvent AppResource HamlogEvent -> EventM AppResource (Next AppState)
+lhandleEvent_sortQsos s ev =
+  case appMode s of
+    AppModeSort prev -> do
+      ms' <- case ev of
+               VtyEvent (EvKey (KChar 't') []) -> snd <$> hamLog s (sortLog _qsoTimeStart) >>= lsetAppMode prev >>= return . Just
+               VtyEvent (EvKey (KChar 'c') []) -> snd <$> hamLog s (sortLog _qsoCallsign)  >>= lsetAppMode prev >>= return . Just
+               VtyEvent (EvKey (KChar 'l') []) -> snd <$> hamLog s (sortLog _qsoLocation)  >>= lsetAppMode prev >>= return . Just
+               _ -> return Nothing
+      maybe (continue s) (\s' -> lupdateQsoList 0 s' >>= lupdateQsoForm >>= continue) ms'
+    _ -> continue s
+
+
+lappStatusWidget :: AppState -> Widget AppResource
+lappStatusWidget _ = str $ "(C) Copyright KM6THJ, 2018."
+
+
+-- | Help text, depending on mode.
+lappHelp :: AppState -> Widget AppResource
+lappHelp s = help
+  where help = padTop (Pad 1) $ borderWithLabel (str "Help") body
+        body = case (appMode s) of
+          AppModeList -> str $ "-   n: New qso       Del: Delete qso\n" <>
+                               "- Tab: Edit            s: Sort Log\n" <>
+                               "-   w: Write to file   q: Quit"
+          AppModeQso -> str $ "- Esc: End edit and accept results\n" <>
+                              "- Tab: Cycle entries\n" <>
+                              "- Ctrl-l: Lookup name for callsign"
+          AppModeSort _ -> str $ "- t: Sort by time\n" <>
+                                 "- c: Sort by callsign\n" <>
+                                 "- l: Sort by location"
+          _ -> str ""
+
+
+
+-- | Modes for the UI.
+data AppMode = AppModeList     -- ^ Editing the log list.
+             | AppModeQso      -- ^ Editing the current QSO entry.
+             | AppModeQuestion
+               { appModeQuestionPrev :: AppMode,
+                 appModeQuestionDialog :: Dialog Bool,
+                 appModeQuestionYes :: (AppState -> EventM AppResource AppState),
+                 appModeQuestionNo  :: (AppState -> EventM AppResource AppState) } -- ^ Asking a yes/no question from the user.
+             | AppModeSort
+               { appModeSortPrev :: AppMode }
+
+
+-- | Event handler for the hamlog application.
+lhandleEvent :: AppState -> BrickEvent AppResource HamlogEvent -> EventM AppResource (Next AppState)
+lhandleEvent s ev = do
+
+  case (appMode s) of
+    AppModeList                     -> lhandleEvent_list s ev
+    AppModeQuestion prev dlg yes no -> lhandleEvent_question s ev
+    AppModeQso                      -> lhandleEvent_qso s ev
+    AppModeSort prev                -> lhandleEvent_sortQsos s ev
+
+
+lappCursor :: AppState -> [T.CursorLocation AppResource] -> Maybe (T.CursorLocation AppResource)
+lappCursor = F.focusRingCursor focusRing
+
+
+lappStartEvent s = (snd <$> hamLog s readLog) >>= lupdateQsoList 0 >>= lupdateQsoForm
+    -- let l = emptyLogState { _stateLog = emptyLog { _logQsos = S.fromList $ take 100000 $ repeat emptyQso } }
+    -- let s' = s { logState = l }
+    -- lupdateQsoList 0 s' >>= lupdateQsoForm
+
+
+-- | 'App' to use for constructing the 'Brick' UI.
+app = App { appDraw = lappDraw
+          , appHandleEvent = lhandleEvent
+          , appStartEvent = lappStartEvent
+          , appAttrMap = const $ attrMap defAttr
+                         [
+                           (E.editAttr, V.white `on` V.black)
+                         , (E.editFocusedAttr, V.black `on` V.yellow)
+                         , (invalidFormInputAttr, V.white `on` V.red)
+                         , (focusedFormInputAttr, V.black `on` V.yellow)
+                         , (attrName "qsoList" <> attrName "selected", V.black `on` V.yellow)
+                         , (attrName "qsoList" <> attrName "normal", defAttr)
+                         , (attrName "dupeWarn", V.white `on` V.red)
+                         , (buttonAttr,  V.black `on` V.white)
+                         , (buttonSelectedAttr, V.black `on` V.green)
+                         ]
+          , appChooseCursor = lappCursor }
diff --git a/test/Spec.hs b/test/Spec.hs
new file mode 100644
--- /dev/null
+++ b/test/Spec.hs
@@ -0,0 +1,21 @@
+import Ham.CAT
+import Ham.Data
+
+import qualified Data.ByteString.Char8 as B
+import System.Exit
+
+
+testFreqParse :: Bool
+testFreqParse = mf == Just (MHz 14.123)
+  where
+    mf = parseFrequency (B.pack "FA014123000;")
+
+
+testOpenSerialTiming :: IO ()
+testOpenSerialTiming =
+  where act =
+
+
+main :: IO ()
+main = if all id tests then exitSuccess else exitFailure
+  where tests = [testFreqParse]
