$ git clone http://tcclient.ion.nu/tc_client.git
commit 686df751432e7fa3396179249c8e4e9e8dedfaff
Author: Alicia <...>
Date:   Tue Apr 7 06:49:00 2015 +0200

    Version 0.1

diff --git a/ChangeLog b/ChangeLog
new file mode 100644
index 0000000..d887e2f
--- /dev/null
+++ b/ChangeLog
@@ -0,0 +1,181 @@
+0.30:
+Adjusted the configure script for compatibility with shells that still interpret escaped characters in single-quotes (contributed by Jade)
+Added a /topic command to set the channel topic.
+tc_client-gtk: allow scrollbars around the cams, otherwise resizing the window to a smaller size will be blocked.
+tc_client-gtk: added optional notification sounds and a settings window to configure it.
+tc_client-gtk: added optional logging.
+tc_client-gtk: added a startup dialog instead of requiring commandline arguments.
+tc_client-gtk: display the color of our outgoing messages.
+tc_client-gtk: added an option to run a command for youtube videos being played.
+cursedchat: keep track of our own nickname and print that when we send a message instead of "You:" (contributed by Pamela)
+cursedchat: added timestamps for outgoing messages.
+0.29:
+Added testbuilds.sh to automatically try building the project with different configurations to verify that the latest changes did not break it in some cases.
+Check for endianness macros in the configure script and if they are missing/broken, test endianness and add our own macros.
+If getkey() returns null, print a descriptive message and exit (instead of segfaulting)
+Added optional code to record incoming RTMP packets, add -DRTMP_DEBUG=1 to CFLAGS to enable.
+Added compatibility hacks for apple systems (building onto android ones)
+Handle /help without sending it as a message.
+camviewer: create a new pipe for showing our own cam instead of mixing it in with tc_client's output.
+camviewer: remove associated cameras when a user leaves (in case there was no explicit message about ending the stream)
+camviewer: support older versions of libav which had parts of libavutil in libavcore instead.
+Forked camviewer into tc_client-gtk to keep camviewer as a simpler demo while tc_client-gtk develops into a more complete client interface.
+tc_client-gtk: added a menubar and moved the broadcasting option to there instead of as a button.
+tc_client-gtk: scale cams to fit/fill into the window.
+tc_client-gtk: added a text view for chat, an input field and a user list, switched to a glade file instead of building the GUI manually from code.
+modbot: added a !syncvid command to synchronize video position (or to see a video that was started while having youtube videos disabled in the flash client)
+0.28:
+Delete streams when they stop, to allow reusing stream IDs.
+Added a /camdown command.
+camviewer: worked around the cam streaming issue.
+camviewer: switched to libavresample instead of libswresample (when available)
+modbot: added a !modstats command to see how often there are moderators present.
+modbot: moved the help-text into an HTML document.
+modbot: added a -v/--verbose option to print/log all incoming messages.
+modbot: pass on error messages from youtube-dl when requesting a video fails.
+cursedchat: added history (up/down arrows)
+0.27:
+Added some more compatibility hacks for android.
+Added support for video broadcasting (adding /camup and /video <length> followed by the encoded data for each frame)
+crossbuild.sh: build ncurses and readline for the target platform.
+cursedchat: disable readline's match-listing, which does not work well with the curses interface.
+cursedchat: made tab completion work with nicknames.
+0.26:
+modbot: fixed a segfault when trying to skip more videos than what's in the queue.
+modbot: fixed a segfault when receiving a manual /mbc command but no video is playing.
+cursedchat: added PM buffers/windows which can be switched between with "/pm <name>", just "/pm" to return to the channel buffer.
+cursedchat: added /help output specific to cursedchat, in addition to tc_client's output.
+camviewer: added an experimental audio mixer.
+0.25:
+Handle short reads in the RTMP headers too.
+Added the option -c/--color <number> to pick color instead of getting a random color at startup (contributed by Pamela)
+cursedchat: use default colors (for background in particular)
+cursedchat: added scrolling.
+modbot: fixed singular form of 'videos' in !queue response.
+modbot: update 'requested' (for !requestedby) also when a video is played manually.
+camviewer: added basic mic code (mixing is still missing so it is disabled by default, to enable, configure with environment variable ENABLE_MIC set to 1)
+0.24:
+Fixed endianness of RTMP set-chunk-size handling.
+modbot: fixed a bug where '!wrongrequest' would claim no request was found when (and only when) the request was last in queue.
+modbot: added the options -d/--daemon and -l/--log plus better handling of -h/--help.
+modbot: moved and changed the note about '!approve entire queue' overuse to a note about making sure none of the videos were inappropriate in the "Queue approved" message.
+camviewer: fixed a bug introduced in 0.23 where audio data was handled improperly, resulting in audio/video data being missed.
+camviewer: ignore 0-byte audio/video packets.
+0.23:
+Added the moderator commands /mute and /push2talk (contributed by Jade)
+Set tc_client as a dependency of utils.
+Implemented RTMP message type 1 (set chunk size)
+Writing audio data the same way video data is written.
+camviewer: fixed a bug where joining a channel where no one is on cam resulted in trying to view the cam for "", leading to an empty GtkImage in the row of cams. 
+camviewer: added labels under each image with people's nicknames.
+Added a basic ncurses utility called cursedchat.
+modbot: for manual /mbc, remove the video from goodvids.
+modbot: fixed a bug that caused a segfault when using !badvid if nothing was playing.
+modbot: added a response for !wrongrequest without an argument when no request is found.
+modbot: renamed !whorequested to !requestedby for the sake of immature minds.
+0.22:
+Cleaned up media.c/h which I forgot to clean up before releasing 0.21.
+Detect when someone cams down.
+Added a /names command to list who is online.
+camviewer: fall back to GTK+2 if GTK+3 is not available.
+camviewer: show multiple cameras (cams to view are now picked up from who is on cam when joining and whenever someone cams up instead of from argv[1])
+modbot: list at most 5 not yet approved videos for !queue to avoid sending messages which are too large.
+modbot: fixed a bug where removing a non-approved video from queue using !wrongrequest and that video was the first in queue, the second video in queue wouldn't be played.
+modbot: added !whorequested to see who requested the currently playing video.
+0.21:
+Renamed streamids to chunkids to better match the specification.
+Added a /close command for mods to close cam/mic streams.
+Added /ban, /banlist and /forgive commands.
+Added a /opencam command to receive cam data, and the 'camviewer' utility to handle the cam data (depends on libavcodec/libswscale and gtk+ 3.x), mostly as a reference.
+Do not echo while entering account password at runtime.
+Announce when someone cams up, and list who is on cam when joining.
+modbot: added !wrongrequest to undo a request.
+modbot: allow entering account password at runtime and without echo.
+modbot: added !skip/!skip <number> to skip videos in the queue.
+irchack: translate between /userinfo and WHOIS.
+0.20:
+Fixed amf0 reading of numbers (type 0)
+Added support for sending format 0 RTMP packets (which include the msgid field)
+Handle "/userinfo $request", responding with the account name if logged in and otherwise "tc_client" (which is not a valid tinychat account name but the flash client will show it anyway)
+Added a /priv command, mostly for use by modbot.
+Improved the way RTMP payloads are read from the stream.
+modbot: when someone joins, send a /mbs (start video) command with the current position in the video, but only to that user.
+0.19:
+Got unicode characters working, as it turns out tinychat doesn't use ISO-8859-1 but UTF-16 (which shares character codes with ISO-8859-1 below 256)
+Enable keepalive on the TCP socket.
+irchack: end session upon bad reads from tc_client.
+modbot: handle playlist links properly (youtube-dl gives us a newline-separated list of IDs)
+modbot: added '!approve entire queue', mostly for playlists.
+modbot: allow searching for ID also in !badvid
+0.18:
+This release only affects modbot:
+Switched to using youtube-dl for getting IDs (including proper searching)
+Fixed and clarified the !help text.
+When a video is next to be played and has not been approved for 2 minutes, move the first approved video to the front instead of moving the first video to the back.
+Added '!approve next' which approves the first thing in queue that is not yet approved.
+Added !time to get the amount of time left for the current video (mostly for debugging)
+Handle /mbsk (seeking)
+0.17:
+irchack: translate tc_client's "No such nick" to IRC's 401 (No such nick/channel)
+modbot: mark manually started videos as playing.
+modbot: fixed a memory error in list_del()
+Added a configure script to better handle platform differences (primarily that some systems need to link to libiconv, for others it is provided by libc)
+crossbuild.sh: build libiconv if necessary.
+modbot: added more responses to !approve to make it less confusing.
+modbot: pass -- to youtube-dl before the ID to avoid issues when IDs start with -
+0.16:
+Get and print the channel topic (contributed by Jade)
+irchack: fork and keep accepting connections.
+irchack: translate IRC's "\x01ACTION stuff\x01" (/me) into "*stuff*" for tc_client.
+modbot: add a 100ms delay between the lines of !help to prevent throttling.
+modbot: handle manual /mbs and /mbc commands (remove from queue, mark as good for /mbs)
+Added a /help command to list commands handled by tc_client at runtime.
+irchack: use USER and PASS IRC commands to get the tinychat account to login as.
+0.15:
+Fixed a bug introduced with the new argument handling in 0.14
+Prompt for password if a username is given with -u/--user but no password (-p/--pass) is given.
+Turn account names lowercase to comply with tinychat's quirks.
+Handle networking being down at startup more graciously.
+Added modbot.c, a bot that deals with playing videos.
+0.14:
+Use iconv to deal with tinychat's ISO-8859-1 instead of the wcs functions.
+irchack: only listen on 127.0.0.1 (localhost)
+Added -u/--user and -p/--pass options to log into tinychat accounts.
+0.13:
+Check the validity of nicknames before switching.
+Roll our own endianness conversion functions since the ones provided by libc are not standardized.
+0.12:
+Wrote a sender for the RTMP code and changed the AMF0 writer to use it, plus working directly with the rtmp struct instead of an intermediate amfmsg struct.
+Added handling of moderators turning into regular users, or 'deop' (contributed by Jade)
+Handle new nicknames being in use when using /nick, and thus failing (contributed by Jade)
+0.11:
+Rewrote the RTMP code to read from the socket instead of from a buffer, this will prevent messages from being dropped when they are larger than the buffer.
+0.10:
+irchack: stay connected if joining a channel fails and tell the IRC client if a channel password is required.
+irchack: keep listening for connections and accept the next after a session ends.
+0.9:
+Added compatibility workarounds for android.
+Keep track of who is a moderator. (contributed by Jade)
+Added crossbuild.sh script to automatically cross-compile tc_client and curl (dependency) for the given host-triplet.
+0.8:
+irchack: convert tc_client's ANSI codes to IRC color codes.
+irchack: convert IRC color codes to '/color <number>' commands for tc_client.
+Made it possible to turn off/on colors being displayed with '/color off' and '/color on'
+0.7:
+Added command handling (/color <number>, /colors, /nick <newnick>, and adding the privacy field for /msg)
+0.6:
+Fixed a bug in the ID list that kept IDs from being removed correctly.
+Show colors using ANSI escape codes.
+0.5:
+Fixed a bug in irchack.c that sent the JOIN confirmation to the wrong file descriptor.
+Avoid sending empty lines.
+Handle messages related to getting kicked out/banned from a channel. (contributed by Jade)
+0.4:
+Adjustments for portability: nested functions are a GCC extension and should not be used, include headers needed on other systems.
+Use memcpy in some places instead of *x=y and x=*y to avoid alignment issues.
+0.3:
+Handle 'joins', 'join', 'nick' and 'quit' messages from the server (contributed by Jade)
+Moved the AMF message writing functions into a separate source file.
+Added irchack.c, a simple application that acts as an IRC server mirroring a tinychat channel using tc_client.
+0.2:
+Added support for non-ascii characters (sent as ISO-8859-1 to/from the server)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..dba13ed
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,661 @@
+                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+our General Public Licenses are 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.
+
+  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.
+
+  Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+  A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate.  Many developers of free software are heartened and
+encouraged by the resulting cooperation.  However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+  The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community.  It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server.  Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+  An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals.  This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+  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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
+
+  Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software.  This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+  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 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 work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source.  For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code.  There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+  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 AGPL, see
+<http://www.gnu.org/licenses/>.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..3e4096d
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,12 @@
+VERSION=0.1
+CFLAGS=-g3 -Wall $(shell curl-config --cflags)
+LIBS=-g3 $(shell curl-config --libs)
+
+tc_client: client.o amfparser.o rtmp.o numlist.o
+ $(CC) $(LDFLAGS) $^ $(LIBS) -o $@
+
+clean:
+ rm -f client.o amfparser.o rtmp.o numlist.o tc_client
+
+tarball:
+ tar -cJf tc_client-$(VERSION).tar.xz --transform='s|^|tc_client-$(VERSION)/|' Makefile client.c amfparser.c rtmp.c numlist.c amfparser.h rtmp.h numlist.h LICENSE README
diff --git a/README b/README
new file mode 100644
index 0000000..d2293ce
--- /dev/null
+++ b/README
@@ -0,0 +1,11 @@
+This is a pre-release of tc_client, it's still not ready for a release beyond sharing it with a small group, most significantly because the channel is hardcoded.
+
+Some other notes about tc_client in its current state (things that should be fixed):
+*there is no real user interface, to send a message you just type it and it might get cut off by incoming messages, it'll be ugly.
+*PMs can be sent by /msg <nickname> <message> and replies appear similarly 
+*you can't log in with an account and thus not to mod stuff, I don't know how this works protocol-wise
+
+Some things that will probably never change:
+*tc_client can't view people's webcams or listen to mics
+*tc_client can't stream/broadcast your webcam/mic
+*tc_client probably won't ever play youtube videos (although you can see when one is launched and get the video ID because it is sent as a message and can then open it yourself)
diff --git a/amfparser.c b/amfparser.c
new file mode 100644
index 0000000..b71dc81
--- /dev/null
+++ b/amfparser.c
@@ -0,0 +1,230 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <string.h>
+#include <stdlib.h>
+#include <arpa/inet.h>
+#include <stdio.h> // For debugging
+#include "amfparser.h"
+
+char amf_comparestrings_c(struct amfstring* a, const char* b)
+{
+  int blen=strlen(b);
+  if(a->length!=blen){return 0;}
+  return !strncmp(a->string, b, blen);
+}
+
+char amf_comparestrings(struct amfstring* a, struct amfstring* b)
+{
+  if(a->length!=b->length){return 0;}
+  return !strncmp(a->string, b->string, a->length);
+}
+
+char amf_compareitems(struct amfitem* a, struct amfitem* b)
+{
+  if(a->type!=b->type){return 0;}
+  char ret=0;
+  switch(a->type)
+  {
+  case AMF_STRING:
+    ret=amf_comparestrings(&a->string, &b->string);
+    break;
+  }
+  return ret;
+}
+
+struct amfitem* amf_newitem(struct amf* amf)
+{
+  ++amf->itemcount;
+  amf->items=realloc(amf->items, sizeof(struct amfitem)*amf->itemcount);
+  return &amf->items[amf->itemcount-1];
+}
+
+struct amf* amf_parse(const unsigned char* buf, int len)
+{
+  struct amf* amf=malloc(sizeof(struct amf));
+  amf->items=0;
+  amf->itemcount=0;
+  struct amfitem* item;
+  struct amfobject* obj;
+  int i;
+  const unsigned char* end=&buf[len];
+  while(buf<end)
+  {
+    obj=0;
+    // Figure out if the last item is an unfinished object
+    if(amf->itemcount && amf->items[amf->itemcount-1].type==AMF_OBJECT && !amf->items[amf->itemcount-1].object.ended)
+    {
+      obj=&amf->items[amf->itemcount-1].object;
+      // TODO: recurse into unfinished member-objects (unimportant, I haven't seen any objects within objects so far)
+      // Add member and set name
+      i=ntohs(*(short*)buf);
+      buf=&buf[sizeof(short)];
+      if(buf[i]!=9) // 9=end-of-object
+      {
+        ++obj->membercount;
+        obj->members=realloc(obj->members, sizeof(struct amfobjectmember)*obj->membercount);
+        obj->members[obj->membercount-1].name=strndup((char*)buf, i);
+        buf=&buf[i];
+      }else{ // String-length 0, 
+        obj->ended=1;
+        obj=0;
+        buf=&buf[1]; // Skip object-end
+      }
+    }
+    switch(buf[0])
+    {
+    case 0:
+      buf=&buf[1];
+      if(obj)
+        item=&obj->members[obj->membercount-1].value;
+      else
+        item=amf_newitem(amf);
+      item->type=AMF_NUMBER;
+      item->number=*(double*)buf;
+      buf=&buf[sizeof(double)];
+      break;
+    case 1:
+      buf=&buf[1];
+      if(obj)
+        item=&obj->members[obj->membercount-1].value;
+      else
+        item=amf_newitem(amf);
+      item->type=AMF_BOOL;
+      item->boolean=buf[0];
+      buf=&buf[1];
+      break;
+    case 2:
+      buf=&buf[1];
+      if(obj)
+        item=&obj->members[obj->membercount-1].value;
+      else
+        item=amf_newitem(amf);
+      i=ntohs(*(short*)buf);
+      buf=&buf[sizeof(short)];
+      item->type=AMF_STRING;
+      item->string.length=i;
+      item->string.string=strndup((char*)buf, i);
+// printf("Allocated AMF string '%s' (%p)\n", item->string.string, item->string.string);
+      buf=&buf[i];
+      break;
+    case 3:
+      buf=&buf[1];
+      if(obj)
+        item=&obj->members[obj->membercount-1].value;
+      else
+        item=amf_newitem(amf);
+      item->type=AMF_OBJECT;
+      item->object.members=0;
+      item->object.membercount=0;
+      item->object.ended=0;
+      break;
+    case 5: // Null element
+      buf=&buf[1];
+      break;
+    default:
+      printf("Unknown datatype %i\n", (int)buf[0]);
+      buf=end;
+      break;
+    }
+  }
+  return amf;
+}
+
+void amf_freeitem(struct amfitem* item)
+{
+  if(item->type==AMF_STRING)
+  {
+    free(item->string.string);
+  }
+  else if(item->type==AMF_OBJECT)
+  {
+    int i;
+    for(i=0; i<item->object.membercount; ++i)
+    {
+      free((void*)item->object.members[i].name);
+      amf_freeitem(&item->object.members[i].value);
+    }
+    free(item->object.members);
+  }
+}
+
+void amf_free(struct amf* amf)
+{
+  int i;
+  for(i=0; i<amf->itemcount; ++i)
+  {
+    amf_freeitem(&amf->items[i]);
+  }
+  free(amf->items);
+  free(amf);
+}
+
+void printamfobject(struct amfobject* obj, int indent)
+{
+  int i, j;
+  for(i=0; i<obj->membercount; ++i)
+  {
+    for(j=0; j<indent; ++j){printf("  ");}
+    printf("%s: ", obj->members[i].name);
+    if(obj->members[i].value.type==AMF_NUMBER)
+    {
+      printf("Number: %f\n", obj->members[i].value.number);
+    }
+    else if(obj->members[i].value.type==AMF_BOOL)
+    {
+      printf("Bool: %s\n", obj->members[i].value.boolean?"True":"False");
+    }
+    else if(obj->members[i].value.type==AMF_STRING)
+    {
+      printf("String: %s\n", obj->members[i].value.string.string);
+    }
+    else if(obj->members[i].value.type==AMF_OBJECT)
+    {
+      printf("Object:\n");
+      printamfobject(&obj->members[i].value.object, indent+1);
+    }
+    else{printf("(Unhandled type)\n");}
+  }
+}
+
+void printamf(struct amf* amf)
+{
+  printf("amf: %p\n", amf);
+  printf("amf->itemcount: %i\n", amf->itemcount);
+  int i;
+  for(i=0; i<amf->itemcount; ++i)
+  {
+    if(amf->items[i].type==AMF_NUMBER)
+    {
+      printf("Number: %f\n", amf->items[i].number);
+    }
+    else if(amf->items[i].type==AMF_BOOL)
+    {
+      printf("Bool: %s\n", amf->items[i].boolean?"True":"False");
+    }
+    else if(amf->items[i].type==AMF_STRING)
+    {
+      printf("String: '%s'\n", amf->items[i].string.string);
+    }
+    else if(amf->items[i].type==AMF_OBJECT)
+    {
+      printf("Object:\n");
+      printamfobject(&amf->items[i].object, 1);
+    }
+    else{printf("(Unhandled type)\n");}
+  }
+}
diff --git a/amfparser.h b/amfparser.h
new file mode 100644
index 0000000..fda86f0
--- /dev/null
+++ b/amfparser.h
@@ -0,0 +1,69 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+enum
+{
+  AMF_NUMBER,
+  AMF_BOOL,
+  AMF_STRING,
+  AMF_OBJECT
+};
+
+struct amfstring
+{
+  int length;
+  char* string;
+};
+
+struct amfobject
+{
+  int membercount;
+  struct amfobjectmember* members;
+  char ended; // Used in the parsing process
+};
+
+struct amfitem
+{
+  char type;
+  union
+  {
+    double number;
+    char boolean;
+    struct amfstring string;
+    struct amfobject object;
+  };
+};
+
+struct amfobjectmember
+{
+  const char* name;
+  struct amfitem value;
+};
+
+struct amf
+{
+  struct amfitem* items;
+  int itemcount;
+};
+
+extern char amf_comparestrings_c(struct amfstring* a, const char* b);
+extern char amf_comparestrings(struct amfstring* a, struct amfstring* b);
+extern char amf_compareitems(struct amfitem* a, struct amfitem* b);
+
+extern struct amf* amf_parse(const unsigned char* buf, int len);
+extern void amf_free(struct amf* amf);
+
+extern void printamf(struct amf* amf);
diff --git a/amfwriter.c b/amfwriter.c
new file mode 100644
index 0000000..3fc07dc
--- /dev/null
+++ b/amfwriter.c
@@ -0,0 +1,106 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014-2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+#include <unistd.h>
+#include "endian.h"
+#include "rtmp.h"
+#include "amfwriter.h"
+
+void amfinit(struct rtmp* msg, unsigned int chunkid)
+{
+  msg->type=RTMP_AMF0;
+  msg->chunkid=chunkid;
+  msg->length=0;
+  msg->msgid=0;
+  msg->buf=0;
+}
+
+void amfnum(struct rtmp* msg, double v)
+{
+  unsigned long long* endian=(void*)&v;
+  *endian=be64(*endian);
+  int offset=msg->length;
+  msg->length+=1+sizeof(double);
+  msg->buf=realloc(msg->buf, msg->length);
+  unsigned char* type=msg->buf+offset;
+  type[0]='\x00';
+  memcpy(msg->buf+offset+1, &v, sizeof(v));
+}
+
+void amfbool(struct rtmp* msg, char v)
+{
+  int offset=msg->length;
+  msg->length+=2;
+  msg->buf=realloc(msg->buf, msg->length);
+  unsigned char* x=msg->buf+offset;
+  x[0]='\x01';
+  x[1]=!!v;
+}
+
+void amfstring(struct rtmp* msg, const char* string)
+{
+  int len=strlen(string);
+  int offset=msg->length;
+  msg->length+=3+len;
+  msg->buf=realloc(msg->buf, msg->length);
+  unsigned char* type=msg->buf+offset;
+  type[0]='\x02';
+  uint16_t* strlength=(uint16_t*)(msg->buf+offset+1);
+  *strlength=be16(len);
+  memcpy(msg->buf+offset+3, string, len);
+}
+
+void amfobjstart(struct rtmp* msg)
+{
+  int offset=msg->length;
+  msg->length+=1;
+  msg->buf=realloc(msg->buf, msg->length);
+  unsigned char* type=msg->buf+offset;
+  type[0]='\x03';
+}
+
+void amfobjitem(struct rtmp* msg, char* name)
+{
+  int len=strlen(name);
+  int offset=msg->length;
+  msg->length+=2+len;
+  msg->buf=realloc(msg->buf, msg->length);
+  uint16_t* strlength=(uint16_t*)(msg->buf+offset);
+  *strlength=be16(len);
+  memcpy(msg->buf+offset+2, name, len);
+}
+
+void amfobjend(struct rtmp* msg)
+{
+  amfobjitem(msg, "");
+  int offset=msg->length;
+  msg->length+=1;
+  msg->buf=realloc(msg->buf, msg->length);
+  unsigned char* type=msg->buf+offset;
+  type[0]='\x09';
+}
+
+void amfnull(struct rtmp* msg)
+{
+  int offset=msg->length;
+  msg->length+=1;
+  msg->buf=realloc(msg->buf, msg->length);
+  unsigned char* type=msg->buf+offset;
+  type[0]='\x05';
+}
diff --git a/amfwriter.h b/amfwriter.h
new file mode 100644
index 0000000..62f735e
--- /dev/null
+++ b/amfwriter.h
@@ -0,0 +1,27 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014-2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+
+extern void amfinit(struct rtmp* msg, unsigned int streamid);
+extern void amfnum(struct rtmp* msg, double v);
+extern void amfbool(struct rtmp* msg, char v);
+extern void amfstring(struct rtmp* msg, const char* string);
+extern void amfobjstart(struct rtmp* msg);
+extern void amfobjitem(struct rtmp* msg, char* name);
+extern void amfobjend(struct rtmp* msg);
+extern void amfnull(struct rtmp* msg);
+
+#define amfsend(rtmp,sock) rtmp_send(sock,rtmp); free((rtmp)->buf); (rtmp)->buf=0
diff --git a/client.c b/client.c
new file mode 100644
index 0000000..451d275
--- /dev/null
+++ b/client.c
@@ -0,0 +1,482 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <string.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <netdb.h>
+#include <poll.h>
+#include <curl/curl.h>
+#include "rtmp.h"
+#include "amfparser.h"
+#include "numlist.h"
+
+struct amfmsg
+{
+  unsigned int len;
+  unsigned char* buf;
+};
+
+unsigned int flip(unsigned int bits, int bytecount)
+{
+  unsigned int ret=0;
+  unsigned char* bytes=(unsigned char*)&bits;
+  unsigned char* retb=(unsigned char*)&ret;
+  int i;
+  for(i=0; i<bytecount; ++i)
+  {
+    retb[i]=bytes[bytecount-1-i];
+  }
+  return ret;
+}
+
+void amfinit(struct amfmsg* msg)
+{
+  msg->len=0;
+  msg->buf=malloc(sizeof(struct rtmph));
+}
+
+void amfsend(struct amfmsg* msg, int sock)
+{
+  struct rtmph* head=(struct rtmph*)msg->buf;
+  head->streamid=3;
+  head->fmt=0;
+  head->timestamp=0; // Time is irrelevant
+  head->length=flip(msg->len, 3);
+  head->type=20;
+  head->msgid=0;
+  // Send 128 bytes at a time separated by 0xc3 (because apparently that's something RTMP requires)
+// printf("Writing %i-byte message\n", msg->len);
+  write(sock, msg->buf, sizeof(struct rtmph));
+  unsigned char* pos=msg->buf+sizeof(struct rtmph);
+  while(msg->len>0)
+  {
+    int w;
+    if(msg->len>128)
+    {
+      w=write(sock, pos, 128);
+      w+=write(sock, "\xc3", 1);
+      msg->len-=128;
+    }else{
+      w=write(sock, pos, msg->len);
+      msg->len=0;
+    }
+// printf("Wrote %i bytes\n", w);
+    pos+=128;
+  }
+  free(msg->buf);
+  msg->buf=0;
+}
+
+void amfnum(struct amfmsg* msg, double v)
+{
+  int offset=sizeof(struct rtmph)+msg->len;
+  msg->len+=1+sizeof(double);
+  msg->buf=realloc(msg->buf, sizeof(struct rtmph)+msg->len);
+  unsigned char* type=msg->buf+offset;
+  type[0]='\x00';
+  double* value=(double*)(msg->buf+offset+1);
+  *value=v;
+}
+
+void amfbool(struct amfmsg* msg, char v)
+{
+  int offset=sizeof(struct rtmph)+msg->len;
+  msg->len+=2;
+  msg->buf=realloc(msg->buf, sizeof(struct rtmph)+msg->len);
+  unsigned char* x=msg->buf+offset;
+  x[0]='\x01';
+  x[1]=!!v;
+}
+
+void amfstring(struct amfmsg* msg, char* string)
+{
+  int len=strlen(string);
+  int offset=sizeof(struct rtmph)+msg->len;
+  msg->len+=3+len;
+  msg->buf=realloc(msg->buf, sizeof(struct rtmph)+msg->len);
+  unsigned char* type=msg->buf+offset;
+  type[0]='\x02';
+  uint16_t* strlength=(uint16_t*)(msg->buf+offset+1);
+  *strlength=htons(len);
+  memcpy(msg->buf+offset+3, string, len);
+}
+
+void amfobjstart(struct amfmsg* msg)
+{
+  int offset=sizeof(struct rtmph)+msg->len;
+  msg->len+=1;
+  msg->buf=realloc(msg->buf, sizeof(struct rtmph)+msg->len);
+  unsigned char* type=msg->buf+offset;
+  type[0]='\x03';
+}
+
+void amfobjitem(struct amfmsg* msg, char* name)
+{
+  int len=strlen(name);
+  int offset=sizeof(struct rtmph)+msg->len;
+  msg->len+=2+len;
+  msg->buf=realloc(msg->buf, sizeof(struct rtmph)+msg->len);
+  uint16_t* strlength=(uint16_t*)(msg->buf+offset);
+  *strlength=htons(len);
+  memcpy(msg->buf+offset+2, name, len);
+}
+
+void amfobjend(struct amfmsg* msg)
+{
+  amfobjitem(msg, "");
+  int offset=sizeof(struct rtmph)+msg->len;
+  msg->len+=1;
+  msg->buf=realloc(msg->buf, sizeof(struct rtmph)+msg->len);
+  unsigned char* type=msg->buf+offset;
+  type[0]='\x09';
+}
+
+void amfnull(struct amfmsg* msg)
+{
+  int offset=sizeof(struct rtmph)+msg->len;
+  msg->len+=1;
+  msg->buf=realloc(msg->buf, sizeof(struct rtmph)+msg->len);
+  unsigned char* type=msg->buf+offset;
+  type[0]='\x05';
+}
+
+void b_read(int sock, void* buf, size_t len)
+{
+  while(len>0)
+  {
+    size_t r=read(sock, buf, len);
+    len-=r;
+    buf+=r;
+  }
+}
+
+char* http_get(char* url)
+{
+  CURL* curl=curl_easy_init();
+  if(!curl){return 0;}
+  curl_easy_setopt(curl, CURLOPT_URL, url);
+  char* buf=0;
+  int len=0;
+  size_t writehttp(char* ptr, size_t size, size_t nmemb, void* x)
+  {
+    size*=nmemb;
+    buf=realloc(buf, len+size+1);
+    memcpy(&buf[len], ptr, size);
+    len+=size;
+    buf[len]=0;
+    return size;
+  }
+  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writehttp);
+  char err[CURL_ERROR_SIZE];
+  curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, err);
+  if(curl_easy_perform(curl)){curl_easy_cleanup(curl); printf(err); return 0;}
+  curl_easy_cleanup(curl);
+  return buf; // should be free()d when no longer needed
+}
+
+char* gethost(char *channel, char *password)
+{
+  int urllen;
+  if(password)
+  {
+    urllen=strlen("http://tinychat.com/api/find.room/?site=tinychat&password=0")+strlen(channel)+strlen(password);
+  }else{
+    urllen=strlen("http://tinychat.com/api/find.room/?site=tinychat0")+strlen(channel);
+  }
+  char url[urllen];
+  if(password)
+  {
+    sprintf(url, "http://tinychat.com/api/find.room/%s?site=tinychat&password=%s", channel, password);
+  }else{
+    sprintf(url, "http://tinychat.com/api/find.room/%s?site=tinychat", channel);
+  }
+  char *response=http_get(url);
+  //response contains result='(OK|RES)|PW' (latter means a password is required)
+  char* result=strstr(response, "result='");
+  if(!result){printf("No result\n"); exit(-1); return 0;}
+  result+=strlen("result='");
+  // Handle the result value
+  if(!strncmp(result, "PW", 2)){printf("Password required\n"); exit(-1); return 0;}
+  if(strncmp(result, "OK", 2) && strncmp(result, "RES", 3)){printf("Result not OK\n"); exit(-1); return 0;}
+  // Find and extract the server responsible for this channel
+  char* rtmp=strstr(response, "rtmp='rtmp://");
+  if(!rtmp){printf("No rtmp found.\n"); exit(-1); return 0;}
+  rtmp+=strlen("rtmp='rtmp://");
+  int len;
+  for(len=0; rtmp[len] && rtmp[len]!='/'; ++len);
+  char* host=strndup(rtmp, len);
+  free(response);
+  return host;
+}
+
+char* getkey(char* id, char* channel)
+{
+  char url[strlen("http://tinychat.com/api/captcha/check.php?guest%5Fid=&room=tinychat%5E0")+strlen(id)+strlen(channel)];
+  sprintf(url, "http://tinychat.com/api/captcha/check.php?guest%%5Fid=%s&room=tinychat%%5E%s", id, channel);
+  char *response=http_get(url);
+  char* key=strstr(response, "\"key\":\"");
+
+  if(!key){return 0;}
+  key+=7;
+  char* keyend=strchr(key, '"');
+  if(!keyend){return 0;}
+  char* backslash;
+  while((backslash=strchr(key, '\\')))
+  {
+    memmove(backslash, &backslash[1], strlen(backslash));
+    --keyend;
+  }
+  key=strndup(key, keyend-key);
+  free(response);
+  return key;
+}
+
+int main(int argc, char** argv)
+{
+  if(argc<3)
+   {
+    printf("Usage: %s <roomname> <nickname> [password]\n", argv[0]);
+    return 1;
+  }
+  char* channel=argv[1];
+  char* nickname=argv[2];
+  char* password=(argc>3?argv[3]:0);
+  char* server=gethost(channel, password);
+  struct addrinfo* res;
+  // Separate IP/domain and port
+  char* port=strchr(server, ':');
+  if(!port){return 3;}
+  port[0]=0;
+  ++port;
+  // Connect
+  getaddrinfo(server, port, 0, &res);
+  int sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if(connect(sock, res->ai_addr, res->ai_addrlen))
+  {
+    perror("Failed to connect");
+    freeaddrinfo(res);
+    return 1;
+  }
+  freeaddrinfo(res);
+  int random=open("/dev/urandom", O_RDONLY);
+  // RTMP handshake
+  unsigned char handshake[1536];
+  read(random, handshake, 1536);
+  close(random);
+  write(sock, "\x03", 1); // Send 0x03 and 1536 bytes of random junk
+  write(sock, handshake, 1536);
+  read(sock, handshake, 1); // Receive server's 0x03+junk
+  b_read(sock, handshake, 1536);
+  write(sock, handshake, 1536); // Send server's junk back
+  b_read(sock, handshake, 1536); // Read our junk back, we don't bother checking that it's the same
+  printf("Handshake complete\n");
+  // Handshake complete, send connect request
+  struct amfmsg amf;
+  amfinit(&amf);
+  amfstring(&amf, "connect");
+  amfnum(&amf, 0);
+  amfobjstart(&amf);
+    amfobjitem(&amf, "app");
+    amfstring(&amf, "tinyconf");
+
+    amfobjitem(&amf, "flashVer");
+    amfstring(&amf, "LNX 11,2,202,424");
+
+    amfobjitem(&amf, "swfUrl");
+    amfstring(&amf, "http://tinychat.com/embed/Tinychat-11.1-1.0.0.0602.swf?version=1.0.0.0602/[[DYNAMIC]]/8");
+
+    amfobjitem(&amf, "tcUrl");
+    char str[strlen("rtmp://:/tinyconf0")+strlen(server)+strlen(port)];
+    sprintf(str, "rtmp://%s:%s/tinyconf", server, port);
+    amfstring(&amf, str);
+
+    amfobjitem(&amf, "fpad");
+    amfbool(&amf, 0);
+
+    amfobjitem(&amf, "capabilities");
+    amfnum(&amf, 0);
+
+    amfobjitem(&amf, "audioCodecs");
+    amfnum(&amf, 0);
+
+    amfobjitem(&amf, "videoCodecs");
+    amfnum(&amf, 0);
+
+    amfobjitem(&amf, "videoFunction");
+    amfnum(&amf, 0);
+
+    amfobjitem(&amf, "pageUrl");
+    char pageurl[strlen("http://tinychat.com/0") + strlen(channel)];
+    sprintf(pageurl, "http://tinychat.com/%s", channel);
+    amfstring(&amf, pageurl);
+
+    amfobjitem(&amf, "objectEncoding");
+    amfnum(&amf, 0);
+    amfobjend(&amf);
+    amfstring(&amf, channel);
+    amfstring(&amf, "none");
+    amfstring(&amf, "show"); // This item is called roomtype in the same HTTP response that gives us the server (IP+port) to connect to
+    amfstring(&amf, "tinychat");
+    amfstring(&amf, "");
+    amfsend(&amf, sock);
+
+    unsigned char buf[2048];
+    int len=read(sock, buf, 2048);
+//  printf("Received %i byte response\n", len);
+/* Debugging
+  int f=open("output", O_WRONLY|O_CREAT|O_TRUNC, 0644);
+  write(f, buf, len);
+  close(f);
+*/
+
+/* As they appear in the flash client:
+    char* colors[]={
+      "#1965b6,en",
+      "#32a5d9,en",
+      "#7db257,en",
+      "#a78901,en",
+      "#9d5bb5,en",
+      "#5c1a7a,en",
+      "#c53332,en",
+      "#821615,en",
+      "#a08f23,en",
+      "#487d21,en",
+      "#c356a3,en",
+      "#1d82eb,en",
+      "#919104,en",
+      "#00a990,en",
+      "#b9807f,en",
+      "#7bb224,en"
+    };
+*/
+    char* colors[]={ // Sorted like a rainbow
+      "#821615,en",
+      "#c53332,en",
+      "#a08f23,en",
+      "#a78901,en",
+      "#919104,en",
+      "#7bb224,en",
+      "#7db257,en",
+      "#487d21,en",
+      "#00a990,en",
+      "#32a5d9,en",
+      "#1d82eb,en",
+      "#1965b6,en",
+      "#5c1a7a,en",
+      "#9d5bb5,en",
+      "#c356a3,en",
+      "#b9807f,en"
+    };
+    unsigned int currentcolor=0;
+
+//  int outnum=2; (Debugging, number for output filenames)
+    struct pollfd pfd[2];
+    pfd[0].fd=0;
+    pfd[0].events=POLLIN;
+    pfd[0].revents=0;
+    pfd[1].fd=sock;
+    pfd[1].events=POLLIN;
+    pfd[1].revents=0;
+    while(1)
+    {
+    // Poll for input, very crude chat UI
+    poll(pfd, 2, -1);
+    if(pfd[0].revents) // Got input, send a privmsg command
+    {
+      pfd[0].revents=0;
+      len=read(0, buf, 2047);
+      while(len>0 && (buf[len-1]=='\n'||buf[len-1]=='\r')){--len;}
+      buf[len]=0;
+      char* msg=tonumlist((char*)buf);
+      amfinit(&amf);
+      amfstring(&amf, "privmsg");
+      amfnum(&amf, 0);
+      amfnull(&amf);
+      amfstring(&amf, msg);
+      // The alternating color thing is an unnecessary but fun feature
+      amfstring(&amf, colors[currentcolor%16]);
+      amfsend(&amf, sock);
+      ++currentcolor;
+      free(msg);
+      continue;
+    }
+    // Got data from server
+    pfd[1].revents=0;
+// TODO: This should be done differently, first reading one byte to get the size of the header, then read the rest of the header and thus get the length of the content
+    len=read(sock, buf, 2048);
+//  printf("Received %i byte response\n", len);
+    if(!len){printf("Server disconnected\n"); break;}
+/* Debugging
+  char name[128];
+  sprintf(name, "output%i", outnum);
+  f=open(name, O_WRONLY|O_CREAT|O_TRUNC, 0644);
+  write(f, buf, len);
+  close(f);
+*/
+    // Separate and handle all AMF0 buffers in the RTMP stream
+    unsigned char* rtmp_pos=buf;
+    int rtmp_len;
+    unsigned char* amfbuf;
+    while((amfbuf=rtmp_getamf(&rtmp_pos, &len, &rtmp_len)))
+    {
+      struct amf* amfin=amf_parse(amfbuf, rtmp_len);
+      if(amfin->itemcount>0 && amfin->items[0].type==AMF_STRING)
+      {
+//        printf("Got command: '%s'\n", amfin->items[0].string.string);
+        if(!strcmp(amfin->items[0].string.string, "_error"))
+          printamf(amfin);
+      }
+      if(amfin->itemcount>0 && amfin->items[0].type==AMF_STRING && amf_comparestrings_c(&amfin->items[0].string, "registered") && amfin->items[amfin->itemcount-1].type==AMF_STRING)
+      {
+        char* id=amfin->items[amfin->itemcount-1].string.string;
+        printf("Guest ID: %s\n", id);
+        char* key=getkey(id, channel);
+
+        amfinit(&amf);
+        amfstring(&amf, "cauth");
+        amfnum(&amf, 0);
+        amfnull(&amf); // Means nothing but is apparently critically important for cauth at least
+        amfstring(&amf, key);
+        amfsend(&amf, sock);
+        free(key);
+
+        amfinit(&amf);
+        amfstring(&amf, "nick");
+        amfnum(&amf, 0);
+        amfnull(&amf);
+        amfstring(&amf, nickname);
+        amfsend(&amf, sock);
+      }
+      // Items for privmsg: 0=cmd, 2=channel, 3=msg, 4=color/lang, 5=nick
+      if(amfin->itemcount>0 && amfin->items[0].type==AMF_STRING && amf_comparestrings_c(&amfin->items[0].string, "privmsg") && amfin->items[3].type==AMF_STRING && amfin->items[5].type==AMF_STRING)
+      {
+        char* msg=fromnumlist(amfin->items[3].string.string);
+        // Timestamps, e.g. "[hh:mm] name: message"
+        time_t timestamp=time(0);
+        struct tm* t=localtime(&timestamp);
+        printf("[%02i:%02i] %s: %s\n", t->tm_hour, t->tm_min, amfin->items[5].string.string, msg);
+        free(msg);
+      }
+      amf_free(amfin);
+    }
+//    ++outnum; (Debugging)
+  }
+  return 0;
+}
diff --git a/colors.c b/colors.c
new file mode 100644
index 0000000..28969eb
--- /dev/null
+++ b/colors.c
@@ -0,0 +1,70 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014-2015  alicia@ion.nu
+    Copyright (C) 2015  Pamela Hiatt
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <string.h>
+#include "colors.h"
+
+// Sorted like rainbows
+const char* colors[COLORCOUNT]={ // The 16 colors accepted by the flash client
+  "#821615,en",
+  "#c53332,en",
+  "#a08f23,en",
+  "#a78901,en",
+  "#919104,en",
+  "#7bb224,en",
+  "#7db257,en",
+  "#487d21,en",
+  "#a990,en",
+  "#32a5d9,en",
+  "#1d82eb,en",
+  "#1965b6,en",
+  "#5c1a7a,en",
+  "#9d5bb5,en",
+  "#c356a3,en",
+  "#b9807f,en"
+};
+
+const char* termcolors[COLORCOUNT]={ // Equivalent color codes for ANSI escape sequences
+  "31",
+  "31;1",
+  "33",
+  "33",
+  "33;1",
+  "32;1",
+  "32;1",
+  "32",
+  "36",
+  "34;1",
+  "34;1",
+  "34",
+  "35",
+  "35;1",
+  "35;1",
+  "35;1"
+};
+
+unsigned int currentcolor=COLORCOUNT;
+
+const char* resolvecolor(const char* tc_color)
+{
+  int i;
+  for(i=0; i<COLORCOUNT; ++i)
+  {
+    if(!strcmp(colors[i], tc_color)){return termcolors[i];}
+  }
+  return "0";
+}
diff --git a/colors.h b/colors.h
new file mode 100644
index 0000000..baa5d9b
--- /dev/null
+++ b/colors.h
@@ -0,0 +1,22 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014-2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#define COLORCOUNT 16
+extern const char* colors[];
+extern const char* termcolors[];
+extern unsigned int currentcolor;
+
+extern const char* resolvecolor(const char* tc_color);
diff --git a/configure b/configure
new file mode 100755
index 0000000..6d37dbf
--- /dev/null
+++ b/configure
@@ -0,0 +1,181 @@
+#!/bin/sh
+# Just a simple handwritten configure
+rm -f config.mk
+
+host=''
+while [ "$#" -gt 0 ]; do
+  case "$1" in
+  --host=*) host="`echo "$1" | sed -e 's/--host=//'`";;
+  esac
+  shift
+done
+
+printf 'Checking for a C compiler... '
+if [ "x$CC" = "x" -a "x$host" != "x" ]; then
+  if which "${host}-cc" > /dev/null 2> /dev/null; then CC="${host}-cc"
+  elif which "${host}-gcc" > /dev/null 2> /dev/null; then CC="${host}-gcc"
+  elif which "${host}-clang" > /dev/null 2> /dev/null; then CC="${host}-clang"
+  fi
+fi
+if [ "x$CC" = "x" ]; then
+  if which cc > /dev/null 2> /dev/null; then CC=cc
+  elif which gcc > /dev/null 2> /dev/null; then CC=gcc
+  elif which clang > /dev/null 2> /dev/null; then CC=clang
+  fi
+fi
+if [ "x$CC" = "x" ]; then echo "None found"; exit 1; fi
+echo "$CC"
+echo "CC=$CC" >> config.mk
+
+printf 'Checking if we need -liconv for iconv... '
+echo '#include <iconv.h>' > iconvtest.c
+echo 'int main(){iconv_t x=iconv_open("a","b");return 0;}' >> iconvtest.c
+if ! "$CC" iconvtest.c -o iconvtest > /dev/null 2> /dev/null; then
+  echo 'LIBS+=-liconv' >> config.mk
+  echo yes
+else
+  echo no
+fi
+rm -f iconvtest iconvtest.c
+
+printf 'Checking for gtk+-3.0... '
+libs="`pkg-config --libs gtk+-3.0 2> /dev/null`"
+if [ "x$libs" != "x" ]; then
+  echo "GTK_LIBS=${libs}" >> config.mk
+  echo "GTK_CFLAGS=`pkg-config --cflags gtk+-3.0`" >> config.mk
+  echo yes
+else
+  echo no
+  printf 'Checking for gtk+-2.0... '
+  libs="`pkg-config --libs gtk+-2.0 2> /dev/null`"
+  if [ "x$libs" != "x" ]; then
+    echo "GTK_LIBS=${libs}" >> config.mk
+    echo "GTK_CFLAGS=`pkg-config --cflags gtk+-2.0`" >> config.mk
+    echo yes
+  else
+    echo no
+  fi
+fi
+
+printf 'Checking for libavcodec... '
+libs="`pkg-config --libs libavcodec 2> /dev/null`"
+if [ "x$libs" != "x" ]; then
+  echo "AVCODEC_LIBS=${libs}" >> config.mk
+  echo "AVCODEC_CFLAGS=`pkg-config --cflags libavcodec`" >> config.mk
+  echo yes
+else
+  echo no
+fi
+
+printf 'Checking for libswscale... '
+libs="`pkg-config --libs libswscale 2> /dev/null`"
+if [ "x$libs" != "x" ]; then
+  echo "SWSCALE_LIBS=${libs}" >> config.mk
+  echo "SWSCALE_CFLAGS=`pkg-config --cflags libswscale`" >> config.mk
+  echo yes
+else
+  echo no
+fi
+
+printf 'Checking for libavutil... '
+libs="`pkg-config --libs libavutil 2> /dev/null`"
+if [ "x$libs" != "x" ]; then
+  echo "AVUTIL_LIBS=${libs}" >> config.mk
+  echo "AVUTIL_CFLAGS=`pkg-config --cflags libavutil`" >> config.mk
+  echo yes
+else
+  echo no
+fi
+
+# TODO: Figure out how to mix sound sources so that this doesn't sound horrible with more than one person on mic, having it disabled by default until then
+if [ "x${ENABLE_MIC}" != "x" ]; then
+printf 'Checking for libavresample... '
+libs="`pkg-config --libs libavresample 2> /dev/null`"
+if [ "x$libs" != "x" ]; then
+  echo "AVRESAMPLE_LIBS=${libs}" >> config.mk
+  echo "AVRESAMPLE_CFLAGS=`pkg-config --cflags libavresample`" >> config.mk
+  echo yes
+else
+  echo no
+  printf 'Checking for libswresample... '
+  libs="`pkg-config --libs libswresample 2> /dev/null`"
+  if [ "x$libs" != "x" ]; then
+    echo "SWRESAMPLE_LIBS=${libs}" >> config.mk
+    echo "SWRESAMPLE_CFLAGS=`pkg-config --cflags libswresample`" >> config.mk
+    echo yes
+  else
+    echo no
+  fi
+fi
+
+printf 'Checking for libao... '
+libs="`pkg-config --libs ao 2> /dev/null`"
+if [ "x$libs" != "x" ]; then
+  echo "AO_LIBS=${libs}" >> config.mk
+  echo "AO_CFLAGS=`pkg-config --cflags ao`" >> config.mk
+  echo yes
+else
+  echo no
+fi
+fi
+
+printf 'Checking for ncurses... '
+libs="`ncursesw5-config --libs 2> /dev/null || ncurses5-config --libs 2> /dev/null`"
+if [ "x$libs" != "x" ]; then
+  echo "CURSES_LIBS=${libs}" >> config.mk
+  echo "CURSES_CFLAGS=`ncursesw5-config --cflags 2> /dev/null || ncurses5-config --cflags 2> /dev/null`" >> config.mk
+  echo yes
+else
+  echo no
+fi
+
+printf 'Checking for readline... '
+echo '#include <stdio.h>' > readlinetest.c
+echo '#include <readline/readline.h>' >> readlinetest.c
+echo 'int main(){rl_initialize();return 0;}' >> readlinetest.c
+if "$CC" readlinetest.c -lreadline ${libs} -o readlinetest > /dev/null 2> /dev/null; then
+  echo "READLINE_LIBS=-lreadline" >> config.mk
+  echo yes
+else
+  echo no
+fi
+rm -f readlinetest.c readlinetest
+
+printf 'Checking for libv4l2... '
+libs="`pkg-config --libs libv4l2 2> /dev/null`"
+if [ "x$libs" != "x" ]; then
+  echo "LIBV4L2_LIBS=${libs}" >> config.mk
+  echo "LIBV4L2_CFLAGS=`pkg-config --cflags libv4l2`" >> config.mk
+  echo yes
+else
+  echo no
+fi
+
+# TODO: handle crosscompiling better
+printf 'Checking if endianness macros work... '
+echo '#include <stdio.h>' > endiantest.c
+echo 'int main(){' >> endiantest.c
+echo '#if defined(__ORDER_LITTLE_ENDIAN__) && defined(__ORDER_BIG_ENDIAN__) && defined(__BYTE_ORDER__)' >> endiantest.c
+echo '  if(__ORDER_LITTLE_ENDIAN__==__ORDER_BIG_ENDIAN__){return 1;}' >> endiantest.c
+echo '  if(__BYTE_ORDER__!=__ORDER_LITTLE_ENDIAN__ && __BYTE_ORDER__!=__ORDER_BIG_ENDIAN__){return 1;}' >> endiantest.c
+echo '  return 0;' >> endiantest.c
+echo '#else' >> endiantest.c
+echo '  return 1;' >> endiantest.c
+echo '#endif' >> endiantest.c
+echo '}' >> endiantest.c
+"$CC" endiantest.c -o endiantest > /dev/null 2> /dev/null
+if ./endiantest 2> /dev/null; then
+  echo yes
+else
+  echo no
+  printf 'Checking endianness and writing our own macros... '
+  echo '#include <stdio.h>' > endiantest.c
+  echo 'int main(){int num=1;char* x=(char*)&num;if(x[0]){printf("CFLAGS+=-D__ORDER_LITTLE_ENDIAN__=1 -D__ORDER_BIG_ENDIAN__=2 -D__BYTE_ORDER__=1");}else{printf("CFLAGS+=-D__ORDER_LITTLE_ENDIAN__=1 -D__ORDER_BIG_ENDIAN__=2 -D__BYTE_ORDER__=2");}return 0;}' >> endiantest.c
+  "$CC" endiantest.c -o endiantest > /dev/null 2> /dev/null
+  ./endiantest >> config.mk
+  echo >> config.mk
+  echo done
+fi
+rm -f endiantest.c endiantest
+
+echo Done
diff --git a/crossbuild.sh b/crossbuild.sh
new file mode 100755
index 0000000..84893a4
--- /dev/null
+++ b/crossbuild.sh
@@ -0,0 +1,65 @@
+#!/bin/sh -e
+host="$1"
+if [ "$host" = "" ]; then
+  host="`cc -dumpmachine`"
+  if [ "$host" = "" ]; then host='i386-pc-linux-gnu'; fi
+  echo "No target host specified (argv[1]), defaulting to ${host}"
+fi
+here="`pwd`"
+export PATH="${here}/curlprefix/bin:${here}/ncursesprefix/bin:${PATH}"
+if [ ! -e ncursesprefix ]; then
+  wget -c http://ftp.gnu.org/gnu/ncurses/ncurses-5.9.tar.gz
+  tar -xzf ncurses-5.9.tar.gz
+  cd ncurses-5.9
+  mkdir build
+  cd build
+  # Some hackery to build ncursesw5-config, which seems to get disabled along with --disable-database
+  ../configure --prefix="${here}/ncursesprefix" --host="${host}" --enable-static --disable-shared --with-termlib --enable-widec --without-cxx ac_cv_header_locale_h=no
+  mv Makefile Makefile.tmp
+  ../configure --prefix="${here}/ncursesprefix" --host="${host}" --enable-static --disable-shared --with-termlib --enable-widec --without-cxx --disable-database --with-fallbacks=linux ac_cv_header_locale_h=no
+  mv Makefile.tmp Makefile
+  make
+  make install
+  cd "$here"
+  cp ncursesprefix/lib/libtinfow.a ncursesprefix/lib/libtinfo.a
+fi
+if [ ! -e readlineprefix ]; then
+  wget -c http://ftp.gnu.org/gnu/readline/readline-6.3.tar.gz
+  tar -xzf readline-6.3.tar.gz
+  cd readline-6.3
+  mkdir build
+  cd build
+  ../configure --prefix="${here}/readlineprefix" --host="${host}" --enable-static --disable-shared bash_cv_wcwidth_broken=no
+  make
+  make install
+  cd "$here"
+fi
+if [ ! -e curlprefix ]; then
+  wget -c http://curl.haxx.se/download/curl-7.40.0.tar.bz2
+  tar -xjf curl-7.40.0.tar.bz2
+  cd curl-7.40.0
+  mkdir -p build
+  cd build
+  ../configure --prefix="${here}/curlprefix" --host="$host" --enable-static --disable-shared --disable-gopher --disable-ftp --disable-tftp --disable-ssh --disable-telnet --disable-dict --disable-file --disable-imap --disable-pop3 --disable-smtp --disable-ldap --without-librtmp --disable-rtsp --without-ssl --disable-sspi --without-nss --without-gnutls --without-libidn
+  make
+  make install
+  cd "$here"
+fi
+./configure --host="$host" > config.log 2>&1
+if grep -q 'LIBS+=-liconv' config.mk && [ ! -e iconvprefix ]; then
+  wget -c http://ftp.gnu.org/gnu/libiconv/libiconv-1.14.tar.gz
+  tar -xzf libiconv-1.14.tar.gz
+  cd libiconv-1.14
+  mkdir -p build
+  cd build
+  ../configure --prefix="${here}/iconvprefix" --host="`echo "$host" | sed -e 's/android/gnu/'`" --enable-static --disable-shared CC="${host}-gcc" # libiconv does not handle android well, so we pretend it's GNU and specify the compiler
+  make
+  make install
+  cd "$here"
+fi
+echo "CFLAGS+=-I${here}/iconvprefix/include" >> config.mk
+echo "LDFLAGS+=-L${here}/iconvprefix/lib" >> config.mk
+echo "READLINE_CFLAGS=-I${here}/readlineprefix/include" >> config.mk
+echo "READLINE_LIBS=-L${here}/readlineprefix/lib -lreadline" >> config.mk
+make
+make utils
diff --git a/endian.c b/endian.c
new file mode 100644
index 0000000..17f9a2c
--- /dev/null
+++ b/endian.c
@@ -0,0 +1,77 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include "endian.h"
+
+unsigned long long be64(unsigned long long in)
+{
+#if(__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__)
+  return ((in&0xff)<<56) |
+         ((in&0xff00)<<40) |
+         ((in&0xff0000)<<24) |
+         ((in&0xff000000)<<8) |
+         ((in&0xff00000000)>>8) |
+         ((in&0xff0000000000)>>24) |
+         ((in&0xff000000000000)>>40) |
+         ((in&0xff00000000000000)>>56);
+#else
+  return in;
+#endif
+}
+
+unsigned long be32(unsigned long in)
+{
+#if(__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__)
+  return ((in&0xff)<<24) |
+         ((in&0xff00)<<8) |
+         ((in&0xff0000)>>8) |
+         ((in&0xff000000)>>24);
+#else
+  return in;
+#endif
+}
+
+unsigned long le32(unsigned long in)
+{
+#if(__BYTE_ORDER__==__ORDER_BIG_ENDIAN__)
+  return ((in&0xff)<<24) |
+         ((in&0xff00)<<8) |
+         ((in&0xff0000)>>8) |
+         ((in&0xff000000)>>24);
+#else
+  return in;
+#endif
+}
+
+unsigned short be16(unsigned short in)
+{
+#if(__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__)
+  return ((in&0xff)<<8) |
+         ((in&0xff00)>>8);
+#else
+  return in;
+#endif
+}
+
+unsigned short le16(unsigned short in)
+{
+#if(__BYTE_ORDER__==__ORDER_BIG_ENDIAN__)
+  return ((in&0xff00)<<8) |
+         ((in&0xff)>>8);
+#else
+  return in;
+#endif
+}
diff --git a/endian.h b/endian.h
new file mode 100644
index 0000000..1f87c60
--- /dev/null
+++ b/endian.h
@@ -0,0 +1,21 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+extern unsigned long long be64(unsigned long long in);
+extern unsigned long be32(unsigned long in);
+extern unsigned long le32(unsigned long in);
+extern unsigned short be16(unsigned short in);
+extern unsigned short le16(unsigned short in);
diff --git a/gtkgui.glade b/gtkgui.glade
new file mode 100644
index 0000000..8a12566
--- /dev/null
+++ b/gtkgui.glade
@@ -0,0 +1,748 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Generated with glade 3.18.3 -->
+<interface>
+  <requires lib="gtk+" version="3.0"/>
+  <object class="GtkWindow" id="channelpasswordwindow">
+    <property name="can_focus">False</property>
+    <property name="title" translatable="yes">Channel password?</property>
+    <signal name="destroy" handler="gtk_main_quit" swapped="no"/>
+    <child>
+      <object class="GtkBox" id="box4">
+        <property name="visible">True</property>
+        <property name="can_focus">False</property>
+        <child>
+          <object class="GtkEntry" id="channelpassword">
+            <property name="visible">True</property>
+            <property name="can_focus">True</property>
+            <property name="visibility">False</property>
+            <property name="input_purpose">password</property>
+          </object>
+          <packing>
+            <property name="expand">False</property>
+            <property name="fill">True</property>
+            <property name="position">0</property>
+          </packing>
+        </child>
+        <child>
+          <object class="GtkButton" id="channelpasswordbutton">
+            <property name="label" translatable="yes">Enter</property>
+            <property name="visible">True</property>
+            <property name="can_focus">True</property>
+            <property name="receives_default">True</property>
+          </object>
+          <packing>
+            <property name="expand">False</property>
+            <property name="fill">True</property>
+            <property name="position">1</property>
+          </packing>
+        </child>
+      </object>
+    </child>
+  </object>
+  <object class="GtkWindow" id="main">
+    <property name="can_focus">False</property>
+    <property name="title" translatable="yes">tc_client</property>
+    <property name="default_width">300</property>
+    <property name="default_height">400</property>
+    <signal name="destroy" handler="gtk_main_quit" swapped="no"/>
+    <child>
+      <object class="GtkBox" id="vbox1">
+        <property name="visible">True</property>
+        <property name="can_focus">False</property>
+        <property name="orientation">vertical</property>
+        <child>
+          <object class="GtkMenuBar" id="menubar">
+            <property name="visible">True</property>
+            <property name="can_focus">False</property>
+            <child>
+              <object class="GtkMenuItem" id="menuitem_broadcast">
+                <property name="visible">True</property>
+                <property name="can_focus">False</property>
+                <property name="label" translatable="yes">Broadcast</property>
+                <child type="submenu">
+                  <object class="GtkMenu" id="menu_broadcast">
+                    <property name="visible">True</property>
+                    <property name="can_focus">False</property>
+                    <child>
+                      <object class="GtkCheckMenuItem" id="menuitem_broadcast_camera">
+                        <property name="visible">True</property>
+                        <property name="can_focus">False</property>
+                        <property name="label" translatable="yes">Camera</property>
+                        <property name="use_underline">True</property>
+                      </object>
+                    </child>
+                  </object>
+                </child>
+              </object>
+            </child>
+            <child>
+              <object class="GtkMenuItem" id="menuitem1">
+                <property name="visible">True</property>
+                <property name="can_focus">False</property>
+                <property name="label" translatable="yes">Options</property>
+                <property name="use_underline">True</property>
+                <child type="submenu">
+                  <object class="GtkMenu" id="menu1">
+                    <property name="visible">True</property>
+                    <property name="can_focus">False</property>
+                    <child>
+                      <object class="GtkMenuItem" id="menuitem_options_settings">
+                        <property name="visible">True</property>
+                        <property name="can_focus">False</property>
+                        <property name="label" translatable="yes">Settings</property>
+                        <property name="use_underline">True</property>
+                      </object>
+                    </child>
+                  </object>
+                </child>
+              </object>
+            </child>
+          </object>
+          <packing>
+            <property name="expand">False</property>
+            <property name="fill">True</property>
+            <property name="position">0</property>
+          </packing>
+        </child>
+        <child>
+          <object class="GtkPaned" id="vpaned">
+            <property name="visible">True</property>
+            <property name="can_focus">False</property>
+            <property name="orientation">vertical</property>
+            <child>
+              <object class="GtkScrolledWindow" id="camerascroll">
+                <property name="visible">True</property>
+                <property name="can_focus">True</property>
+                <child>
+                  <object class="GtkViewport" id="viewport1">
+                    <property name="visible">True</property>
+                    <property name="can_focus">False</property>
+                    <child>
+                      <object class="GtkBox" id="cambox">
+                        <property name="visible">True</property>
+                        <property name="can_focus">False</property>
+                        <child>
+                          <placeholder/>
+                        </child>
+                      </object>
+                    </child>
+                  </object>
+                </child>
+              </object>
+              <packing>
+                <property name="resize">True</property>
+                <property name="shrink">True</property>
+              </packing>
+            </child>
+            <child>
+              <object class="GtkBox" id="chatui">
+                <property name="visible">True</property>
+                <property name="can_focus">False</property>
+                <property name="orientation">vertical</property>
+                <child>
+                  <object class="GtkPaned" id="chatnick">
+                    <property name="visible">True</property>
+                    <property name="can_focus">False</property>
+                    <child>
+                      <object class="GtkScrolledWindow" id="chatscroll">
+                        <property name="visible">True</property>
+                        <property name="can_focus">True</property>
+                        <child>
+                          <object class="GtkTextView" id="chatview">
+                            <property name="visible">True</property>
+                            <property name="can_focus">True</property>
+                            <property name="editable">False</property>
+                            <property name="wrap_mode">char</property>
+                            <property name="cursor_visible">False</property>
+                          </object>
+                        </child>
+                      </object>
+                      <packing>
+                        <property name="resize">True</property>
+                        <property name="shrink">True</property>
+                      </packing>
+                    </child>
+                    <child>
+                      <object class="GtkScrolledWindow" id="userlistscroll">
+                        <property name="visible">True</property>
+                        <property name="can_focus">True</property>
+                        <child>
+                          <object class="GtkViewport" id="userlistview">
+                            <property name="visible">True</property>
+                            <property name="can_focus">False</property>
+                            <child>
+                              <object class="GtkBox" id="userlistbox">
+                                <property name="visible">True</property>
+                                <property name="can_focus">False</property>
+                                <property name="orientation">vertical</property>
+                                <child>
+                                  <placeholder/>
+                                </child>
+                              </object>
+                            </child>
+                          </object>
+                        </child>
+                      </object>
+                      <packing>
+                        <property name="resize">True</property>
+                        <property name="shrink">True</property>
+                      </packing>
+                    </child>
+                  </object>
+                  <packing>
+                    <property name="expand">True</property>
+                    <property name="fill">True</property>
+                    <property name="position">0</property>
+                  </packing>
+                </child>
+                <child>
+                  <object class="GtkEntry" id="inputfield">
+                    <property name="visible">True</property>
+                    <property name="can_focus">True</property>
+                    <property name="has_focus">True</property>
+                  </object>
+                  <packing>
+                    <property name="expand">False</property>
+                    <property name="fill">True</property>
+                    <property name="position">1</property>
+                  </packing>
+                </child>
+              </object>
+              <packing>
+                <property name="resize">True</property>
+                <property name="shrink">True</property>
+              </packing>
+            </child>
+          </object>
+          <packing>
+            <property name="expand">True</property>
+            <property name="fill">True</property>
+            <property name="position">1</property>
+          </packing>
+        </child>
+      </object>
+    </child>
+  </object>
+  <object class="GtkWindow" id="settings">
+    <property name="can_focus">False</property>
+    <property name="title" translatable="yes">tc_client settings</property>
+    <property name="default_width">350</property>
+    <property name="default_height">200</property>
+    <signal name="delete-event" handler="gtk_widget_hide_on_delete" swapped="no"/>
+    <child>
+      <object class="GtkBox" id="box1">
+        <property name="visible">True</property>
+        <property name="can_focus">False</property>
+        <property name="orientation">vertical</property>
+        <child>
+          <object class="GtkNotebook" id="pager">
+            <property name="visible">True</property>
+            <property name="can_focus">True</property>
+            <property name="tab_pos">left</property>
+            <property name="scrollable">True</property>
+            <child>
+              <object class="GtkScrolledWindow" id="scrolledwindow1">
+                <property name="visible">True</property>
+                <property name="can_focus">True</property>
+                <property name="shadow_type">in</property>
+                <child>
+                  <object class="GtkViewport" id="viewport2">
+                    <property name="visible">True</property>
+                    <property name="can_focus">False</property>
+                    <child>
+                      <object class="GtkBox" id="box2">
+                        <property name="visible">True</property>
+                        <property name="can_focus">False</property>
+                        <property name="orientation">vertical</property>
+                        <child>
+                          <object class="GtkCheckButton" id="enable_logging">
+                            <property name="label" translatable="yes">Enable logging</property>
+                            <property name="visible">True</property>
+                            <property name="can_focus">True</property>
+                            <property name="receives_default">False</property>
+                            <property name="halign">start</property>
+                            <property name="xalign">0</property>
+                            <property name="draw_indicator">True</property>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">0</property>
+                          </packing>
+                        </child>
+                        <child>
+                          <object class="GtkLabel" id="label3">
+                            <property name="visible">True</property>
+                            <property name="can_focus">False</property>
+                            <property name="halign">start</property>
+                            <property name="label" translatable="yes">Path for channel: (%h=home directory, %c=channelname)</property>
+                            <property name="wrap">True</property>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">1</property>
+                          </packing>
+                        </child>
+                        <child>
+                          <object class="GtkEntry" id="logpath_channel">
+                            <property name="visible">True</property>
+                            <property name="sensitive">False</property>
+                            <property name="can_focus">True</property>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">2</property>
+                          </packing>
+                        </child>
+                        <child>
+                          <object class="GtkLabel" id="label4">
+                            <property name="visible">True</property>
+                            <property name="can_focus">False</property>
+                            <property name="halign">start</property>
+                            <property name="label" translatable="yes">Path for PMs: (%h=home directory, %c=channelname, %n=nickname)</property>
+                            <property name="wrap">True</property>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">3</property>
+                          </packing>
+                        </child>
+                        <child>
+                          <object class="GtkEntry" id="logpath_pm">
+                            <property name="visible">True</property>
+                            <property name="sensitive">False</property>
+                            <property name="can_focus">True</property>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">4</property>
+                          </packing>
+                        </child>
+                      </object>
+                    </child>
+                  </object>
+                </child>
+              </object>
+            </child>
+            <child type="tab">
+              <object class="GtkLabel" id="label1">
+                <property name="visible">True</property>
+                <property name="can_focus">False</property>
+                <property name="label" translatable="yes">Logging</property>
+              </object>
+              <packing>
+                <property name="tab_fill">False</property>
+              </packing>
+            </child>
+            <child>
+              <object class="GtkScrolledWindow" id="scrolledwindow2">
+                <property name="visible">True</property>
+                <property name="can_focus">True</property>
+                <property name="shadow_type">in</property>
+                <child>
+                  <object class="GtkViewport" id="viewport3">
+                    <property name="visible">True</property>
+                    <property name="can_focus">False</property>
+                    <child>
+                      <object class="GtkBox" id="box3">
+                        <property name="visible">True</property>
+                        <property name="can_focus">False</property>
+                        <property name="orientation">vertical</property>
+                        <child>
+                          <object class="GtkRadioButton" id="soundradio_none">
+                            <property name="visible">True</property>
+                            <property name="can_focus">True</property>
+                            <property name="receives_default">False</property>
+                            <property name="halign">start</property>
+                            <property name="xalign">0</property>
+                            <property name="active">True</property>
+                            <property name="draw_indicator">True</property>
+                            <child>
+                              <object class="GtkLabel" id="label14">
+                                <property name="visible">True</property>
+                                <property name="can_focus">False</property>
+                                <property name="label" translatable="yes">Do not play notification sounds</property>
+                                <property name="wrap">True</property>
+                              </object>
+                            </child>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">0</property>
+                          </packing>
+                        </child>
+                        <child>
+                          <object class="GtkRadioButton" id="soundradio_cmd">
+                            <property name="visible">True</property>
+                            <property name="can_focus">True</property>
+                            <property name="receives_default">False</property>
+                            <property name="halign">start</property>
+                            <property name="xalign">0</property>
+                            <property name="draw_indicator">True</property>
+                            <property name="group">soundradio_none</property>
+                            <child>
+                              <object class="GtkLabel" id="label13">
+                                <property name="visible">True</property>
+                                <property name="can_focus">False</property>
+                                <property name="label" translatable="yes">Run a command to play sounds:</property>
+                                <property name="wrap">True</property>
+                              </object>
+                            </child>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">1</property>
+                          </packing>
+                        </child>
+                        <child>
+                          <object class="GtkEntry" id="soundcmd">
+                            <property name="visible">True</property>
+                            <property name="sensitive">False</property>
+                            <property name="can_focus">True</property>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">2</property>
+                          </packing>
+                        </child>
+                      </object>
+                    </child>
+                  </object>
+                </child>
+              </object>
+              <packing>
+                <property name="position">1</property>
+              </packing>
+            </child>
+            <child type="tab">
+              <object class="GtkLabel" id="label2">
+                <property name="visible">True</property>
+                <property name="can_focus">False</property>
+                <property name="label" translatable="yes">Sound</property>
+              </object>
+              <packing>
+                <property name="position">1</property>
+                <property name="tab_fill">False</property>
+              </packing>
+            </child>
+            <child>
+              <object class="GtkScrolledWindow" id="scrolledwindow3">
+                <property name="visible">True</property>
+                <property name="can_focus">True</property>
+                <property name="shadow_type">in</property>
+                <child>
+                  <object class="GtkViewport" id="viewport4">
+                    <property name="visible">True</property>
+                    <property name="can_focus">False</property>
+                    <child>
+                      <object class="GtkBox" id="box5">
+                        <property name="visible">True</property>
+                        <property name="can_focus">False</property>
+                        <property name="orientation">vertical</property>
+                        <child>
+                          <object class="GtkRadioButton" id="youtuberadio_none">
+                            <property name="visible">True</property>
+                            <property name="can_focus">True</property>
+                            <property name="receives_default">False</property>
+                            <property name="halign">start</property>
+                            <property name="xalign">0</property>
+                            <property name="active">True</property>
+                            <property name="draw_indicator">True</property>
+                            <child>
+                              <object class="GtkLabel" id="label12">
+                                <property name="visible">True</property>
+                                <property name="can_focus">False</property>
+                                <property name="halign">start</property>
+                                <property name="label" translatable="yes">Do not play youtube videos</property>
+                                <property name="wrap">True</property>
+                              </object>
+                            </child>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">0</property>
+                          </packing>
+                        </child>
+                        <child>
+                          <object class="GtkRadioButton" id="youtuberadio_cmd">
+                            <property name="visible">True</property>
+                            <property name="can_focus">True</property>
+                            <property name="receives_default">False</property>
+                            <property name="halign">start</property>
+                            <property name="xalign">0</property>
+                            <property name="active">True</property>
+                            <property name="draw_indicator">True</property>
+                            <property name="group">youtuberadio_none</property>
+                            <child>
+                              <object class="GtkLabel" id="label11">
+                                <property name="visible">True</property>
+                                <property name="can_focus">False</property>
+                                <property name="halign">start</property>
+                                <property name="label" translatable="yes">Run a command to play youtube videos (%i=video ID, %t=offset in milliseconds):</property>
+                                <property name="wrap">True</property>
+                              </object>
+                            </child>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">1</property>
+                          </packing>
+                        </child>
+                        <child>
+                          <object class="GtkEntry" id="youtubecmd">
+                            <property name="visible">True</property>
+                            <property name="can_focus">True</property>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">2</property>
+                          </packing>
+                        </child>
+                        <child>
+                          <object class="GtkLabel" id="label15">
+                            <property name="visible">True</property>
+                            <property name="can_focus">False</property>
+                            <property name="label" translatable="yes">Example: youtube-dl -o - -- '%i' | mplayer -ss "`expr '%t' / 1000`" -</property>
+                            <property name="wrap">True</property>
+                            <property name="selectable">True</property>
+                          </object>
+                          <packing>
+                            <property name="expand">False</property>
+                            <property name="fill">True</property>
+                            <property name="position">3</property>
+                          </packing>
+                        </child>
+                      </object>
+                    </child>
+                  </object>
+                </child>
+              </object>
+              <packing>
+                <property name="position">2</property>
+              </packing>
+            </child>
+            <child type="tab">
+              <object class="GtkLabel" id="label10">
+                <property name="visible">True</property>
+                <property name="can_focus">False</property>
+                <property name="label" translatable="yes">Youtube</property>
+              </object>
+              <packing>
+                <property name="position">2</property>
+                <property name="tab_fill">False</property>
+              </packing>
+            </child>
+          </object>
+          <packing>
+            <property name="expand">True</property>
+            <property name="fill">True</property>
+            <property name="position">0</property>
+          </packing>
+        </child>
+        <child>
+          <object class="GtkButton" id="save_settings">
+            <property name="label" translatable="yes">OK</property>
+            <property name="visible">True</property>
+            <property name="can_focus">True</property>
+            <property name="receives_default">True</property>
+            <property name="halign">end</property>
+          </object>
+          <packing>
+            <property name="expand">False</property>
+            <property name="fill">False</property>
+            <property name="position">1</property>
+          </packing>
+        </child>
+      </object>
+    </child>
+  </object>
+  <object class="GtkWindow" id="startwindow">
+    <property name="can_focus">False</property>
+    <property name="title" translatable="yes">tc_client</property>
+    <property name="resizable">False</property>
+    <signal name="destroy" handler="gtk_main_quit" swapped="no"/>
+    <child>
+      <object class="GtkBox" id="box6">
+        <property name="visible">True</property>
+        <property name="can_focus">False</property>
+        <property name="orientation">vertical</property>
+        <child>
+          <object class="GtkExpander" id="expander1">
+            <property name="visible">True</property>
+            <property name="can_focus">True</property>
+            <child>
+              <object class="GtkBox" id="box7">
+                <property name="visible">True</property>
+                <property name="can_focus">False</property>
+                <property name="orientation">vertical</property>
+                <child>
+                  <object class="GtkLabel" id="label8">
+                    <property name="visible">True</property>
+                    <property name="can_focus">False</property>
+                    <property name="halign">start</property>
+                    <property name="label" translatable="yes">Username:</property>
+                  </object>
+                  <packing>
+                    <property name="expand">False</property>
+                    <property name="fill">True</property>
+                    <property name="position">0</property>
+                  </packing>
+                </child>
+                <child>
+                  <object class="GtkEntry" id="acc_username">
+                    <property name="visible">True</property>
+                    <property name="can_focus">True</property>
+                  </object>
+                  <packing>
+                    <property name="expand">False</property>
+                    <property name="fill">True</property>
+                    <property name="position">1</property>
+                  </packing>
+                </child>
+                <child>
+                  <object class="GtkLabel" id="label9">
+                    <property name="visible">True</property>
+                    <property name="can_focus">False</property>
+                    <property name="halign">start</property>
+                    <property name="label" translatable="yes">Password:</property>
+                  </object>
+                  <packing>
+                    <property name="expand">False</property>
+                    <property name="fill">True</property>
+                    <property name="position">2</property>
+                  </packing>
+                </child>
+                <child>
+                  <object class="GtkEntry" id="acc_password">
+                    <property name="visible">True</property>
+                    <property name="can_focus">True</property>
+                    <property name="visibility">False</property>
+                    <property name="input_purpose">password</property>
+                  </object>
+                  <packing>
+                    <property name="expand">False</property>
+                    <property name="fill">True</property>
+                    <property name="position">3</property>
+                  </packing>
+                </child>
+                <child>
+                  <object class="GtkCheckButton" id="start_rememberacc">
+                    <property name="label" translatable="yes">Remember account</property>
+                    <property name="visible">True</property>
+                    <property name="can_focus">True</property>
+                    <property name="receives_default">False</property>
+                    <property name="xalign">0</property>
+                    <property name="draw_indicator">True</property>
+                  </object>
+                  <packing>
+                    <property name="expand">False</property>
+                    <property name="fill">True</property>
+                    <property name="position">4</property>
+                  </packing>
+                </child>
+              </object>
+            </child>
+            <child type="label">
+              <object class="GtkLabel" id="label5">
+                <property name="visible">True</property>
+                <property name="can_focus">False</property>
+                <property name="label" translatable="yes">Account</property>
+              </object>
+            </child>
+          </object>
+          <packing>
+            <property name="expand">False</property>
+            <property name="fill">True</property>
+            <property name="position">0</property>
+          </packing>
+        </child>
+        <child>
+          <object class="GtkLabel" id="label6">
+            <property name="visible">True</property>
+            <property name="can_focus">False</property>
+            <property name="halign">start</property>
+            <property name="label" translatable="yes">Nickname:</property>
+          </object>
+          <packing>
+            <property name="expand">False</property>
+            <property name="fill">True</property>
+            <property name="position">1</property>
+          </packing>
+        </child>
+        <child>
+          <object class="GtkEntry" id="start_nick">
+            <property name="visible">True</property>
+            <property name="can_focus">True</property>
+          </object>
+          <packing>
+            <property name="expand">False</property>
+            <property name="fill">True</property>
+            <property name="position">2</property>
+          </packing>
+        </child>
+        <child>
+          <object class="GtkLabel" id="label7">
+            <property name="visible">True</property>
+            <property name="can_focus">False</property>
+            <property name="halign">start</property>
+            <property name="label" translatable="yes">Channel:</property>
+          </object>
+          <packing>
+            <property name="expand">False</property>
+            <property name="fill">True</property>
+            <property name="position">3</property>
+          </packing>
+        </child>
+        <child>
+          <object class="GtkEntry" id="start_channel">
+            <property name="visible">True</property>
+            <property name="can_focus">True</property>
+          </object>
+          <packing>
+            <property name="expand">False</property>
+            <property name="fill">True</property>
+            <property name="position">4</property>
+          </packing>
+        </child>
+        <child>
+          <object class="GtkCheckButton" id="start_rememberchan">
+            <property name="label" translatable="yes">Remember nickname and channel</property>
+            <property name="visible">True</property>
+            <property name="can_focus">True</property>
+            <property name="receives_default">False</property>
+            <property name="xalign">0</property>
+            <property name="draw_indicator">True</property>
+          </object>
+          <packing>
+            <property name="expand">False</property>
+            <property name="fill">True</property>
+            <property name="position">5</property>
+          </packing>
+        </child>
+        <child>
+          <object class="GtkButton" id="connectbutton">
+            <property name="label" translatable="yes">Connect</property>
+            <property name="visible">True</property>
+            <property name="can_focus">True</property>
+            <property name="receives_default">True</property>
+          </object>
+          <packing>
+            <property name="expand">False</property>
+            <property name="fill">True</property>
+            <property name="position">6</property>
+          </packing>
+        </child>
+      </object>
+    </child>
+  </object>
+</interface>
diff --git a/idlist.c b/idlist.c
new file mode 100644
index 0000000..8cc0e16
--- /dev/null
+++ b/idlist.c
@@ -0,0 +1,102 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014  alicia@ion.nu
+    Copyright (C) 2014-2015  Jade Lea
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <stdlib.h>
+#include <string.h>
+#include "idlist.h"
+
+struct idmap* idlist=0;
+int idlistlen=0;
+
+void idlist_add(int id, const char* name)
+{
+  idlist_remove(name);
+  ++idlistlen;
+  idlist=realloc(idlist, sizeof(struct idmap)*idlistlen);
+  idlist[idlistlen-1].id=id;
+  idlist[idlistlen-1].name=strdup(name);
+}
+
+void idlist_remove(const char* name)
+{
+  int i;
+  for(i=0; i<idlistlen; ++i)
+  {
+    if(!strcmp(name, idlist[i].name))
+    {
+      free((void*)idlist[i].name);
+      --idlistlen;
+      memmove(&idlist[i], &idlist[i+1], sizeof(struct idmap)*(idlistlen-i));
+      return;
+    }
+  }
+}
+
+void idlist_rename(const char* oldname, const char* newname)
+{
+  int i;
+  for(i=0; i<idlistlen; ++i)
+  {
+    if(!strcmp(oldname, idlist[i].name))
+    {
+      free((void*)idlist[i].name);
+      idlist[i].name=strdup(newname);
+      return;
+    }
+  }
+}
+
+int idlist_get(const char* name)
+{
+  int len;
+  for(len=0; name[len]&&name[len]!=' '; ++len);
+  int i;
+  for(i=0; i<idlistlen; ++i)
+  {
+    if(!strncmp(name, idlist[i].name, len) && !idlist[i].name[len])
+    {
+      return idlist[i].id;
+    }
+  }
+  return -1;
+}
+
+void idlist_set_op(const char* name, char op)
+{
+  int i;
+  for(i=0; i<idlistlen; ++i)
+  {
+    if(!strcmp(name, idlist[i].name))
+    {
+      idlist[i].op=op;
+      return;
+    }
+  }
+}
+
+char idlist_is_op(const char* name)
+{
+  int i;
+  for(i=0; i<idlistlen; ++i)
+  {
+    if(!strcmp(name, idlist[i].name))
+    {
+      return idlist[i].op;
+    }
+  }
+  return 0;
+}
diff --git a/idlist.h b/idlist.h
new file mode 100644
index 0000000..b7c7f81
--- /dev/null
+++ b/idlist.h
@@ -0,0 +1,33 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014  alicia@ion.nu
+    Copyright (C) 2014-2015  Jade Lea
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+struct idmap
+{
+  const char* name;
+  int id;
+  char op;
+};
+
+extern struct idmap* idlist;
+extern int idlistlen;
+
+extern void idlist_add(int id, const char* name);
+extern void idlist_remove(const char* name);
+extern void idlist_rename(const char* oldname, const char* newname);
+extern int idlist_get(const char* name);
+extern void idlist_set_op(const char* name, char op);
+extern char idlist_is_op(const char* name);
diff --git a/irchack.c b/irchack.c
new file mode 100644
index 0000000..fa527f8
--- /dev/null
+++ b/irchack.c
@@ -0,0 +1,414 @@
+/*
+    irchack, a simple application to reuse IRC clients as user interfaces for tc_client
+    Copyright (C) 2014-2015  alicia@ion.nu
+    Copyright (C) 2015  Jade Lea
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <netinet/in.h>
+#include <unistd.h>
+#include <poll.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <sys/socket.h>
+#include <ctype.h>
+#include <signal.h>
+
+#ifdef __ANDROID__
+// Android has no dprintf, so we make our own
+#include <stdarg.h>
+size_t dprintf(int fd, const char* fmt, ...)
+{
+  va_list va;
+  va_start(va, fmt);
+  int len=vsnprintf(0, 0, fmt, va);
+  va_end(va);
+  char buf[len+1];
+  va_start(va, fmt);
+  vsnprintf(buf, len+1, fmt, va);
+  va_end(va);
+  buf[len]=0;
+  write(fd, buf, len);
+  return len;
+}
+#endif
+
+// ANSI colors and their IRC equivalents
+struct color{const char* ansi; const char* irc;};
+struct color colortable[]={
+  {"31",   "\x03""05"},
+  {"31;1", "\x03""04"},
+  {"33",   "\x03""07"},
+  {"33",   "\x03""07"},
+  {"33;1", "\x03""08"},
+  {"32;1", "\x03""09"},
+  {"32;1", "\x03""09"},
+  {"32",   "\x03""03"},
+  {"36",   "\x03""10"},
+  {"34;1", "\x03""12"},
+  {"34;1", "\x03""12"},
+  {"34",   "\x03""02"},
+  {"35",   "\x03""06"},
+  {"35;1", "\x03""13"},
+  {"35;1", "\x03""13"},
+  {"35;1", "\x03""13"}
+};
+
+const char* findcolor_irc(const char* ansi)
+{
+  int len;
+  for(len=0; ansi[len]&&ansi[len]!='m'; ++len);
+  int i;
+  for(i=0; i<16; ++i)
+  {
+    if(!strncmp(colortable[i].ansi, ansi, len) && !colortable[i].ansi[len])
+    {
+      return colortable[i].irc;
+    }
+  }
+  return 0;
+}
+
+int findcolor_ansi(char* irc, char** end)
+{
+  char color[4];
+  strncpy(color, irc, 3);
+  color[3]=0;
+  if(!isdigit(color[1])){*end=&irc[1]; return -1;}
+  if(!isdigit(color[2])){*end=&irc[2]; color[2]=color[1]; color[1]='0';}else{*end=&irc[3];}
+  int i;
+  for(i=0; i<16; ++i)
+  {
+    if(!strcmp(colortable[i].irc, color))
+    {
+      return i;
+    }
+  }
+  return -1;
+}
+
+extern char session(int sock, const char* nick, const char* channel, const char* pass, const char* acc_user, const char* acc_pass);
+
+int main(int argc, char** argv)
+{
+  int port=(argc>1?atoi(argv[1]):6667);
+  struct sockaddr_in addr;
+  memset(&addr, 0, sizeof(addr));
+  addr.sin_family=AF_INET;
+  addr.sin_addr.s_addr=htonl(0x7f000001); // 127.0.0.1
+  addr.sin_port=htons(port);
+  int lsock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if(bind(lsock, (struct sockaddr*)&addr, sizeof(addr))){perror("bind"); return 1;}
+  listen(lsock, 1);
+  printf("Done! Open an IRC client and connect to localhost on port %i\n", port);
+  signal(SIGCHLD, SIG_IGN);
+  int sock;
+  while((sock=accept(lsock, 0, 0))>-1)
+  {
+    if(fork()){continue;}
+    char buf[2048];
+    char* nick=0;
+    char* channel=0;
+    char* pass=0;
+    char* acc_user=0;
+    char* acc_pass=0;
+    int len;
+    while(1)
+    {
+      len=0;
+      int r;
+      while(len<2047)
+      {
+        if((r=read(sock, &buf[len], 1))!=1 || buf[len]=='\r' || buf[len]=='\n'){break;}
+        ++len;
+      }
+      if(r!=1){break;}
+      buf[len]=0;
+      if(!strncmp(buf, "USER ", 5))
+      {
+        acc_user=&buf[5];
+        char* end=strchr(acc_user, ' ');
+        if(end){end[0]=0;}
+        acc_user=strdup(acc_user);
+      }
+      else if(!strncmp(buf, "PASS ", 5))
+      {
+        acc_pass=&buf[5];
+        if(acc_pass[0]==':'){acc_pass=&acc_pass[1];}
+        acc_pass=strdup(acc_pass);
+      }
+      else if(!strncmp(buf, "NICK ", 5))
+      {
+        char* newnick=&buf[5];
+        if(newnick[0]==':'){newnick=&nick[1];}
+        if(!nick)
+        {
+          dprintf(sock, ":irchack 001 %s :Welcome\n", newnick);
+        }else{
+          dprintf(sock, ":%s!user@host NICK :%s\n", nick, newnick);
+        }
+        free(nick);
+        nick=strdup(newnick);
+      }
+      else if(nick && !strncmp(buf, "JOIN ", 5))
+      {
+        free(channel);
+        channel=&buf[5];
+        if(channel[0]==':'){channel=&channel[1];}
+        free(pass);
+        pass=strchr(channel, ' ');
+        if(pass)
+        {
+          pass[0]=0;
+          pass=&pass[1];
+          if(pass[0]==':'){pass=strdup(&pass[1]);}
+        }
+        if(channel[0]=='#'){channel=&channel[1];}
+        channel=strdup(channel);
+        if(!session(sock, nick, channel, pass, acc_user, acc_pass)){break;}
+      }
+      else if(!strncmp(buf, "PING ", 5))
+      {
+        dprintf(sock, ":irchack PONG %s\n", &buf[5]);
+      }
+    }
+    shutdown(sock, SHUT_RDWR);
+    _exit(0);
+  }
+  close(lsock);
+  return 0;
+}
+
+char session(int sock, const char* nick, const char* channel, const char* pass, const char* acc_user, const char* acc_pass)
+{
+  printf("Nick: %s\n", nick);
+  printf("Channel: %s\n", channel);
+  printf("Password: %s\n", pass);
+  int tc_in[2];
+  int tc_out[2];
+  pipe(tc_in);
+  pipe(tc_out);
+  if(!fork())
+  {
+    close(tc_in[1]);
+    close(tc_out[0]);
+    dup2(tc_in[0], 0);
+    dup2(tc_out[1], 1);
+    if(acc_user && acc_pass)
+    {
+      execl("./tc_client", "./tc_client", "-u", acc_user, "-p", acc_pass, channel, nick, pass, (char*)0);
+    }else{
+      execl("./tc_client", "./tc_client", channel, nick, pass, (char*)0);
+    }
+    perror("Failed to exec tc_client");
+    _exit(1);
+  }
+  close(tc_in[0]);
+  close(tc_out[1]);
+  struct pollfd pfd[2];
+  pfd[0].fd=tc_out[0];
+  pfd[0].events=POLLIN;
+  pfd[0].revents=0;
+  pfd[1].fd=sock;
+  pfd[1].events=POLLIN;
+  pfd[1].revents=0;
+  char buf[2048];
+  int len;
+  char joins=0;
+  while(1)
+  {
+    poll(pfd, 2, -1);
+    if(pfd[0].revents)
+    {
+      pfd[0].revents=0;
+      len=0;
+      int r;
+      while(len<2047)
+      {
+        if((r=read(tc_out[0], &buf[len], 1))!=1 || buf[len]=='\r' || buf[len]=='\n'){break;}
+        ++len;
+      }
+      if(r!=1){break;}
+      buf[len]=0;
+printf("Got from tc_client: '%s'\n", buf);
+      if(!strncmp(buf, "Currently online: ", 18))
+      {
+        dprintf(sock, ":irchack 353 %s = #%s :", nick, channel);
+        char* user=&buf[18];
+        while(user)
+        {
+          char* next=strchr(user, ',');
+          if(next){next[0]=0; next=&next[2];}
+          dprintf(sock, "%s%s", user, next?" ":"");
+          user=next;
+        }
+        write(sock, "\n", 1);
+        joins=1;
+        continue;
+      }
+      else if(joins)
+      {
+        dprintf(sock, ":irchack 366 %s #%s :End of /NAMES list.\n", nick, channel);
+        joins=0;
+      }
+      if(!strncmp(buf, "Room topic: ", 12))
+      {
+        dprintf(sock, ":irchack 332 %s #%s :%s\n", nick, channel, &buf[12]);
+        continue;
+      }
+      if(!strcmp(buf, "Password required"))
+      {
+        dprintf(sock, ":irchack 475 %s :Cannot join %s without the correct password\n", channel, channel);
+        close(tc_in[1]);
+        close(tc_out[0]);
+        return 1;
+      }
+      if(!strncmp(buf, "Guest ID: ", 10))
+      {
+        dprintf(sock, ":%s!user@host NICK :guest-%s\n", nick, &buf[10]);
+        continue;
+      }
+      if(!strncmp(buf, "No such nick: ", 14))
+      {
+        dprintf(sock, ":irchack 401 %s %s :No such nick/channel\n", nick, &buf[14]);
+        continue;
+      }
+      char* space=strchr(buf, ' ');
+      if(space && !strcmp(space, " is a moderator."))
+      {
+        space[0]=0;
+        dprintf(sock, ":irchack MODE #%s +o %s\n", channel, buf);
+        continue;
+      }
+      if(space && !strcmp(space, " is no longer a moderator."))
+      {
+        space[0]=0;
+        dprintf(sock, ":irchack MODE #%s -o %s\n", channel, buf);
+        continue;
+      }
+      if(buf[0]!='['){continue;} // Beyond this we only care about timestamped lines
+      // Translate ANSI escape codes to IRC color code instead
+      char* ansi;
+      const char* color="";
+      while((ansi=strstr(buf, "\x1b[")))
+      {
+        int len;
+        for(len=0; ansi[len]&&ansi[len]!='m'; ++len);
+        if(ansi[len]=='m'){++len;}
+        const char* c=findcolor_irc(&ansi[2]);
+        if(c){color=c;}
+        memmove(ansi, &ansi[len], strlen(&ansi[len])+1);
+      }
+
+      char* name=strchr(buf, ' ');
+      if(!name){continue;}
+      name[0]=0;
+      name=&name[1];
+      char* msg=name;
+      while(msg[0]&&msg[0]!=':'&&msg[0]!=' '){msg=&msg[1];}
+      if(msg[0]==':') // message
+      {
+        msg[0]=0;
+        msg=&msg[2];
+        if(!strncmp(msg, "/msg ", 5)) // PM
+        {
+          msg=strchr(&msg[5], ' ');
+          if(!msg){continue;}
+          msg=&msg[1];
+          dprintf(sock, ":%s!user@host PRIVMSG %s :%s%s\n", name, nick, color, msg);
+        }else{ // Regular channel message
+          dprintf(sock, ":%s!user@host PRIVMSG #%s :%s%s\n", name, channel, color, msg);
+        }
+      }else{ // action, parse the actions and send them as JOINs, NICKs and QUITs etc. instead
+        msg[0]=0;
+        msg=&msg[1];
+        if(!strcmp(msg, "entered the channel"))
+        {
+          dprintf(sock, ":%s!user@host JOIN #%s\n", name, channel);
+        }
+        else if(!strncmp(msg, "changed nickname to ", 20))
+        {
+          dprintf(sock, ":%s!user@host NICK :%s\n", name, &msg[20]);
+        }
+        else if(!strcmp(msg, "left the channel"))
+        {
+          dprintf(sock, ":%s!user@host QUIT :left the channel\n", name);
+        }
+        else // Unhandled action
+        {
+          dprintf(sock, ":%s!user@host PRIVMSG #%s :\x01""ACTION %s\x01\n", name, channel, msg);
+        }
+      }
+    }
+    if(pfd[1].revents)
+    {
+      pfd[1].revents=0;
+      len=0;
+      int r;
+      while(len<2047)
+      {
+        if((r=read(sock, &buf[len], 1))!=1 || buf[len]=='\r' || buf[len]=='\n'){break;}
+        ++len;
+      }
+      if(r!=1){break;}
+      buf[len]=0;
+printf("Got from IRC client: '%s'\n", buf);
+      if(!strncmp(buf, "PRIVMSG ", 8))
+      {
+        char* target=&buf[8];
+        char* msg=strchr(&buf[8], ' ');
+        if(!msg){continue;}
+        msg[0]=0;
+        msg=&msg[1];
+        if(msg[0]==':'){msg=&msg[1];}
+        char* color;
+        while((color=strchr(msg, '\x03')))
+        {
+          char* end;
+          int c=findcolor_ansi(color, &end);
+          if(c!=-1){dprintf(tc_in[1], "/color %i\n", c);}
+          memmove(color, end, strlen(end)+1);
+        }
+        if(!strncmp(msg, "\x01""ACTION ", 8)) // Translate '/me'
+        {
+          msg=&msg[7];
+          msg[0]='*';
+          char* end=strchr(msg, '\x01');
+          if(end){end[0]='*';}
+        }
+        if(target[0]=='#' && !strcmp(&target[1], channel))
+        {
+          dprintf(tc_in[1], "%s\n", msg);
+        }else{
+          dprintf(tc_in[1], "/msg %s %s\n", target, msg);
+        }
+      }
+      else if(!strncmp(buf, "NICK ", 5))
+      {
+        char* nick=&buf[5];
+        if(nick[0]==':'){nick=&nick[1];}
+        dprintf(tc_in[1], "/nick %s\n", nick);
+      }
+      else if(!strncmp(buf, "PING ", 5))
+      {
+        dprintf(sock, ":irchack PONG %s\n", &buf[5]);
+      }
+      else if(!strncmp(buf, "QUIT ", 5)){break;}
+    }
+  }
+
+  close(tc_in[1]);
+  close(tc_out[0]);
+  return 0;
+}
diff --git a/media.c b/media.c
new file mode 100644
index 0000000..b224911
--- /dev/null
+++ b/media.c
@@ -0,0 +1,201 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "endian.h"
+#include "media.h"
+#include "amfwriter.h"
+#include "idlist.h"
+
+struct stream* streams=0;
+unsigned int streamcount=0;
+
+char stream_idtaken(unsigned int id)
+{
+  unsigned int i;
+  for(i=0; i<streamcount; ++i)
+  {
+    if(streams[i].streamid==id){return 1;}
+  }
+  return 0;
+}
+
+void stream_start(const char* nick, int sock) // called upon privmsg "/opencam ..."
+{
+  unsigned int userid=idlist_get(nick);
+  unsigned int streamid=1;
+  while(stream_idtaken(streamid)){++streamid;}
+  ++streamcount;
+  streams=realloc(streams, sizeof(struct stream)*streamcount);
+  streams[streamcount-1].userid=userid;
+  streams[streamcount-1].streamid=streamid;
+  streams[streamcount-1].outgoing=0;
+  struct rtmp amf;
+  amfinit(&amf, 3);
+  amfstring(&amf, "createStream");
+  amfnum(&amf, streamid+1);
+  amfnull(&amf);
+  amfsend(&amf, sock);
+  printf("Starting media stream for %s (%u)\n", nick, userid);
+  fflush(stdout);
+}
+
+void streamout_start(unsigned int id, int sock) // called upon privmsg "/camup"
+{
+  unsigned int streamid=1;
+  while(stream_idtaken(streamid)){++streamid;}
+  ++streamcount;
+  streams=realloc(streams, sizeof(struct stream)*streamcount);
+  streams[streamcount-1].userid=id;
+  streams[streamcount-1].streamid=streamid;
+  streams[streamcount-1].outgoing=1;
+  struct rtmp amf;
+  amfinit(&amf, 3);
+  amfstring(&amf, "createStream");
+  amfnum(&amf, streamid+1);
+  amfnull(&amf);
+  amfsend(&amf, sock);
+  printf("Starting outgoing media stream\n");
+  fflush(stdout);
+}
+
+void stream_play(struct amf* amf, int sock) // called upon _result
+{
+  unsigned int i;
+  for(i=0; i<streamcount; ++i)
+  {
+    if(streams[i].streamid==amf->items[2].number)
+    {
+      struct rtmp amf;
+      amfinit(&amf, 8);
+      amfstring(&amf, streams[i].outgoing?"publish":"play");
+      amfnum(&amf, 0);
+      amfnull(&amf);
+      char camid[snprintf(0,0,"%u0", streams[i].userid)];
+      sprintf(camid, "%u", streams[i].userid);
+      amfstring(&amf, camid);
+      if(streams[i].outgoing){amfstring(&amf, "live");}
+      amf.msgid=le32(streams[i].streamid);
+      amfsend(&amf, sock);
+      return;
+    }
+  }
+}
+
+void stream_handledata(struct rtmp* rtmp)
+{
+  unsigned int i;
+  for(i=0; i<streamcount; ++i)
+  {
+    if(streams[i].streamid!=rtmp->msgid){continue;}
+// fprintf(stderr, "Chunk: chunkid: %u, streamid: %u, userid: %u\n", rtmp->chunkid, rtmp->msgid, streams[i].userid);
+    if(rtmp->type==RTMP_VIDEO)
+    {
+      printf("Video: %u %u\n", streams[i].userid, rtmp->length);
+    }else if(rtmp->type==RTMP_AUDIO){
+      printf("Audio: %u %u\n", streams[i].userid, rtmp->length);
+    }
+    fwrite(rtmp->buf, rtmp->length, 1, stdout);
+    fflush(stdout);
+    return;
+  }
+  printf("Received media data to unknown stream ID %u\n", rtmp->msgid);
+}
+
+void stream_handlestatus(struct amf* amf, int sock)
+{
+  if(amf->itemcount<3 || amf->items[2].type!=AMF_OBJECT){return;}
+  struct amfobject* obj=&amf->items[2].object;
+  struct amfitem* code=amf_getobjmember(obj, "code");
+  struct amfitem* details=amf_getobjmember(obj, "details");
+  if(!code || !details){return;}
+  if(code->type!=AMF_STRING || details->type!=AMF_STRING){return;}
+  if(!strcmp(code->string.string, "NetStream.Play.Stop"))
+  {
+    unsigned int id=strtoul(details->string.string, 0, 0);
+    unsigned int i;
+    for(i=0; i<streamcount; ++i)
+    {
+      if(streams[i].userid==id)
+      {
+        printf("VideoEnd: %u\n", streams[i].userid);
+        // Delete the stream
+        struct rtmp amf;
+        amfinit(&amf, 3);
+        amfstring(&amf, "deleteStream");
+        amfnum(&amf, 0);
+        amfnull(&amf);
+        amfnum(&amf, streams[i].streamid);
+        amfsend(&amf, sock);
+        // Remove from list of streams
+        --streamcount;
+        memmove(&streams[i], &streams[i+1], sizeof(struct stream)*(streamcount-i));
+        return;
+      }
+    }
+  }
+}
+
+void stream_sendvideo(int sock, void* buf, size_t len)
+{
+  unsigned int i;
+  for(i=0; i<streamcount; ++i)
+  {
+    if(streams[i].outgoing)
+    {
+      struct rtmp msg;
+      msg.type=RTMP_VIDEO;
+      msg.chunkid=6;
+      msg.length=len;
+      msg.msgid=streams[i].streamid;
+      msg.buf=buf;
+      rtmp_send(sock, &msg);
+      return;
+    }
+  }
+}
+
+void stream_stopvideo(int sock)
+{
+  unsigned int i;
+  for(i=0; i<streamcount; ++i)
+  {
+    if(streams[i].outgoing)
+    {
+      struct rtmp amf;
+      // Close the stream
+      amfinit(&amf, 8);
+      amfstring(&amf, "closeStream");
+      amfnum(&amf, 0);
+      amfnull(&amf);
+      amf.msgid=le32(streams[i].streamid);
+      amfsend(&amf, sock);
+      // Delete the stream
+      amfinit(&amf, 3);
+      amfstring(&amf, "deleteStream");
+      amfnum(&amf, 0);
+      amfnull(&amf);
+      amfnum(&amf, streams[i].streamid);
+      amfsend(&amf, sock);
+      // Remove from list of streams
+      --streamcount;
+      memmove(&streams[i], &streams[i+1], sizeof(struct stream)*(streamcount-i));
+      return;
+    }
+  }
+}
diff --git a/media.h b/media.h
new file mode 100644
index 0000000..25195ab
--- /dev/null
+++ b/media.h
@@ -0,0 +1,35 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include "amfparser.h"
+#include "rtmp.h"
+struct stream
+{
+  unsigned int streamid;
+  unsigned int userid;
+  char outgoing;
+};
+
+extern struct stream* streams;
+extern unsigned int streamcount;
+
+extern void stream_start(const char* nick, int sock); // called upon privmsg "/opencam ..."
+extern void streamout_start(unsigned int id, int sock); // called upon privmsg "/camup"
+extern void stream_play(struct amf* amf, int sock); // called upon _result
+extern void stream_handledata(struct rtmp* rtmp);
+extern void stream_handlestatus(struct amf* amf, int sock);
+extern void stream_sendvideo(int sock, void* buf, size_t len);
+extern void stream_stopvideo(int sock);
diff --git a/modbot.c b/modbot.c
new file mode 100644
index 0000000..5cffbb9
--- /dev/null
+++ b/modbot.c
@@ -0,0 +1,578 @@
+/*
+    modbot, a bot for tc_client that queues and plays videos
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <sys/wait.h>
+#include <stdarg.h>
+#include <time.h>
+
+struct list
+{
+  char** items;
+  unsigned int itemcount;
+};
+
+struct list mods={0,0};
+struct list queue={0,0};
+struct list goodvids={0,0}; // pre-approved videos
+struct list badvids={0,0}; // not allowed, essentially banned
+char* playing=0;
+time_t started=0;
+int tc_client;
+
+void list_del(struct list* list, const char* item)
+{
+  unsigned int i;
+  unsigned int len;
+  while(item[0])
+  {
+    if(item[0]=='\r' || item[0]=='\n'){item=&item[1]; continue;} // Skip empty lines
+    for(len=0; item[len] && item[len]!='\r' && item[len]!='\n'; ++len);
+    for(i=0; i<list->itemcount; ++i)
+    {
+      if(!strncmp(list->items[i], item, len) && !list->items[i][len])
+      {
+        free(list->items[i]);
+        --list->itemcount;
+        memmove(&list->items[i], &list->items[i+1], sizeof(char*)*(list->itemcount-i));
+      }
+    }
+    item=&item[len];
+  }
+}
+
+void list_add(struct list* list, const char* item)
+{
+  list_del(list, item);
+  unsigned int len;
+  while(item[0])
+  {
+    if(item[0]=='\r' || item[0]=='\n'){item=&item[1]; continue;} // Skip empty lines
+    for(len=0; item[len] && item[len]!='\r' && item[len]!='\n'; ++len);
+    ++list->itemcount;
+    list->items=realloc(list->items, sizeof(char*)*list->itemcount);
+    list->items[list->itemcount-1]=strndup(item, len);
+    item=&item[len];
+  }
+}
+
+void list_switch(struct list* list, char* olditem, char* newitem)
+{
+  unsigned int i;
+  for(i=0; i<list->itemcount; ++i)
+  {
+    if(!strcmp(list->items[i], olditem))
+    {
+      free(list->items[i]);
+      list->items[i]=strdup(newitem);
+    }
+  }
+}
+
+int list_getpos(struct list* list, char* item)
+{
+  int i;
+  unsigned int len;
+  while(item[0])
+  {
+    if(item[0]=='\r' || item[0]=='\n'){item=&item[1]; continue;} // Skip empty lines
+    for(len=0; item[len] && item[len]!='\r' && item[len]!='\n'; ++len);
+    for(i=0; i<list->itemcount; ++i)
+    {
+      if(!strncmp(list->items[i], item, len) && !list->items[i][len]){return i;}
+    }
+    item=&item[len];
+  }
+  return -1;
+}
+
+char list_contains(struct list* list, char* item)
+{
+  return (list_getpos(list, item)!=-1);
+}
+
+void list_load(struct list* list, const char* file)
+{
+  struct stat st;
+  if(stat(file, &st)){return;}
+  int f=open(file, O_RDONLY);
+  char buf[st.st_size+1];
+  read(f, buf, st.st_size);
+  buf[st.st_size]=0;
+  close(f);
+  char* start=buf;
+  char* end;
+  while((end=strchr(start, '\n'))) // TODO: support \r?
+  {
+    end[0]=0;
+    list_add(list, start);
+    start=&end[1];
+  }
+  printf("Loaded %u lines from %s\n", list->itemcount, file);
+}
+
+void list_save(struct list* list, const char* file)
+{
+  int f=open(file, O_WRONLY|O_TRUNC|O_CREAT, 0600);
+  unsigned int i;
+  for(i=0; i<list->itemcount; ++i)
+  {
+    write(f, list->items[i], strlen(list->items[i]));
+    write(f, "\n", 1);
+  }
+  close(f);
+}
+
+void list_movetofront(struct list* list, unsigned int pos)
+{
+  if(pos>=list->itemcount){return;}
+  char* move=list->items[pos];
+  memmove(&list->items[1], list->items, sizeof(char*)*pos);
+  list->items[0]=move;
+}
+
+void say(const char* pm, const char* fmt, ...)
+{
+  va_list va;
+  va_start(va, fmt);
+  unsigned int len=vsnprintf(0,0,fmt,va);
+  va_end(va);
+  va_start(va, fmt);
+  char buf[len+1+(pm?strlen("/msg  ")+strlen(pm):0)];
+  char* msg=buf;
+  if(pm)
+  {
+    msg=&buf[strlen("/msg  ")+strlen(pm)];
+    sprintf(buf, "/msg %s ", pm);
+  }
+  vsprintf(msg, fmt, va);
+  va_end(va);
+  write(tc_client, buf, strlen(buf));
+}
+
+void getvidinfo(const char* vid, const char* type, char* buf, unsigned int len)
+{
+  int out[2];
+  pipe(out);
+  if(!fork())
+  {
+    close(out[0]);
+    dup2(out[1], 1);
+    execlp("youtube-dl", "youtube-dl", "--default-search", "auto", type, "--", vid, (char*)0);
+    perror("execlp(youtube-dl)");
+    _exit(1);
+  }
+  wait(0);
+  close(out[1]);
+  len=read(out[0], buf, len-1);
+  if(len<0){len=0;}
+  while(len>0 && (buf[len-1]=='\r' || buf[len-1]=='\n')){--len;} // Strip newlines
+  buf[len]=0;
+  close(out[0]);
+}
+
+unsigned int getduration(const char* vid)
+{
+  char timebuf[128];
+  timebuf[0]=':'; // Sacrifice 1 byte to avoid having to deal with a special case later on, where no ':' is found and we go from the start of the string, but only once
+  getvidinfo(vid, "--get-duration", &timebuf[1], 127);
+  if(!timebuf[1]){printf("Failed to get video duration using youtube-dl, assuming 60s\n"); return 60;} // If using youtube-dl fails, assume videos are 1 minute long
+  // youtube-dl prints it out in hh:mm:ss format, convert it to plain seconds
+  unsigned int len;
+  // Seconds
+  char* sep=strrchr(timebuf, ':');
+  if(sep){sep[0]=0; len=atoi(&sep[1]);}
+  // Minutes
+  sep=strrchr(timebuf, ':');
+  if(sep){sep[0]=0; len+=atoi(&sep[1])*60;}
+  // Hours
+  sep=strrchr(timebuf, ':');
+  if(sep){sep[0]=0; len+=atoi(&sep[1])*60;}
+  // Days
+  sep=strrchr(timebuf, ':');
+  if(sep){sep[0]=0; len+=atoi(&sep[1])*24;}
+  return len;
+}
+
+unsigned int waitskip=0;
+void playnextvid()
+{
+  waitskip=0;
+  playing=queue.items[0];
+  --queue.itemcount;
+  memmove(queue.items, &queue.items[1], sizeof(char*)*queue.itemcount);
+  say(0, "/mbs youTube %s 0\n", playing);
+  // Find out the video's length and schedule an alarm for then
+  alarm(getduration(playing));
+  started=time(0);
+}
+
+void playnext(int x)
+{
+  free(playing);
+  playing=0;
+  if(queue.itemcount<1){alarm(0); printf("Nothing more to play\n"); return;} // Nothing more to play
+  if(!list_contains(&goodvids, queue.items[0]))
+  {
+    if(!waitskip)
+    {
+      say(0, "Next video (http://youtube.com/watch?v=%s) is not yet approved by mods\n", queue.items[0]);
+      unsigned int i;
+      for(i=1; i<queue.itemcount; ++i)
+      {
+        if(list_contains(&goodvids, queue.items[i]))
+        {
+          waitskip=i;
+          alarm(120);
+          break;
+        }
+      }
+      return;
+    }else{
+      say(0, "Skipping http://youtube.com/watch?v=%s because it is still not approved after 2 minutes\n", queue.items[0]);
+      list_movetofront(&queue, waitskip);
+      waitskip=0;
+    }
+  }
+  playnextvid();
+}
+
+int main(int argc, char** argv)
+{
+  int in[2];
+  int out[2];
+  pipe(in);
+  pipe(out);
+  if(!fork())
+  {
+    close(in[1]);
+    close(out[0]);
+    dup2(in[0], 0);
+    dup2(out[1], 1);
+    execv("./tc_client", argv);
+    _exit(1);
+  }
+  close(in[0]);
+  close(out[1]);
+  tc_client=in[1];
+  signal(SIGALRM, playnext);
+  list_load(&goodvids, "goodvids.txt");
+  list_load(&badvids, "badvids.txt");
+  char buf[1024];
+  int len=0;
+  while(1)
+  {
+    if(read(out[0], &buf[len], 1)<1){break;}
+    if(len<1023&&buf[len]!='\r'&&buf[len]!='\n'){++len; continue;}
+    if(!len){continue;}
+    buf[len]=0;
+    char* esc;
+    while((esc=strstr(buf, "\x1b["))) // Strip out ANSI colors
+    {
+      for(len=2; isdigit(esc[len])||esc[len]==';'; ++len);
+      memmove(esc, &esc[len+1], strlen(&esc[len]));
+    }
+    len=0;
+    // printf("Got line '%s'\n", buf);
+    char* space=strchr(buf, ' ');
+    if(!space){continue;}
+    if(!strcmp(space, " is a moderator."))
+    {
+      // If there are not-yet-approved videos in the queue when a mod joins, ask them to review them
+      space[0]=0;
+      list_add(&mods, buf);
+      continue;
+    }
+    if(!strcmp(space, " is no longer a moderator."))
+    {
+      space[0]=0;
+      list_del(&mods, buf);
+      continue;
+    }
+    space[0]=0;
+    if(buf[0]=='['&&isdigit(buf[1])&&isdigit(buf[2])&&buf[3]==':') // Timestamp
+    {
+      char* nick=&space[1];
+      space=strchr(nick, ' ');
+      if(!space){continue;}
+      if(space[-1]==':') // Sent a message
+      {
+        space[-1]=0;
+        char* msg=&space[1];
+        // Handle commands sent in PMs
+        char* pm=0;
+        if(!strncmp(msg, "/msg ", 5))
+        {
+          msg=strchr(&msg[5], ' ');
+          if(!msg){continue;}
+          msg=&msg[1];
+          pm=nick;
+        }
+        if(!strncmp(msg, "!request ", 9))
+        {
+          char title[256];
+          char vid[1024];
+          getvidinfo(&msg[9], "--get-id", vid, 1024);
+          if(!vid[0]){say(pm, "No video found, sorry\n"); continue;} // Nothing found
+          char* plist;
+          for(plist=vid; plist[0] && plist[0]!='\r' && plist[0]!='\n'; plist=&plist[1]);
+          if(plist[0]) // Link was a playlist, do some trickery to get the title of the first video (instead of getting nothing)
+          {
+            strcpy(title, "Playlist, starting with ");
+            plist[0]=0;
+            getvidinfo(vid, "--get-title", &title[24], 256-24);
+            plist[0]='\n';
+          }else{
+            plist=0;
+            getvidinfo(vid, "--get-title", title, 256);
+          }
+          printf("Requested ID '%s' by '%s'\n", vid, nick);
+          // Check if it's already queued and mention which spot it's in, or if it's marked as bad and shouldn't be queued
+          int pos;
+          if((pos=list_getpos(&queue, vid))>-1)
+          {
+            say(pm, "Video '%s' is already in queue (number %i)\n", title, pos);
+            continue;
+          }
+          if(list_contains(&badvids, vid))
+          {
+            say(pm, "Video '%s' is marked as bad, won't add to queue\n", title);
+            continue;
+          }
+          if(list_contains(&mods, nick)) // Auto-approve for mods
+          {
+            list_add(&goodvids, vid);
+            list_del(&badvids, vid);
+            list_save(&goodvids, "goodvids.txt");
+            list_save(&badvids, "badvids.txt");
+          }
+
+          list_add(&queue, vid);
+          if(!list_contains(&goodvids, vid))
+          {
+            if(plist)
+            {
+              say(pm, "Playlist '%s' is added to the queue but will need to be approved by a mod\n", title);
+            }else{
+              say(pm, "Video '%s' (%s) is added to the queue but will need to be approved by a mod\n", vid, title);
+            }
+          }
+          else if(!playing){playnext(0);}
+          else{say(pm, "Added to queue\n");}
+        }
+        else if(!strcmp(msg, "!queue"))
+        {
+          unsigned int notapproved=0;
+          unsigned int len=0;
+          unsigned int i;
+          for(i=0; i<queue.itemcount; ++i)
+          {
+            if(!list_contains(&goodvids, queue.items[i])){++notapproved; len+=strlen(queue.items[i])+2;}
+          }
+          if(notapproved)
+          {
+            char buf[len];
+            buf[0]=0;
+            for(i=0; i<queue.itemcount; ++i)
+            {
+              if(!list_contains(&goodvids, queue.items[i]))
+              {
+                if(buf[0]){strcat(buf, ", ");}
+                strcat(buf, queue.items[i]);
+              }
+            }
+            say(pm, "%u videos in queue, %u of which are not yet approved by mods (%s)\n", queue.itemcount, notapproved, buf);
+          }else{
+            say(pm, "%u videos in queue\n", queue.itemcount);
+          }
+        }
+        else if(!strcmp(msg, "!time")) // Debugging
+        {
+          unsigned int remaining=alarm(0);
+          alarm(remaining);
+          say(pm, "'%s' is scheduled to end in %u seconds\n", playing, remaining);
+        }
+        else if(!strcmp(msg, "!help"))
+        {
+          say(nick, "The following commands can be used:\n");
+          usleep(100000);
+          say(nick, "!request <link> = request a video to be played\n");
+          usleep(100000);
+          say(nick, "!queue          = get the number of songs in queue and which (if any) need to  be approved\n");
+          usleep(100000);
+          say(nick, "Mod commands:\n"); // TODO: don't bother filling non-mods' chats with these?
+          usleep(100000);
+          say(nick, "!playnext       = play the next video in queue without approving it (to see if it's ok)\n");
+          usleep(100000);
+          say(nick, "!approve        = mark the currently playing video as good, or if none is playing the next in queue\n");
+          usleep(100000);
+          say(nick, "!approve <link> = mark the specified video as okay\n");
+          say(nick, "!approve next   = mark the next not yet approved video as okay\n");
+          say(nick, "!approve entire queue = approve all videos in queue (for playlists)\n");
+          usleep(100000);
+          say(nick, "!badvid         = stop playing the current video and mark it as bad\n");
+          usleep(100000);
+          say(nick, "!badvid <link>  = mark the specified video as bad, preventing it from ever being queued again\n");
+          say(nick, "You can also just play videos manually and they will be marked as good.\n");
+        }
+        else if(list_contains(&mods, nick)) // Mods-only commands
+        {
+          if(!strcmp(msg, "!playnext"))
+          {
+            if(playing){say(pm, "A video (%s) is already playing\n", playing); continue;}
+            if(queue.itemcount<1){say(pm, "There are no videos in queue, sorry\n"); continue;}
+            playnextvid();
+          }
+          else if(!strcmp(msg, "!approve"))
+          {
+            if(playing)
+            {
+              if(list_contains(&goodvids, playing) && !list_contains(&badvids, playing)){say(pm, "'%s' is already approved, use !approve <ID> to approve another video (or 'next' instead of an ID to approve the next not-yet-approved video in queue)\n", playing); continue;}
+              list_add(&goodvids, playing);
+              list_del(&badvids, playing);
+              list_save(&goodvids, "goodvids.txt");
+              list_save(&badvids, "badvids.txt");
+            }else if(queue.itemcount>0){
+              if(list_contains(&goodvids, queue.items[0]) && !list_contains(&badvids, queue.items[0])){say(pm, "'%s' is already approved, use !approve <ID> to approve another video\n", queue.items[0]); continue;}
+              list_add(&goodvids, queue.items[0]);
+              list_del(&badvids, queue.items[0]);
+              list_save(&goodvids, "goodvids.txt");
+              list_save(&badvids, "badvids.txt");
+              playnext(0);
+            }else{say(pm, "Approve what? please specify a video\n");}
+          }
+          else if(!strncmp(msg, "!approve ", 9))
+          {
+            char* vid=&msg[9];
+            if(!vid[0]){continue;} // No video specified
+            char vidbuf[256];
+            if(!strcmp(vid, "next"))
+            {
+              unsigned int i;
+              for(i=0; i<queue.itemcount; ++i)
+              {
+                if(!list_contains(&goodvids, queue.items[i])){vid=queue.items[i]; break;}
+              }
+              if(i==queue.itemcount){say(pm, "Nothing more to approve :)\n"); continue;}
+            }
+            else if(!strcmp(vid, "entire queue"))
+            {
+              char approved=0;
+              unsigned int i;
+              for(i=0; i<queue.itemcount; ++i)
+              {
+                if(list_contains(&goodvids, queue.items[i])){continue;}
+                list_add(&goodvids, queue.items[i]);
+                approved=1;
+              }
+              if(approved)
+              {
+                list_save(&goodvids, "goodvids.txt");
+                if(!playing){playnext(0);} // Next in queue just got approved, so play it
+              }else{
+                say(0, "%s: there is nothing in the queue that isn't already approved, please do not overuse this function\n", nick);
+              }
+              continue;
+            }else{
+              getvidinfo(vid, "--get-id", vidbuf, 256);
+              vid=vidbuf;
+            }
+            list_add(&goodvids, vid);
+            list_del(&badvids, vid);
+            list_save(&goodvids, "goodvids.txt");
+            list_save(&badvids, "badvids.txt");
+            if(!playing && queue.itemcount>0 && !strcmp(vid, queue.items[0])){playnext(0);} // Next in queue just got approved, so play it
+          }
+          else if(!strcmp(msg, "!badvid") || !strncmp(msg, "!badvid ", 8))
+          {
+            if(!msg[7] && !playing){say(pm, "Nothing is playing, please use !badvid <URL/ID> instead\n"); continue;}
+            char vid[1024];
+            if(msg[7])
+            {
+              getvidinfo(&msg[8], "--get-id", vid, 256);
+            }else{strncpy(vid, playing, 1023); vid[1023]=0;}
+            if(!vid[0]){say(pm, "Video not found, sorry\n");}
+            list_del(&queue, vid);
+            list_del(&goodvids, vid);
+            list_add(&badvids, vid);
+            list_save(&goodvids, "goodvids.txt");
+            list_save(&badvids, "badvids.txt");
+            if(!strcmp(vid, playing)){say(0, "/mbc youTube\n"); playnext(0);}
+          }
+          else if(!strncmp(msg, "/mbs youTube ", 13))
+          {
+            // Someone manually started a video, mark that video as good, remove it from queue, and set an alarm for when it's modbot's turn to play stuff again
+            char* vid=&msg[13];
+            char* end=strchr(vid, ' ');
+            if(end){end[0]=0;}
+            list_del(&queue, vid);
+            list_add(&goodvids, vid);
+            list_save(&goodvids, "goodvids.txt");
+            free(playing);
+            playing=strdup(vid);
+            unsigned int pos=(end?(strtol(&end[1], 0, 0)/1000):0);
+            alarm(getduration(playing)-pos);
+            started=time(0)-pos;
+          }
+          else if(!strcmp(msg, "/mbc youTube")){playnext(0);} // Video cancelled
+          else if(!strncmp(msg, "/mbsk youTube ", 14)) // Seeking
+          {
+            unsigned int pos=strtol(&msg[14], 0, 0)/1000;
+            alarm(getduration(playing)-pos);
+            started=time(0)-pos;
+          }
+          // TODO: handle /mbpa (pause) and /mbpl (resume play)
+        }
+      }else{ // Actions
+        if(!strncmp(space, " changed nickname to ", 21))
+        {
+          space[0]=0;
+          if(list_contains(&mods, nick))
+          {
+            list_switch(&mods, nick, &space[21]);
+            nick=&space[21];
+            unsigned int i;
+            for(i=0; i<queue.itemcount; ++i)
+            {
+              if(!list_contains(&goodvids, queue.items[i]))
+              {
+                say(nick, "there are 1 or more videos in queue that are not yet approved, please type !queue to review them\n");
+                break;
+              }
+            }
+          }
+          continue;
+        }
+        else if(!strcmp(space, " entered the channel")) // Newcomer, inform about the currently playing video
+        {
+          if(playing)
+          {
+            space[0]=0;
+            say(0, "/priv %s /mbs youTube %s %u\n", nick, playing, (time(0)-started)*1000);
+          }
+        }
+      }
+    }
+  }
+  return 0;
+}
diff --git a/numlist.c b/numlist.c
new file mode 100644
index 0000000..d28c5f6
--- /dev/null
+++ b/numlist.c
@@ -0,0 +1,57 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include "numlist.h"
+
+// Functions for converting to/from the comma-separated decimal character code format that tinychat uses for chat messages, e.g. "97,98,99" = "abc"
+
+char* fromnumlist(char* in)
+{
+  int len=1;
+  char* x=in;
+  while((x=strchr(x, ',')))
+  {
+    ++len;
+    x=&x[1];
+  }
+  char* string=malloc(len+1);
+  int i;
+  for(i=0; i<len; ++i)
+  {
+    string[i]=strtol(in, &in, 0);
+    if(!in){break;}
+    in=&in[1];
+  }
+  string[len]=0;
+  return string;
+}
+
+char* tonumlist(const char* in)
+{
+  char* out=malloc(strlen(in)*strlen("255,"));
+  out[0]=0;
+  char* x=out;
+  int i;
+  for(i=0; in[i]; ++i)
+  {
+    sprintf(x, "%s%i", x==out?"":",", (int)in[i]&0xff);
+    x=&x[strlen(x)];
+  }
+  return out;
+}
diff --git a/numlist.h b/numlist.h
new file mode 100644
index 0000000..c76aece
--- /dev/null
+++ b/numlist.h
@@ -0,0 +1,18 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+extern char* fromnumlist(char* in);
+extern char* tonumlist(const char* in);
diff --git a/rtmp.c b/rtmp.c
new file mode 100644
index 0000000..9926621
--- /dev/null
+++ b/rtmp.c
@@ -0,0 +1,81 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <string.h>
+#include "rtmp.h"
+
+extern unsigned int flip(unsigned int bits, int bytecount);
+
+int rtmp_lastlen=0;
+int rtmp_lasttype=0;
+unsigned char* rtmp_getamf(unsigned char** msg, int* length, int* amflen)
+{
+  int headsize;
+  struct rtmph* head=(struct rtmph*)*msg;
+  while((void*)head<((void*)*msg)+*length)
+  {
+    int len=flip(head->length, 3);
+    int type;
+    switch(head->fmt)
+    {
+      case 0: headsize=12; break;
+      case 1: headsize=8; break;
+      case 2: headsize=4; break;
+      case 3: headsize=1; break;
+    }
+//  printf("fmt: %u\n", (unsigned int)head->fmt);
+//  printf("streamid: %u\n", (unsigned int)head->streamid);
+//  printf("timestamp: %u\n", (unsigned int)head->timestamp);
+    if(headsize>=8){
+//    printf("length: %u\n", flip(head->length, 3));
+//    printf("type: %u\n", (unsigned int)head->type);
+      type=head->type;
+//    if(head->fmt==0){printf("msgid: %u\n", (unsigned int)head->msgid);}
+      rtmp_lasttype=head->type;
+      rtmp_lastlen=len;
+    }else{
+      type=rtmp_lasttype;
+      len=rtmp_lastlen;
+    }
+
+    int skip=headsize+len+(len/128);
+//      printf("Skipping %i bytes to next message (%i + %i + %i)\n\n", skip, headsize, len, len/128);
+    *msg+=skip;
+    *length-=skip;
+    if(type==0x14)
+    {
+      unsigned char* data=((void*)head)+headsize;
+      // Cut out every 128th byte (0xc3 garbage required by RTMP)
+      int i;
+      skip=0;
+      for(i=128; i<len; i+=128)
+      {
+        ++skip;
+// printf("Skipping garbage byte '%x' at offset %i\n", (int)data[i]&0xff, i);
+        if(i+128<len)
+        {
+          memmove(&data[i], &data[i+skip], 128);
+        }else{
+          memmove(&data[i], &data[i+skip], len-i);
+        }
+      }
+      *amflen=len;
+      return data;
+    }
+    head=((void*)head)+skip;
+  }
+  return 0;
+}
diff --git a/rtmp.h b/rtmp.h
new file mode 100644
index 0000000..fb4035d
--- /dev/null
+++ b/rtmp.h
@@ -0,0 +1,30 @@
+/*
+    tc_client, a simple non-flash client for tinychat(.com)
+    Copyright (C) 2014  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#pragma pack(push)
+#pragma pack(1)
+struct rtmph
+{
+  unsigned int streamid:6;
+  unsigned int fmt:2;
+  unsigned int timestamp:24;
+  unsigned int length:24;
+  unsigned char type;
+  unsigned int msgid;
+};
+#pragma pack(pop)
+
+extern unsigned char* rtmp_getamf(unsigned char** msg, int* length, int* amflen);
diff --git a/testbuilds.sh b/testbuilds.sh
new file mode 100755
index 0000000..0b1488b
--- /dev/null
+++ b/testbuilds.sh
@@ -0,0 +1,38 @@
+#!/bin/sh
+# Utility to make sure that changes did not break the project in certain configurations
+make clean > /dev/null 2> /dev/null
+printf "Without mic, with gtk+-2.x, with streaming, without RTMP_DEBUG: "
+res="broken"
+while true; do
+  ./configure > /dev/null 2> /dev/null || break
+  sed -i -e '/^GTK_/d' config.mk
+  echo "GTK_LIBS=`pkg-config --libs gtk+-2.0 2> /dev/null`" >> config.mk
+  echo "GTK_CFLAGS=`pkg-config --cflags gtk+-2.0`" >> config.mk
+  if ! grep -q 'GTK_LIBS=.*-lgtk-[^- ]*-2' config.mk; then res="gtk+-2.x not found, can't test"; break; fi
+  if ! grep -q '^AVCODEC_LIBS' config.mk; then res="libavcodec not found, can't test"; break; fi
+  if ! grep -q '^SWSCALE_LIBS' config.mk; then res="libswscale not found, can't test"; break; fi
+  if ! grep -q '^LIBV4L2_LIBS' config.mk; then res="libv4l2 not found, can't test"; break; fi
+  echo 'CFLAGS+=-Werror' >> config.mk
+  make utils > /dev/null 2> /dev/null || break
+  res="works"
+  break
+done
+echo "$res"
+
+make clean > /dev/null 2> /dev/null
+printf "With mic, with gtk+-3.x, without streaming, with RTMP_DEBUG: "
+res="broken"
+while true; do
+  ENABLE_MIC=1 ./configure > /dev/null 2> /dev/null || break
+  if ! grep -q 'GTK_LIBS=.*-lgtk-3' config.mk; then res="gtk+-3.x not found, can't test"; break; fi
+  if ! grep -q '^AO_LIBS' config.mk; then res="libao not found, can't test"; break; fi
+  if ! grep -q 'RESAMPLE_LIBS' config.mk; then res="lib(av|sw)resample not found, can't test"; break; fi
+  if ! grep -q '^AVCODEC_LIBS' config.mk; then res="libavcodec not found, can't test"; break; fi
+  if ! grep -q '^SWSCALE_LIBS' config.mk; then res="libswscale not found, can't test"; break; fi
+  sed -i -e '/^LIBV4L2_LIBS/d' config.mk
+  echo 'CFLAGS+=-DRTMP_DEBUG=1 -Werror' >> config.mk
+  make utils > /dev/null 2> /dev/null || break
+  res="works"
+  break
+done
+echo "$res"
diff --git a/utilities/camviewer/camviewer.c b/utilities/camviewer/camviewer.c
new file mode 100644
index 0000000..174c60a
--- /dev/null
+++ b/utilities/camviewer/camviewer.c
@@ -0,0 +1,540 @@
+/*
+    camviewer, a sample application to view tinychat cam streams
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <unistd.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <libavcodec/avcodec.h>
+#include <libswscale/swscale.h>
+#if LIBAVUTIL_VERSION_MAJOR>50 || (LIBAVUTIL_VERSION_MAJOR==50 && LIBAVUTIL_VERSION_MINOR>37)
+  #include <libavutil/imgutils.h>
+#else
+  #include <libavcore/imgutils.h>
+#endif
+#ifdef HAVE_SOUND
+// TODO: use libavresample instead if available
+  #if HAVE_SOUND==avresample
+    #include <libavutil/opt.h>
+    #include <libavresample/avresample.h>
+  #else
+    #include <libswresample/swresample.h>
+  #endif
+  #include <ao/ao.h>
+#endif
+#include <gtk/gtk.h>
+#ifdef HAVE_V4L2
+  #include <libv4l2.h>
+  #include <linux/videodev2.h>
+#endif
+
+#if GTK_MAJOR_VERSION==2
+  #define GTK_ORIENTATION_HORIZONTAL 0
+  #define GTK_ORIENTATION_VERTICAL 1
+  GtkWidget* gtk_box_new(int vertical, int spacing)
+  {
+    if(vertical)
+    {
+      return gtk_vbox_new(1, spacing);
+    }else{
+      return gtk_hbox_new(1, spacing);
+    }
+  }
+#endif
+
+struct camera
+{
+  AVFrame* frame;
+  AVFrame* dstframe;
+  GtkWidget* cam;
+  AVCodecContext* vctx;
+  AVCodecContext* actx;
+  short* samples;
+  unsigned int samplecount;
+  char* id;
+  char* nick;
+  GtkWidget* box; // holds label and cam
+};
+
+struct viddata
+{
+  struct camera* cams;
+  unsigned int camcount;
+  GtkWidget* box;
+  AVCodec* vdecoder;
+  AVCodec* vencoder;
+  AVCodec* adecoder;
+#ifdef HAVE_SOUND
+  int audiopipe;
+  #if HAVE_SOUND==avresample
+    AVAudioResampleContext* resamplectx;
+  #else
+    SwrContext* swrctx;
+  #endif
+#endif
+};
+
+int tc_client[2];
+int tc_client_in[2];
+
+#ifdef HAVE_SOUND
+// Experimental mixer, not sure if it really works
+void camera_playsnd(struct viddata* data, struct camera* cam, short* samples, unsigned int samplecount)
+{
+  if(cam->samples)
+  {
+// int sources=1;
+    unsigned int i;
+    for(i=0; i<data->camcount; ++i)
+    {
+      if(!data->cams[i].samples){continue;}
+      if(cam==&data->cams[i]){continue;}
+      unsigned j;
+      for(j=0; j<cam->samplecount && j<data->cams[i].samplecount; ++j)
+      {
+        cam->samples[j]+=data->cams[i].samples[j];
+      }
+      free(data->cams[i].samples);
+      data->cams[i].samples=0;
+// ++sources;
+    }
+    write(data->audiopipe, cam->samples, cam->samplecount*sizeof(short));
+    free(cam->samples);
+// printf("Mixed sound from %i sources (cam: %p)\n", sources, cam);
+  }
+  cam->samples=malloc(samplecount*sizeof(short));
+  memcpy(cam->samples, samples, samplecount*sizeof(short));
+  cam->samplecount=samplecount;
+}
+#endif
+
+void camera_remove(struct viddata* data, const char* nick)
+{
+  unsigned int i;
+  for(i=0; i<data->camcount; ++i)
+  {
+    if(!strcmp(data->cams[i].id, nick))
+    {
+      gtk_widget_destroy(data->cams[i].box);
+      av_frame_free(&data->cams[i].frame);
+      avcodec_free_context(&data->cams[i].vctx);
+#ifdef HAVE_SOUND
+      avcodec_free_context(&data->cams[i].actx);
+#endif
+      free(data->cams[i].id);
+      free(data->cams[i].nick);
+      --data->camcount;
+      memmove(&data->cams[i], &data->cams[i+1], (data->camcount-i)*sizeof(struct camera));
+      break;
+    }
+  }
+}
+
+char buf[1024];
+gboolean handledata(GIOChannel* channel, GIOCondition condition, gpointer datap)
+{
+  struct viddata* data=datap;
+  unsigned int i;
+  for(i=0; i<1023; ++i)
+  {
+    if(read(tc_client[0], &buf[i], 1)<1){printf("No more data\n"); gtk_main_quit(); return 0;}
+    if(buf[i]=='\r'||buf[i]=='\n'){break;}
+  }
+  buf[i]=0;
+  // Start streams once we're properly connected
+  if(!strncmp(buf, "Currently on cam: ", 18))
+  {
+    char* next=&buf[16];
+    while(next)
+    {
+      char* user=&next[2];
+      next=strstr(user, ", ");
+      if(!user[0]){continue;}
+      if(next){next[0]=0;}
+      dprintf(tc_client_in[1], "/opencam %s\n", user);
+    }
+    return 1;
+  }
+  char* space=strchr(buf, ' ');
+  // Start a stream when someone cams up
+  if(space && !strcmp(space, " cammed up"))
+  {
+    space[0]=0;
+    dprintf(tc_client_in[1], "/opencam %s\n", buf);
+    return 1;
+  }
+  // Make sure the cam goes away when a user leaves
+  else if(space && !strcmp(space, " left the channel"))
+  {
+    space[0]=0;
+    camera_remove(data, buf);
+    return 1;
+  }
+  if(!strncmp(buf, "Starting media stream for ", 26))
+  {
+    char* nick=&buf[26];
+    char* id=strstr(nick, " (");
+    if(!id){return 1;}
+    id[0]=0;
+    id=&id[2];
+    char* idend=strchr(id, ')');
+    if(!idend){return 1;}
+    idend[0]=0;
+    ++data->camcount;
+    data->cams=realloc(data->cams, sizeof(struct camera)*data->camcount);
+    struct camera* cam=&data->cams[data->camcount-1];
+    cam->frame=av_frame_alloc();
+    cam->dstframe=av_frame_alloc();
+    cam->nick=strdup(nick);
+    cam->id=strdup(id);
+    cam->vctx=avcodec_alloc_context3(data->vdecoder);
+    avcodec_open2(cam->vctx, data->vdecoder, 0);
+#ifdef HAVE_SOUND
+    cam->actx=avcodec_alloc_context3(data->adecoder);
+    avcodec_open2(cam->actx, data->adecoder, 0);
+    cam->samples=0;
+#endif
+    cam->cam=gtk_image_new();
+    cam->box=gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
+    gtk_box_pack_start(GTK_BOX(cam->box), cam->cam, 0, 0, 0);
+    gtk_box_pack_start(GTK_BOX(cam->box), gtk_label_new(cam->nick), 0, 0, 0);
+    gtk_box_pack_start(GTK_BOX(data->box), cam->box, 0, 0, 0);
+    gtk_widget_show_all(cam->box);
+    return 1;
+  }
+  if(!strcmp(buf, "Starting outgoing media stream"))
+  {
+    ++data->camcount;
+    data->cams=realloc(data->cams, sizeof(struct camera)*data->camcount);
+    struct camera* cam=&data->cams[data->camcount-1];
+    cam->frame=av_frame_alloc();
+    cam->dstframe=av_frame_alloc();
+    cam->nick=strdup("You");
+    cam->id=strdup("out");
+    cam->vctx=avcodec_alloc_context3(data->vdecoder);
+    avcodec_open2(cam->vctx, data->vdecoder, 0);
+    cam->cam=gtk_image_new();
+    cam->box=gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
+    gtk_box_pack_start(GTK_BOX(cam->box), cam->cam, 0, 0, 0);
+    gtk_box_pack_start(GTK_BOX(cam->box), gtk_label_new(cam->nick), 0, 0, 0);
+    gtk_box_pack_start(GTK_BOX(data->box), cam->box, 0, 0, 0);
+    gtk_widget_show_all(cam->box);
+    return 1;
+  }
+  if(!strncmp(buf, "VideoEnd: ", 10))
+  {
+    camera_remove(data, &buf[10]);
+    return 1;
+  }
+  if(!strncmp(buf, "Audio: ", 7))
+  {
+    char* sizestr=strchr(&buf[7], ' ');
+    if(!sizestr){return 1;}
+    sizestr[0]=0;
+    unsigned int size=strtoul(&sizestr[1], 0, 0);
+    if(!size){return 1;}
+    unsigned char frameinfo;
+    read(tc_client[0], &frameinfo, 1);
+    --size; // For the byte we read above
+    AVPacket pkt;
+    av_init_packet(&pkt);
+    unsigned char databuf[size];
+    pkt.data=databuf;
+    pkt.size=size;
+    unsigned int pos=0;
+    while(pos<size)
+    {
+      pos+=read(tc_client[0], pkt.data+pos, size-pos);
+    }
+#ifdef HAVE_SOUND
+    // Find the camera representation for the given ID (for decoder context)
+    struct camera* cam=0;
+    for(i=0; i<data->camcount; ++i)
+    {
+      if(!strcmp(data->cams[i].id, &buf[7])){cam=&data->cams[i]; break;}
+    }
+    if(!cam){printf("No cam found with ID '%s'\n", &buf[7]); return 1;}
+    int gotframe;
+    avcodec_decode_audio4(cam->actx, cam->frame, &gotframe, &pkt);
+    if(!gotframe){return 1;}
+  #if HAVE_SOUND==avresample
+    int outlen=avresample_convert(data->resamplectx, cam->frame->data, cam->frame->linesize[0], cam->frame->nb_samples, cam->frame->data, cam->frame->linesize[0], cam->frame->nb_samples);
+  #else
+    int outlen=swr_convert(data->resamplectx, cam->frame->data, cam->frame->nb_samples, (const uint8_t**)cam->frame->data, cam->frame->nb_samples);
+  #endif
+    camera_playsnd(data, cam, (short*)cam->frame->data[0], outlen);
+#endif
+    return 1;
+  }
+  if(strncmp(buf, "Video: ", 7)){printf("Got '%s'\n", buf); fflush(stdout); return 1;} // Ignore anything else that isn't video
+  char* sizestr=strchr(&buf[7], ' ');
+  if(!sizestr){return 1;}
+  sizestr[0]=0;
+  // Find the camera representation for the given ID
+  struct camera* cam=0;
+  for(i=0; i<data->camcount; ++i)
+  {
+    if(!strcmp(data->cams[i].id, &buf[7])){cam=&data->cams[i]; break;}
+  }
+  unsigned int size=strtoul(&sizestr[1], 0, 0);
+  if(!size){return 1;}
+  // Mostly ignore the first byte (contains frame type (e.g. keyframe etc.) in 4 bits and codec in the other 4)
+  --size;
+  AVPacket pkt;
+  av_init_packet(&pkt);
+  unsigned char databuf[size+4];
+  pkt.data=databuf;
+  unsigned char frameinfo;
+  read(tc_client[0], &frameinfo, 1);
+// printf("Frametype-frame: %x\n", ((unsigned int)frameinfo&0xf0)/16);
+// printf("Frametype-codec: %x\n", (unsigned int)frameinfo&0xf);
+  unsigned int pos=0;
+  while(pos<size)
+  {
+    pos+=read(tc_client[0], pkt.data+pos, size-pos);
+  }
+  if((frameinfo&0xf)!=2){return 1;} // Not FLV1, get data but discard it
+  if(!cam){printf("No cam found with ID '%s'\n", &buf[7]); return 1;}
+  pkt.size=size;
+  int gotframe;
+  avcodec_decode_video2(cam->vctx, cam->frame, &gotframe, &pkt);
+  if(!gotframe){return 1;}
+
+  // Convert to RGB24 format
+  unsigned int bufsize=avpicture_get_size(PIX_FMT_RGB24, cam->frame->width, cam->frame->height);
+  unsigned char buf[bufsize];
+  cam->dstframe->data[0]=buf;
+  cam->dstframe->linesize[0]=cam->frame->width*3;
+  struct SwsContext* swsctx=sws_getContext(cam->frame->width, cam->frame->height, cam->frame->format, cam->frame->width, cam->frame->height, AV_PIX_FMT_RGB24, 0, 0, 0, 0);
+  sws_scale(swsctx, (const uint8_t*const*)cam->frame->data, cam->frame->linesize, 0, cam->frame->height, cam->dstframe->data, cam->dstframe->linesize);
+  sws_freeContext(swsctx);
+
+  GdkPixbuf* gdkframe=gdk_pixbuf_new_from_data(cam->dstframe->data[0], GDK_COLORSPACE_RGB, 0, 8, cam->frame->width, cam->frame->height, cam->dstframe->linesize[0], 0, 0);
+  gtk_image_set_from_pixbuf(GTK_IMAGE(cam->cam), gdkframe);
+  // Make sure it gets redrawn in time
+  gdk_window_process_updates(gtk_widget_get_window(cam->cam), 1);
+
+  g_object_unref(gdkframe);
+  return 1;
+}
+
+#ifdef HAVE_SOUND
+void audiothread(int fd)
+{
+  ao_initialize();
+  ao_sample_format samplefmt;
+  samplefmt.bits=16;
+  samplefmt.rate=22050;
+  samplefmt.channels=1;
+  samplefmt.byte_format=AO_FMT_NATIVE; // I'm guessing libavcodec decodes it to native
+  samplefmt.matrix=0;
+  ao_option clientname={.key="client_name", .value="tc_client/camviewer", .next=0};
+  ao_device* dev=ao_open_live(ao_default_driver_id(), &samplefmt, &clientname);
+  char buf[2048];
+  size_t len;
+  while((len=read(fd, buf, 2048))>0)
+  {
+    ao_play(dev, buf, len);
+  }
+  ao_close(dev);
+}
+#endif
+
+#ifdef HAVE_V4L2
+pid_t camproc=0;
+void togglecam(GtkButton* button, struct viddata* data)
+{
+  if(camproc)
+  {
+    kill(camproc, SIGINT);
+    camproc=0;
+    gtk_button_set_label(button, "Broadcast cam");
+    dprintf(tc_client_in[1], "/camdown\n");
+    dprintf(tc_client[1], "VideoEnd: out\n"); // Close our local display
+    return;
+  }
+  // Set up a second pipe to be handled by handledata() to avoid overlap with tc_client's output
+  int campipe[2];
+  pipe(campipe);
+  dprintf(tc_client_in[1], "/camup\n");
+  gtk_button_set_label(button, "Stop broadcasting");
+// printf("Camming up!\n");
+  camproc=fork();
+  if(!camproc)
+  {
+    close(campipe[0]);
+    prctl(PR_SET_PDEATHSIG, SIGHUP);
+    unsigned int delay=500000;
+    // Set up camera
+    int fd=v4l2_open("/dev/video0", O_RDWR);
+    struct v4l2_format fmt;
+    fmt.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
+    fmt.fmt.pix.width=320;
+    fmt.fmt.pix.height=240;
+    fmt.fmt.pix.pixelformat=V4L2_PIX_FMT_RGB24;
+    fmt.fmt.pix.field=V4L2_FIELD_NONE;
+    fmt.fmt.pix.bytesperline=fmt.fmt.pix.width*3;
+    fmt.fmt.pix.sizeimage=fmt.fmt.pix.bytesperline*fmt.fmt.pix.height;
+    v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt);
+    AVCodecContext* ctx=avcodec_alloc_context3(data->vencoder);
+    ctx->width=fmt.fmt.pix.width;
+    ctx->height=fmt.fmt.pix.height;
+    ctx->pix_fmt=PIX_FMT_YUV420P;
+    ctx->time_base.num=1;
+    ctx->time_base.den=10;
+    avcodec_open2(ctx, data->vencoder, 0);
+    AVFrame* frame=av_frame_alloc();
+    frame->format=PIX_FMT_RGB24;
+    frame->width=fmt.fmt.pix.width;
+    frame->height=fmt.fmt.pix.height;
+    av_image_alloc(frame->data, frame->linesize, ctx->width, ctx->height, frame->format, 1);
+    AVPacket packet;
+    packet.buf=0;
+    packet.data=0;
+    packet.size=0;
+    packet.dts=AV_NOPTS_VALUE;
+    packet.pts=AV_NOPTS_VALUE;
+
+    // Set up frame for conversion from the camera's format to a format the encoder can use
+    AVFrame* dstframe=av_frame_alloc();
+    dstframe->format=ctx->pix_fmt;
+    dstframe->width=ctx->width;
+    dstframe->height=ctx->height;
+    av_image_alloc(dstframe->data, dstframe->linesize, ctx->width, ctx->height, ctx->pix_fmt, 1);
+
+    struct SwsContext* swsctx=sws_getContext(frame->width, frame->height, PIX_FMT_RGB24, frame->width, frame->height, AV_PIX_FMT_YUV420P, 0, 0, 0, 0);
+
+    while(1)
+    {
+      usleep(delay);
+      if(delay>100000){delay-=50000;}
+      v4l2_read(fd, frame->data[0], fmt.fmt.pix.sizeimage);
+      int gotpacket;
+      sws_scale(swsctx, (const uint8_t*const*)frame->data, frame->linesize, 0, frame->height, dstframe->data, dstframe->linesize);
+      av_init_packet(&packet);
+      packet.data=0;
+packet.size=0;
+      avcodec_encode_video2(ctx, &packet, dstframe, &gotpacket);
+      unsigned char frameinfo=0x22; // Note: differentiating between keyframes and non-keyframes seems to break stuff, so let's just go with all being interframes (1=keyframe, 2=interframe, 3=disposable interframe)
+      dprintf(tc_client_in[1], "/video %i\n", packet.size+1);
+      write(tc_client_in[1], &frameinfo, 1);
+      write(tc_client_in[1], packet.data, packet.size);
+      // Also send the packet to our main thread so we can see ourselves
+      dprintf(campipe[1], "Video: out %i\n", packet.size+1);
+      write(campipe[1], &frameinfo, 1);
+      write(campipe[1], packet.data, packet.size);
+
+      av_free_packet(&packet);
+    }
+    sws_freeContext(swsctx);
+    _exit(0);
+  }
+  close(campipe[1]);
+  GIOChannel* channel=g_io_channel_unix_new(campipe[0]);
+  g_io_channel_set_encoding(channel, 0, 0);
+  g_io_add_watch(channel, G_IO_IN, handledata, data);
+}
+#endif
+
+int main(int argc, char** argv)
+{
+  struct viddata data={0,0,0,0,0};
+  avcodec_register_all();
+  data.vdecoder=avcodec_find_decoder(AV_CODEC_ID_FLV1);
+  data.adecoder=avcodec_find_decoder(AV_CODEC_ID_NELLYMOSER);
+
+#ifdef HAVE_SOUND
+  #if HAVE_SOUND==avresample
+  data.resamplectx=avresample_alloc_context();
+  av_opt_set_int(data.resamplectx, "in_channel_layout", AV_CH_FRONT_CENTER, 0);
+  av_opt_set_int(data.resamplectx, "in_sample_fmt", AV_SAMPLE_FMT_FLT, 0);
+  // TODO: any way to get the sample rate from the frame/decoder? cam->frame->sample_rate seems to be 0
+  av_opt_set_int(data.resamplectx, "in_sample_rate", 11025, 0);
+  av_opt_set_int(data.resamplectx, "out_channel_layout", AV_CH_FRONT_CENTER, 0);
+  av_opt_set_int(data.resamplectx, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);
+  av_opt_set_int(data.resamplectx, "out_sample_rate", 22050, 0);
+  avresample_open(data.resamplectx);
+  #else
+  data.resamplectx=swr_alloc_set_opts(0, AV_CH_FRONT_CENTER, AV_SAMPLE_FMT_S16, 22050, AV_CH_FRONT_CENTER, AV_SAMPLE_FMT_FLT, 11025, 0, 0);
+  swr_init(data.swrctx);
+  #endif
+  int audiopipe[2];
+  pipe(audiopipe);
+  data.audiopipe=audiopipe[1];
+  if(!fork())
+  {
+    prctl(PR_SET_PDEATHSIG, SIGHUP);
+    close(audiopipe[1]);
+    audiothread(audiopipe[0]);
+    _exit(0);
+  }
+  close(audiopipe[0]);
+#endif
+
+  gtk_init(&argc, &argv);
+  GtkWidget* w=gtk_window_new(GTK_WINDOW_TOPLEVEL);
+  g_signal_connect(w, "destroy", gtk_main_quit, 0);
+  data.box=gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
+  gtk_container_add(GTK_CONTAINER(w), data.box);
+#ifdef HAVE_V4L2
+  data.vencoder=avcodec_find_encoder(AV_CODEC_ID_FLV1);
+  GtkWidget* cambutton=gtk_button_new_with_label("Broadcast cam");
+  g_signal_connect(cambutton, "clicked", G_CALLBACK(togglecam), &data);
+  gtk_box_pack_start(GTK_BOX(data.box), cambutton, 0, 0, 0);
+#endif
+  gtk_widget_show_all(w);
+
+  pipe(tc_client);
+  pipe(tc_client_in);
+  if(!fork())
+  {
+    prctl(PR_SET_PDEATHSIG, SIGHUP);
+    close(tc_client[0]);
+    close(tc_client_in[1]);
+    dup2(tc_client[1], 1);
+    dup2(tc_client_in[0], 0);
+    argv[0]="./tc_client";
+    execv("./tc_client", argv);
+  }
+  close(tc_client_in[0]);
+  GIOChannel* tcchannel=g_io_channel_unix_new(tc_client[0]);
+  g_io_channel_set_encoding(tcchannel, 0, 0);
+  unsigned int channel_id=g_io_add_watch(tcchannel, G_IO_IN, handledata, &data);
+
+  gtk_main();

+  g_source_remove(channel_id);
+  g_io_channel_shutdown(tcchannel, 0, 0);
+  unsigned int i;
+  for(i=0; i<data.camcount; ++i)
+  {
+    av_frame_free(&data.cams[i].frame);
+    avcodec_free_context(&data.cams[i].vctx);
+#ifdef HAVE_SOUND
+    avcodec_free_context(&data.cams[i].actx);
+  #if HAVE_SOUND==avresample
+    avresample_free(&data.resamplectx);
+  #else
+    swr_free(&data.swrctx);
+  #endif
+#endif
+    free(data.cams[i].id);
+    free(data.cams[i].nick);
+  }
+  free(data.cams);
+  return 0;
+}
diff --git a/utilities/compat.c b/utilities/compat.c
new file mode 100644
index 0000000..e620559
--- /dev/null
+++ b/utilities/compat.c
@@ -0,0 +1,35 @@
+/*
+    Some compatibility code to work on more limited platforms
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include "compat.h"
+#ifdef __ANDROID__
+// Android has no dprintf, so we make our own
+#include <stdarg.h>
+size_t dprintf(int fd, const char* fmt, ...)
+{
+  va_list va;
+  va_start(va, fmt);
+  int len=vsnprintf(0, 0, fmt, va);
+  va_end(va);
+  char buf[len+1];
+  va_start(va, fmt);
+  vsnprintf(buf, len+1, fmt, va);
+  va_end(va);
+  buf[len]=0;
+  write(fd, buf, len);
+  return len;
+}
+#endif
diff --git a/utilities/compat.h b/utilities/compat.h
new file mode 100644
index 0000000..2cfb39b
--- /dev/null
+++ b/utilities/compat.h
@@ -0,0 +1,21 @@
+/*
+    Some compatibility code to work on more limited platforms
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#ifdef __ANDROID__
+#include <stdint.h>
+extern size_t dprintf(int fd, const char* fmt, ...);
+#define mbtowc(x,y,z) 1
+#endif
diff --git a/utilities/cursedchat/buffer.c b/utilities/cursedchat/buffer.c
new file mode 100644
index 0000000..af06a16
--- /dev/null
+++ b/utilities/cursedchat/buffer.c
@@ -0,0 +1,62 @@
+/*
+    cursedchat, a simple curses interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <string.h>
+#include <stdlib.h>
+#include <curses.h>
+#include "buffer.h"
+
+struct buffer* buffers=0;
+unsigned int buffercount=0;
+unsigned int currentbuf=0;
+
+unsigned int createbuffer(const char* name)
+{
+  ++buffercount;
+  buffers=realloc(buffers, buffercount*sizeof(struct buffer));
+  buffers[buffercount-1].pad=newpad(2048, COLS);
+  scrollok(buffers[buffercount-1].pad, 1);
+  buffers[buffercount-1].name=(name?strdup(name):0);
+  buffers[buffercount-1].scroll=-1;
+  buffers[buffercount-1].seen=1;
+  return buffercount-1;
+}
+
+unsigned int findbuffer(const char* name)
+{
+  unsigned int i;
+  for(i=1; i<buffercount; ++i)
+  {
+    if(!strcmp(buffers[i].name, name)){return i;}
+  }
+  return 0;
+}
+
+void renamebufferunique(unsigned int id)
+{
+  unsigned int i=0;
+  while(i<buffercount)
+  {
+    int len=strlen(buffers[id].name);
+    buffers[id].name=realloc(buffers[id].name, len+2);
+    buffers[id].name[len]='_';
+    buffers[id].name[len+1]=0;
+    for(i=1; i<buffercount; ++i)
+    {
+      if(i!=id && !strcmp(buffers[i].name, buffers[id].name)){break;}
+    }
+  }
+}
diff --git a/utilities/cursedchat/buffer.h b/utilities/cursedchat/buffer.h
new file mode 100644
index 0000000..79ec1fc
--- /dev/null
+++ b/utilities/cursedchat/buffer.h
@@ -0,0 +1,31 @@
+/*
+    cursedchat, a simple curses interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+struct buffer
+{
+  WINDOW* pad;
+  char* name;
+  int scroll;
+  char seen;
+};
+
+extern struct buffer* buffers;
+extern unsigned int buffercount;
+extern unsigned int currentbuf;
+
+extern unsigned int createbuffer(const char* name);
+extern unsigned int findbuffer(const char* name);
+extern void renamebufferunique(unsigned int id);
diff --git a/utilities/cursedchat/cursedchat.c b/utilities/cursedchat/cursedchat.c
new file mode 100644
index 0000000..6e5385c
--- /dev/null
+++ b/utilities/cursedchat/cursedchat.c
@@ -0,0 +1,499 @@
+/*
+    cursedchat, a simple curses interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+    Copyright (C) 2015  Pamela Hiatt
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <unistd.h>
+#include <stdlib.h>
+#include <poll.h>
+#include <signal.h>
+#include <sys/ioctl.h>
+#include <termios.h>
+#include <locale.h>
+#include <curses.h>
+#include <readline/readline.h>
+#include <readline/history.h>
+#include "../compat.h"
+#include "../list.h"
+#include "buffer.h"
+
+#define HALFSCREEN (LINES>4?(LINES-3)/2:1)
+
+WINDOW* topic;
+char* channeltopic;
+WINDOW* input;
+int to_app;
+struct list userlist={0,0};
+char* nickname=0;
+
+// Translate ANSI escape codes to curses commands and write the text to a window
+void waddansi(WINDOW* w, char* str)
+{
+  while(str[0])
+  {
+    char* esc=strstr(str, "\x1b[");
+    if(esc==str)
+    {
+      str=&str[2];
+      while(str[0]!='m')
+      {
+        if(str[0]=='3'&&str[1]!='m') // Color
+        {
+          unsigned int c=strtoul(&str[1], &str, 10);
+          wattron(w, COLOR_PAIR(c+1));
+        }
+        else if(str[0]=='1') // Bold
+        {
+          wattron(w, A_BOLD);
+          str=&str[1];
+        }
+        else if(str[0]=='0') // Reset
+        {
+          wattroff(w, COLOR_PAIR(1));
+          wattroff(w, A_BOLD);
+          str=&str[1];
+        }
+        else{str=&str[1];}
+      }
+      str=&str[1];
+      continue;
+    }
+    if(esc)
+    {
+      waddnstr(w, str, esc-str);
+      str=esc;
+    }else{
+      waddstr(w, str);
+      return;
+    }
+  }
+}
+
+void drawchat(void)
+{
+  WINDOW* w=buffers[currentbuf].pad;
+  int scroll=buffers[currentbuf].scroll;
+  prefresh(w, (scroll>-1?scroll:getcury(w)-LINES+4), 0, 1, 0, LINES-3, COLS);
+}
+
+void drawtopic(void)
+{
+  werase(topic);
+  unsigned int i;
+  for(i=1; i<buffercount && buffers[i].seen; ++i);
+  if(i<buffercount)
+  {
+    waddstr(topic, "Unread PMs from: ");
+    char first=1;
+    for(i=1; i<buffercount; ++i)
+    {
+      if(!buffers[i].seen)
+      {
+        if(first){first=0;}else{waddstr(topic, ", ");}
+        waddstr(topic, buffers[i].name);
+      }
+    }
+  }
+  else if(currentbuf)
+  {
+    waddstr(topic, "To return to public chat type: /pm");
+  }else{
+    waddstr(topic, channeltopic);
+  }
+  wrefresh(topic);
+}
+
+void gotline(char* line)
+{
+  if(!line){close(to_app); return;} // TODO: handle EOF on stdin better?
+  add_history(line);
+  if(!strcmp(line, "/pm"))
+  {
+    currentbuf=0;
+    drawchat();
+    drawtopic();
+    return;
+  }
+  else if(!strncmp(line, "/pm ", 4))
+  {
+    currentbuf=findbuffer(&line[4]);
+    if(!currentbuf){currentbuf=createbuffer(&line[4]);}
+    buffers[currentbuf].seen=1;
+    drawchat();
+    drawtopic();
+    return;
+  }
+  else if(!strncmp(line, "/buffer ", 8))
+  {
+    unsigned int num=atoi(&line[8]);
+    if(num<0 || num>=buffercount)
+    {
+      wprintw(buffers[currentbuf].pad, "\nInvalid buffer number: %u", num);
+    }else{
+      currentbuf=num;
+      buffers[currentbuf].seen=1;
+      drawtopic();
+    }
+    drawchat();
+    return;
+  }
+  else if(!strcmp(line, "/bufferlist"))
+  {
+    unsigned int i;
+    for(i=0; i<buffercount; ++i)
+    {
+      wprintw(buffers[currentbuf].pad, "\n% 3i: %s", i, i?buffers[i].name:"");
+    }
+    drawchat();
+    return;
+  }
+  else if(!strncmp(line, "/msg ", 5))
+  {
+    char* name=&line[5];
+    char* msg=strchr(name, ' ');
+    if(!msg){return;}
+    msg[0]=0;
+    currentbuf=findbuffer(name);
+    if(!currentbuf){currentbuf=createbuffer(name);}
+    buffers[currentbuf].seen=1;
+    drawtopic();
+    memmove(line, &msg[1], strlen(&msg[1])+1);
+  }
+  else if(!strcmp(line, "/help"))
+  {
+    waddstr(buffers[0].pad, "\nFor cursedchat:\n"
+      "/pm <name>    = switch to the PM buffer for <name>\n"
+      "/pm           = return to the channel/public chat's buffer\n"
+      "/buffer <num> = switch to buffer by number\n"
+      "/bufferlist   = list open buffers, their numbers and associated names\n"
+      "\nFor tc_client (through cursedchat):");
+    write(to_app, line, strlen(line));
+    write(to_app, "\n", 1);
+    return;
+  }
+
+  if(currentbuf) // We're in a PM window, make the message a PM
+  {
+    dprintf(to_app, "/msg %s ", buffers[currentbuf].name);
+  }
+  write(to_app, line, strlen(line));
+  write(to_app, "\n", 1);
+  time_t timestamp=time(0);
+  struct tm* t=localtime(&timestamp);
+  wprintw(buffers[currentbuf].pad, "\n[%02i:%02i] %s: %s", t->tm_hour, t->tm_min, nickname, line);
+  drawchat();
+}
+
+unsigned int bytestochars(const char* buf, unsigned int buflen, unsigned int bytes)
+{
+  unsigned int pos=0;
+  unsigned int i;
+  for(i=0; i<bytes; ++pos)
+  {
+    i+=mbtowc(0,&buf[i],buflen-i);
+  }
+  return pos;
+}
+
+unsigned int charstobytes(const char* buf, unsigned int buflen, unsigned int chars)
+{
+  unsigned int pos;
+  unsigned int i=0;
+  for(pos=0; pos<chars; ++pos)
+  {
+    i+=mbtowc(0,&buf[i],buflen-i);
+  }
+  return i;
+}
+
+int escinput(int a, int byte)
+{
+  char buf[4];
+  read(0, buf, 2);
+  buf[2]=0;
+  if(!strcmp(buf, "[A")||!strcmp(buf, "OA")){rl_get_previous_history(1,27);return 0;}
+  if(!strcmp(buf, "[B")||!strcmp(buf, "OB")){rl_get_next_history(1,27);return 0;}
+  if(!strcmp(buf, "[C")||!strcmp(buf, "OC")){rl_forward(1,27);return 0;}
+  if(!strcmp(buf, "[D")||!strcmp(buf, "OD")){rl_backward(1,27);return 0;}
+  if(!strcmp(buf, "[H")||!strcmp(buf, "OH")){rl_beg_of_line(1,27);return 0;}
+  if(!strcmp(buf, "[F")||!strcmp(buf, "OF")){rl_end_of_line(1,27);return 0;}
+  if(!strcmp(buf, "[3")&&read(0, buf, 1)&&buf[0]=='~'){rl_delete(1,27);return 0;}
+  if(!strcmp(buf, "[5")) // Page up
+  {
+    read(0, buf, 1);
+    struct buffer* b=&buffers[currentbuf];
+    if(b->scroll<0){b->scroll=getcury(b->pad)-LINES+4;}
+    b->scroll-=HALFSCREEN;
+    if(b->scroll<0){b->scroll=0;}
+    drawchat();
+    return 0;
+  }
+  if(!strcmp(buf, "[6")) // Page down
+  {
+    read(0, buf, 1);
+    struct buffer* b=&buffers[currentbuf];
+    if(b->scroll<0){return 0;} // Already at the bottom
+    b->scroll+=HALFSCREEN;
+    if(b->scroll>getcury(b->pad)-LINES+3){b->scroll=-1;}
+    drawchat();
+    return 0;
+  }
+  return 0;
+}
+
+void drawinput(void)
+{
+  werase(input);
+  unsigned int pos=bytestochars(rl_line_buffer, rl_end, rl_point);
+
+  waddstr(input, "> ");
+  int cursor_row=(pos+2)/COLS;
+  int end_row=(rl_end+2)/COLS;
+  // Figure out how much of the buffer to print to not scroll past the cursor
+  unsigned int eol=charstobytes(rl_line_buffer, rl_end, (cursor_row+2)*COLS-3); // -2 for cursor, -1 to avoid wrapping
+  waddnstr(input, rl_line_buffer, eol);
+
+  wmove(input, cursor_row==end_row && cursor_row>0, (pos+2)%COLS); // +2 for prompt
+  wrefresh(input);
+}
+
+void resizechat(int sig)
+{
+  struct winsize size;
+  ioctl(0, TIOCGWINSZ, &size);
+  if(size.ws_row<3){return;} // Too small, would result in negative numbers breaking the chat window
+  resize_term(size.ws_row, size.ws_col);
+  clear();
+  refresh();
+  wresize(topic, 1, COLS);
+  unsigned int i;
+  for(i=0; i<buffercount; ++i)
+  {
+    wresize(buffers[i].pad, buffers[i].pad->_maxy+1, COLS);
+  }
+  wresize(input, 2, COLS);
+  mvwin(input, LINES-2, 0);
+  redrawwin(buffers[currentbuf].pad);
+  redrawwin(topic);
+  redrawwin(input);
+  drawchat();
+  drawtopic();
+  drawinput();
+}
+
+void dontprintmatches(char** matches, int num, int maxlen)
+{
+}
+
+unsigned int completionmatch;
+char* completenicks(const char* text, int state)
+{
+  // text is the word we're completing on, state is the iteration count (one iteration per matching name, until we return 0)
+  if(!state){completionmatch=0;}
+  while(completionmatch<userlist.itemcount)
+  {
+    if(!strncmp(userlist.items[completionmatch], text, strlen(text)))
+    {
+      char* completion=malloc(strlen(userlist.items[completionmatch])+2);
+      strcpy(completion, userlist.items[completionmatch]);
+      // Check if we're on the first word and only add the ":" if we are
+      if(strlen(text)>=rl_point){strcat(completion, ":");}
+      ++completionmatch;
+      return completion;
+    }
+    ++completionmatch;
+  }
+  return 0;
+}
+
+int main(int argc, char** argv)
+{
+  if(argc<3){execv("./tc_client", argv); return 1;}
+  setlocale(LC_ALL, "");
+  WINDOW* w=initscr();
+  signal(SIGWINCH, resizechat);
+  start_color();
+  cbreak();
+  noecho();
+  keypad(w, 1);
+  use_default_colors();
+  topic=newwin(1, COLS, 0, 0);
+  init_pair(1, COLOR_WHITE, COLOR_BLUE);
+
+  // Define colors mapped to ANSI color codes (at least the ones tc_client uses)
+  init_pair(2, COLOR_RED, -1);
+  init_pair(3, COLOR_GREEN, -1);
+  init_pair(4, COLOR_YELLOW, -1);
+  init_pair(5, COLOR_BLUE, -1);
+  init_pair(6, COLOR_MAGENTA, -1);
+  init_pair(7, COLOR_CYAN, -1);
+
+  wbkgd(topic, COLOR_PAIR(1)|' ');
+  createbuffer(0);
+  input=newwin(2, COLS, LINES-2, 0);
+  scrollok(input, 1);
+  rl_initialize();
+  rl_callback_handler_install(0, gotline);
+  rl_bind_key('\x1b', escinput);
+  rl_completion_display_matches_hook=dontprintmatches;
+  rl_completion_entry_function=completenicks;
+  wprintw(input, "> ");
+  wrefresh(topic);
+  wrefresh(input);
+  int app_in[2];
+  int app_out[2];
+  pipe(app_in);
+  pipe(app_out);
+  if(!fork())
+  {
+    close(app_in[1]);
+    close(app_out[0]);
+    dup2(app_in[0],0);
+    dup2(app_out[1],1);
+    argv[0]="./tc_client";
+    execv("./tc_client", argv);
+    _exit(1);
+  }
+  close(app_in[0]);
+  close(app_out[1]);
+  to_app=app_in[1];
+  struct pollfd p[2]={{.fd=0, .events=POLLIN, .revents=0},
+                      {.fd=app_out[0], .events=POLLIN, .revents=0}};
+  while(1)
+  {
+    poll(p, 2, -1);
+    if(p[1].revents) // Getting data from tc_client
+    {
+      p[1].revents=0;
+      char buf[1024];
+      size_t len=0;
+      while(len<1023)
+      {
+        if(read(app_out[0], &buf[len], 1)!=1){len=-1; break;}
+        if(buf[len]=='\r'||buf[len]=='\n'){break;}
+        ++len;
+      }
+      if(len==-1){break;} // Bad read
+      buf[len]=0;
+      unsigned int buffer=0;
+      if(!strncmp(buf, "Room topic: ", 12))
+      {
+        free(channeltopic);
+        channeltopic=strdup(&buf[12]);
+        drawtopic();
+      }
+      else if(!strncmp(buf, "Connection ID: ", 15)) // Our initial nickname is "guest-" plus our connection ID
+      {
+        unsigned int length=strlen(&buf[15]);
+        nickname=malloc(length+strlen("guest-")+1);
+        sprintf(nickname, "guest-%s", &(buf[15]));
+      }
+      else if(!strncmp(buf, "Currently online: ", 18))
+      {
+        // Populate the userlist
+        char* name=&buf[16];
+        while(name)
+        {
+          name=&name[2];
+          char* next=strstr(name, ", ");
+          if(next){next[0]=0;}
+          list_add(&userlist, name);
+          if(next){next[0]=',';}
+          name=next;
+        }
+      }
+      else if(buf[0]=='['&&isdigit(buf[1])&&isdigit(buf[2])&&buf[3]==':'&&isdigit(buf[4])&&isdigit(buf[5])&&buf[6]==']'&&buf[7]==' ')
+      {
+        char* nick=&buf[8];
+        char* msg=strchr(nick, ' ');
+        if(msg[-1]==':')
+        {
+          nick=strchr(nick, 'm')+1;
+          char* nickend=&msg[-1];
+          msg=&msg[1];
+          if(!strncmp(msg, "/msg ", 5)) // message is a PM
+          {
+            char* pm=strchr(&msg[5], ' ');
+            if(!pm){waddstr(buffers[0].pad, "\npm is null!"); continue;}
+            pm=&pm[1];
+            nickend[0]=0;
+            buffer=findbuffer(nick);
+            if(!buffer){buffer=createbuffer(nick);}
+            nickend[0]=':';
+            memmove(msg, pm, strlen(pm)+1);
+            if(buffer!=currentbuf)
+            {
+              buffers[buffer].seen=0;
+              drawtopic();
+            }
+          }
+        }
+        else if(!strncmp(msg, " changed nickname to ", 21))
+        {
+          msg[0]=0;
+          // Update name in userlist
+          list_switch(&userlist, nick, &msg[21]);
+          // If it was us, keep track of the new nickname
+          if(!strcmp(nickname, nick))
+          {
+            free(nickname);
+            nickname=strdup(&msg[21]);
+          }
+          // Prevent duplicate names for buffers, and all the issues that would bring
+          unsigned int i;
+          if((i=findbuffer(&msg[21])))
+          {
+            renamebufferunique(i);
+          }
+          for(i=1; i<buffercount; ++i)
+          {
+            if(!strcmp(buffers[i].name, nick))
+            {
+              free(buffers[i].name);
+              buffers[i].name=strdup(&msg[21]);
+            }
+          }
+          msg[0]=' ';
+        }
+        else if(!strcmp(msg, " entered the channel"))
+        {
+          msg[0]=0;
+          // Add to the userlist
+          list_add(&userlist, nick);
+          msg[0]=' ';
+        }
+        else if(!strcmp(msg, " left the channel"))
+        {
+          msg[0]=0;
+          // Remove from the userlist
+          list_del(&userlist, nick);
+          msg[0]=' ';
+        }
+      }
+      waddstr(buffers[buffer].pad, "\n");
+      waddansi(buffers[buffer].pad, buf);
+      drawchat();
+      wrefresh(input);
+      continue;
+    }
+    if(!p[0].revents){continue;}
+    p[0].revents=0;
+    rl_callback_read_char();
+    drawinput();
+  }
+  rl_callback_handler_remove();
+  endwin();
+  return 0;
+}
diff --git a/utilities/gtk/camviewer.c b/utilities/gtk/camviewer.c
new file mode 100644
index 0000000..dd65a8d
--- /dev/null
+++ b/utilities/gtk/camviewer.c
@@ -0,0 +1,888 @@
+/*
+    tc_client-gtk, a graphical user interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <unistd.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <sys/wait.h>
+#include <ctype.h>
+#include <libavcodec/avcodec.h>
+#include <libswscale/swscale.h>
+#if LIBAVUTIL_VERSION_MAJOR>50 || (LIBAVUTIL_VERSION_MAJOR==50 && LIBAVUTIL_VERSION_MINOR>37)
+  #include <libavutil/imgutils.h>
+#else
+  #include <libavcore/imgutils.h>
+#endif
+#ifdef HAVE_SOUND
+  // Use libavresample if available, otherwise fall back on libswresample
+  #if HAVE_SOUND==avresample
+    #include <libavutil/opt.h>
+    #include <libavresample/avresample.h>
+  #else
+    #include <libswresample/swresample.h>
+  #endif
+  #include <ao/ao.h>
+#endif
+#include <gtk/gtk.h>
+#include <gdk/gdkkeysyms.h>
+#ifdef HAVE_V4L2
+  #include <libv4l2.h>
+  #include <linux/videodev2.h>
+#endif
+#include "userlist.h"
+#include "media.h"
+#include "compat.h"
+#include "config.h"
+#include "gui.h"
+#include "logging.h"
+#include "../stringutils.h"
+
+struct viddata
+{
+  GtkWidget* box;
+  AVCodec* vdecoder;
+  AVCodec* vencoder;
+  AVCodec* adecoder;
+  int scalewidth;
+  int scaleheight;
+#ifdef HAVE_SOUND
+  int audiopipe;
+  #if HAVE_SOUND==avresample
+    AVAudioResampleContext* resamplectx;
+  #else
+    SwrContext* swrctx;
+  #endif
+#endif
+  GtkTextBuffer* buffer; // TODO: struct buffer array, for PMs
+  GtkAdjustment* scroll;
+  GtkBuilder* gui;
+};
+
+int tc_client[2];
+int tc_client_in[2];
+const char* channel=0;
+const char* mycolor=0;
+
+void updatescaling(struct viddata* data, unsigned int width, unsigned int height)
+{
+// TODO: Move updatescaling into media.c?
+  if(!camcount){return;}
+  if(!width){width=gtk_widget_get_allocated_width(data->box);}
+  if(!height){height=gtk_widget_get_allocated_height(data->box);}
+  data->scalewidth=width/camcount;
+  // 3/4 ratio
+  data->scaleheight=data->scalewidth*3/4;
+  unsigned int i;
+  unsigned int labelsize=0;
+  for(i=0; i<camcount; ++i)
+  {
+    if(gtk_widget_get_allocated_height(cams[i].label)>labelsize)
+      labelsize=gtk_widget_get_allocated_height(cams[i].label);
+  }
+  // Fit by height
+  if(height<data->scaleheight+labelsize)
+  {
+    data->scaleheight=height-labelsize;
+    data->scalewidth=data->scaleheight*4/3;
+  }
+  if(data->scalewidth<8){data->scalewidth=8;}
+  if(data->scaleheight<1){data->scaleheight=1;}
+  // TODO: wrapping and stuff
+  // Rescale current images to fit
+  for(i=0; i<camcount; ++i)
+  {
+    GdkPixbuf* pixbuf=gtk_image_get_pixbuf(GTK_IMAGE(cams[i].cam));
+    if(!pixbuf){continue;}
+    pixbuf=gdk_pixbuf_scale_simple(pixbuf, data->scalewidth, data->scaleheight, GDK_INTERP_BILINEAR);
+    gtk_image_set_from_pixbuf(GTK_IMAGE(cams[i].cam), pixbuf);
+// TODO: figure out/fix the "static" noise that seems to happen here
+  }
+}
+
+void printchat(struct viddata* data, const char* text)
+{
+  char bottom=autoscroll_before(data->scroll);
+  // Insert new content
+  GtkTextIter end;
+  gtk_text_buffer_get_end_iter(data->buffer, &end);
+  gtk_text_buffer_insert(data->buffer, &end, "\n", -1);
+  gtk_text_buffer_insert(data->buffer, &end, text, -1);
+  if(bottom){autoscroll_after(data->scroll);}
+}
+
+void printchat_color(struct viddata* data, const char* text, const char* color, unsigned int offset)
+{
+  char bottom=autoscroll_before(data->scroll);
+  // Insert new content
+  GtkTextIter end;
+  gtk_text_buffer_get_end_iter(data->buffer, &end);
+  gtk_text_buffer_insert(data->buffer, &end, "\n", -1);
+  int startnum=gtk_text_iter_get_offset(&end);
+  gtk_text_buffer_insert(data->buffer, &end, text, -1);
+  // Set color if there was one
+  GtkTextIter start;
+  gtk_text_buffer_get_iter_at_offset(data->buffer, &start, startnum+offset);
+  gtk_text_buffer_apply_tag_by_name(data->buffer, color, &start, &end);
+  if(bottom){autoscroll_after(data->scroll);}
+}
+
+char buf[1024];
+gboolean handledata(GIOChannel* iochannel, GIOCondition condition, gpointer datap)
+{
+  int fd=g_io_channel_unix_get_fd(iochannel);
+  struct viddata* data=datap;
+  unsigned int i;
+  for(i=0; i<1023; ++i)
+  {
+    if(read(fd, &buf[i], 1)<1){printf("No more data\n"); gtk_main_quit(); return 0;}
+    if(buf[i]=='\r'||buf[i]=='\n'){break;}
+  }
+  buf[i]=0;
+  if(!strncmp(buf, "Currently online: ", 18))
+  {
+    printchat(data, buf);
+    char* next=&buf[16];
+    while(next)
+    {
+      char* nick=&next[2];
+      next=strstr(nick, ", ");
+      if(next){next[0]=0;}
+      adduser(nick);
+    }
+    return 1;
+  }
+  // Start streams once we're properly connected
+  if(!strncmp(buf, "Currently on cam: ", 18))
+  {
+    printchat(data, buf);
+    char* next=&buf[16];
+    while(next)
+    {
+      char* user=&next[2];
+      next=strstr(user, ", ");
+      if(!user[0]){continue;}
+      if(next){next[0]=0;}
+      dprintf(tc_client_in[1], "/opencam %s\n", user);
+    }
+    return 1;
+  }
+  if(!strcmp(buf, "Password required"))
+  {
+    wait(0); // Reap the previous process
+    gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(data->gui, "main")));
+    gtk_widget_show_all(GTK_WIDGET(gtk_builder_get_object(data->gui, "channelpasswordwindow")));
+    return 1;
+  }
+  if(buf[0]=='/') // For the /help text
+  {
+    printchat(data, buf);
+    return 1;
+  }
+  // Remove escape codes and pick up the text color while we're at it
+  char* color=0;
+  char* esc;
+  char* escend;
+  while((esc=strchr(buf, '\x1b'))&&(escend=strchr(esc, 'm')))
+  {
+    escend[0]=0;
+    if(!color && strcmp(&esc[1], "[0")){color=strdup(&esc[1]);}
+    memmove(esc, &escend[1], strlen(&escend[1])+1);
+  }
+  char* space=strchr(buf, ' ');
+  // Timestamped events
+  if(buf[0]=='['&&isdigit(buf[1])&&isdigit(buf[2])&&buf[3]==':'&&isdigit(buf[4])&&isdigit(buf[5])&&buf[6]==']'&&buf[7]==' ')
+  {
+    char* nick=&buf[8];
+    space=strchr(nick, ' ');
+    if(!space){return 1;}
+    if(space[-1]==':')
+    {
+// TODO: handle /msg (PMs)
+      if(config_get_bool("soundradio_cmd") && !fork())
+      {
+        execlp("sh", "sh", "-c", config_get_str("soundcmd"), (char*)0);
+        _exit(0);
+      }
+      if(!strncmp(space, " /mbs youTube ", 14) && config_get_bool("youtuberadio_cmd") && !fork())
+      {
+// TODO: store the PID and make sure it's dead before starting a new video?
+// TODO: only play videos from mods?
+        char* id=&space[14];
+        char* offset=strchr(id, ' ');
+        if(!offset){_exit(1);}
+        offset[0]=0;
+        offset=&offset[1];
+        // Handle format string
+        const char* fmt=config_get_str("youtubecmd");
+        int len=strlen(fmt)+1;
+        len+=strcount(fmt, "%i")*(strlen(id)-2);
+        len+=strcount(fmt, "%t")*(strlen(id)-2);
+        char cmd[len];
+        cmd[0]=0;
+        while(fmt[0])
+        {
+          if(!strncmp(fmt, "%i", 2)){strcat(cmd, id); fmt=&fmt[2]; continue;}
+          if(!strncmp(fmt, "%t", 2)){strcat(cmd, offset); fmt=&fmt[2]; continue;}
+          for(len=0; fmt[len] && strncmp(&fmt[len], "%i", 2) && strncmp(&fmt[len], "%t", 2); ++len);
+          strncat(cmd, fmt, len);
+          fmt=&fmt[len];
+        }
+        execlp("sh", "sh", "-c", cmd, (char*)0);
+        _exit(0);
+      }
+    }
+// TODO: handle logging PMs
+    if(config_get_bool("enable_logging")){logger_write(buf, channel, 0);}
+    // Insert new content
+    printchat_color(data, buf, color, 8);
+    if(space[-1]!=':') // Not a message
+    {
+      if(!strcmp(space, " entered the channel"))
+      {
+        space[0]=0;
+        adduser(nick);
+      }
+      else if(!strcmp(space, " left the channel"))
+      {
+        space[0]=0;
+        removeuser(nick);
+        camera_removebynick(nick);
+      }
+      else if(!strncmp(space, " changed nickname to ", 21))
+      {
+        space[0]=0;
+        renameuser(nick, &space[21]);
+        struct camera* cam=camera_findbynick(nick);
+        if(cam)
+        {
+          free(cam->nick);
+          cam->nick=strdup(&space[21]);
+          gtk_label_set_text(GTK_LABEL(cam->label), cam->nick);
+        }
+      }
+    }
+    free(color);
+    return 1;
+  }
+  if(!strcmp(buf, "Changed color") || !strncmp(buf, "Current color: ", 15))
+  {
+    printchat_color(data, buf, color, 0);
+    free((void*)mycolor);
+    mycolor=color;
+    return 1;
+  }
+  if(!strncmp(buf, "Color ", 6))
+  {
+    printchat_color(data, buf, color, 0);
+  }
+  free(color);
+  if(space && !strcmp(space, " is a moderator."))
+  {
+    space[0]=0;
+    struct user* user=finduser(buf);
+    if(user)
+    {
+      user->ismod=1;
+      renameuser(buf, buf); // Update the userlist label
+    }
+    return 1;
+  }
+  if(space && !strcmp(space, " is no longer a moderator."))
+  {
+    space[0]=0;
+    struct user* user=finduser(buf);
+    if(user){user->ismod=0;}
+    return 1;
+  }
+  // Start a stream when someone cams up
+  if(space && !strcmp(space, " cammed up"))
+  {
+    space[0]=0;
+    dprintf(tc_client_in[1], "/opencam %s\n", buf);
+    return 1;
+  }
+  if(!strncmp(buf, "Starting media stream for ", 26))
+  {
+    char* nick=&buf[26];
+    char* id=strstr(nick, " (");
+    if(!id){return 1;}
+    id[0]=0;
+    id=&id[2];
+    char* idend=strchr(id, ')');
+    if(!idend){return 1;}
+    idend[0]=0;
+    camera_removebynick(nick); // Remove any duplicates
+    struct camera* cam=camera_new();
+    cam->frame=av_frame_alloc();
+    cam->dstframe=av_frame_alloc();
+    cam->nick=strdup(nick);
+    cam->id=strdup(id);
+    cam->vctx=avcodec_alloc_context3(data->vdecoder);
+    avcodec_open2(cam->vctx, data->vdecoder, 0);
+#ifdef HAVE_SOUND
+    cam->actx=avcodec_alloc_context3(data->adecoder);
+    avcodec_open2(cam->actx, data->adecoder, 0);
+    cam->samples=0;
+#endif
+    cam->cam=gtk_image_new();
+    cam->box=gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
+    gtk_box_set_homogeneous(GTK_BOX(cam->box), 0);
+    gtk_box_pack_start(GTK_BOX(cam->box), cam->cam, 0, 0, 0);
+    cam->label=gtk_label_new(cam->nick);
+    gtk_box_pack_start(GTK_BOX(cam->box), cam->label, 0, 0, 0);
+    gtk_box_pack_start(GTK_BOX(data->box), cam->box, 0, 0, 0);
+    gtk_widget_show_all(cam->box);
+    updatescaling(data, 0, 0);
+    while(gtk_events_pending()){gtk_main_iteration();} // Make sure the label gets its size before we calculate scaling
+    updatescaling(data, 0, 0);
+    return 1;
+  }
+  if(!strcmp(buf, "Starting outgoing media stream"))
+  {
+    struct camera* cam=camera_new();
+    cam->frame=av_frame_alloc();
+    cam->dstframe=av_frame_alloc();
+    cam->nick=strdup("You");
+    cam->id=strdup("out");
+    cam->vctx=avcodec_alloc_context3(data->vdecoder);
+    avcodec_open2(cam->vctx, data->vdecoder, 0);
+    cam->actx=0;
+    cam->cam=gtk_image_new();
+    cam->box=gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
+    gtk_box_pack_start(GTK_BOX(cam->box), cam->cam, 0, 0, 0);
+    cam->label=gtk_label_new(cam->nick);
+    gtk_box_pack_start(GTK_BOX(cam->box), cam->label, 0, 0, 0);
+    gtk_box_pack_start(GTK_BOX(data->box), cam->box, 0, 0, 0);
+    gtk_widget_show_all(cam->box);
+    updatescaling(data, 0, 0);
+    while(gtk_events_pending()){gtk_main_iteration();} // Make sure the label gets its size before we calculate scaling
+    updatescaling(data, 0, 0);
+    return 1;
+  }
+  if(!strncmp(buf, "VideoEnd: ", 10))
+  {
+    camera_remove(&buf[10]);
+    updatescaling(data, 0, 0);
+    return 1;
+  }
+  if(!strncmp(buf, "Audio: ", 7))
+  {
+    char* sizestr=strchr(&buf[7], ' ');
+    if(!sizestr){return 1;}
+    sizestr[0]=0;
+    unsigned int size=strtoul(&sizestr[1], 0, 0);
+    if(!size){return 1;}
+    unsigned char frameinfo;
+    read(fd, &frameinfo, 1);
+    --size; // For the byte we read above
+    AVPacket pkt;
+    av_init_packet(&pkt);
+    unsigned char databuf[size];
+    pkt.data=databuf;
+    pkt.size=size;
+    unsigned int pos=0;
+    while(pos<size)
+    {
+      pos+=read(fd, pkt.data+pos, size-pos);
+    }
+#ifdef HAVE_SOUND
+    // Find the camera representation for the given ID (for decoder context)
+    struct camera* cam=camera_find(&buf[7]);
+    if(!cam){printf("No cam found with ID '%s'\n", &buf[7]); return 1;}
+    int gotframe;
+    avcodec_decode_audio4(cam->actx, cam->frame, &gotframe, &pkt);
+    if(!gotframe){return 1;}
+  #if HAVE_SOUND==avresample
+    int outlen=avresample_convert(data->resamplectx, cam->frame->data, cam->frame->linesize[0], cam->frame->nb_samples, cam->frame->data, cam->frame->linesize[0], cam->frame->nb_samples);
+  #else
+    int outlen=swr_convert(data->resamplectx, cam->frame->data, cam->frame->nb_samples, (const uint8_t**)cam->frame->data, cam->frame->nb_samples);
+  #endif
+    camera_playsnd(data->audiopipe, cam, (short*)cam->frame->data[0], outlen);
+#endif
+    return 1;
+  }
+  if(strncmp(buf, "Video: ", 7)){printf("Got '%s'\n", buf); fflush(stdout); return 1;} // Ignore anything else that isn't video
+  char* sizestr=strchr(&buf[7], ' ');
+  if(!sizestr){return 1;}
+  sizestr[0]=0;
+  // Find the camera representation for the given ID
+  struct camera* cam=camera_find(&buf[7]);
+  unsigned int size=strtoul(&sizestr[1], 0, 0);
+  if(!size){return 1;}
+  // Mostly ignore the first byte (contains frame type (e.g. keyframe etc.) in 4 bits and codec in the other 4)
+  --size;
+  AVPacket pkt;
+  av_init_packet(&pkt);
+  unsigned char databuf[size+4];
+  pkt.data=databuf;
+  unsigned char frameinfo;
+  read(fd, &frameinfo, 1);
+// printf("Frametype-frame: %x\n", ((unsigned int)frameinfo&0xf0)/16);
+// printf("Frametype-codec: %x\n", (unsigned int)frameinfo&0xf);
+  unsigned int pos=0;
+  while(pos<size)
+  {
+    pos+=read(fd, pkt.data+pos, size-pos);
+  }
+  if((frameinfo&0xf)!=2){return 1;} // Not FLV1, get data but discard it
+  if(!cam){printf("No cam found with ID '%s'\n", &buf[7]); return 1;}
+  pkt.size=size;
+  int gotframe;
+  avcodec_decode_video2(cam->vctx, cam->frame, &gotframe, &pkt);
+  if(!gotframe){return 1;}
+
+  // Scale and convert to RGB24 format
+  unsigned int bufsize=avpicture_get_size(PIX_FMT_RGB24, data->scalewidth, data->scaleheight);
+  unsigned char buf[bufsize];
+  cam->dstframe->data[0]=buf;
+  cam->dstframe->linesize[0]=data->scalewidth*3;
+  struct SwsContext* swsctx=sws_getContext(cam->frame->width, cam->frame->height, cam->frame->format, data->scalewidth, data->scaleheight, AV_PIX_FMT_RGB24, 0, 0, 0, 0);
+  sws_scale(swsctx, (const uint8_t*const*)cam->frame->data, cam->frame->linesize, 0, cam->frame->height, cam->dstframe->data, cam->dstframe->linesize);
+  sws_freeContext(swsctx);
+
+  GdkPixbuf* gdkframe=gdk_pixbuf_new_from_data(cam->dstframe->data[0], GDK_COLORSPACE_RGB, 0, 8, data->scalewidth, data->scaleheight, cam->dstframe->linesize[0], 0, 0);
+  gtk_image_set_from_pixbuf(GTK_IMAGE(cam->cam), gdkframe);
+  // Make sure it gets redrawn in time
+  gdk_window_process_updates(gtk_widget_get_window(cam->cam), 1);
+
+  return 1;
+}
+
+#ifdef HAVE_SOUND
+void audiothread(int fd)
+{
+  ao_initialize();
+  ao_sample_format samplefmt;
+  samplefmt.bits=16;
+  samplefmt.rate=22050;
+  samplefmt.channels=1;
+  samplefmt.byte_format=AO_FMT_NATIVE; // I'm guessing libavcodec decodes it to native
+  samplefmt.matrix=0;
+  ao_option clientname={.key="client_name", .value="tc_client/camviewer", .next=0};
+  ao_device* dev=ao_open_live(ao_default_driver_id(), &samplefmt, &clientname);
+  char buf[2048];
+  size_t len;
+  while((len=read(fd, buf, 2048))>0)
+  {
+    ao_play(dev, buf, len);
+  }
+  ao_close(dev);
+}
+#endif
+
+#ifdef HAVE_V4L2
+pid_t camproc=0;
+void togglecam(GtkCheckMenuItem* item, struct viddata* data)
+{
+  if(!gtk_check_menu_item_get_active(item))
+  {
+    kill(camproc, SIGINT);
+    camproc=0;
+    dprintf(tc_client_in[1], "/camdown\n");
+    dprintf(tc_client[1], "VideoEnd: out\n"); // Close our local display
+    return;
+  }
+  // Set up a second pipe to be handled by handledata() to avoid overlap with tc_client's output
+  int campipe[2];
+  pipe(campipe);
+  dprintf(tc_client_in[1], "/camup\n");
+// printf("Camming up!\n");
+  camproc=fork();
+  if(!camproc)
+  {
+    close(campipe[0]);
+    prctl(PR_SET_PDEATHSIG, SIGHUP);
+    unsigned int delay=500000;
+    // Set up camera
+    int fd=v4l2_open("/dev/video0", O_RDWR);
+    struct v4l2_format fmt;
+    fmt.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
+    fmt.fmt.pix.width=320;
+    fmt.fmt.pix.height=240;
+    fmt.fmt.pix.pixelformat=V4L2_PIX_FMT_RGB24;
+    fmt.fmt.pix.field=V4L2_FIELD_NONE;
+    fmt.fmt.pix.bytesperline=fmt.fmt.pix.width*3;
+    fmt.fmt.pix.sizeimage=fmt.fmt.pix.bytesperline*fmt.fmt.pix.height;
+    v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt);
+    AVCodecContext* ctx=avcodec_alloc_context3(data->vencoder);
+    ctx->width=fmt.fmt.pix.width;
+    ctx->height=fmt.fmt.pix.height;
+    ctx->pix_fmt=PIX_FMT_YUV420P;
+    ctx->time_base.num=1;
+    ctx->time_base.den=10;
+    avcodec_open2(ctx, data->vencoder, 0);
+    AVFrame* frame=av_frame_alloc();
+    frame->format=PIX_FMT_RGB24;
+    frame->width=fmt.fmt.pix.width;
+    frame->height=fmt.fmt.pix.height;
+    av_image_alloc(frame->data, frame->linesize, ctx->width, ctx->height, frame->format, 1);
+    AVPacket packet;
+    packet.buf=0;
+    packet.data=0;
+    packet.size=0;
+    packet.dts=AV_NOPTS_VALUE;
+    packet.pts=AV_NOPTS_VALUE;
+
+    // Set up frame for conversion from the camera's format to a format the encoder can use
+    AVFrame* dstframe=av_frame_alloc();
+    dstframe->format=ctx->pix_fmt;
+    dstframe->width=ctx->width;
+    dstframe->height=ctx->height;
+    av_image_alloc(dstframe->data, dstframe->linesize, ctx->width, ctx->height, ctx->pix_fmt, 1);
+
+    struct SwsContext* swsctx=sws_getContext(frame->width, frame->height, PIX_FMT_RGB24, frame->width, frame->height, AV_PIX_FMT_YUV420P, 0, 0, 0, 0);
+
+    while(1)
+    {
+      usleep(delay);
+      if(delay>100000){delay-=50000;}
+      v4l2_read(fd, frame->data[0], fmt.fmt.pix.sizeimage);
+      int gotpacket;
+      sws_scale(swsctx, (const uint8_t*const*)frame->data, frame->linesize, 0, frame->height, dstframe->data, dstframe->linesize);
+      av_init_packet(&packet);
+      packet.data=0;
+packet.size=0;
+      avcodec_encode_video2(ctx, &packet, dstframe, &gotpacket);
+      unsigned char frameinfo=0x22; // Note: differentiating between keyframes and non-keyframes seems to break stuff, so let's just go with all being interframes (1=keyframe, 2=interframe, 3=disposable interframe)
+      dprintf(tc_client_in[1], "/video %i\n", packet.size+1);
+      write(tc_client_in[1], &frameinfo, 1);
+      write(tc_client_in[1], packet.data, packet.size);
+      // Also send the packet to our main thread so we can see ourselves
+      dprintf(campipe[1], "Video: out %i\n", packet.size+1);
+      write(campipe[1], &frameinfo, 1);
+      write(campipe[1], packet.data, packet.size);
+
+      av_free_packet(&packet);
+    }
+    sws_freeContext(swsctx);
+    _exit(0);
+  }
+  close(campipe[1]);
+  GIOChannel* channel=g_io_channel_unix_new(campipe[0]);
+  g_io_channel_set_encoding(channel, 0, 0);
+  g_io_add_watch(channel, G_IO_IN, handledata, data);
+}
+#endif
+
+gboolean handleresize(GtkWidget* widget, GdkEventConfigure* event, struct viddata* data)
+{
+  char bottom=autoscroll_before(data->scroll);
+  if(event->width!=gtk_widget_get_allocated_width(data->box))
+  {
+    updatescaling(data, event->width, 0);
+  }
+  if(bottom){autoscroll_after(data->scroll);}
+  return 0;
+}
+
+void handleresizepane(GObject* obj, GParamSpec* spec, struct viddata* data)
+{
+  char bottom=autoscroll_before(data->scroll);
+  updatescaling(data, 0, gtk_paned_get_position(GTK_PANED(obj)));
+  if(bottom){autoscroll_after(data->scroll);}
+}
+
+gboolean inputkeys(GtkWidget* widget, GdkEventKey* event, void* data)
+{
+  if(event->keyval==GDK_KEY_Up || event->keyval==GDK_KEY_Down){return 1;}
+  if(event->keyval==GDK_KEY_Tab)
+  {
+    // Tab completion
+    int cursor=gtk_editable_get_position(GTK_EDITABLE(widget));;
+    GtkEntryBuffer* buf=gtk_entry_get_buffer(GTK_ENTRY(widget));
+    const char* text=gtk_entry_buffer_get_text(buf);
+    unsigned int namestart=0;
+    unsigned int i;
+    for(i=0; i<cursor; ++i)
+    {
+      if(text[i]==' '){namestart=i+1;}
+    }
+    const char* matches[usercount];
+    unsigned int matchcount=0;
+    unsigned int commonlen=128;
+    for(i=0; i<usercount; ++i)
+    {
+      if(!strncmp(&text[namestart], userlist[i].nick, cursor-namestart))
+      {
+        unsigned int j;
+        for(j=0; j<matchcount; ++j)
+        {
+          if(strncmp(matches[j], userlist[i].nick, commonlen))
+          {
+            for(commonlen=0; userlist[i].nick[commonlen] && matches[j][commonlen] && userlist[i].nick[commonlen]==matches[j][commonlen]; ++commonlen);
+          }
+        }
+        matches[matchcount]=userlist[i].nick;
+        ++matchcount;
+      }
+    }
+    if(matchcount==1)
+    {
+      gtk_entry_buffer_insert_text(buf, cursor, &matches[0][cursor-namestart], -1);
+      cursor+=strlen(&matches[0][cursor-namestart]);
+      if(!namestart){gtk_entry_buffer_insert_text(buf, cursor, ": ", -1); cursor+=2;}
+      gtk_editable_set_position(GTK_EDITABLE(widget), cursor);
+    }
+    else if(matchcount>1)
+    {
+      gtk_entry_buffer_insert_text(buf, cursor, &matches[0][cursor-namestart], commonlen+namestart-cursor);
+      cursor=namestart+commonlen;
+      gtk_editable_set_position(GTK_EDITABLE(widget), cursor);
+    }
+    return 1;
+  }
+  return 0;
+}
+
+void sendmessage(GtkEntry* entry, struct viddata* data)
+{
+  const char* msg=gtk_entry_get_text(entry);
+  dprintf(tc_client_in[1], "%s\n", msg);
+  // Don't print commands
+  if(!strcmp(msg, "/help") ||
+     !strncmp(msg, "/color ", 7) ||
+     !strcmp(msg, "/color") ||
+     !strcmp(msg, "/colors") ||
+     !strncmp(msg, "/nick ", 6) ||
+//     !strncmp(msg, "/msg ", 5) || // except PM commands
+     !strncmp(msg, "/opencam ", 9) ||
+     !strncmp(msg, "/close ", 7) ||
+     !strncmp(msg, "/ban ", 5) ||
+     !strcmp(msg, "/banlist") ||
+     !strncmp(msg, "/forgive ", 9) ||
+     !strcmp(msg, "/names") ||
+     !strcmp(msg, "/mute") ||
+     !strcmp(msg, "/push2talk") ||
+     !strcmp(msg, "/camup") ||
+     !strcmp(msg, "/camdown") ||
+     !strncmp(msg, "/video ", 7) ||
+     !strncmp(msg, "/topic ", 7))
+  {
+    gtk_entry_set_text(entry, "");
+    return;
+  }
+  char text[strlen("[00:00] ")+strlen("You: ")+strlen(msg)+1];
+  time_t timestamp=time(0);
+  struct tm* t=localtime(&timestamp);
+  sprintf(text, "[%02i:%02i] ", t->tm_hour, t->tm_min);
+  sprintf(&text[8], "You: %s", msg);
+  if(config_get_bool("enable_logging")){logger_write(text, channel, 0);}
+  printchat_color(data, text, mycolor, 8);
+  gtk_entry_set_text(entry, "");
+}
+
+void startsession(GtkButton* button, struct viddata* data)
+{
+  gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(data->gui, "startwindow")));
+  gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(data->gui, "channelpasswordwindow")));
+  gtk_widget_show_all(GTK_WIDGET(gtk_builder_get_object(data->gui, "main")));
+  const char* nick=gtk_entry_get_text(GTK_ENTRY(gtk_builder_get_object(data->gui, "start_nick")));
+  channel=gtk_entry_get_text(GTK_ENTRY(gtk_builder_get_object(data->gui, "start_channel")));
+  const char* chanpass=gtk_entry_get_text(GTK_ENTRY(gtk_builder_get_object(data->gui, "channelpassword")));
+  const char* acc_user=gtk_entry_get_text(GTK_ENTRY(gtk_builder_get_object(data->gui, "acc_username")));
+  const char* acc_pass=gtk_entry_get_text(GTK_ENTRY(gtk_builder_get_object(data->gui, "acc_password")));
+  pipe(tc_client);
+  pipe(tc_client_in);
+  if(!fork())
+  {
+    prctl(PR_SET_PDEATHSIG, SIGHUP);
+    close(tc_client[0]);
+    close(tc_client_in[1]);
+    dup2(tc_client[1], 1);
+    dup2(tc_client_in[0], 0);
+    if(acc_user[0])
+    {
+      execl("./tc_client", "./tc_client", "-u", acc_user, channel, nick, chanpass, (char*)0);
+    }else{
+      execl("./tc_client", "./tc_client", channel, nick, chanpass, (char*)0);
+    }
+  }
+  if(acc_user[0]){dprintf(tc_client_in[1], "%s\n", acc_pass);}
+  write(tc_client_in[1], "/color\n", 7);
+  GIOChannel* tcchannel=g_io_channel_unix_new(tc_client[0]);
+  g_io_channel_set_encoding(tcchannel, 0, 0);
+  g_io_add_watch(tcchannel, G_IO_IN, handledata, data);
+  // Remember, if asked to
+  char save=0;
+  if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(gtk_builder_get_object(data->gui, "start_rememberchan"))))
+  {
+    config_set("remember_nick", gtk_entry_get_text(GTK_ENTRY(gtk_builder_get_object(data->gui, "start_nick"))));
+    config_set("remember_chan", gtk_entry_get_text(GTK_ENTRY(gtk_builder_get_object(data->gui, "start_channel"))));
+    config_set("remember_chan_nick", "True");
+    save=1;
+  }
+  else if(config_get_bool("remember_chan_nick")) // Remove previously remembered info
+  {
+    config_set("remember_nick", "");
+    config_set("remember_chan", "");
+    config_set("remember_chan_nick", "False");
+    save=1;
+  }
+  // Same for account
+  if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(gtk_builder_get_object(data->gui, "start_rememberacc"))))
+  {
+    config_set("remember_username", gtk_entry_get_text(GTK_ENTRY(gtk_builder_get_object(data->gui, "acc_username"))));
+    config_set("remember_password", gtk_entry_get_text(GTK_ENTRY(gtk_builder_get_object(data->gui, "acc_password"))));
+    config_set("remember_acc", "True");
+    save=1;
+  }
+  else if(config_get_bool("remember_acc")) // Remove previously remembered info
+  {
+    config_set("remember_username", "");
+    config_set("remember_password", "");
+    config_set("remember_acc", "False");
+    save=1;
+  }
+  if(save){config_save();}
+}
+
+int main(int argc, char** argv)
+{
+  struct viddata data={0,0,0,0,0};
+  avcodec_register_all();
+  data.vdecoder=avcodec_find_decoder(AV_CODEC_ID_FLV1);
+  data.adecoder=avcodec_find_decoder(AV_CODEC_ID_NELLYMOSER);
+
+#ifdef HAVE_SOUND
+  #if HAVE_SOUND==avresample
+  data.resamplectx=avresample_alloc_context();
+  av_opt_set_int(data.resamplectx, "in_channel_layout", AV_CH_FRONT_CENTER, 0);
+  av_opt_set_int(data.resamplectx, "in_sample_fmt", AV_SAMPLE_FMT_FLT, 0);
+  // TODO: any way to get the sample rate from the frame/decoder? cam->frame->sample_rate seems to be 0
+  av_opt_set_int(data.resamplectx, "in_sample_rate", 11025, 0);
+  av_opt_set_int(data.resamplectx, "out_channel_layout", AV_CH_FRONT_CENTER, 0);
+  av_opt_set_int(data.resamplectx, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);
+  av_opt_set_int(data.resamplectx, "out_sample_rate", 22050, 0);
+  avresample_open(data.resamplectx);
+  #else
+  data.resamplectx=swr_alloc_set_opts(0, AV_CH_FRONT_CENTER, AV_SAMPLE_FMT_S16, 22050, AV_CH_FRONT_CENTER, AV_SAMPLE_FMT_FLT, 11025, 0, 0);
+  swr_init(data.swrctx);
+  #endif
+  int audiopipe[2];
+  pipe(audiopipe);
+  data.audiopipe=audiopipe[1];
+  if(!fork())
+  {
+    prctl(PR_SET_PDEATHSIG, SIGHUP);
+    close(audiopipe[1]);
+    audiothread(audiopipe[0]);
+    _exit(0);
+  }
+  close(audiopipe[0]);
+#endif
+
+  gtk_init(&argc, &argv);
+  GtkBuilder* gui=gtk_builder_new_from_file("gtkgui.glade");
+  gtk_builder_connect_signals(gui, 0);
+  data.gui=gui;
+
+#ifdef HAVE_V4L2
+  GtkWidget* item=GTK_WIDGET(gtk_builder_get_object(gui, "menuitem_broadcast_camera"));
+  g_signal_connect(item, "toggled", G_CALLBACK(togglecam), &data);
+  data.vencoder=avcodec_find_encoder(AV_CODEC_ID_FLV1);
+#else
+  GtkWidget* item=GTK_WIDGET(gtk_builder_get_object(gui, "menuitem_broadcast"));
+  gtk_widget_destroy(item);
+#endif
+
+  item=GTK_WIDGET(gtk_builder_get_object(gui, "menuitem_options_settings"));
+  g_signal_connect(item, "activate", G_CALLBACK(showsettings), gui);
+  
+  data.box=GTK_WIDGET(gtk_builder_get_object(gui, "cambox"));
+  userlistwidget=GTK_WIDGET(gtk_builder_get_object(gui, "userlistbox"));
+  GtkWidget* chatview=GTK_WIDGET(gtk_builder_get_object(gui, "chatview"));
+  data.scroll=gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(gtk_builder_get_object(gui, "chatscroll")));
+
+  data.buffer=gtk_text_view_get_buffer(GTK_TEXT_VIEW(chatview));
+  #define colormap(code, color) gtk_text_buffer_create_tag(data.buffer, code, "foreground", color, (char*)0)
+  colormap("[31", "#821615");
+  colormap("[31;1", "#c53332");
+  colormap("[33", "#a08f23");
+  //colormap("[33", "#a78901");
+  colormap("[33;1", "#919104");
+  colormap("[32;1", "#7bb224");
+  //colormap("[32;1", "#7db257");
+  colormap("[32", "#487d21");
+  colormap("[36", "#00a990");
+  colormap("[34;1", "#32a5d9");
+  //colormap("[34;1", "#1d82eb");
+  colormap("[34", "#1965b6");
+  colormap("[35", "#5c1a7a");
+  colormap("[35;1", "#9d5bb5");
+  //colormap("[35;1", "#c356a3");
+  //colormap("[35;1", "#b9807f");
+
+  GtkWidget* panes=GTK_WIDGET(gtk_builder_get_object(gui, "vpaned"));
+  g_signal_connect(panes, "notify::position", G_CALLBACK(handleresizepane), &data);
+
+  GtkWidget* inputfield=GTK_WIDGET(gtk_builder_get_object(gui, "inputfield"));
+  g_signal_connect(inputfield, "activate", G_CALLBACK(sendmessage), &data);
+  g_signal_connect(inputfield, "key-press-event", G_CALLBACK(inputkeys), &data);
+
+  config_load();
+  // Sound
+  GtkWidget* option=GTK_WIDGET(gtk_builder_get_object(gui, "soundradio_cmd"));
+  g_signal_connect(option, "toggled", G_CALLBACK(toggle_soundcmd), gui);
+  // Logging
+  option=GTK_WIDGET(gtk_builder_get_object(gui, "enable_logging"));
+  g_signal_connect(option, "toggled", G_CALLBACK(toggle_logging), gui);
+  option=GTK_WIDGET(gtk_builder_get_object(gui, "save_settings"));
+  g_signal_connect(option, "clicked", G_CALLBACK(savesettings), gui);
+  // Youtube
+  option=GTK_WIDGET(gtk_builder_get_object(gui, "youtuberadio_cmd"));
+  g_signal_connect(option, "toggled", G_CALLBACK(toggle_youtubecmd), gui);
+
+  GtkWidget* window=GTK_WIDGET(gtk_builder_get_object(gui, "main"));
+  g_signal_connect(window, "configure-event", G_CALLBACK(handleresize), &data);
+
+  // Start window and channel password window signals
+  GtkWidget* button=GTK_WIDGET(gtk_builder_get_object(gui, "connectbutton"));
+  g_signal_connect(button, "clicked", G_CALLBACK(startsession), &data);
+  button=GTK_WIDGET(gtk_builder_get_object(gui, "channelpasswordbutton"));
+  g_signal_connect(button, "clicked", G_CALLBACK(startsession), &data);
+  button=GTK_WIDGET(gtk_builder_get_object(gui, "channelpassword"));
+  g_signal_connect(button, "activate", G_CALLBACK(startsession), &data);
+  GtkWidget* startwindow=GTK_WIDGET(gtk_builder_get_object(gui, "startwindow"));
+  // Set channel and nick from last session
+  if(config_get_bool("remember_chan_nick"))
+  {
+    gtk_entry_set_text(GTK_ENTRY(gtk_builder_get_object(gui, "start_nick")), config_get_str("remember_nick"));
+    gtk_entry_set_text(GTK_ENTRY(gtk_builder_get_object(gui, "start_channel")), config_get_str("remember_chan"));
+    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(gtk_builder_get_object(gui, "start_rememberchan")), 1);
+  }
+  // Set username and password from last session
+  if(config_get_bool("remember_acc"))
+  {
+    gtk_entry_set_text(GTK_ENTRY(gtk_builder_get_object(gui, "acc_username")), config_get_str("remember_username"));
+    gtk_entry_set_text(GTK_ENTRY(gtk_builder_get_object(gui, "acc_password")), config_get_str("remember_password"));
+    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(gtk_builder_get_object(gui, "start_rememberacc")), 1);
+  }
+  gtk_widget_show_all(startwindow);
+
+  gtk_main();

+  camera_cleanup();
+#ifdef HAVE_SOUND
+  #if HAVE_SOUND==avresample
+  avresample_free(&data.resamplectx);
+  #else
+  swr_free(&data.swrctx);
+  #endif
+#endif
+  return 0;
+}
diff --git a/utilities/gtk/compat.c b/utilities/gtk/compat.c
new file mode 100644
index 0000000..3f2efd4
--- /dev/null
+++ b/utilities/gtk/compat.c
@@ -0,0 +1,95 @@
+/*
+    tc_client-gtk, a graphical user interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <unistd.h>
+#include <fcntl.h>
+#include <string.h>
+#include <ctype.h>
+#include <sys/stat.h>
+#include <gtk/gtk.h>
+#include "compat.h"
+
+#if GTK_MAJOR_VERSION<3
+  GtkWidget* gtk_box_new(int vertical, int spacing)
+  {
+    if(vertical)
+    {
+      return gtk_vbox_new(1, spacing);
+    }else{
+      return gtk_hbox_new(1, spacing);
+    }
+  }
+  int gtk_widget_get_allocated_width(GtkWidget* widget)
+  {
+    GtkAllocation alloc;
+    gtk_widget_get_allocation(widget, &alloc);
+    return alloc.width;
+  }
+  int gtk_widget_get_allocated_height(GtkWidget* widget)
+  {
+    GtkAllocation alloc;
+    gtk_widget_get_allocation(widget, &alloc);
+    return alloc.height;
+  }
+  char* newline(char* line)
+  {
+    unsigned int i;
+    for(i=0; line[i] && line[i]!='\n' && line[i]!='\r'; ++i);
+    return &line[i];
+  }
+  // Hack to let us load a glade GUI designed for gtk+-3.x
+  GtkBuilder* gtk_builder_new_from_file(const char* filename)
+  {
+    struct stat st;
+    if(stat(filename, &st)){return 0;}
+    char buf[st.st_size+10];
+    int f=open(filename, O_RDONLY);
+    read(f, buf, st.st_size);
+    close(f);
+    buf[st.st_size]=0;
+    char* pos;
+    if((pos=strstr(buf, "<requires "))) // Don't require anything
+    {
+      char* end=newline(pos);
+      memmove(pos, end, strlen(end)+1);
+    }
+    // Convert orientation properties into GtkV/GtkH object types
+    char* orientation;
+    while((orientation=strstr(buf, "<property name=\"orientation\">")))
+    {
+      char dir=toupper(orientation[29]);
+      pos=newline(orientation);
+      memmove(orientation, pos, strlen(pos)+1);
+      pos=orientation;
+      while(pos>buf && strncmp(pos, "class=\"Gtk", 10)){--pos;}
+      if(pos>buf)
+      {
+        memmove(&pos[11], &pos[10], strlen(&pos[10])+1);
+        pos[10]=dir;
+      }
+    }
+    // Convert remaining GtkBoxes and GtkPaneds with the default orientation
+    while((pos=strstr(buf, "class=\"GtkBox\"")) || (pos=strstr(buf, "class=\"GtkPaned\"")))
+    {
+      memmove(&pos[11], &pos[10], strlen(&pos[10])+1);
+      pos[10]='H'; // Default is horizontal
+    }
+    GtkBuilder* gui=gtk_builder_new();
+    GError* error=0;
+    if(!gtk_builder_add_from_string(gui, buf, -1, &error)){g_error("%s\n", error->message);}
+    return gui;
+  }
+#endif
diff --git a/utilities/gtk/compat.h b/utilities/gtk/compat.h
new file mode 100644
index 0000000..88004d2
--- /dev/null
+++ b/utilities/gtk/compat.h
@@ -0,0 +1,24 @@
+/*
+    tc_client-gtk, a graphical user interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#if GTK_MAJOR_VERSION<3
+  #define GTK_ORIENTATION_HORIZONTAL 0
+  #define GTK_ORIENTATION_VERTICAL 1
+  extern GtkWidget* gtk_box_new(int vertical, int spacing);
+  extern int gtk_widget_get_allocated_width(GtkWidget* widget);
+  extern int gtk_widget_get_allocated_height(GtkWidget* widget);
+  extern GtkBuilder* gtk_builder_new_from_file(const char* filename);
+#endif
diff --git a/utilities/gtk/config.c b/utilities/gtk/config.c
new file mode 100644
index 0000000..7d5a813
--- /dev/null
+++ b/utilities/gtk/config.c
@@ -0,0 +1,127 @@
+/*
+    tc_client-gtk, a graphical user interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include "config.h"
+
+struct configitem
+{
+  const char* name;
+  char* value;
+};
+
+struct configitem* configitems=0;
+unsigned int configitemcount=0;
+
+void config_load(void)
+{
+  const char* home=getenv("HOME");
+  char filename[strlen(home)+strlen("/.config/tc_client-gtk0")];
+  sprintf(filename, "%s/.config/tc_client-gtk", home);
+  FILE* f=fopen(filename, "r");
+  if(!f){return;}
+  char buf[2048];
+  while(fgets(buf, 2048, f))
+  {
+    char* sep=strchr(buf, ':');
+    if(!sep){continue;}
+    sep[0]=0;
+    char* value=&sep[1];
+    while(value[0]==' '){value=&value[1];}
+    while((sep=strchr(value, '\r'))||(sep=strchr(value, '\n'))){sep[0]=0;}
+    ++configitemcount;
+    configitems=realloc(configitems, sizeof(struct configitem)*configitemcount);
+    configitems[configitemcount-1].name=strdup(buf);
+    configitems[configitemcount-1].value=strdup(value);
+  }
+  fclose(f);
+}
+
+void config_save(void)
+{
+  const char* home=getenv("HOME");
+  char filename[strlen(home)+strlen("/.config/tc_client-gtk0")];
+  sprintf(filename, "%s/.config", home);
+  mkdir(filename, 0700);
+  strcat(filename, "/tc_client-gtk");
+  FILE* f=fopen(filename, "w");
+  if(!f){perror("fopen(~/.config/tc_client-gtk)"); return;}
+  unsigned int i;
+  for(i=0; i<configitemcount; ++i)
+  {
+    fprintf(f, "%s: %s\n", configitems[i].name, configitems[i].value);
+  }
+  fclose(f);
+}
+
+char config_get_bool(const char* name)
+{
+  unsigned int i;
+  for(i=0; i<configitemcount; ++i)
+  {
+    if(!strcmp(configitems[i].name, name)){return !strcasecmp(configitems[i].value, "True");}
+  }
+  return 0;
+}
+
+const char* config_get_str(const char* name)
+{
+  unsigned int i;
+  for(i=0; i<configitemcount; ++i)
+  {
+    if(!strcmp(configitems[i].name, name)){return configitems[i].value;}
+  }
+  return "";
+}
+
+int config_get_int(const char* name)
+{
+  unsigned int i;
+  for(i=0; i<configitemcount; ++i)
+  {
+    if(!strcmp(configitems[i].name, name)){return atoi(configitems[i].value);}
+  }
+  return 0;
+}
+
+void config_set(const char* name, const char* value)
+{
+  unsigned int i;
+  for(i=0; i<configitemcount; ++i)
+  {
+    if(!strcmp(configitems[i].name, name))
+    {
+      free(configitems[i].value);
+      configitems[i].value=strdup(value);
+      return;
+    }
+  }
+  ++configitemcount;
+  configitems=realloc(configitems, sizeof(struct configitem)*configitemcount);
+  configitems[configitemcount-1].name=strdup(name);
+  configitems[configitemcount-1].value=strdup(value);
+}
+
+void config_set_int(const char* name, int value)
+{
+  int size=snprintf(0,0, "%i", value);
+  char buf[size+1];
+  sprintf(buf, "%i", value);
+  config_set(name, buf);
+}
diff --git a/utilities/gtk/config.h b/utilities/gtk/config.h
new file mode 100644
index 0000000..a12032c
--- /dev/null
+++ b/utilities/gtk/config.h
@@ -0,0 +1,25 @@
+/*
+    tc_client-gtk, a graphical user interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+extern void config_load(void);
+extern void config_save(void);
+
+extern char config_get_bool(const char* name);
+extern const char* config_get_str(const char* name);
+extern int config_get_int(const char* name);
+
+extern void config_set(const char* name, const char* value);
+extern void config_set_int(const char* name, int value);
diff --git a/utilities/gtk/gui.c b/utilities/gtk/gui.c
new file mode 100644
index 0000000..c59a207
--- /dev/null
+++ b/utilities/gtk/gui.c
@@ -0,0 +1,111 @@
+/*
+    tc_client-gtk, a graphical user interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <gtk/gtk.h>
+#include "gui.h"
+#include "config.h"
+#include "logging.h"
+
+char autoscroll_before(GtkAdjustment* scroll)
+{
+  // Figure out if we're at the bottom and should autoscroll with new content
+  int upper=gtk_adjustment_get_upper(scroll);
+  int size=gtk_adjustment_get_page_size(scroll);
+  int value=gtk_adjustment_get_value(scroll);
+  return (value+size==upper);
+}
+
+void autoscroll_after(GtkAdjustment* scroll)
+{
+  while(gtk_events_pending()){gtk_main_iteration();} // Make sure the textview's new size affects scroll's "upper" value first
+  int upper=gtk_adjustment_get_upper(scroll);
+  int size=gtk_adjustment_get_page_size(scroll);
+  gtk_adjustment_set_value(scroll, upper-size);
+}
+
+void settings_reset(GtkBuilder* gui)
+{
+  // Sound
+  GtkWidget* option=GTK_WIDGET(gtk_builder_get_object(gui, "soundradio_cmd"));
+  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(option), config_get_bool("soundradio_cmd"));
+  option=GTK_WIDGET(gtk_builder_get_object(gui, "soundcmd"));
+  gtk_entry_set_text(GTK_ENTRY(option), config_get_str("soundcmd"));
+  // Logging
+  option=GTK_WIDGET(gtk_builder_get_object(gui, "enable_logging"));
+  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(option), config_get_bool("enable_logging"));
+  GtkWidget* logpath=GTK_WIDGET(gtk_builder_get_object(gui, "logpath_channel"));
+  gtk_entry_set_text(GTK_ENTRY(logpath), config_get_str("logpath_channel"));
+  logpath=GTK_WIDGET(gtk_builder_get_object(gui, "logpath_pm"));
+  gtk_entry_set_text(GTK_ENTRY(logpath), config_get_str("logpath_pm"));
+  // Youtube
+  option=GTK_WIDGET(gtk_builder_get_object(gui, "youtuberadio_cmd"));
+  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(option), config_get_bool("youtuberadio_cmd"));
+  option=GTK_WIDGET(gtk_builder_get_object(gui, "youtubecmd"));
+  gtk_entry_set_text(GTK_ENTRY(option), config_get_str("youtubecmd"));
+}
+
+void showsettings(GtkMenuItem* item, GtkBuilder* gui)
+{
+  settings_reset(gui);
+  GtkWidget* w=GTK_WIDGET(gtk_builder_get_object(gui, "settings"));
+  gtk_widget_show_all(w);
+}
+
+void savesettings(GtkButton* button, GtkBuilder* gui)
+{
+  // Sound
+  GtkWidget* soundcmd=GTK_WIDGET(gtk_builder_get_object(gui, "soundcmd"));
+  config_set("soundcmd", gtk_entry_get_text(GTK_ENTRY(soundcmd)));
+  GtkWidget* soundradio_cmd=GTK_WIDGET(gtk_builder_get_object(gui, "soundradio_cmd"));
+  config_set("soundradio_cmd", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(soundradio_cmd))?"True":"False");
+  // Logging
+  GtkWidget* logging=GTK_WIDGET(gtk_builder_get_object(gui, "enable_logging"));
+  config_set("enable_logging", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(logging))?"True":"False");
+  if(!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(logging))){logger_close_all();}
+  GtkWidget* logpath=GTK_WIDGET(gtk_builder_get_object(gui, "logpath_channel"));
+  config_set("logpath_channel", gtk_entry_get_text(GTK_ENTRY(logpath)));
+  logpath=GTK_WIDGET(gtk_builder_get_object(gui, "logpath_pm"));
+  config_set("logpath_pm", gtk_entry_get_text(GTK_ENTRY(logpath)));
+  // Youtube
+  GtkWidget* youtubecmd=GTK_WIDGET(gtk_builder_get_object(gui, "youtubecmd"));
+  config_set("youtubecmd", gtk_entry_get_text(GTK_ENTRY(youtubecmd)));
+  GtkWidget* youtuberadio_cmd=GTK_WIDGET(gtk_builder_get_object(gui, "youtuberadio_cmd"));
+  config_set("youtuberadio_cmd", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(youtuberadio_cmd))?"True":"False");
+
+  config_save();
+  GtkWidget* settings=GTK_WIDGET(gtk_builder_get_object(gui, "settings"));
+  gtk_widget_hide(settings);
+}
+
+void toggle_soundcmd(GtkToggleButton* button, GtkBuilder* gui)
+{
+  GtkWidget* field=GTK_WIDGET(gtk_builder_get_object(gui, "soundcmd"));
+  gtk_widget_set_sensitive(field, gtk_toggle_button_get_active(button));
+}
+
+void toggle_logging(GtkToggleButton* button, GtkBuilder* gui)
+{
+  GtkWidget* field1=GTK_WIDGET(gtk_builder_get_object(gui, "logpath_channel"));
+  GtkWidget* field2=GTK_WIDGET(gtk_builder_get_object(gui, "logpath_pm"));
+  gtk_widget_set_sensitive(field1, gtk_toggle_button_get_active(button));
+  gtk_widget_set_sensitive(field2, gtk_toggle_button_get_active(button));
+}
+
+void toggle_youtubecmd(GtkToggleButton* button, GtkBuilder* gui)
+{
+  GtkWidget* field=GTK_WIDGET(gtk_builder_get_object(gui, "youtubecmd"));
+  gtk_widget_set_sensitive(field, gtk_toggle_button_get_active(button));
+}
diff --git a/utilities/gtk/gui.h b/utilities/gtk/gui.h
new file mode 100644
index 0000000..e4cfa68
--- /dev/null
+++ b/utilities/gtk/gui.h
@@ -0,0 +1,26 @@
+/*
+    tc_client-gtk, a graphical user interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <gtk/gtk.h>
+
+extern char autoscroll_before(GtkAdjustment* scroll);
+extern void autoscroll_after(GtkAdjustment* scroll);
+extern void settings_reset(GtkBuilder* gui);
+extern void showsettings(GtkMenuItem* item, GtkBuilder* gui);
+extern void savesettings(GtkButton* button, GtkBuilder* gui);
+extern void toggle_soundcmd(GtkToggleButton* button, GtkBuilder* gui);
+extern void toggle_logging(GtkToggleButton* button, GtkBuilder* gui);
+extern void toggle_youtubecmd(GtkToggleButton* button, GtkBuilder* gui);
diff --git a/utilities/gtk/logging.c b/utilities/gtk/logging.c
new file mode 100644
index 0000000..6b1a107
--- /dev/null
+++ b/utilities/gtk/logging.c
@@ -0,0 +1,97 @@
+/*
+    tc_client-gtk, a graphical user interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <sys/stat.h>
+#include "config.h"
+#include "../stringutils.h"
+
+struct logfile
+{
+  FILE* f;
+  const char* path;
+};
+struct logfile* logfiles=0;
+unsigned int logfilecount=0;
+
+void logger_write(const char* line, const char* channel, const char* nick)
+{
+  const char* home=getenv("HOME");
+  const char* path=config_get_str(nick?"logpath_pm":"logpath_channel");
+  int namelen=strlen(path)+1;
+  namelen+=strcount(path, "%h")*(strlen(home)-2);
+  namelen+=strcount(path, "%c")*(strlen(channel)-2);
+  if(nick){namelen+=strcount(path, "%n")*(strlen(nick)-2);}
+  char filename[namelen];
+  filename[0]=0;
+  int len;
+  while(path[0])
+  {
+    if(!strncmp(path, "%h", 2)){strcat(filename, home); path=&path[2]; continue;}
+    if(!strncmp(path, "%c", 2)){strcat(filename, channel); path=&path[2]; continue;}
+    if(nick && !strncmp(path, "%n", 2)){strcat(filename, nick); path=&path[2]; continue;}
+    for(len=0; path[len] && strncmp(&path[len], "%h", 2) && strncmp(&path[len], "%c", 2) && (!nick||strncmp(&path[len], "%n", 2)); ++len);
+    strncat(filename, path, len);
+    path=&path[len];
+  }
+  unsigned int i;
+  for(i=0; i<logfilecount; ++i)
+  {
+    if(!strcmp(filename, logfiles[i].path)){break;}
+  }
+  if(i==logfilecount)
+  {
+    ++logfilecount;
+    logfiles=realloc(logfiles, logfilecount*sizeof(struct logfile));
+    logfiles[i].path=strdup(filename);
+    // Make sure the whole path exists
+    char* sep=filename;
+    while((sep=strchr(sep, '/')))
+    {
+      sep[0]=0;
+printf("Creating '%s' if it doesn't exist yet\n", filename);
+      mkdir(filename, 0700);
+      sep[0]='/';
+      sep=&sep[1];
+    }
+    logfiles[i].f=fopen(logfiles[i].path, "a");
+    if(!logfiles[i].f)
+    {
+      perror("fopen(logfile)");
+      free((void*)logfiles[i].path);
+      --logfilecount;
+      return;
+    }
+    fprintf(logfiles[i].f, "Opening logfile on %ti (TODO: format)\n", time(0));
+  }
+  fprintf(logfiles[i].f, "%s\n", line);
+}
+
+void logger_close_all(void)
+{
+  unsigned int i;
+  for(i=0; i<logfilecount; ++i)
+  {
+    fclose(logfiles[i].f);
+    free((void*)logfiles[i].path);
+  }
+  free(logfiles);
+  logfiles=0;
+  logfilecount=0;
+}
diff --git a/utilities/gtk/logging.h b/utilities/gtk/logging.h
new file mode 100644
index 0000000..76c1831
--- /dev/null
+++ b/utilities/gtk/logging.h
@@ -0,0 +1,19 @@
+/*
+    tc_client-gtk, a graphical user interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+
+extern void logger_write(const char* line, const char* channel, const char* nick);
+extern void logger_close_all(void);
diff --git a/utilities/gtk/media.c b/utilities/gtk/media.c
new file mode 100644
index 0000000..e7fbb24
--- /dev/null
+++ b/utilities/gtk/media.c
@@ -0,0 +1,141 @@
+/*
+    tc_client-gtk, a graphical user interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <stdlib.h>
+#include <string.h>
+#include <gtk/gtk.h>
+#include <libavcodec/avcodec.h>
+#include "media.h"
+struct camera* cams=0;
+unsigned int camcount=0;
+
+#ifdef HAVE_SOUND
+// Experimental mixer, not sure if it really works
+void camera_playsnd(int audiopipe, struct camera* cam, short* samples, unsigned int samplecount)
+{
+  if(cam->samples)
+  {
+// int sources=1;
+    unsigned int i;
+    for(i=0; i<camcount; ++i)
+    {
+      if(!cams[i].samples){continue;}
+      if(cam==&cams[i]){continue;}
+      unsigned j;
+      for(j=0; j<cam->samplecount && j<cams[i].samplecount; ++j)
+      {
+        cam->samples[j]+=cams[i].samples[j];
+      }
+      free(cams[i].samples);
+      cams[i].samples=0;
+// ++sources;
+    }
+    write(audiopipe, cam->samples, cam->samplecount*sizeof(short));
+    free(cam->samples);
+// printf("Mixed sound from %i sources (cam: %p)\n", sources, cam);
+  }
+  cam->samples=malloc(samplecount*sizeof(short));
+  memcpy(cam->samples, samples, samplecount*sizeof(short));
+  cam->samplecount=samplecount;
+}
+#endif
+
+void camera_remove(const char* id)
+{
+  unsigned int i;
+  for(i=0; i<camcount; ++i)
+  {
+    if(!strcmp(cams[i].id, id))
+    {
+      gtk_widget_destroy(cams[i].box);
+      av_frame_free(&cams[i].frame);
+      avcodec_free_context(&cams[i].vctx);
+#ifdef HAVE_SOUND
+      avcodec_free_context(&cams[i].actx);
+#endif
+      free(cams[i].id);
+      free(cams[i].nick);
+      --camcount;
+      memmove(&cams[i], &cams[i+1], (camcount-i)*sizeof(struct camera));
+      break;
+    }
+  }
+}
+
+void camera_removebynick(const char* nick)
+{
+  unsigned int i;
+  for(i=0; i<camcount; ++i)
+  {
+    if(!strcmp(cams[i].nick, nick))
+    {
+      gtk_widget_destroy(cams[i].box);
+      av_frame_free(&cams[i].frame);
+      avcodec_free_context(&cams[i].vctx);
+#ifdef HAVE_SOUND
+      avcodec_free_context(&cams[i].actx);
+#endif
+      free(cams[i].id);
+      free(cams[i].nick);
+      --camcount;
+      memmove(&cams[i], &cams[i+1], (camcount-i)*sizeof(struct camera));
+      break;
+    }
+  }
+}
+
+struct camera* camera_find(const char* id)
+{
+  unsigned int i;
+  for(i=0; i<camcount; ++i)
+  {
+    if(!strcmp(cams[i].id, id)){return &cams[i];}
+  }
+  return 0;
+}
+
+struct camera* camera_findbynick(const char* nick)
+{
+  unsigned int i;
+  for(i=0; i<camcount; ++i)
+  {
+    if(!strcmp(cams[i].nick, nick)){return &cams[i];}
+  }
+  return 0;
+}
+
+struct camera* camera_new(void)
+{
+  ++camcount;
+  cams=realloc(cams, sizeof(struct camera)*camcount);
+  return &cams[camcount-1];
+}
+
+void camera_cleanup(void)
+{
+  unsigned int i;
+  for(i=0; i<camcount; ++i)
+  {
+    av_frame_free(&cams[i].frame);
+    avcodec_free_context(&cams[i].vctx);
+#ifdef HAVE_SOUND
+    avcodec_free_context(&cams[i].actx);
+#endif
+    free(cams[i].id);
+    free(cams[i].nick);
+  }
+  free(cams);
+}
diff --git a/utilities/gtk/media.h b/utilities/gtk/media.h
new file mode 100644
index 0000000..159e998
--- /dev/null
+++ b/utilities/gtk/media.h
@@ -0,0 +1,42 @@
+/*
+    tc_client-gtk, a graphical user interface for tc_client
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+struct camera
+{
+  AVFrame* frame;
+  AVFrame* dstframe;
+  GtkWidget* cam;
+  AVCodecContext* vctx;
+  AVCodecContext* actx;
+  short* samples;
+  unsigned int samplecount;
+  char* id;
+  char* nick;
+  GtkWidget* box; // holds label and cam
+  GtkWidget* label;
+};
+extern struct camera* cams;
+extern unsigned int camcount;
+
+#ifdef HAVE_SOUND
+extern void camera_playsnd(int audiopipe, struct camera* cam, short* samples, unsigned int samplecount);
+#endif
+extern void camera_remove(const char* nick);
+extern void camera_removebynick(const char* nick);
+extern struct camera* camera_find(const char* id);
+extern struct camera* camera_findbynick(const char* nick);
+extern struct camera* camera_new(void);
+extern void camera_cleanup(void);
diff --git a/utilities/gtk/userlist.c b/utilities/gtk/userlist.c
new file mode 100644
index 0000000..89d1df5
--- /dev/null
+++ b/utilities/gtk/userlist.c
@@ -0,0 +1,84 @@
+/*
+    camviewer, a sample application to view tinychat cam streams
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <stdlib.h>
+#include <string.h>
+#include <gtk/gtk.h>
+#include "userlist.h"
+
+struct user* userlist=0;
+unsigned int usercount=0;
+GtkWidget* userlistwidget=0;
+
+struct user* finduser(const char* nick)
+{
+  unsigned int i;
+  for(i=0; i<usercount; ++i)
+  {
+    if(!strcmp(userlist[i].nick, nick)){return &userlist[i];}
+  }
+  return 0;
+}
+
+struct user* adduser(const char* nick)
+{
+  struct user* user=finduser(nick);
+  if(user){return user;} // User already existed (this might happen when running /names)
+  ++usercount;
+  userlist=realloc(userlist, sizeof(struct user)*usercount);
+  userlist[usercount-1].nick=strdup(nick);
+  userlist[usercount-1].label=gtk_label_new(nick); // TODO: some kind of menubutton for actions?
+#if GTK_MAJOR_VERSION>=3
+  gtk_widget_set_halign(userlist[usercount-1].label, GTK_ALIGN_START);
+#endif
+  userlist[usercount-1].ismod=0;
+  gtk_box_pack_start(GTK_BOX(userlistwidget), userlist[usercount-1].label, 0, 0, 0);
+  gtk_widget_show(userlist[usercount-1].label);
+  return &userlist[usercount-1];
+}
+
+void renameuser(const char* old, const char* newnick)
+{
+  struct user* user=finduser(old);
+  if(!user){return;}
+  free(user->nick);
+  user->nick=strdup(newnick);
+  if(user->ismod)
+  {
+    char newlabel[strlen(newnick)+2];
+    newlabel[0]='@';
+    strcpy(&newlabel[1], newnick);
+    gtk_label_set_text(GTK_LABEL(user->label), newlabel);
+  }else{
+    gtk_label_set_text(GTK_LABEL(user->label), newnick);
+  }
+}
+
+void removeuser(const char* nick)
+{
+  unsigned int i;
+  for(i=0; i<usercount; ++i)
+  {
+    if(!strcmp(userlist[i].nick, nick))
+    {
+      free(userlist[i].nick);
+      gtk_widget_destroy(userlist[i].label);
+      --usercount;
+      memmove(&userlist[i], &userlist[i+1], (usercount-i)*sizeof(struct user));
+      return;
+    }
+  }
+}
diff --git a/utilities/gtk/userlist.h b/utilities/gtk/userlist.h
new file mode 100644
index 0000000..98b886e
--- /dev/null
+++ b/utilities/gtk/userlist.h
@@ -0,0 +1,32 @@
+/*
+    camviewer, a sample application to view tinychat cam streams
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+struct user
+{
+  char* nick;
+  GtkWidget* label;
+//  unsigned int id; // hm, tc_client doesn't share IDs other than in guestnicks, this might be useful for a ban-after-they-left situation
+  char ismod;
+};
+
+extern struct user* userlist;
+extern unsigned int usercount;
+extern GtkWidget* userlistwidget;
+
+extern struct user* finduser(const char* nick);
+extern struct user* adduser(const char* nick);
+extern void renameuser(const char* old, const char* newnick);
+extern void removeuser(const char* nick);
diff --git a/utilities/irchack/irchack.c b/utilities/irchack/irchack.c
new file mode 100644
index 0000000..d9fc248
--- /dev/null
+++ b/utilities/irchack/irchack.c
@@ -0,0 +1,408 @@
+/*
+    irchack, a simple application to reuse IRC clients as user interfaces for tc_client
+    Copyright (C) 2014-2015  alicia@ion.nu
+    Copyright (C) 2015  Jade Lea
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <netinet/in.h>
+#include <unistd.h>
+#include <poll.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <sys/socket.h>
+#include <ctype.h>
+#include <signal.h>
+#include "../compat.h"
+
+// ANSI colors and their IRC equivalents
+struct color{const char* ansi; const char* irc;};
+struct color colortable[]={
+  {"31",   "\x03""05"},
+  {"31;1", "\x03""04"},
+  {"33",   "\x03""07"},
+  {"33",   "\x03""07"},
+  {"33;1", "\x03""08"},
+  {"32;1", "\x03""09"},
+  {"32;1", "\x03""09"},
+  {"32",   "\x03""03"},
+  {"36",   "\x03""10"},
+  {"34;1", "\x03""12"},
+  {"34;1", "\x03""12"},
+  {"34",   "\x03""02"},
+  {"35",   "\x03""06"},
+  {"35;1", "\x03""13"},
+  {"35;1", "\x03""13"},
+  {"35;1", "\x03""13"}
+};
+
+const char* findcolor_irc(const char* ansi)
+{
+  int len;
+  for(len=0; ansi[len]&&ansi[len]!='m'; ++len);
+  int i;
+  for(i=0; i<16; ++i)
+  {
+    if(!strncmp(colortable[i].ansi, ansi, len) && !colortable[i].ansi[len])
+    {
+      return colortable[i].irc;
+    }
+  }
+  return 0;
+}
+
+int findcolor_ansi(char* irc, char** end)
+{
+  char color[4];
+  strncpy(color, irc, 3);
+  color[3]=0;
+  if(!isdigit(color[1])){*end=&irc[1]; return -1;}
+  if(!isdigit(color[2])){*end=&irc[2]; color[2]=color[1]; color[1]='0';}else{*end=&irc[3];}
+  int i;
+  for(i=0; i<16; ++i)
+  {
+    if(!strcmp(colortable[i].irc, color))
+    {
+      return i;
+    }
+  }
+  return -1;
+}
+
+extern char session(int sock, const char* nick, const char* channel, const char* pass, const char* acc_user, const char* acc_pass);
+
+int main(int argc, char** argv)
+{
+  int port=(argc>1?atoi(argv[1]):6667);
+  struct sockaddr_in addr;
+  memset(&addr, 0, sizeof(addr));
+  addr.sin_family=AF_INET;
+  addr.sin_addr.s_addr=htonl(0x7f000001); // 127.0.0.1
+  addr.sin_port=htons(port);
+  int lsock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if(bind(lsock, (struct sockaddr*)&addr, sizeof(addr))){perror("bind"); return 1;}
+  listen(lsock, 1);
+  printf("Done! Open an IRC client and connect to localhost on port %i\n", port);
+  signal(SIGCHLD, SIG_IGN);
+  int sock;
+  while((sock=accept(lsock, 0, 0))>-1)
+  {
+    if(fork()){continue;}
+    char buf[2048];
+    char* nick=0;
+    char* channel=0;
+    char* pass=0;
+    char* acc_user=0;
+    char* acc_pass=0;
+    int len;
+    while(1)
+    {
+      len=0;
+      int r;
+      while(len<2047)
+      {
+        if((r=read(sock, &buf[len], 1))!=1 || buf[len]=='\r' || buf[len]=='\n'){break;}
+        ++len;
+      }
+      if(r!=1){break;}
+      buf[len]=0;
+      if(!strncmp(buf, "USER ", 5))
+      {
+        acc_user=&buf[5];
+        char* end=strchr(acc_user, ' ');
+        if(end){end[0]=0;}
+        acc_user=strdup(acc_user);
+      }
+      else if(!strncmp(buf, "PASS ", 5))
+      {
+        acc_pass=&buf[5];
+        if(acc_pass[0]==':'){acc_pass=&acc_pass[1];}
+        acc_pass=strdup(acc_pass);
+      }
+      else if(!strncmp(buf, "NICK ", 5))
+      {
+        char* newnick=&buf[5];
+        if(newnick[0]==':'){newnick=&nick[1];}
+        if(!nick)
+        {
+          dprintf(sock, ":irchack 001 %s :Welcome\n", newnick);
+        }else{
+          dprintf(sock, ":%s!user@host NICK :%s\n", nick, newnick);
+        }
+        free(nick);
+        nick=strdup(newnick);
+      }
+      else if(nick && !strncmp(buf, "JOIN ", 5))
+      {
+        free(channel);
+        channel=&buf[5];
+        if(channel[0]==':'){channel=&channel[1];}
+        free(pass);
+        pass=strchr(channel, ' ');
+        if(pass)
+        {
+          pass[0]=0;
+          pass=&pass[1];
+          if(pass[0]==':'){pass=strdup(&pass[1]);}
+        }
+        if(channel[0]=='#'){channel=&channel[1];}
+        channel=strdup(channel);
+        if(!session(sock, nick, channel, pass, acc_user, acc_pass)){break;}
+      }
+      else if(!strncmp(buf, "PING ", 5))
+      {
+        dprintf(sock, ":irchack PONG %s\n", &buf[5]);
+      }
+    }
+    shutdown(sock, SHUT_RDWR);
+    _exit(0);
+  }
+  close(lsock);
+  return 0;
+}
+
+char session(int sock, const char* nick, const char* channel, const char* pass, const char* acc_user, const char* acc_pass)
+{
+  printf("Nick: %s\n", nick);
+  printf("Channel: %s\n", channel);
+  printf("Password: %s\n", pass);
+  int tc_in[2];
+  int tc_out[2];
+  pipe(tc_in);
+  pipe(tc_out);
+  if(!fork())
+  {
+    close(tc_in[1]);
+    close(tc_out[0]);
+    dup2(tc_in[0], 0);
+    dup2(tc_out[1], 1);
+    if(acc_user && acc_pass)
+    {
+      execl("./tc_client", "./tc_client", "-u", acc_user, "-p", acc_pass, channel, nick, pass, (char*)0);
+    }else{
+      execl("./tc_client", "./tc_client", channel, nick, pass, (char*)0);
+    }
+    perror("Failed to exec tc_client");
+    _exit(1);
+  }
+  close(tc_in[0]);
+  close(tc_out[1]);
+  struct pollfd pfd[2];
+  pfd[0].fd=tc_out[0];
+  pfd[0].events=POLLIN;
+  pfd[0].revents=0;
+  pfd[1].fd=sock;
+  pfd[1].events=POLLIN;
+  pfd[1].revents=0;
+  char buf[2048];
+  int len;
+  char joins=0;
+  while(1)
+  {
+    poll(pfd, 2, -1);
+    if(pfd[0].revents)
+    {
+      pfd[0].revents=0;
+      len=0;
+      int r;
+      while(len<2047)
+      {
+        if((r=read(tc_out[0], &buf[len], 1))!=1 || buf[len]=='\r' || buf[len]=='\n'){break;}
+        ++len;
+      }
+      if(r!=1){break;}
+      buf[len]=0;
+printf("Got from tc_client: '%s'\n", buf);
+      if(!strncmp(buf, "Currently online: ", 18))
+      {
+        dprintf(sock, ":irchack 353 %s = #%s :", nick, channel);
+        char* user=&buf[18];
+        while(user)
+        {
+          char* next=strchr(user, ',');
+          if(next){next[0]=0; next=&next[2];}
+          dprintf(sock, "%s%s", user, next?" ":"");
+          user=next;
+        }
+        write(sock, "\n", 1);
+        joins=1;
+        continue;
+      }
+      else if(joins)
+      {
+        dprintf(sock, ":irchack 366 %s #%s :End of /NAMES list.\n", nick, channel);
+        joins=0;
+      }
+      if(!strncmp(buf, "Room topic: ", 12))
+      {
+        dprintf(sock, ":irchack 332 %s #%s :%s\n", nick, channel, &buf[12]);
+        continue;
+      }
+      if(!strcmp(buf, "Password required"))
+      {
+        dprintf(sock, ":irchack 475 %s :Cannot join %s without the correct password\n", channel, channel);
+        close(tc_in[1]);
+        close(tc_out[0]);
+        return 1;
+      }
+      if(!strncmp(buf, "Connection ID: ", 15))
+      {
+        dprintf(sock, ":%s!user@host NICK :guest-%s\n", nick, &buf[15]);
+        continue;
+      }
+      if(!strncmp(buf, "No such nick: ", 14))
+      {
+        dprintf(sock, ":irchack 401 %s %s :No such nick/channel\n", nick, &buf[14]);
+        continue;
+      }
+      char* space=strchr(buf, ' ');
+      if(space && !strcmp(space, " is a moderator."))
+      {
+        space[0]=0;
+        dprintf(sock, ":irchack MODE #%s +o %s\n", channel, buf);
+        continue;
+      }
+      if(space && !strcmp(space, " is no longer a moderator."))
+      {
+        space[0]=0;
+        dprintf(sock, ":irchack MODE #%s -o %s\n", channel, buf);
+        continue;
+      }
+      if(buf[0]!='['){continue;} // Beyond this we only care about timestamped lines
+      // Translate ANSI escape codes to IRC color code instead
+      char* ansi;
+      const char* color="";
+      while((ansi=strstr(buf, "\x1b[")))
+      {
+        int len;
+        for(len=0; ansi[len]&&ansi[len]!='m'; ++len);
+        if(ansi[len]=='m'){++len;}
+        const char* c=findcolor_irc(&ansi[2]);
+        if(c){color=c;}
+        memmove(ansi, &ansi[len], strlen(&ansi[len])+1);
+      }
+
+      char* name=strchr(buf, ' ');
+      if(!name){continue;}
+      name[0]=0;
+      name=&name[1];
+      char* msg=name;
+      while(msg[0]&&msg[0]!=':'&&msg[0]!=' '){msg=&msg[1];}
+      if(msg[0]==':') // message
+      {
+        msg[0]=0;
+        msg=&msg[2];
+        if(!strncmp(msg, "/msg ", 5)) // PM
+        {
+          msg=strchr(&msg[5], ' ');
+          if(!msg){continue;}
+          msg=&msg[1];
+          dprintf(sock, ":%s!user@host PRIVMSG %s :%s%s\n", name, nick, color, msg);
+        }
+        else if(!strncmp(msg, "/userinfo ", 10)) // /userinfo response (translated as whois)
+        {
+          if(msg[10]=='$'){continue;} // Special, ignore
+          dprintf(sock, ":server 311 %s %s user host * :%s\n", nick, name, &msg[10]);
+          dprintf(sock, ":server 318 %s %s :End of /WHOIS list\n", nick, name);
+        }else{ // Regular channel message
+          dprintf(sock, ":%s!user@host PRIVMSG #%s :%s%s\n", name, channel, color, msg);
+        }
+      }else{ // action, parse the actions and send them as JOINs, NICKs and QUITs etc. instead
+        msg[0]=0;
+        msg=&msg[1];
+        if(!strcmp(msg, "entered the channel"))
+        {
+          dprintf(sock, ":%s!user@host JOIN #%s\n", name, channel);
+        }
+        else if(!strncmp(msg, "changed nickname to ", 20))
+        {
+          dprintf(sock, ":%s!user@host NICK :%s\n", name, &msg[20]);
+        }
+        else if(!strcmp(msg, "left the channel"))
+        {
+          dprintf(sock, ":%s!user@host QUIT :left the channel\n", name);
+        }
+        else // Unhandled action
+        {
+          dprintf(sock, ":%s!user@host PRIVMSG #%s :\x01""ACTION %s\x01\n", name, channel, msg);
+        }
+      }
+    }
+    if(pfd[1].revents)
+    {
+      pfd[1].revents=0;
+      len=0;
+      int r;
+      while(len<2047)
+      {
+        if((r=read(sock, &buf[len], 1))!=1 || buf[len]=='\r' || buf[len]=='\n'){break;}
+        ++len;
+      }
+      if(r!=1){break;}
+      buf[len]=0;
+printf("Got from IRC client: '%s'\n", buf);
+      if(!strncasecmp(buf, "PRIVMSG ", 8))
+      {
+        char* target=&buf[8];
+        char* msg=strchr(&buf[8], ' ');
+        if(!msg){continue;}
+        msg[0]=0;
+        msg=&msg[1];
+        if(msg[0]==':'){msg=&msg[1];}
+        char* color;
+        while((color=strchr(msg, '\x03')))
+        {
+          char* end;
+          int c=findcolor_ansi(color, &end);
+          if(c!=-1){dprintf(tc_in[1], "/color %i\n", c);}
+          memmove(color, end, strlen(end)+1);
+        }
+        if(!strncmp(msg, "\x01""ACTION ", 8)) // Translate '/me'
+        {
+          msg=&msg[7];
+          msg[0]='*';
+          char* end=strchr(msg, '\x01');
+          if(end){end[0]='*';}
+        }
+        if(target[0]=='#' && !strcmp(&target[1], channel))
+        {
+          dprintf(tc_in[1], "%s\n", msg);
+        }else{
+          dprintf(tc_in[1], "/msg %s %s\n", target, msg);
+        }
+      }
+      else if(!strncasecmp(buf, "NICK ", 5))
+      {
+        char* nick=&buf[5];
+        if(nick[0]==':'){nick=&nick[1];}
+        dprintf(tc_in[1], "/nick %s\n", nick);
+      }
+      else if(!strncasecmp(buf, "PING ", 5))
+      {
+        dprintf(sock, ":irchack PONG %s\n", &buf[5]);
+      }
+      else if(!strncasecmp(buf, "QUIT ", 5)){break;}
+      else if(!strncasecmp(buf, "WHOIS ", 6))
+      {
+        char* space=strchr(&buf[6], ' ');
+        if(space){space[0]=0;}
+        dprintf(tc_in[1], "/priv %s /userinfo $request\n", buf[6]==':'?&buf[7]:&buf[6]);
+      }
+    }
+  }
+
+  close(tc_in[1]);
+  close(tc_out[0]);
+  return 0;
+}
diff --git a/utilities/list.c b/utilities/list.c
new file mode 100644
index 0000000..707a182
--- /dev/null
+++ b/utilities/list.c
@@ -0,0 +1,126 @@
+/*
+    A simple list implementation
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <unistd.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include "list.h"
+
+void list_del(struct list* list, const char* item)
+{
+  unsigned int i;
+  unsigned int len;
+  while(item[0])
+  {
+    if(item[0]=='\r' || item[0]=='\n'){item=&item[1]; continue;} // Skip empty lines
+    for(len=0; item[len] && item[len]!='\r' && item[len]!='\n'; ++len);
+    for(i=0; i<list->itemcount; ++i)
+    {
+      if(!strncmp(list->items[i], item, len) && !list->items[i][len])
+      {
+        free(list->items[i]);
+        --list->itemcount;
+        memmove(&list->items[i], &list->items[i+1], sizeof(char*)*(list->itemcount-i));
+      }
+    }
+    item=&item[len];
+  }
+}
+
+void list_add(struct list* list, const char* item)
+{
+  list_del(list, item);
+  unsigned int len;
+  while(item[0])
+  {
+    if(item[0]=='\r' || item[0]=='\n'){item=&item[1]; continue;} // Skip empty lines
+    for(len=0; item[len] && item[len]!='\r' && item[len]!='\n'; ++len);
+    ++list->itemcount;
+    list->items=realloc(list->items, sizeof(char*)*list->itemcount);
+    list->items[list->itemcount-1]=strndup(item, len);
+    item=&item[len];
+  }
+}
+
+void list_switch(struct list* list, char* olditem, char* newitem)
+{
+  unsigned int i;
+  for(i=0; i<list->itemcount; ++i)
+  {
+    if(!strcmp(list->items[i], olditem))
+    {
+      free(list->items[i]);
+      list->items[i]=strdup(newitem);
+    }
+  }
+}
+
+int list_getpos(struct list* list, char* item)
+{
+  int i;
+  unsigned int len;
+  while(item[0])
+  {
+    if(item[0]=='\r' || item[0]=='\n'){item=&item[1]; continue;} // Skip empty lines
+    for(len=0; item[len] && item[len]!='\r' && item[len]!='\n'; ++len);
+    for(i=0; i<list->itemcount; ++i)
+    {
+      if(!strncmp(list->items[i], item, len) && !list->items[i][len]){return i;}
+    }
+    item=&item[len];
+  }
+  return -1;
+}
+
+char list_contains(struct list* list, char* item)
+{
+  return (list_getpos(list, item)!=-1);
+}
+
+void list_load(struct list* list, const char* file)
+{
+  struct stat st;
+  if(stat(file, &st)){return;}
+  int f=open(file, O_RDONLY);
+  char buf[st.st_size+1];
+  read(f, buf, st.st_size);
+  buf[st.st_size]=0;
+  close(f);
+  char* start=buf;
+  char* end;
+  while((end=strchr(start, '\n'))) // TODO: support \r?
+  {
+    end[0]=0;
+    list_add(list, start);
+    start=&end[1];
+  }
+  printf("Loaded %u lines from %s\n", list->itemcount, file);
+}
+
+void list_save(struct list* list, const char* file)
+{
+  int f=open(file, O_WRONLY|O_TRUNC|O_CREAT, 0600);
+  unsigned int i;
+  for(i=0; i<list->itemcount; ++i)
+  {
+    write(f, list->items[i], strlen(list->items[i]));
+    write(f, "\n", 1);
+  }
+  close(f);
+}
diff --git a/utilities/list.h b/utilities/list.h
new file mode 100644
index 0000000..5e8e7d5
--- /dev/null
+++ b/utilities/list.h
@@ -0,0 +1,29 @@
+/*
+    A simple list implementation
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+struct list
+{
+  char** items;
+  unsigned int itemcount;
+};
+
+extern void list_del(struct list* list, const char* item);
+extern void list_add(struct list* list, const char* item);
+extern void list_switch(struct list* list, char* olditem, char* newitem);
+extern int list_getpos(struct list* list, char* item);
+extern char list_contains(struct list* list, char* item);
+extern void list_load(struct list* list, const char* file);
+extern void list_save(struct list* list, const char* file);
diff --git a/utilities/modbot/commands.html b/utilities/modbot/commands.html
new file mode 100644
index 0000000..b7b8325
--- /dev/null
+++ b/utilities/modbot/commands.html
@@ -0,0 +1,31 @@
+<html>
+<head>
+  <title>modbot commands</title>
+  <style>
+  <!--
+  th{text-align:left;}
+  -->
+  </style>
+</head>
+<body>
+  modbot is a utility to queue videos to be played, with a list of approved videos that will automatically play when requested. Below is a list of supported commands.<br /><br />
+  <table cellspacing="1" border="0">
+    <tr><th>Command</th><th>Description</th></tr>
+    <tr><td>!request &lt;link/searchterm&gt;</td><td>request a video to be played</td></tr>
+    <tr><td>!queue</td><td>get the number of songs in queue and which (if any) need to  be approved</td></tr>
+    <tr><td>!wrongrequest</td><td>undo the last request you made</td></tr>
+    <tr><td>!requestedby</td><td>see who requested the current video</td></tr>
+    <tr><td>!modstats</td><td>get a percentage of how often there are mods in the channel (aside from modbot)</td></tr>
+    <tr><td>!syncvid</td><td>synchronize video position (or see a video that was started while having youtube videos disabled in the flash client)</td></tr>
+    <tr><th colspan="2">Mod commands:</th></tr>
+    <tr><td>!playnext</td><td>play the next video in queue without approving it (to see if it's ok)</td></tr>
+    <tr><td>!approve</td><td>mark the currently playing video as good, or if none is playing the next in queue</td></tr>
+    <tr><td>!approve &lt;link/searchterm&gt;</td><td>mark the specified video as okay</td></tr>
+    <tr><td>!approve next</td><td>mark the next not yet approved video as okay</td></tr>
+    <tr><td>!approve entire queue</td><td>approve all videos in queue (for playlists)</td></tr>
+    <tr><td>!badvid</td><td>stop playing the current video and mark it as bad</td></tr>
+    <tr><td>!badvid &lt;link/searchterm&gt;</td><td>mark the specified video as bad, preventing it from ever being queued again</td></tr>
+  </table><br />
+  You can also just play videos manually/the good old way and they will be marked as good.
+</body>
+</html>
diff --git a/utilities/modbot/modbot.c b/utilities/modbot/modbot.c
new file mode 100644
index 0000000..bb193b8
--- /dev/null
+++ b/utilities/modbot/modbot.c
@@ -0,0 +1,686 @@
+/*
+    modbot, a bot for tc_client that queues and plays videos
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <sys/wait.h>
+#include <stdarg.h>
+#include <time.h>
+#include <termios.h>
+#include "../list.h"
+#include "queue.h"
+
+struct list mods={0,0};
+struct queue queue={0,0};
+struct list goodvids={0,0}; // pre-approved videos
+struct list badvids={0,0}; // not allowed, essentially banned
+char* playing=0;
+char* requester=0;
+time_t started=0;
+int tc_client;
+
+time_t time_with_mods=0;
+time_t time_modcount;
+char havemods=0;
+void timemods(void)
+{
+  time_t now=time(0);
+  if(havemods)
+  {
+    time_with_mods+=now-time_modcount;
+  }
+  time_modcount=now;
+  havemods=(mods.itemcount>1); // Not counting modbot as a mod
+}
+
+void say(const char* pm, const char* fmt, ...)
+{
+  va_list va;
+  va_start(va, fmt);
+  unsigned int len=vsnprintf(0,0,fmt,va);
+  va_end(va);
+  va_start(va, fmt);
+  char buf[len+1+(pm?strlen("/msg  ")+strlen(pm):0)];
+  char* msg=buf;
+  if(pm)
+  {
+    msg=&buf[strlen("/msg  ")+strlen(pm)];
+    sprintf(buf, "/msg %s ", pm);
+  }
+  vsprintf(msg, fmt, va);
+  va_end(va);
+  write(tc_client, buf, strlen(buf));
+}
+
+void getvidinfo(const char* vid, const char* type, char* buf, char* errbuf, unsigned int len)
+{
+  int out[2];
+  int err[2];
+  pipe(out);
+  pipe(err);
+  if(!fork())
+  {
+    close(out[0]);
+    close(err[0]);
+    dup2(out[1], 1);
+    dup2(err[1], 2);
+    execlp("youtube-dl", "youtube-dl", "--default-search", "auto", type, "--", vid, (char*)0);
+    perror("execlp(youtube-dl)");
+    _exit(1);
+  }
+  wait(0);
+  close(out[1]);
+  close(err[1]);
+  size_t r;
+  // Read output
+  r=read(out[0], buf, len-1);
+  if(r<0){r=0;}
+  while(r>0 && (buf[r-1]=='\r' || buf[r-1]=='\n')){--r;} // Strip newlines
+  buf[r]=0;
+  close(out[0]);
+  // Read any error messages
+  if(errbuf)
+  {
+    r=read(err[0], errbuf, len-1);
+    if(r<0){r=0;}
+    while(r>0 && (errbuf[r-1]=='\r' || errbuf[r-1]=='\n')){--r;} // Strip newlines
+    errbuf[r]=0;
+    char* newline; // No need for newlines in error messages
+    while((newline=strchr(errbuf, '\n'))){newline[0]=' ';}
+    while((newline=strchr(errbuf, '\r'))){newline[0]=' ';}
+  }
+  close(err[0]);
+}
+
+unsigned int getduration(const char* vid)
+{
+  char timebuf[128];
+  timebuf[0]=':'; // Sacrifice 1 byte to avoid having to deal with a special case later on, where no ':' is found and we go from the start of the string, but only once
+  getvidinfo(vid, "--get-duration", &timebuf[1], 0, 127);
+  if(!timebuf[1]){printf("Failed to get video duration using youtube-dl, assuming 60s\n"); return 60;} // If using youtube-dl fails, assume videos are 1 minute long
+  // youtube-dl prints it out in hh:mm:ss format, convert it to plain seconds
+  unsigned int len;
+  // Seconds
+  char* sep=strrchr(timebuf, ':');
+  if(sep){sep[0]=0; len=atoi(&sep[1]);}
+  // Minutes
+  sep=strrchr(timebuf, ':');
+  if(sep){sep[0]=0; len+=atoi(&sep[1])*60;}
+  // Hours
+  sep=strrchr(timebuf, ':');
+  if(sep){sep[0]=0; len+=atoi(&sep[1])*60;}
+  // Days
+  sep=strrchr(timebuf, ':');
+  if(sep){sep[0]=0; len+=atoi(&sep[1])*24;}
+  return len;
+}
+
+unsigned int waitskip=0;
+void playnextvid()
+{
+  waitskip=0;
+  playing=queue.items[0].video;
+  requester=queue.items[0].requester;
+  free(queue.items[0].title);
+  --queue.itemcount;
+  memmove(queue.items, &queue.items[1], sizeof(struct queueitem)*queue.itemcount);
+  say(0, "/mbs youTube %s 0\n", playing);
+  // Find out the video's length and schedule an alarm for then
+  alarm(getduration(playing));
+  started=time(0);
+}
+
+void playnext(int x)
+{
+  free(playing);
+  free(requester);
+  playing=0;
+  requester=0;
+  if(queue.itemcount<1){alarm(0); printf("Nothing more to play\n"); return;} // Nothing more to play
+  if(!list_contains(&goodvids, queue.items[0].video))
+  {
+    if(!waitskip)
+    {
+      say(0, "Next video (%s, %s) is not yet approved by mods\n", queue.items[0].video, queue.items[0].title);
+      unsigned int i;
+      for(i=1; i<queue.itemcount; ++i)
+      {
+        if(list_contains(&goodvids, queue.items[i].video))
+        {
+          waitskip=i;
+          alarm(120);
+          break;
+        }
+      }
+      return;
+    }else{
+      say(0, "Skipping http://youtube.com/watch?v=%s because it is still not approved after 2 minutes\n", queue.items[0].video);
+      queue_movetofront(&queue, waitskip);
+      waitskip=0;
+    }
+  }
+  playnextvid();
+}
+
+int main(int argc, char** argv)
+{
+  // Handle arguments (-d, -l, -h additions, the rest are handled by tc_client)
+  char daemon=0;
+  char* logfile=0;
+  char verbose=0;
+  unsigned int i;
+  for(i=1; i<argc; ++i)
+  {
+    if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--daemon"))
+    {
+      daemon=1;
+      // Remove non-tc_client argument
+      --argc;
+      memmove(&argv[i], &argv[i+1], sizeof(char*)*(argc-i));
+      argv[argc]=0;
+      --i;
+    }
+    else if(i+1<argc && (!strcmp(argv[i], "-l") || !strcmp(argv[i], "--log")))
+    {
+      logfile=argv[i+1];
+      // Remove non-tc_client argument
+      argc-=2;
+      memmove(&argv[i], &argv[i+2], sizeof(char*)*(argc-i));
+      argv[argc]=0;
+      --i;
+    }
+    else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose"))
+    {
+      verbose=1;
+      // Remove non-tc_client argument
+      --argc;
+      memmove(&argv[i], &argv[i+1], sizeof(char*)*(argc-i));
+      argv[argc]=0;
+      --i;
+    }
+    else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
+    {
+      printf("Additional options for modbot:\n"
+             "-d/--daemon     = daemonize after startup\n"
+             "-l/--log <file> = log output into <file>\n"
+             "-v/--verbose    = print/log all incoming messages\n"
+             "\n");
+      execv("./tc_client", argv);
+      return 1;
+    }
+  }
+  int in[2];
+  int out[2];
+  pipe(in);
+  pipe(out);
+  if(!fork())
+  {
+    close(in[1]);
+    close(out[0]);
+    dup2(in[0], 0);
+    dup2(out[1], 1);
+    execv("./tc_client", argv);
+    _exit(1);
+  }
+  close(in[0]);
+  close(out[1]);
+  tc_client=in[1];
+  signal(SIGALRM, playnext);
+  list_load(&goodvids, "goodvids.txt");
+  list_load(&badvids, "badvids.txt");
+  char buf[1024];
+  int len=0;
+  time_t sessionstart=time(0);
+  time_modcount=sessionstart;
+  while(1)
+  {
+    if(read(out[0], &buf[len], 1)<1){break;}
+    if(len<1023&&buf[len]!='\r'&&buf[len]!='\n')
+    {
+      ++len;
+      if(len==18 && !strncmp(buf, "Account password: ", 18))
+      {
+        len=0;
+        struct termios term;
+        tcgetattr(0, &term);
+        term.c_lflag&=~ECHO;
+        tcsetattr(0, TCSANOW, &term);
+        fprintf(stdout, "Account password: ");
+        fflush(stdout);
+        fgets(buf, 1024, stdin);
+        write(tc_client, buf, strlen(buf));
+        term.c_lflag|=ECHO;
+        tcsetattr(0, TCSANOW, &term);
+        printf("\n");
+      }
+      continue;
+    }
+    if(!len){continue;}
+    buf[len]=0;
+    char* esc;
+    while((esc=strstr(buf, "\x1b["))) // Strip out ANSI colors
+    {
+      for(len=2; isdigit(esc[len])||esc[len]==';'; ++len);
+      memmove(esc, &esc[len+1], strlen(&esc[len]));
+    }
+    len=0;
+    // Note: daemonizing and setting up logging here to avoid interfering with account password entry
+    if(daemon)
+    {
+      if(fork()){return 0;}
+      daemon=0;
+      if(!logfile){logfile="/dev/null";} // Prevent writing to stdout as a daemon
+    }
+    if(logfile)
+    {
+      int f=open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0600);
+      dup2(f, 1);
+      dup2(f, 2);
+      close(f);
+      logfile=0;
+    }
+    if(verbose){printf("Got line '%s'\n", buf); fflush(stdout);}
+    char* space=strchr(buf, ' ');
+    if(!space){continue;}
+    if(!strcmp(space, " is a moderator."))
+    {
+      // If there are not-yet-approved videos in the queue when a mod joins, ask them to review them
+      space[0]=0;
+      list_add(&mods, buf);
+      timemods();
+      continue;
+    }
+    if(!strcmp(space, " is no longer a moderator."))
+    {
+      space[0]=0;
+      list_del(&mods, buf);
+      timemods();
+      continue;
+    }
+    space[0]=0;
+    if(buf[0]=='['&&isdigit(buf[1])&&isdigit(buf[2])&&buf[3]==':') // Timestamp
+    {
+      char* nick=&space[1];
+      space=strchr(nick, ' ');
+      if(!space){continue;}
+      if(space[-1]==':') // Sent a message
+      {
+        space[-1]=0;
+        char* msg=&space[1];
+        // Handle commands sent in PMs
+        char* pm=0;
+        if(!strncmp(msg, "/msg ", 5))
+        {
+          msg=strchr(&msg[5], ' ');
+          if(!msg){continue;}
+          msg=&msg[1];
+          pm=nick;
+        }
+        if(!strncmp(msg, "!request ", 9))
+        {
+          char title[256];
+          char vid[1024];
+          char viderr[1024];
+          getvidinfo(&msg[9], "--get-id", vid, viderr, 1024);
+          if(!vid[0]) // Nothing found
+          {
+            say(pm, "No video found, sorry (%s)\n", viderr);
+            continue;
+          }
+          char* plist;
+          for(plist=vid; plist[0] && plist[0]!='\r' && plist[0]!='\n'; plist=&plist[1]);
+          if(plist[0]) // Link was a playlist, do some trickery to get the title of the first video (instead of getting nothing)
+          {
+            strcpy(title, "Playlist, starting with ");
+            plist[0]=0;
+            getvidinfo(vid, "--get-title", &title[24], 0, 256-24);
+            plist[0]='\n';
+          }else{
+            plist=0;
+            getvidinfo(vid, "--get-title", title, 0, 256);
+          }
+          printf("Requested ID '%s' by '%s'\n", vid, nick);
+          // Check if it's already queued and mention which spot it's in, or if it's marked as bad and shouldn't be queued
+          int pos;
+          if((pos=queue_getpos(&queue, vid))>-1)
+          {
+            say(pm, "Video '%s' is already in queue (number %i, requested by %s)\n", title, pos, queue.items[pos].requester);
+            continue;
+          }
+          if(list_contains(&badvids, vid))
+          {
+            say(pm, "Video '%s' is marked as bad, won't add to queue\n", title);
+            continue;
+          }
+          if(list_contains(&mods, nick)) // Auto-approve for mods
+          {
+            list_add(&goodvids, vid);
+            list_del(&badvids, vid);
+            list_save(&goodvids, "goodvids.txt");
+            list_save(&badvids, "badvids.txt");
+          }
+
+          queue_add(&queue, vid, nick, title);
+          if(!list_contains(&goodvids, vid))
+          {
+            if(plist)
+            {
+              say(pm, "Playlist '%s' is added to the queue but will need to be approved by a mod\n", title);
+            }else{
+              say(pm, "Video '%s' (%s) is added to the queue but will need to be approved by a mod\n", vid, title);
+            }
+          }
+          else if(!playing){playnext(0);}
+          else{say(pm, "Added '%s' to queue\n", title);}
+        }
+        // Undo
+        else if(!strcmp(msg, "!wrongrequest"))
+        {
+          unsigned int i=queue.itemcount;
+          while(i>0)
+          {
+            --i;
+            if(!strcmp(queue.items[i].requester, nick))
+            {
+              queue_del(&queue, queue.items[i].video);
+              if(!playing && i==0){playnext(0);}
+              i=1; // distinguish from just having reached the front of the queue
+              break;
+            }
+          }
+          if(!i)
+          {
+            say(pm, "I can't find any request by you, sorry\n");
+          }
+        }
+        else if(!strncmp(msg, "!wrongrequest ", 14))
+        {
+          char vid[1024];
+          getvidinfo(&msg[14], "--get-id", vid, 0, 1024);
+          unsigned int i;
+          for(i=0; i<queue.itemcount; ++i)
+          {
+            if(!strcmp(queue.items[i].requester, nick) && !strcmp(queue.items[i].video, vid))
+            {
+              queue_del(&queue, queue.items[i].video);
+              break;
+            }
+          }
+          if(i==queue.itemcount)
+          {
+            say(pm, "I can't find that request by you, sorry\n");
+          }
+        }
+        else if(!strcmp(msg, "!queue"))
+        {
+          unsigned int notapproved=0;
+          unsigned int len=0;
+          unsigned int i;
+          for(i=0; i<queue.itemcount; ++i)
+          {
+            if(!list_contains(&goodvids, queue.items[i].video)){++notapproved; len+=strlen(queue.items[i].video)+strlen(queue.items[i].title)+strlen(" (), ");}
+          }
+          if(notapproved)
+          {
+            char buf[len];
+            buf[0]=0;
+            unsigned int listed=0;
+            for(i=0; i<queue.itemcount; ++i)
+            {
+              if(listed<5 && !list_contains(&goodvids, queue.items[i].video))
+              {
+                if(buf[0]){strcat(buf, ", ");}
+                strcat(buf, queue.items[i].video);
+                strcat(buf, " (");
+                strcat(buf, queue.items[i].title);
+                strcat(buf, ")");
+                ++listed;
+              }
+            }
+            say(pm, "%u video%s in queue, %u of which are not yet approved by mods (%s%s)\n", queue.itemcount, (queue.itemcount==1)?"":"s", notapproved, buf, (listed<notapproved)?", etc.":"");
+          }else{
+            say(pm, "%u video%s in queue\n", queue.itemcount, (queue.itemcount==1)?"":"s");
+          }
+        }
+        else if(!strcmp(msg, "!requestedby"))
+        {
+          if(!playing){say(pm, "Nothing is playing\n");}
+          else{say(pm, "%s requested %s\n", requester, playing);}
+        }
+        else if(!strcmp(msg, "!time")) // Debugging
+        {
+          unsigned int remaining=alarm(0);
+          alarm(remaining);
+          say(pm, "'%s' is scheduled to end in %u seconds\n", playing, remaining);
+        }
+        else if(!strcmp(msg, "!help"))
+        {
+          say(pm, "http://tc_client.ion.nu/misc/modbotcommands.html\n");
+        }
+        else if(!strcmp(msg, "!modstats"))
+        {
+          unsigned int session=time(0)-sessionstart;
+          timemods();
+          unsigned int hasmods=time_with_mods*100/session;
+          const char* timeformat="seconds";
+          if(session>=120)
+          {
+            session/=60;
+            timeformat="minutes";
+            if(session>=120)
+            {
+              session/=60;
+              timeformat="hours";
+              if(session>=48)
+              {
+                session/=24;
+                timeformat="days";
+              }
+            }
+          }
+          say(pm, "The channel has had mods %u%% of the time for the past %u %s\n", hasmods, session, timeformat);
+        }
+        else if(!strcmp(msg, "!syncvid"))
+        {
+          if(playing)
+          {
+            space[0]=0;
+            say(0, "/priv %s /mbs youTube %s %u\n", nick, playing, (time(0)-started)*1000);
+          }else{
+            say(pm, "Nothing is playing\n");
+          }
+        }
+        else if(list_contains(&mods, nick)) // Mods-only commands
+        {
+          if(!strcmp(msg, "!playnext"))
+          {
+            if(playing){say(pm, "A video (%s) is already playing\n", playing); continue;}
+            if(queue.itemcount<1){say(pm, "There are no videos in queue, sorry\n"); continue;}
+            playnextvid();
+          }
+          else if(!strcmp(msg, "!approve"))
+          {
+            if(playing)
+            {
+              if(list_contains(&goodvids, playing) && !list_contains(&badvids, playing)){say(pm, "'%s' is approved, use !approve <ID> to approve another video (or 'next' instead of an ID to approve the next not-yet-approved video in queue)\n", playing); continue;}
+              list_add(&goodvids, playing);
+              list_del(&badvids, playing);
+              list_save(&goodvids, "goodvids.txt");
+              list_save(&badvids, "badvids.txt");
+            }else if(queue.itemcount>0){
+              if(list_contains(&goodvids, queue.items[0].video) && !list_contains(&badvids, queue.items[0].video)){say(pm, "'%s' is approved, use !approve <ID> to approve another video\n", queue.items[0].video); continue;}
+              list_add(&goodvids, queue.items[0].video);
+              list_del(&badvids, queue.items[0].video);
+              list_save(&goodvids, "goodvids.txt");
+              list_save(&badvids, "badvids.txt");
+              playnext(0);
+            }else{say(pm, "Please specify a video to approve\n");}
+          }
+          else if(!strncmp(msg, "!approve ", 9))
+          {
+            char* vid=&msg[9];
+            if(!vid[0]){continue;} // No video specified
+            char vidbuf[256];
+            if(!strcmp(vid, "next"))
+            {
+              unsigned int i;
+              for(i=0; i<queue.itemcount; ++i)
+              {
+                if(!list_contains(&goodvids, queue.items[i].video))
+                {
+                  vid=queue.items[i].video;
+                  say(pm, "Approved '%s'\n", queue.items[i].title);
+                  break;
+                }
+              }
+              if(i==queue.itemcount){say(pm, "Nothing more to approve :)\n"); continue;}
+            }
+            else if(!strcmp(vid, "entire queue"))
+            {
+              char approved=0;
+              unsigned int i;
+              for(i=0; i<queue.itemcount; ++i)
+              {
+                if(list_contains(&goodvids, queue.items[i].video)){continue;}
+                list_add(&goodvids, queue.items[i].video);
+                approved=1;
+              }
+              if(approved)
+              {
+                list_save(&goodvids, "goodvids.txt");
+                if(!playing){playnext(0);} // Next in queue just got approved, so play it
+                else{say(pm, "Queue approved. Make sure none of the videos were inappropriate\n");}
+              }else{
+                say(pm, "The queue is already approved (or empty)\n");
+              }
+              continue;
+            }else{
+              getvidinfo(vid, "--get-id", vidbuf, 0, 256);
+              vid=vidbuf;
+            }
+            list_add(&goodvids, vid);
+            list_del(&badvids, vid);
+            list_save(&goodvids, "goodvids.txt");
+            list_save(&badvids, "badvids.txt");
+            if(!playing && queue.itemcount>0 && !strcmp(vid, queue.items[0].video)){playnext(0);} // Next in queue just got approved, so play it
+          }
+          else if(!strcmp(msg, "!badvid") || !strcmp(msg, "!badvideo") || !strncmp(msg, "!badvid ", 8) || !strncmp(msg, "!badvideo ", 10))
+          {
+            char* space=strchr(msg, ' ');
+            if((!space || !space[1]) && !playing){say(pm, "Nothing is playing, please use !badvid <URL/ID> instead\n"); continue;}
+            char vid[1024];
+            if(space && space[1])
+            {
+              getvidinfo(&space[1], "--get-id", vid, 0, 256);
+            }else{strncpy(vid, playing, 1023); vid[1023]=0;}
+            if(!vid[0]){say(pm, "Video not found, sorry\n"); continue;}
+            queue_del(&queue, vid);
+            list_del(&goodvids, vid);
+            list_add(&badvids, vid);
+            list_save(&goodvids, "goodvids.txt");
+            list_save(&badvids, "badvids.txt");
+            if(playing && !strcmp(vid, playing)){say(0, "/mbc youTube\n");}
+            say(pm, "Marked '%s' as bad, it will not be allowed into the queue again. You can reverse this by !approve'ing the video by ID/link/name\n", vid);
+            playnext(0);
+          }
+          else if(!strcmp(msg, "!skip") || !strncmp(msg, "!skip ", 6))
+          {
+            unsigned int num=((msg[5]&&msg[6])?strtoul(&msg[6], 0, 0):1);
+            if(num<1){say(pm, "The given value evaluates to 0, please specify the number of videos you would like to skip (or if you do not specify it will default to 1)\n"); continue;}
+            if(playing){free(playing); playing=0; --num; say(0, "/mbc youTube\n");}
+            while(num>0&&queue.itemcount>0)
+            {
+              queue_del(&queue, queue.items[0].video);
+              --num;
+            }
+            playnext(0);
+          }
+          else if(!strncmp(msg, "/mbs youTube ", 13))
+          {
+            // Someone manually started a video, mark that video as good, remove it from queue, and set an alarm for when it's modbot's turn to play stuff again
+            char* vid=&msg[13];
+            char* end=strchr(vid, ' ');
+            if(end){end[0]=0;}
+            queue_del(&queue, vid);
+            list_add(&goodvids, vid);
+            list_save(&goodvids, "goodvids.txt");
+            free(playing);
+            playing=strdup(vid);
+            free(requester);
+            requester=strdup(nick);
+            unsigned int pos=(end?(strtol(&end[1], 0, 0)/1000):0);
+            alarm(getduration(playing)-pos);
+            started=time(0)-pos;
+          }
+          else if(!strcmp(msg, "/mbc youTube") && playing) // Video cancelled
+          {
+            list_del(&goodvids, playing); // manual /mbc is often used when !badvid should be used, so at least remove it from the list of approved videos
+            list_save(&goodvids, "goodvids.txt");
+            playnext(0);
+          }
+          else if(!strncmp(msg, "/mbsk youTube ", 14)) // Seeking
+          {
+            unsigned int pos=strtol(&msg[14], 0, 0)/1000;
+            alarm(getduration(playing)-pos);
+            started=time(0)-pos;
+          }
+          // TODO: handle /mbpa (pause) and /mbpl (resume play)
+        }
+      }else{ // Actions
+        if(!strncmp(space, " changed nickname to ", 21))
+        {
+          space[0]=0;
+          if(list_contains(&mods, nick))
+          {
+            list_switch(&mods, nick, &space[21]);
+            nick=&space[21];
+            unsigned int i;
+            for(i=0; i<queue.itemcount; ++i)
+            {
+              if(!list_contains(&goodvids, queue.items[i].video))
+              {
+                say(nick, "there are 1 or more videos in queue that are not yet approved, please type !queue to review them\n");
+                break;
+              }
+            }
+          }
+          continue;
+        }
+        else if(!strcmp(space, " entered the channel")) // Newcomer, inform about the currently playing video
+        {
+          if(playing)
+          {
+            space[0]=0;
+            say(0, "/priv %s /mbs youTube %s %u\n", nick, playing, (time(0)-started)*1000);
+          }
+        }
+        else if(!strcmp(space, " left the channel"))
+        {
+          space[0]=0;
+          list_del(&mods, nick); // Absent people can't be mods
+          timemods();
+        }
+      }
+    }
+  }
+  return 0;
+}
diff --git a/utilities/modbot/queue.c b/utilities/modbot/queue.c
new file mode 100644
index 0000000..1583e2b
--- /dev/null
+++ b/utilities/modbot/queue.c
@@ -0,0 +1,84 @@
+/*
+    modbot, a bot for tc_client that queues and plays videos
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <string.h>
+#include <stdlib.h>
+#include "queue.h"
+
+void queue_del(struct queue* queue, const char* item)
+{
+  unsigned int i;
+  unsigned int len;
+  while(item[0])
+  {
+    if(item[0]=='\r' || item[0]=='\n'){item=&item[1]; continue;} // Skip empty lines
+    for(len=0; item[len] && item[len]!='\r' && item[len]!='\n'; ++len);
+    for(i=0; i<queue->itemcount; ++i)
+    {
+      if(!strncmp(queue->items[i].video, item, len) && !queue->items[i].video[len])
+      {
+        free(queue->items[i].video);
+        free(queue->items[i].requester);
+        free(queue->items[i].title);
+        --queue->itemcount;
+        memmove(&queue->items[i], &queue->items[i+1], sizeof(struct queueitem)*(queue->itemcount-i));
+      }
+    }
+    item=&item[len];
+  }
+}
+
+void queue_add(struct queue* queue, const char* item, const char* requester, const char* title)
+{
+  queue_del(queue, item);
+  unsigned int len;
+  while(item[0])
+  {
+    if(item[0]=='\r' || item[0]=='\n'){item=&item[1]; continue;} // Skip empty lines
+    for(len=0; item[len] && item[len]!='\r' && item[len]!='\n'; ++len);
+    ++queue->itemcount;
+    queue->items=realloc(queue->items, sizeof(struct queueitem)*queue->itemcount);
+    queue->items[queue->itemcount-1].video=strndup(item, len);
+    queue->items[queue->itemcount-1].requester=strdup(requester);
+    queue->items[queue->itemcount-1].title=strdup(title);
+    item=&item[len];
+  }
+}
+
+int queue_getpos(struct queue* queue, char* item)
+{
+  int i;
+  unsigned int len;
+  while(item[0])
+  {
+    if(item[0]=='\r' || item[0]=='\n'){item=&item[1]; continue;} // Skip empty lines
+    for(len=0; item[len] && item[len]!='\r' && item[len]!='\n'; ++len);
+    for(i=0; i<queue->itemcount; ++i)
+    {
+      if(!strncmp(queue->items[i].video, item, len) && !queue->items[i].video[len]){return i;}
+    }
+    item=&item[len];
+  }
+  return -1;
+}
+
+void queue_movetofront(struct queue* queue, unsigned int pos)
+{
+  if(pos>=queue->itemcount){return;}
+  struct queueitem move=queue->items[pos];
+  memmove(&queue->items[1], queue->items, sizeof(struct queueitem)*pos);
+  queue->items[0]=move;
+}
diff --git a/utilities/modbot/queue.h b/utilities/modbot/queue.h
new file mode 100644
index 0000000..0fa1370
--- /dev/null
+++ b/utilities/modbot/queue.h
@@ -0,0 +1,33 @@
+/*
+    modbot, a bot for tc_client that queues and plays videos
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+struct queueitem
+{
+  char* video;
+  char* requester;
+  char* title;
+};
+
+struct queue
+{
+  struct queueitem* items;
+  unsigned int itemcount;
+};
+
+extern void queue_del(struct queue* queue, const char* item);
+extern void queue_add(struct queue* queue, const char* item, const char* requester, const char* title);
+extern int queue_getpos(struct queue* queue, char* item);
+extern void queue_movetofront(struct queue* queue, unsigned int pos);
diff --git a/utilities/stringutils.c b/utilities/stringutils.c
new file mode 100644
index 0000000..e7d33b4
--- /dev/null
+++ b/utilities/stringutils.c
@@ -0,0 +1,29 @@
+/*
+    A few simple string utilities
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <string.h>
+
+int strcount(const char* haystack, const char* needle)
+{
+  int c=0;
+  haystack=strstr(haystack, needle);
+  while(haystack)
+  {
+    ++c;
+    haystack=strstr(&haystack[1], needle);
+  }
+  return c;
+}
diff --git a/utilities/stringutils.h b/utilities/stringutils.h
new file mode 100644
index 0000000..c942bfe
--- /dev/null
+++ b/utilities/stringutils.h
@@ -0,0 +1,17 @@
+/*
+    A few simple string utilities
+    Copyright (C) 2015  alicia@ion.nu
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, version 3 of the License.
+
+    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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+extern int strcount(const char* haystack, const char* needle);