[Pkg-running-devel] [openambit] 04/131: Lots of new memory readout features

Christian Perrier bubulle at moszumanska.debian.org
Thu Jul 17 20:19:06 UTC 2014


This is an automated email from the git hooks/post-receive script.

bubulle pushed a commit to branch master
in repository openambit.

commit 79e3ed6c1bfac2134f311de30f26e5e82d7accc6
Author: Emil Ljungdahl <emil at kratern.se>
Date:   Wed Dec 11 23:12:27 2013 +0100

    Lots of new memory readout features
---
 src/libambit/CMakeLists.txt |   6 +-
 src/libambit/COPYING        | 674 ++++++++++++++++++++++++++++++++++++++++
 src/libambit/libambit.c     | 394 ++++++++++++++++-------
 src/libambit/libambit.h     | 400 +++++++++++++++++++++++-
 src/libambit/libambit_int.h | 107 ++++++-
 src/libambit/personal.c     | 119 +++++++
 src/libambit/pmem20.c       | 738 ++++++++++++++++++++++++++++++++++++++++++++
 src/libambit/protocol.c     |  27 +-
 8 files changed, 2330 insertions(+), 135 deletions(-)

diff --git a/src/libambit/CMakeLists.txt b/src/libambit/CMakeLists.txt
index 5c5d60d..a5aaac1 100644
--- a/src/libambit/CMakeLists.txt
+++ b/src/libambit/CMakeLists.txt
@@ -2,16 +2,18 @@ find_package(libusb REQUIRED)
 find_package(UDev REQUIRED)
 
 add_library (
-  libambit
+  ambit
   SHARED
   crc16.c
   libambit.c
   hid.c
+  personal.c
+  pmem20.c
   protocol.c
 )
 
 target_link_libraries(
-  libambit
+  ambit
   ${UDEV_LIBS}
   ${LIBUSB_LIBRARIES}
   m
diff --git a/src/libambit/COPYING b/src/libambit/COPYING
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/src/libambit/COPYING
@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/src/libambit/libambit.c b/src/libambit/libambit.c
index 2b2e139..ad0164c 100644
--- a/src/libambit/libambit.c
+++ b/src/libambit/libambit.c
@@ -1,3 +1,24 @@
+/*
+ * (C) Copyright 2013 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
 #include "libambit.h"
 #include "libambit_int.h"
 
@@ -8,27 +29,39 @@
 /*
  * Local definitions
  */
-#define AMBIT_USB_VENDOR_ID 0x1493
+#define SUUNTO_USB_VENDOR_ID 0x1493
+
+struct ambit_supported_device_s {
+    uint16_t vid;
+    uint16_t pid;
+    char *model;
+    uint8_t min_sw_version[4];
+    char *name;
+    bool supported;
+};
 
 /*
  * Static functions
  */
+static int device_info_get(ambit_object_t *object, ambit_device_info_t *info);
+static int lock_log(ambit_object_t *object, bool lock);
 
 /*
  * Static variables
  */
-uint16_t ambit_known_ids[] = { 0x10, 0x19 };
-enum ambit_commands_e {
-    ambit_command_device_info       = 0x0000,
-    ambit_command_time              = 0x0300,
-    ambit_command_date              = 0x0302,
-    ambit_command_status            = 0x0306,
-    ambit_command_personal_settings = 0x0b00,
-    ambit_command_log_head_first    = 0x0b07,
-    ambit_command_log_head_next     = 0x0b08,
-    ambit_command_log_head_step     = 0x0b0a,
-    ambit_command_log_head          = 0x0b0b,
-    ambit_command_log_read          = 0x0b17,
+static ambit_supported_device_t supported_devices[] = {
+    { SUUNTO_USB_VENDOR_ID, 0x001a, "Colibri", {0x01,0x01,0x02,0x00}, "Suunto Ambit2 S", false },
+    { SUUNTO_USB_VENDOR_ID, 0x0019, "Duck", {0x01,0x01,0x02,0x00}, "Suunto Ambit2", true },
+    { SUUNTO_USB_VENDOR_ID, 0x001a, "Colibri", {0x00,0x02,0x03,0x00}, "Suunto Ambit2 S", false },
+    { SUUNTO_USB_VENDOR_ID, 0x0019, "Duck", {0x00,0x02,0x03,0x00}, "Suunto Ambit2", false },
+    { SUUNTO_USB_VENDOR_ID, 0x001a, "Colibri", {0x00,0x02,0x02,0x00}, "Suunto Ambit2 S (up to 0.2.2)", false },
+    { SUUNTO_USB_VENDOR_ID, 0x0019, "Duck", {0x00,0x02,0x02,0x00}, "Suunto Ambit2 (up to 0.2.2)", false },
+    { SUUNTO_USB_VENDOR_ID, 0x0010, "Bluebird", {0x02,0x01,0x00,0x00}, "Suunto Ambit", false },
+    { SUUNTO_USB_VENDOR_ID, 0x0010, "Bluebird", {0x01,0x09,0x00,0x00}, "Suunto Ambit", false }, /* First with PMEM 2.0!? */
+    { SUUNTO_USB_VENDOR_ID, 0x0010, "Bluebird", {0x01,0x06,0x00,0x00}, "Suunto Ambit", false },
+    { SUUNTO_USB_VENDOR_ID, 0x0010, "Bluebird", {0x01,0x01,0x00,0x00}, "Suunto Ambit", false },
+    { SUUNTO_USB_VENDOR_ID, 0x0010, "Bluebird", {0x00,0x00,0x00,0x00}, "Suunto Ambit", false },
+    { 0x0000, 0x0000, NULL, {0x00,0x00,0x00,0x00}, NULL, false }
 };
 
 /*
@@ -40,35 +73,28 @@ ambit_object_t *libambit_detect(void)
     struct hid_device_info *devs, *cur_dev;
     ambit_object_t *ret_object = NULL;
     int i;
-    uint16_t product_id = 0;
+    ambit_supported_device_t *device = NULL;
 
     devs = hid_enumerate(0x0, 0x0);
     cur_dev = devs;
     while (cur_dev) {
-        //printf("Device Found\n  type: %04hx %04hx\n  path: %s\n  serial_number: %ls", cur_dev->vendor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_number);
-        //printf("\n");
-        //printf("  Manufacturer: %ls\n", cur_dev->manufacturer_string);
-        //printf("  Product:      %ls\n", cur_dev->product_string);
-        //printf("  Release:      %hx\n", cur_dev->release_number);
-        //printf("  Interface:    %d\n",  cur_dev->interface_number);
-        //printf("\n");
-        if (cur_dev->vendor_id == AMBIT_USB_VENDOR_ID) {
-            for (i=0; i<(sizeof(ambit_known_ids)/sizeof(ambit_known_ids[0])); i++) {
-                if (cur_dev->product_id == ambit_known_ids[i]) {
-                    product_id = cur_dev->product_id;
-                    break;
-                }
-            }
-            if (product_id != 0) {
+        for (i=0; i<sizeof(supported_devices)/sizeof(supported_devices[0]); i++) {
+            if (cur_dev->vendor_id == supported_devices[i].vid && cur_dev->product_id == supported_devices[i].pid) {
+                // Found at least one supported row, lets remember that!
+                device = &supported_devices[i];
                 break;
             }
         }
+        if (device != NULL) {
+            // Devcice was found, we can stop looping through devices now...
+            break;
+        }
         cur_dev = cur_dev->next;
     }
     hid_free_enumeration(devs);
 
-    if (product_id != 0) {
-        handle = hid_open(AMBIT_USB_VENDOR_ID, product_id, NULL);
+    if (device != NULL) {
+        handle = hid_open(device->vid, device->pid, NULL);
         if (handle != NULL) {
             // Setup hid device correctly
             hid_set_nonblocking(handle, 1);
@@ -76,8 +102,36 @@ ambit_object_t *libambit_detect(void)
             ret_object = malloc(sizeof(ambit_object_t));
             memset(ret_object, 0, sizeof(ambit_object_t));
             ret_object->handle = handle;
-            ret_object->vendor_id = AMBIT_USB_VENDOR_ID;
-            ret_object->product_id = product_id;
+            ret_object->vendor_id = device->vid;
+            ret_object->product_id = device->pid;
+
+            // Get device info to resolve supported functionality
+            if (device_info_get(ret_object, &ret_object->device_info) == 0) {
+                // Let's resolve the correct device
+                for (i=0; i<sizeof(supported_devices)/sizeof(supported_devices[0]); i++) {
+                    if (device->vid == supported_devices[i].vid &&
+                        device->pid == supported_devices[i].pid &&
+                        strncmp(device->model, ret_object->device_info.model, LIBAMBIT_MODEL_NAME_LENGTH) == 0 &&
+                        (ret_object->device_info.fw_version[0] > device->min_sw_version[0] ||
+                         (ret_object->device_info.fw_version[0] == device->min_sw_version[0] &&
+                          (ret_object->device_info.fw_version[1] > device->min_sw_version[1] ||
+                           (ret_object->device_info.fw_version[1] == device->min_sw_version[1] &&
+                            (ret_object->device_info.fw_version[2] > device->min_sw_version[2] ||
+                             (ret_object->device_info.fw_version[2] == device->min_sw_version[2] &&
+                              (ret_object->device_info.fw_version[3] >= device->min_sw_version[3])))))))) {
+                        // Found matching entry, reset to this one!
+                        device = &supported_devices[i];
+                        break;
+                    }
+                }
+                ret_object->device = device;
+                strncpy(ret_object->device_info.name, device->name, LIBAMBIT_PRODUCT_NAME_LENGTH);
+            }
+            else {
+                free(ret_object);
+                ret_object = NULL;
+                printf("Failed to get device info\n");
+            }
         }
         else {
             printf("Failed to open device\n");
@@ -94,31 +148,33 @@ void libambit_close(ambit_object_t *object)
             hid_close(object->handle);
         }
 
+        libambit_pmem20_deinit(object);
         free(object);
     }
 }
 
+bool libambit_device_supported(ambit_object_t *object)
+{
+    bool ret = false;
+
+    if (object != NULL && object->device != NULL) {
+        ret = object->device->supported;
+    }
+
+    return ret;
+}
+
 int libambit_device_info_get(ambit_object_t *object, ambit_device_info_t *info)
 {
-    uint8_t send_data[] = { 0x01, 0x06, 0x14, 0x00 };
-    uint8_t *reply_data = NULL;
-    size_t replylen;
     int ret = -1;
 
-    if (libambit_protocol_command(object, ambit_command_device_info, send_data, sizeof(send_data), &reply_data, &replylen, 1) == 0) {
+    if (object != NULL && object->device != NULL) {
         if (info != NULL) {
-            memcpy(info->model, reply_data, 16);
-            info->model[16] = 0;
-            memcpy(info->serial, &reply_data[16], 16);
-            info->serial[16] = 0;
-            memcpy(info->fw_version, &reply_data[32], 4);
-            memcpy(info->hw_version, &reply_data[36], 4);
+            memcpy(info, &object->device_info, sizeof(ambit_device_info_t));
         }
         ret = 0;
     }
 
-    libambit_protocol_free(reply_data);
-
     return ret;
 }
 
@@ -173,105 +229,215 @@ int libambit_personal_settings_get(ambit_object_t *object, ambit_personal_settin
     int ret = -1;
 
     if (libambit_protocol_command(object, ambit_command_personal_settings, NULL, 0, &reply_data, &replylen, 0) == 0) {
-
-        ret = 0;
+        ret = libambit_personal_settings_parse(reply_data, replylen, settings);
+        libambit_protocol_free(reply_data);
     }
 
-    libambit_protocol_free(reply_data);
-
     return ret;
 }
 
-int libambit_log_read_get_next(ambit_object_t *object)
+int libambit_log_read(ambit_object_t *object, ambit_log_skip_cb skip_cb, ambit_log_push_cb push_cb, ambit_log_progress_cb progress_cb, void *userref)
 {
-    uint8_t send_data[8];
+    int entries_read = 0;
+
     uint8_t *reply_data = NULL;
     size_t replylen = 0;
+    uint16_t log_entries_total = 0;
+    uint16_t log_entries_walked = 0;
 
-    uint32_t *address = (uint32_t*)&send_data[0];
-    uint32_t *length = (uint32_t*)&send_data[4];
-    int i=0, j, q;
     uint32_t more = 0x00000400;
 
-    if (libambit_protocol_command(object, ambit_command_log_head_first, NULL, 0, &reply_data, &replylen, 0) == 0) {
+    int i=0, j, q;
+    bool read_pmem = false;
+
+    ambit_log_header_t log_header;
+    ambit_log_entry_t *log_entry;
+
+    lock_log(object, true);
+
+    /*
+     * Read number of log entries
+     */
+    if (libambit_protocol_command(object, ambit_command_log_count, NULL, 0, &reply_data, &replylen, 0) != 0) {
+        lock_log(object, false);
+        return -1;
+    }
+    log_entries_total = le16toh(*(uint16_t*)(reply_data + 2));
+    libambit_protocol_free(reply_data);
+
+    /*
+     * First part walks through headers to check if there is any point in start
+     * reading the PMEM content. If no skip callback is defined, there is no
+     * point in checking the headers, because no one can tell us to not include
+     * the logs...
+     */
+
+    if (skip_cb != NULL) {
+        // Rewind
+        if (libambit_protocol_command(object, ambit_command_log_head_first, NULL, 0, &reply_data, &replylen, 0) != 0) {
+            lock_log(object, false);
+            return -1;
+        }
         more = le32toh(*(uint32_t*)reply_data);
         libambit_protocol_free(reply_data);
-    }
 
-    while(more == 0x00000400) {
-        printf("Round %d:\n", ++i);
-        if (libambit_protocol_command(object, ambit_command_log_head_step, NULL, 0, &reply_data, &replylen, 0) == 0) {
+        // Loop through logs while more entries exists
+        while (more == 0x00000400) {
+            // Go to next entry
+            if (libambit_protocol_command(object, ambit_command_log_head_step, NULL, 0, &reply_data, &replylen, 0) != 0) {
+                lock_log(object, false);
+                return -1;
+            }
             libambit_protocol_free(reply_data);
-        }
-        if (libambit_protocol_command(object, ambit_command_log_head, NULL, 0, &reply_data, &replylen, 0) == 0) {
-            printf("1st, length: %lu\n", replylen);
-            for(j=0; j<replylen; j+=16) {
-                for(q=0; q<16; q++) {
-                    printf("%02x ", reply_data[j+q]);
-                }
-                printf(" ");
-                for(q=0; q<16; q++) {
-                    if(reply_data[j+q] >= 0x20)
-                        printf("%c", reply_data[j+q]);
-                    else
-                        printf(".");
-                }
-                printf("\n");
+
+            // Assume every header is composited by 2 parts, where only the
+            // second is of interrest right now
+            if (libambit_protocol_command(object, ambit_command_log_head, NULL, 0, &reply_data, &replylen, 0) != 0) {
+                lock_log(object, false);
+                return -1;
             }
-            printf("\n");
             libambit_protocol_free(reply_data);
-        }
-        if (libambit_protocol_command(object, ambit_command_log_head, NULL, 0, &reply_data, &replylen, 0) == 0) {
-            printf("2nd, length: %lu\n", replylen);
-            for(j=0; j<replylen; j+=16) {
-                for(q=0; q<16; q++) {
-                    printf("%02x ", reply_data[j+q]);
+
+            if (libambit_protocol_command(object, ambit_command_log_head, NULL, 0, &reply_data, &replylen, 0) == 0) {
+                if (replylen > 8 && libambit_pmem20_parse_header(reply_data + 8, replylen - 8, &log_header) == 0) {
+                    if (skip_cb(userref, &log_header) != 0) {
+                        // Header was NOT skipped, break out!
+                        read_pmem = true;
+                        break;
+                    }
                 }
-                printf(" ");
-                for(q=0; q<16; q++) {
-                    if(reply_data[j+q] >= 0x20)
-                        printf("%c", reply_data[j+q]);
-                    else
-                        printf(".");
+                else {
+                    printf("Failed to parse log header\n");
+                    lock_log(object, false);
+                    return -1;
                 }
-                printf("\n");
+                libambit_protocol_free(reply_data);
+            }
+            else {
+                lock_log(object, false);
+                return -1;
+            }
+
+            // Is there more entries to read?
+            if (libambit_protocol_command(object, ambit_command_log_head_peek, NULL, 0, &reply_data, &replylen, 0) != 0) {
+                lock_log(object, false);
+                return -1;
             }
-            printf("\n");
-            libambit_protocol_free(reply_data);
-        }
-        if (libambit_protocol_command(object, ambit_command_log_head_next, NULL, 0, &reply_data, &replylen, 0) == 0) {
             more = le32toh(*(uint32_t*)reply_data);
             libambit_protocol_free(reply_data);
         }
-        printf("\n\n\n");
+    }
+    else {
+        read_pmem = true;
     }
 
-    *length = 1024;
-/*
-    for(i=0; i<5; i++) {
-        *address = 0x000f4240 + i*1024;
-
-        if (libambit_protocol_command(object, ambit_command_log_read, send_data, sizeof(send_data), &reply_data, &replylen, 0) == 0) {
-            printf("Address: %08x\n", *address);
-            for(j=8; j<replylen; j+=16) {
-                for(q=0; q<16; q++) {
-                    printf("%02x ", reply_data[j+q]);
+    if (read_pmem) {
+        if (libambit_pmem20_init(object) != 0) {
+            printf("%s:%d\n", __FILE__, __LINE__);
+            lock_log(object, false);
+            return -1;
+        }
+
+        // Loop through all log entries, first check headers
+        while (log_entries_walked < log_entries_total && libambit_pmem20_next_header(object, &log_header) == 1) {
+            if (progress_cb != NULL) {
+                progress_cb(userref, log_entries_total, log_entries_walked+1, 100*log_entries_walked/log_entries_total);
+            }
+            // Check if this entry needs to be read
+            if (skip_cb(userref, &log_header) != 0) {
+                log_entry = libambit_pmem20_read_entry(object);
+                if (log_entry != NULL) {
+                    if (push_cb != NULL) {
+                        push_cb(userref, log_entry);
+                    }
+                    entries_read++;
+                }
+            }
+            log_entries_walked++;
+            if (progress_cb != NULL) {
+                progress_cb(userref, log_entries_total, log_entries_walked, 100*log_entries_walked/log_entries_total);
+            }
+        }
+    }
+
+    lock_log(object, false);
+
+    return entries_read;
+}
+
+void libambit_log_entry_free(ambit_log_entry_t *log_entry)
+{
+    int i;
+
+    if (log_entry != NULL) {
+        if (log_entry->samples != NULL) {
+            for (i=0; i<log_entry->samples_count; i++) {
+                if (log_entry->samples[i].type == ambit_log_sample_type_periodic) {
+                    if (log_entry->samples[i].u.periodic.values != NULL) {
+                        free(log_entry->samples[i].u.periodic.values);
+                    }
                 }
-                printf(" ");
-                for(q=0; q<16; q++) {
-                    if(reply_data[j+q] >= 0x20)
-                        printf("%c", reply_data[j+q]);
-                    else
-                        printf(".");
+                if (log_entry->samples[i].type == ambit_log_sample_type_gps_base) {
+                    if (log_entry->samples[i].u.gps_base.satellites != NULL) {
+                        free(log_entry->samples[i].u.gps_base.satellites);
+                    }
                 }
-                printf("\n");
             }
-            printf("\n");
-            libambit_protocol_free(reply_data);
+            free(log_entry->samples);
+        }
+        free(log_entry);
+    }
+}
+
+static int device_info_get(ambit_object_t *object, ambit_device_info_t *info)
+{
+    uint8_t send_data[] = { 0x01, 0x06, 0x14, 0x00 };
+    uint8_t *reply_data = NULL;
+    size_t replylen;
+    int ret = -1;
+
+    if (libambit_protocol_command(object, ambit_command_device_info, send_data, sizeof(send_data), &reply_data, &replylen, 1) == 0) {
+        if (info != NULL) {
+            memcpy(info->model, reply_data, 16);
+            info->model[16] = 0;
+            memcpy(info->serial, &reply_data[16], 16);
+            info->serial[16] = 0;
+            memcpy(info->fw_version, &reply_data[32], 4);
+            memcpy(info->hw_version, &reply_data[36], 4);
         }
+        ret = 0;
+    }
+
+    libambit_protocol_free(reply_data);
+
+    return ret;
+}
+
+static int lock_log(ambit_object_t *object, bool lock)
+{
+    int ret = -1;
+    uint8_t send_data[] = { 0x00, 0x00, 0x00, 0x00 };
+    uint8_t *reply_data = NULL;
+    size_t replylen;
+
+    uint32_t current_lock = 0xffffffff;
+
+    if ((ret = libambit_protocol_command(object, ambit_command_lock_check, NULL, 0, &reply_data, &replylen, 0)) == 0) {
+        current_lock = le32toh(*(uint32_t*)reply_data);
+        libambit_protocol_free(reply_data);
     }
-*/
 
-    return 0;
+    if (lock && current_lock == 0) {
+        send_data[0] = 1;
+        ret = libambit_protocol_command(object, ambit_command_lock_set, send_data, sizeof(send_data), &reply_data, &replylen, 0);
+        libambit_protocol_free(reply_data);
+    }
+    else if (!lock && current_lock == 1) {
+        send_data[0] = 0;
+        ret = libambit_protocol_command(object, ambit_command_lock_set, send_data, sizeof(send_data), &reply_data, &replylen, 0);
+        libambit_protocol_free(reply_data);
+    }
+
+    return ret;
 }
 
diff --git a/src/libambit/libambit.h b/src/libambit/libambit.h
index 9d4cd92..4b245a1 100644
--- a/src/libambit/libambit.h
+++ b/src/libambit/libambit.h
@@ -1,39 +1,336 @@
+/*
+ * (C) Copyright 2013 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
 #ifndef __LIBAMBIT_H__
 #define __LIBAMBIT_H__
 
+#ifdef __cplusplus /* If this is a C++ compiler, use C linkage */
+extern "C" {
+#endif
+
 #include <stdint.h>
+#include <stdbool.h>
 #include <time.h>
 
+#define LIBAMBIT_MODEL_NAME_LENGTH    16
+#define LIBAMBIT_SERIAL_LENGTH        16
+#define LIBAMBIT_PRODUCT_NAME_LENGTH  32
+
 typedef struct ambit_object_s ambit_object_t;
 
 typedef struct ambit_device_info_s {
-    char model[17];
-    char serial[17];
+    char name[LIBAMBIT_PRODUCT_NAME_LENGTH+1];
+    char model[LIBAMBIT_MODEL_NAME_LENGTH+1];
+    char serial[LIBAMBIT_SERIAL_LENGTH+1];
     uint8_t fw_version[4];
     uint8_t hw_version[4];
 } ambit_device_info_t;
 
-typedef struct ambit_device_data_time_s {
-    uint16_t year;
-    uint8_t  month;
-    uint8_t  day;
-    uint8_t  hour;
-    uint8_t  minute;
-    uint16_t ms;
-} ambit_device_data_time_t;
-
 typedef struct ambit_device_status_s {
     uint8_t  charge;
 } ambit_device_status_t;
 
 typedef struct ambit_personal_settings_s {
-    uint16_t weight;
+    uint8_t  sportmode_button_lock;
+    uint8_t  timemode_button_lock;
+    uint16_t compass_declination;
+    uint8_t  units_mode;
+    struct {
+        uint8_t pressure;
+        uint8_t altitude;
+        uint8_t distance;
+        uint8_t height;
+        uint8_t temperature;
+        uint8_t verticalspeed;
+        uint8_t weight;
+        uint8_t compass;
+        uint8_t heartrate;
+        uint8_t speed;
+    } units;
+    uint8_t  gps_position_format;
+    uint8_t  language;
+    uint8_t  navigation_style;
+    uint8_t  sync_time_w_gps;
+    uint8_t  time_format;
+    struct {
+        uint8_t hour;
+        uint8_t minute;
+    } alarm;
+    uint8_t  alarm_enable;
+    struct {
+        uint8_t hour;
+        uint8_t minute;
+    } dual_time;
+    uint8_t  date_format;
+    uint8_t  tones_mode;
+    uint8_t  backlight_mode;
+    uint8_t  backlight_brightness;
+    uint8_t  display_brightness;
+    uint8_t  display_is_negative;
+    uint16_t weight;                  /* kg scale 0.01 */
     uint16_t birthyear;
     uint8_t  max_hr;
     uint8_t  rest_hr;
+    uint8_t  fitness_level;
+    uint8_t  is_male;
     uint8_t  length;
+    uint8_t  alti_baro_mode;
+    uint8_t  fused_alti_disabled;
+    uint16_t bikepod_calibration;     /* scale 0.0001 */
+    uint16_t bikepod_calibration2;    /* scale 0.0001 */
+    uint16_t bikepod_calibration3;    /* scale 0.0001 */
+    uint16_t footpod_calibration;     /* scale 0.0001 */
+    uint8_t  automatic_bikepower_calib;
 } ambit_personal_settings_t;
 
+typedef struct ambit_log_date_time_s {
+    uint16_t year;
+    uint8_t  month;
+    uint8_t  day;
+    uint8_t  hour;
+    uint8_t  minute;
+    uint16_t msec;
+} ambit_date_time_t;
+
+typedef enum ambit_log_sample_type_e {
+    ambit_log_sample_type_periodic = 0x0200,
+    ambit_log_sample_type_logpause = 0x0304,
+    ambit_log_sample_type_logrestart = 0x0305,
+    ambit_log_sample_type_ibi = 0x0306,
+    ambit_log_sample_type_ttff = 0x0307,
+    ambit_log_sample_type_distance_source = 0x0308,
+    ambit_log_sample_type_lapinfo = 0x0309,
+    ambit_log_sample_type_altitude_source = 0x030d,
+    ambit_log_sample_type_gps_base = 0x030f,
+    ambit_log_sample_type_gps_small = 0x0310,
+    ambit_log_sample_type_gps_tiny = 0x0311,
+    ambit_log_sample_type_time = 0x0312,
+    ambit_log_sample_type_activity = 0x0318,
+    ambit_log_sample_type_position = 0x031b
+} ambit_log_sample_type_t;
+
+typedef enum ambit_log_sample_periodic_type_e {
+    ambit_log_sample_periodic_type_latitude = 0x01,
+    ambit_log_sample_periodic_type_longitude = 0x02,
+    ambit_log_sample_periodic_type_distance = 0x03,
+    ambit_log_sample_periodic_type_speed = 0x04,
+    ambit_log_sample_periodic_type_hr = 0x05,
+    ambit_log_sample_periodic_type_time = 0x06,
+    ambit_log_sample_periodic_type_gpsspeed = 0x07,
+    ambit_log_sample_periodic_type_wristaccspeed = 0x08,
+    ambit_log_sample_periodic_type_bikepodspeed = 0x09,
+    ambit_log_sample_periodic_type_ehpe = 0x0a,
+    ambit_log_sample_periodic_type_evpe = 0x0b,
+    ambit_log_sample_periodic_type_altitude = 0x0c,
+    ambit_log_sample_periodic_type_abspressure = 0x0d,
+    ambit_log_sample_periodic_type_energy = 0x0e,
+    ambit_log_sample_periodic_type_temperature = 0x0f,
+    ambit_log_sample_periodic_type_charge = 0x10,
+    ambit_log_sample_periodic_type_gpsaltitude = 0x11,
+    ambit_log_sample_periodic_type_gpsheading = 0x12,
+    ambit_log_sample_periodic_type_gpshdop = 0x13,
+    ambit_log_sample_periodic_type_gpsvdop = 0x14,
+    ambit_log_sample_periodic_type_wristcadence = 0x15,
+    ambit_log_sample_periodic_type_snr = 0x16,
+    ambit_log_sample_periodic_type_noofsatellites = 0x17,
+    ambit_log_sample_periodic_type_sealevelpressure = 0x18,
+    ambit_log_sample_periodic_type_verticalspeed = 0x19,
+    ambit_log_sample_periodic_type_cadence = 0x1a,
+    ambit_log_sample_periodic_type_bikepower = 0x1f,
+    ambit_log_sample_periodic_type_swimingstrokecnt = 0x20,
+    ambit_log_sample_periodic_type_ruleoutput1 = 0x64,
+    ambit_log_sample_periodic_type_ruleoutput2 = 0x65,
+    ambit_log_sample_periodic_type_ruleoutput3 = 0x66,
+    ambit_log_sample_periodic_type_ruleoutput4 = 0x67,
+    ambit_log_sample_periodic_type_ruleoutput5 = 0x68
+} ambit_log_sample_periodic_type_t;
+
+typedef struct ambit_log_sample_periodic_value_s {
+    ambit_log_sample_periodic_type_t type;
+    union {
+        int32_t  latitude;          /* degree, scale: 0.0000001, -90 <= latitude <= 90 */
+        int32_t  longitude;         /* degree, scale: 0.0000001, -180 <= latitude <= 180 */
+        uint32_t distance;          /* meter, scale: 1 */
+        uint16_t speed;             /* m/s scale: 0.01, ignore if 0xffff */
+        uint8_t  hr;                /* bpm, ignore if 0xff */
+        uint32_t time;              /* msec */
+        uint16_t gpsspeed;          /* m/s scale: 0.01 */
+        uint16_t wristaccspeed;     /* m/s scale: 0.01 */
+        uint16_t bikepodspeed;      /* m/s scale: 0.01 */
+        uint32_t ehpe;              /* meters scale: 0.01 */
+        uint32_t evpe;              /* meters scale: 0.01 */
+        int16_t  altitude;          /* meters, -1000 <= altitude <= 10000 */
+        uint16_t abspressure;      /* hpa scale 0.1 */
+        uint16_t energy;            /* hcal/min */
+        int16_t  temperature;       /* celsius scale 0.1, -100 <= temp <= 100 */
+        uint8_t  charge;            /* percent */
+        int32_t  gpsaltitude;       /* meters scale: 0.01, -1000 <= altitude <= 10000 */
+        uint16_t gpsheading;        /* degrees, scale: 0.01, 0 <= heading <= 360 */
+        uint8_t  gpshdop;           /* ? */
+        uint8_t  gpsvdop;           /* ? */
+        uint16_t wristcadence;      /* rpm, ignore if 0xffff */
+        uint8_t  snr[16];           /* ? */
+        uint8_t  noofsatellites;    /* ignore if 0xff */
+        int16_t  sealevelpressure; /* hpa scale: 0.1 */
+        int16_t  verticalspeed;     /* m/s scale: 0.01 */
+        uint8_t  cadence;           /* rpm, ignore if 0xff */
+        uint16_t bikepower;         /* watt */
+        uint32_t swimingstrokecnt;  /* counter */
+        int32_t  ruleoutput1;       /* ignore if 0x80000000 */
+        int32_t  ruleoutput2;       /* ignore if 0x80000000 */
+        int32_t  ruleoutput3;       /* ignore if 0x80000000 */
+        int32_t  ruleoutput4;       /* ignore if 0x80000000 */
+        int32_t  ruleoutput5;       /* ignore if 0x80000000 */
+    } u;
+} ambit_log_sample_periodic_value_t;
+
+typedef struct ambit_log_gps_satellite_s {
+    uint8_t sv;
+    uint8_t snr;
+    uint8_t state;
+} ambit_log_gps_satellite_t;
+
+typedef struct ambit_log_sample_s {
+    ambit_log_sample_type_t type;  /* type of sample */
+    uint32_t time;                 /* time from zero */
+    ambit_date_time_t utc_time;
+    union {
+        struct {
+            uint8_t value_count;
+            ambit_log_sample_periodic_value_t *values;
+        } periodic;
+        struct {
+            uint8_t ibi_count;
+            uint16_t ibi[32];
+        } ibi;
+        uint16_t ttff;
+        uint8_t  distance_source; /* 2 = GPS, 3 = Wrist */
+        struct {
+            uint8_t event_type;                 /* 0x01 = manual lap,
+                                                   0x14 = high interval end,
+                                                   0x15 = low interval end,
+                                                   0x16 = interval start,
+                                                   0x1e = pause,
+                                                   0x1f = start */
+            ambit_date_time_t date_time;
+            uint32_t duration;                  /* ms */
+            uint32_t distance;                  /* meters */
+        } lapinfo;
+        struct {
+            uint8_t source_type;                /* 0x04 = pressure */
+            int16_t altitude_offset;
+            int16_t pressure_offset;
+        } altitude_source;
+        struct {
+            uint16_t navvalid;
+            uint16_t navtype;
+            ambit_date_time_t utc_base_time;
+            int32_t  latitude;                  /* degree, scale: 0.0000001, -90 <= latitude <= 90 */
+            int32_t  longitude;                 /* degree, scale: 0.0000001, -180 <= latitude <= 180 */
+            int32_t  altitude;                  /* meters scale: 0.01, -1000 <= altitude <= 10000 */
+            uint16_t speed;                     /* m/s scale: 0.01 */
+            uint16_t heading;                   /* degrees, scale: 0.01, 0 <= heading <= 360 */
+            uint32_t ehpe;                      /* meters scale: 0.01 */
+            uint8_t  noofsatellites;            /* */
+            uint8_t  hdop;                      /* ? scale: 0.2 */
+            uint8_t  satellites_count;
+            ambit_log_gps_satellite_t *satellites;
+        } gps_base;
+        struct {
+            uint8_t  noofsatellites;            /* */
+            int32_t  latitude;                  /* degree, scale: 0.0000001, -90 <= latitude <= 90 */
+            int32_t  longitude;                 /* degree, scale: 0.0000001, -180 <= latitude <= 180 */
+            uint32_t ehpe;                      /* meters scale: 0.01 */
+        } gps_small;
+        struct {
+            int32_t  latitude;                  /* degree, scale: 0.0000001, -90 <= latitude <= 90 */
+            int32_t  longitude;                 /* degree, scale: 0.0000001, -180 <= latitude <= 180 */
+            uint32_t ehpe;                      /* meters scale: 0.01 */
+            uint8_t  unknown;                   /* Unknown data */
+        } gps_tiny;
+        struct {
+            uint8_t  hour;
+            uint8_t  minute;
+            uint8_t  second;
+        } time;
+        struct {
+            uint16_t activitytype;
+            uint32_t custommode;
+        } activity;
+        struct {
+            int32_t  latitude;                  /* degree, scale: 0.0000001, -90 <= latitude <= 90 */
+            int32_t  longitude;                 /* degree, scale: 0.0000001, -180 <= latitude <= 180 */
+        } position;
+    } u;
+} ambit_log_sample_t;
+
+typedef struct ambit_log_header_s {
+    ambit_date_time_t date_time;
+    uint32_t duration;              /* ms */
+    uint16_t ascent;                /* m */
+    uint16_t descent;               /* m */
+    uint32_t ascent_time;           /* ms */
+    uint32_t descent_time;          /* ms */
+    uint32_t recovery_time;         /* ms */
+    uint16_t speed_avg;             /* m/h */
+    uint16_t speed_max;             /* m/h */
+    uint32_t speed_max_time;        /* ms */
+    int16_t  altitude_max;          /* m */
+    int16_t  altitude_min;          /* m */
+    uint32_t altitude_max_time;     /* ms */
+    uint32_t altitude_min_time;     /* ms */
+    uint8_t  heartrate_avg;         /* bpm */
+    uint8_t  heartrate_max;         /* bpm */
+    uint8_t  heartrate_min;         /* bpm */
+    uint32_t heartrate_max_time;    /* ms */
+    uint32_t heartrate_min_time;    /* ms */
+    uint8_t  peak_training_effect;  /* effect scale 0.1 */
+    uint8_t  activity_type;
+    char     activity_name[16];
+    int16_t  temperature_max;       /* degree celsius scale 0.1 */
+    int16_t  temperature_min;       /* degree celsius scale 0.1 */
+    uint32_t temperature_max_time;  /* ms */
+    uint32_t temperature_min_time;  /* ms */
+    uint32_t distance;              /* m */
+    uint32_t samples_count;         /* number of samples in log */
+    uint16_t energy_consumption;    /* kcal */
+    uint32_t first_fix_time;        /* ms */
+    uint8_t  battery_start;         /* percent */
+    uint8_t  battery_end;           /* percent */
+    uint32_t distance_before_calib; /* m */
+
+    uint8_t  unknown1[5];
+    uint8_t  unknown2;
+    uint8_t  unknown3[6];
+    uint8_t  unknown4[8];
+    uint8_t  unknown5[4];
+    uint8_t  unknown6[24];
+} ambit_log_header_t;
+
+typedef struct ambit_log_entry_s {
+    ambit_log_header_t header;
+    uint32_t samples_count;
+    ambit_log_sample_t *samples;
+} ambit_log_entry_t;
+
 /**
  * Try to detect clock
  * If clock detected, object handle is returned
@@ -47,14 +344,91 @@ ambit_object_t *libambit_detect(void);
  */
 void libambit_close(ambit_object_t *object);
 
+/**
+ * Check if detected device is currently supported
+ * \param object Object to check
+ * \return true if device supported, else false
+ */
+bool libambit_device_supported(ambit_object_t *object);
+
+/**
+ * Get device info on connected dev
+ * \param object Object to get info from
+ * \param status Status object to be filled
+ * \return 0 on success, else -1
+ */
 int libambit_device_info_get(ambit_object_t *object, ambit_device_info_t *status);
 
+/**
+ * Set current date and time to clock
+ * \param object Object to write to
+ * \param date_time Date and time to set
+ * \return 0 on success, else -1
+ */
 int libambit_date_time_set(ambit_object_t *object, struct tm *date_time);
 
+/**
+ * Get status info from device
+ * \param object Object to get status from
+ * \param status Status object to be filled
+ * \return 0 on success, else -1
+ */
 int libambit_device_status_get(ambit_object_t *object, ambit_device_status_t *status);
 
+/**
+ * Get settings from device
+ * \param object Object to get settings from
+ * \param settings Settings object to be filled
+ * \return 0 on success, else -1
+ */
 int libambit_personal_settings_get(ambit_object_t *object, ambit_personal_settings_t *settings);
 
-int libambit_log_read_get_next(ambit_object_t *object);
+/**
+ * Callback function for checking if a specific log entry should be read out or
+ * skipped during log readouts
+ * \param object Object reference
+ * \param log_header Pointer to log header that is about to be read out
+ * \return Should return 0 to skip entry, else -1
+ */
+typedef int (*ambit_log_skip_cb)(void *userref, ambit_log_header_t *log_header);
+
+/**
+ * Callback function to push log entry to calling application
+ * \param object Object reference
+ * \param log_entry Complete log entry. NOTE! Caller is responsible of freeing
+ * allocated memory with lib_ambit_log_entry_free()
+ */
+typedef void (*ambit_log_push_cb)(void *userref, ambit_log_entry_t *log_entry);
+
+/**
+ * Callback function to notify about progress
+ * \param object Object reference
+ * \param log_count Number of available logs
+ * \param log_current Current log number in progress
+ * \param progress_percent Total progress in percent
+ */
+typedef void (*ambit_log_progress_cb)(void *userref, uint16_t log_count, uint16_t log_current, uint8_t progress_percent);
+
+/**
+ * Read complete log of all excercises from device (filtered by skip_cb
+ * \param object Object reference
+ * \param skip_cb Callback to be used to check if a specific entry should read
+ * or skipped. Use NULL to get all entries.
+ * \param push_cb Callback to use for pushing read out entry to caller.
+ * \return Number of entries read, or -1 on error
+ * \note Caller is responsible of freeing log entries with
+ * libambit_log_entry_free()
+ */
+int libambit_log_read(ambit_object_t *object, ambit_log_skip_cb skip_cb, ambit_log_push_cb push_cb, ambit_log_progress_cb progress_cb, void *userref);
+
+/**
+ * Free log entry allocated by libambit_log_read
+ * \param log_entry Log entry to free
+ */
+void libambit_log_entry_free(ambit_log_entry_t *log_entry);
+
+#ifdef __cplusplus /* If this is a C++ compiler, end C linkage */
+}
+#endif
 
 #endif /* __LIBAMBIT_H__ */
diff --git a/src/libambit/libambit_int.h b/src/libambit/libambit_int.h
index f643e02..16a2c4c 100644
--- a/src/libambit/libambit_int.h
+++ b/src/libambit/libambit_int.h
@@ -1,22 +1,123 @@
+/*
+ * (C) Copyright 2013 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
 #ifndef __LIBAMBIT_INT_H__
 #define __LIBAMBIT_INT_H__
 
 #include <stdint.h>
 #include "hidapi/hidapi.h"
+#include "libambit.h"
+
+typedef struct ambit_supported_device_s ambit_supported_device_t;
 
 typedef struct ambit_object_s {
     hid_device *handle;
     uint16_t vendor_id;
     uint16_t product_id;
     uint16_t sequence_no;
+    ambit_supported_device_t *device;
+    ambit_device_info_t device_info;
+
+    struct {
+        bool initialized;
+        uint32_t first_entry;
+        uint32_t last_entry;
+        uint32_t entries;
+        uint32_t next_free_address;
+        struct {
+            uint32_t current;
+            uint32_t next;
+            uint32_t prev;
+        } current;
+        uint8_t *buffer;
+        uint32_t prev_read;
+        uint32_t last_addr;
+    } pmem20;
 } ambit_object_t;
 
-// protocol.c
-int libambit_protocol_command(ambit_object_t *object, uint16_t command, uint8_t *data, size_t datalen, uint8_t **reply_data, size_t *replylen, uint8_t legacy_format);
-void libambit_protocol_free(uint8_t *data);
+enum ambit_commands_e {
+    ambit_command_device_info        = 0x0000,
+    ambit_command_time               = 0x0300,
+    ambit_command_date               = 0x0302,
+    ambit_command_status             = 0x0306,
+    ambit_command_personal_settings  = 0x0b00,
+    ambit_command_log_count          = 0x0b06,
+    ambit_command_log_head_first     = 0x0b07,
+    ambit_command_log_head_peek      = 0x0b08,
+    ambit_command_log_head_step      = 0x0b0a,
+    ambit_command_log_head           = 0x0b0b,
+    ambit_command_log_read           = 0x0b17,
+    ambit_command_lock_check         = 0x0b19,
+    ambit_command_lock_set           = 0x0b1a,
+};
 
 // crc16.c
 uint16_t crc16_ccitt_false(unsigned char *buf, size_t buflen);
 uint16_t crc16_ccitt_false_init(unsigned char *buf, size_t buflen, uint16_t crc);
 
+// personal.c
+int libambit_personal_settings_parse(uint8_t *data, size_t datalen, ambit_personal_settings_t *settings);
+
+// pmem20.c
+int libambit_pmem20_init(ambit_object_t *object);
+int libambit_pmem20_deinit(ambit_object_t *object);
+int libambit_pmem20_next_header(ambit_object_t *object, ambit_log_header_t *log_header);
+ambit_log_entry_t *libambit_pmem20_read_entry(ambit_object_t *object);
+int libambit_pmem20_parse_header(uint8_t *data, size_t datalen, ambit_log_header_t *log_header);
+
+// protocol.c
+int libambit_protocol_command(ambit_object_t *object, uint16_t command, uint8_t *data, size_t datalen, uint8_t **reply_data, size_t *replylen, uint8_t legacy_format);
+void libambit_protocol_free(uint8_t *data);
+
+
+
+// static helpers
+static inline uint8_t read8(uint8_t *buf, size_t offset)
+{
+    return buf[offset];
+}
+
+static inline uint16_t read16(uint8_t *buf, size_t offset)
+{
+    return (buf[offset] | (buf[offset+1] << 8));
+}
+
+static inline uint32_t read32(uint8_t *buf, size_t offset)
+{
+    return (buf[offset] | (buf[offset+1] << 8) | (buf[offset+2] << 16) | (buf[offset+3] << 24));
+}
+
+static inline uint8_t read8inc(uint8_t *buf, size_t *offset)
+{
+    return buf[(*offset)++];
+}
+
+static inline uint16_t read16inc(uint8_t *buf, size_t *offset)
+{
+    return (buf[(*offset)++] | (buf[(*offset)++] << 8));
+}
+
+static inline uint32_t read32inc(uint8_t *buf, size_t *offset)
+{
+    return (buf[(*offset)++] | (buf[(*offset)++] << 8) | (buf[(*offset)++] << 16) | (buf[(*offset)++] << 24));
+}
+
 #endif /* __LIBAMBIT_INT_H__ */
diff --git a/src/libambit/personal.c b/src/libambit/personal.c
new file mode 100644
index 0000000..36fc7ac
--- /dev/null
+++ b/src/libambit/personal.c
@@ -0,0 +1,119 @@
+/*
+ * (C) Copyright 2013 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
+#include "libambit.h"
+#include "libambit_int.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+/*
+ * Local definitions
+ */
+
+/*
+ * Public functions
+ */
+int libambit_personal_settings_parse(uint8_t *data, size_t datalen, ambit_personal_settings_t *settings)
+{
+    size_t offset = 0;
+    int i;
+
+    // Check that data is long enough
+    if (datalen < 137) {
+        return -1;
+    }
+
+    offset = 1;
+    settings->sportmode_button_lock = read8inc(data, &offset);
+    settings->timemode_button_lock = read8inc(data, &offset);
+    offset += 1;
+    settings->compass_declination = read16inc(data, &offset);
+    offset += 2;
+    settings->units_mode = read8inc(data, &offset);
+
+    settings->units.pressure = read8inc(data, &offset);
+    settings->units.altitude = read8inc(data, &offset);
+    settings->units.distance = read8inc(data, &offset);
+    settings->units.height = read8inc(data, &offset);
+    settings->units.temperature = read8inc(data, &offset);
+    settings->units.verticalspeed = read8inc(data, &offset);
+    settings->units.weight = read8inc(data, &offset);
+    settings->units.compass = read8inc(data, &offset);
+    settings->units.heartrate = read8inc(data, &offset);
+    settings->units.speed = read8inc(data, &offset);
+
+    settings->gps_position_format = read8inc(data, &offset);
+    settings->language = read8inc(data, &offset);
+    settings->navigation_style = read8inc(data, &offset);
+    offset += 2;
+    settings->sync_time_w_gps = read8inc(data, &offset);
+    settings->time_format = read8inc(data, &offset);
+
+    settings->alarm.hour = read8inc(data, &offset);
+    settings->alarm.minute = read8inc(data, &offset);
+
+    settings->alarm_enable = read8inc(data, &offset);
+
+    offset += 2;
+    settings->dual_time.hour = read8inc(data, &offset);
+    settings->dual_time.minute = read8inc(data, &offset);
+
+    offset += 3;
+
+    settings->date_format = read8inc(data, &offset);
+
+    offset += 3;
+
+    settings->tones_mode = read8inc(data, &offset);
+
+    offset += 3;
+
+    settings->backlight_mode = read8inc(data, &offset);
+    settings->backlight_brightness = read8inc(data, &offset);
+    settings->display_brightness = read8inc(data, &offset);
+    settings->display_is_negative = read8inc(data, &offset);
+    settings->weight = read16inc(data, &offset);
+    settings->birthyear = read16inc(data, &offset);
+    settings->max_hr = read8inc(data, &offset);
+    settings->rest_hr = read8inc(data, &offset);
+    settings->fitness_level = read8inc(data, &offset);
+    settings->is_male = read8inc(data, &offset);
+    settings->length = read8inc(data, &offset);
+
+    offset += 3;
+
+    settings->alti_baro_mode = read8inc(data, &offset);
+
+    offset += 1;
+
+    settings->fused_alti_disabled = read8inc(data, &offset);
+
+    offset = 0x80;
+    settings->bikepod_calibration = read16inc(data, &offset);
+    settings->bikepod_calibration2 = read16inc(data, &offset);
+    settings->bikepod_calibration3 = read16inc(data, &offset);
+    settings->footpod_calibration = read16inc(data, &offset);
+    settings->automatic_bikepower_calib = read8inc(data, &offset);
+
+    return 0;
+}
diff --git a/src/libambit/pmem20.c b/src/libambit/pmem20.c
new file mode 100644
index 0000000..2485e8b
--- /dev/null
+++ b/src/libambit/pmem20.c
@@ -0,0 +1,738 @@
+/*
+ * (C) Copyright 2013 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
+#include "libambit.h"
+#include "libambit_int.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+/*
+ * Local definitions
+ */
+#define PMEM20_LOG_START          0x000f4240
+#define PMEM20_LOG_SIZE           0x0029f630 /* 2 750 000 */
+#define PMEM20_LOG_READ_CHUNKS    0x00000400 /* 1024 */
+#define PMEM20_LOG_HEADER_MIN_LEN        512 /* Header actually longer, but not interesting*/
+
+typedef struct __attribute__((__packed__)) periodic_sample_spec_s {
+    uint16_t type;
+    uint16_t offset;
+    uint16_t length;
+} periodic_sample_spec_t;
+
+/*
+ * Static functions
+ */
+static int parse_sample(uint8_t *buf, size_t *offset, uint8_t **spec, ambit_log_entry_t *log_entry, size_t *sample_count);
+static int read_upto(ambit_object_t *object, uint32_t address, uint32_t length);
+static int read_log_chunk(ambit_object_t *object, uint32_t address, uint32_t length, uint8_t *buffer);
+static void add_time(ambit_date_time_t *intime, int32_t offset, ambit_date_time_t *outtime);
+static int is_leap(unsigned int y);
+static void to_timeval(ambit_date_time_t *ambit_time, struct timeval *timeval);
+
+/*
+ * Static variables
+ */
+
+
+
+/*
+ * Public functions
+ */
+int libambit_pmem20_init(ambit_object_t *object)
+{
+    int ret = -1;
+    size_t offset;
+
+    // Allocate buffer for complete memory
+    if (object->pmem20.buffer != NULL) {
+        free(object->pmem20.buffer);
+    }
+    memset(&object->pmem20, 0, sizeof(object->pmem20));
+    object->pmem20.buffer = malloc(PMEM20_LOG_SIZE);
+    if (object->pmem20.buffer != NULL) {
+        // Read initial log header
+        ret = read_log_chunk(object, PMEM20_LOG_START, PMEM20_LOG_READ_CHUNKS, object->pmem20.buffer);
+        if (ret == 0) {
+            object->pmem20.prev_read = PMEM20_LOG_START;
+
+            // Parse PMEM header
+            offset = 0;
+            object->pmem20.last_entry = read32inc(object->pmem20.buffer, &offset);
+            object->pmem20.first_entry = read32inc(object->pmem20.buffer, &offset);
+            object->pmem20.entries = read32inc(object->pmem20.buffer, &offset);
+            object->pmem20.next_free_address = read32inc(object->pmem20.buffer, &offset);
+            object->pmem20.current.current = PMEM20_LOG_START;
+            object->pmem20.current.next = object->pmem20.first_entry;
+            object->pmem20.current.prev = PMEM20_LOG_START;
+
+            // Set initialized
+            object->pmem20.initialized = true;
+        }
+    }
+
+    return ret;
+}
+
+int libambit_pmem20_deinit(ambit_object_t *object)
+{
+    if (object->pmem20.buffer != NULL) {
+        free(object->pmem20.buffer);
+    }
+    memset(&object->pmem20, 0, sizeof(object->pmem20));
+
+    return 0;
+}
+
+int libambit_pmem20_next_header(ambit_object_t *object, ambit_log_header_t *log_header)
+{
+    int ret = -1, tmp_ret;
+    size_t buffer_offset;
+    uint16_t tmp_len;
+
+    if (!object->pmem20.initialized) {
+        return -1;
+    }
+
+    // Check if we reached end of entries
+    if (object->pmem20.current.current == object->pmem20.current.next) {
+        return 0;
+    }
+
+    if (read_upto(object, object->pmem20.current.next, PMEM20_LOG_HEADER_MIN_LEN) == 0) {
+        buffer_offset = (object->pmem20.current.next - PMEM20_LOG_START);
+        // First check that header seems to be correctly present
+        if (strncmp(object->pmem20.buffer + buffer_offset, "PMEM", 4) == 0) {
+            object->pmem20.current.current = object->pmem20.current.next;
+            buffer_offset += 4;
+            object->pmem20.current.next = read32inc(object->pmem20.buffer, &buffer_offset);
+            object->pmem20.current.prev = read32inc(object->pmem20.buffer, &buffer_offset);
+            tmp_len = read16inc(object->pmem20.buffer, &buffer_offset);
+            buffer_offset += tmp_len;
+            tmp_len = read16inc(object->pmem20.buffer, &buffer_offset);
+            if (libambit_pmem20_parse_header(object->pmem20.buffer + buffer_offset, tmp_len, log_header) == 0) {
+                ret = 1;
+            }
+        }
+    }
+
+    // Unset initialized of something went wrong
+    if (ret < 0) {
+        object->pmem20.initialized = false;
+    }
+
+    return ret;
+}
+
+ambit_log_entry_t *libambit_pmem20_read_entry(ambit_object_t *object)
+{
+    // Note! We assume that the caller has called libambit_pmem20_next_header just before
+    uint8_t *periodic_sample_spec;
+    uint16_t tmp_len;
+    size_t buffer_offset, sample_count = 0, i;
+    ambit_log_entry_t *log_entry;
+    ambit_log_sample_t *last_periodic = NULL, *utcsource = NULL, *gpsbase = NULL, *altisource = NULL;
+    ambit_date_time_t utcbase;
+    uint32_t altisource_index = 0;
+    uint32_t last_base_lat = 0, last_base_long = 0;
+    uint32_t last_small_lat = 0, last_small_long = 0;
+    uint32_t last_ehpe = 0;
+
+    if (!object->pmem20.initialized) {
+        return NULL;
+    }
+
+    // Allocate log entry
+    if ((log_entry = calloc(1, sizeof(ambit_log_entry_t))) == NULL) {
+        object->pmem20.initialized = false;
+        return NULL;
+    }
+
+    buffer_offset = (object->pmem20.current.current - PMEM20_LOG_START);
+    buffer_offset += 12;
+    // Read samples content definition
+    tmp_len = read16inc(object->pmem20.buffer, &buffer_offset);
+    periodic_sample_spec = object->pmem20.buffer + buffer_offset;
+    buffer_offset += tmp_len;
+    // Parse header
+    tmp_len = read16inc(object->pmem20.buffer, &buffer_offset);
+    if (libambit_pmem20_parse_header(object->pmem20.buffer + buffer_offset, tmp_len, &log_entry->header) != 0) {
+        free(log_entry);
+        object->pmem20.initialized = false;
+        return NULL;
+    }
+    buffer_offset += tmp_len;
+    // Now that we know number of samples, allocate space for them!
+    if ((log_entry->samples = calloc(log_entry->header.samples_count, sizeof(ambit_log_sample_t))) == NULL) {
+        free(log_entry);
+        object->pmem20.initialized = false;
+        return NULL;
+    }
+    log_entry->samples_count = log_entry->header.samples_count;
+
+    // OK, so we are at start of samples, get them all!
+    while (sample_count < log_entry->samples_count) {
+        if (PMEM20_LOG_START + buffer_offset + 2 >= object->pmem20.last_addr ||
+            PMEM20_LOG_START + buffer_offset + 2 + read16(object->pmem20.buffer, buffer_offset) >= object->pmem20.last_addr) {
+            read_upto(object, PMEM20_LOG_START + buffer_offset, PMEM20_LOG_READ_CHUNKS);
+        }
+
+        if (parse_sample(object->pmem20.buffer, &buffer_offset, &periodic_sample_spec, log_entry, &sample_count) == 1) {
+            // Calculate times
+            if (log_entry->samples[sample_count-1].type == ambit_log_sample_type_periodic) {
+                last_periodic = &log_entry->samples[sample_count-1];
+            }
+            else if (last_periodic != NULL) {
+                log_entry->samples[sample_count-1].time += last_periodic->time;
+            }
+            else {
+                log_entry->samples[sample_count-1].time = 0;
+            }
+
+            if (utcsource == NULL && log_entry->samples[sample_count-1].type == ambit_log_sample_type_gps_base) {
+                utcsource = &log_entry->samples[sample_count-1];
+                // Calculate UTC base time
+                add_time(&utcsource->u.gps_base.utc_base_time, 0-utcsource->time, &utcbase);
+            }
+
+            // Calculate positions
+            if (log_entry->samples[sample_count-1].type == ambit_log_sample_type_gps_base) {
+                last_base_lat = log_entry->samples[sample_count-1].u.gps_base.latitude;
+                last_base_long = log_entry->samples[sample_count-1].u.gps_base.longitude;
+                last_small_lat = log_entry->samples[sample_count-1].u.gps_base.latitude;
+                last_small_long = log_entry->samples[sample_count-1].u.gps_base.longitude;
+                last_ehpe = log_entry->samples[sample_count-1].u.gps_base.ehpe;
+            }
+            else if (log_entry->samples[sample_count-1].type == ambit_log_sample_type_gps_small) {
+                log_entry->samples[sample_count-1].u.gps_small.latitude = last_base_lat + log_entry->samples[sample_count-1].u.gps_small.latitude*10;
+                log_entry->samples[sample_count-1].u.gps_small.longitude = last_base_long + log_entry->samples[sample_count-1].u.gps_small.longitude*10;
+                last_small_lat = log_entry->samples[sample_count-1].u.gps_small.latitude;
+                last_small_long = log_entry->samples[sample_count-1].u.gps_small.longitude;
+                last_ehpe = log_entry->samples[sample_count-1].u.gps_small.ehpe;
+            }
+            else if (log_entry->samples[sample_count-1].type == ambit_log_sample_type_gps_tiny) {
+                log_entry->samples[sample_count-1].u.gps_tiny.latitude = last_small_lat + log_entry->samples[sample_count-1].u.gps_tiny.latitude*10;
+                log_entry->samples[sample_count-1].u.gps_tiny.longitude = last_small_long + log_entry->samples[sample_count-1].u.gps_tiny.longitude*10;
+                log_entry->samples[sample_count-1].u.gps_tiny.ehpe = (last_ehpe > 700 ? 700 : last_ehpe);
+                last_small_lat = log_entry->samples[sample_count-1].u.gps_tiny.latitude;
+                last_small_long = log_entry->samples[sample_count-1].u.gps_tiny.longitude;
+            }
+
+            if (altisource == NULL && log_entry->samples[sample_count-1].type == ambit_log_sample_type_altitude_source) {
+                altisource = &log_entry->samples[sample_count-1];
+                altisource_index = sample_count-1;
+            }
+        }
+    }
+
+    // Loop through samples again and correct times etc
+    for (sample_count = 0; sample_count < log_entry->header.samples_count; sample_count++) {
+        // Set UTC times (if UTC source found)
+        if (utcsource != NULL) {
+            add_time(&utcbase, log_entry->samples[sample_count].time, &log_entry->samples[sample_count].utc_time);
+        }
+        // Correct altitude based on altitude offset in altitude source
+        if (altisource != NULL && log_entry->samples[sample_count].type == ambit_log_sample_type_periodic && sample_count < altisource_index) {
+            for (i=0; i<log_entry->samples[sample_count].u.periodic.value_count; i++) {
+                if (log_entry->samples[sample_count].u.periodic.values[i].type == ambit_log_sample_periodic_type_sealevelpressure) {
+                    log_entry->samples[sample_count].u.periodic.values[i].u.sealevelpressure += altisource->u.altitude_source.pressure_offset;
+                }
+                if (log_entry->samples[sample_count].u.periodic.values[i].type == ambit_log_sample_periodic_type_altitude) {
+                    log_entry->samples[sample_count].u.periodic.values[i].u.altitude += altisource->u.altitude_source.altitude_offset;
+                }
+            }
+        }
+    }
+
+    return log_entry;
+}
+
+int libambit_pmem20_parse_header(uint8_t *data, size_t datalen, ambit_log_header_t *log_header)
+{
+    size_t offset = 0;
+    int i;
+
+    // Check that header is long enough to be parsed correctly
+    if (datalen < 129) {
+        return -1;
+    }
+
+    offset = 1;
+    log_header->date_time.year = read16inc(data, &offset);
+    log_header->date_time.month = read8inc(data, &offset);
+    log_header->date_time.day = read8inc(data, &offset);
+    log_header->date_time.hour = read8inc(data, &offset);
+    log_header->date_time.minute = read8inc(data, &offset);
+    log_header->date_time.msec = read8inc(data, &offset)*1000;
+
+    memcpy(log_header->unknown1, data+offset, 5);
+    offset += 5;
+
+    log_header->duration = read32inc(data, &offset)*100; // seconds 0.1
+    log_header->ascent = read16inc(data, &offset);
+    log_header->descent = read16inc(data, &offset);
+    log_header->ascent_time = read32inc(data, &offset)*1000;
+    log_header->descent_time = read32inc(data, &offset)*1000;
+    log_header->recovery_time = read16inc(data, &offset)*60*1000;
+    log_header->speed_avg = read16inc(data, &offset)*10; // 10 m/h
+    log_header->speed_max = read16inc(data, &offset)*10; // 10 m/h
+    log_header->altitude_max = read16inc(data, &offset);
+    log_header->altitude_min = read16inc(data, &offset);
+    log_header->heartrate_avg = read8inc(data, &offset);
+    log_header->heartrate_max = read8inc(data, &offset);
+    log_header->peak_training_effect = read8inc(data, &offset);
+    log_header->activity_type = read8inc(data, &offset);
+    memcpy(log_header->activity_name, data + offset, 16);
+    offset += 16;
+    log_header->heartrate_min = read8inc(data, &offset);
+
+    log_header->unknown2 = read8inc(data, &offset);
+
+    log_header->temperature_max = read16inc(data, &offset);
+    log_header->temperature_min = read16inc(data, &offset);
+    log_header->distance = read32inc(data, &offset);
+    log_header->samples_count = read32inc(data, &offset);
+    log_header->energy_consumption = read16inc(data, &offset);
+
+    memcpy(log_header->unknown3, data+offset, 6);
+    offset += 6;
+
+    log_header->speed_max_time = read32inc(data, &offset);
+    log_header->altitude_max_time = read32inc(data, &offset);
+    log_header->altitude_min_time = read32inc(data, &offset);
+    log_header->heartrate_max_time = read32inc(data, &offset);
+    log_header->heartrate_min_time = read32inc(data, &offset);
+    log_header->temperature_max_time = read32inc(data, &offset);
+    log_header->temperature_min_time = read32inc(data, &offset);
+
+    memcpy(log_header->unknown4, data+offset, 8);
+    offset += 8;
+
+    log_header->first_fix_time = read16inc(data, &offset)*1000;
+    log_header->battery_start = read8inc(data, &offset);
+    log_header->battery_end = read8inc(data, &offset);
+
+    memcpy(log_header->unknown5, data+offset, 4);
+    offset += 4;
+
+    log_header->distance_before_calib = read32inc(data, &offset);
+
+    memcpy(log_header->unknown6, data+offset, 24);
+    offset += 24;
+
+    return 0;
+}
+
+/**
+ * Parse the given sample
+ * \return number of samples added (1 or 0)
+ */
+static int parse_sample(uint8_t *buf, size_t *offset, uint8_t **spec, ambit_log_entry_t *log_entry, size_t *sample_count)
+{
+    int ret = 0;
+    size_t int_offset = *offset;
+    uint16_t sample_len = read16inc(buf, &int_offset);
+    uint8_t  sample_type = read8inc(buf, &int_offset);
+    uint8_t  episodic_type;
+    uint16_t spec_count, spec_type, spec_offset;
+    periodic_sample_spec_t *spec_entry;
+    int i;
+
+    switch (sample_type) {
+      case 0:   /* periodic sample specifier */
+        // Update specifier on input
+        *spec = buf + *offset + 2;
+        break;
+      case 2:   /* periodic sample */
+        log_entry->samples[*sample_count].type = ambit_log_sample_type_periodic;
+        log_entry->samples[*sample_count].time = read32(buf, *offset + sample_len - 2);
+        
+        // Loop through specifier and set corresponding fields
+        spec_count = read16(*spec, 1);
+        log_entry->samples[*sample_count].u.periodic.value_count = spec_count;
+        log_entry->samples[*sample_count].u.periodic.values = calloc(spec_count, sizeof(ambit_log_sample_periodic_value_t));
+        for (i=0, spec_entry = (periodic_sample_spec_t*)(*spec + 3); i<spec_count; i++, spec_entry++) {
+            spec_type = le16toh(spec_entry->type);
+            spec_offset = le16toh(spec_entry->offset);
+            switch(spec_type) {
+              case ambit_log_sample_periodic_type_latitude:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_latitude;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.latitude = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_longitude:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_longitude;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.longitude = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_distance:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_distance;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.distance = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_speed:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_speed;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.speed = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_hr:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_hr;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.hr = read8(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_time:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_time;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.time = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_gpsspeed:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_gpsspeed;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.gpsspeed = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_wristaccspeed:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_wristaccspeed;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.wristaccspeed = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_bikepodspeed:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_bikepodspeed;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.bikepodspeed = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_ehpe:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ehpe;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.ehpe = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_evpe:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_evpe;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.evpe = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_altitude:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_altitude;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.altitude = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_abspressure:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_abspressure;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.abspressure = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_energy:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_energy;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.energy = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_temperature:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_temperature;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.temperature = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_charge:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_charge;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.charge = read8(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_gpsaltitude:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_gpsaltitude;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.gpsaltitude = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_gpsheading:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_gpsheading;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.gpsheading = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_gpshdop:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_gpshdop;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.gpshdop = read8(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_gpsvdop:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_gpsvdop;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.gpsvdop = read8(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_wristcadence:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_wristcadence;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.wristcadence = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_snr:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_snr;
+                memcpy(log_entry->samples[*sample_count].u.periodic.values[i].u.snr, buf + int_offset + spec_offset, 16);
+                break;
+              case ambit_log_sample_periodic_type_noofsatellites:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_noofsatellites;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.noofsatellites = read8(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_sealevelpressure:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_sealevelpressure;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.sealevelpressure = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_verticalspeed:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_verticalspeed;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.verticalspeed = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_cadence:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_cadence;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.cadence = read8(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_bikepower:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_bikepower;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.bikepower = read16(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_swimingstrokecnt:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_swimingstrokecnt;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.swimingstrokecnt = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_ruleoutput1:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ruleoutput1;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.ruleoutput1 = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_ruleoutput2:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ruleoutput2;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.ruleoutput2 = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_ruleoutput3:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ruleoutput3;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.ruleoutput3 = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_ruleoutput4:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ruleoutput4;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.ruleoutput4 = read32(buf, int_offset + spec_offset);
+                break;
+              case ambit_log_sample_periodic_type_ruleoutput5:
+                log_entry->samples[*sample_count].u.periodic.values[i].type = ambit_log_sample_periodic_type_ruleoutput5;
+                log_entry->samples[*sample_count].u.periodic.values[i].u.ruleoutput5 = read32(buf, int_offset + spec_offset);
+                break;
+            }
+        }
+        ret = 1;
+        break;
+      case 3:
+        // First parameter is relative time
+        log_entry->samples[*sample_count].time = read32inc(buf, &int_offset);
+        episodic_type = read8inc(buf, &int_offset);
+        switch (episodic_type) {
+          case 0x04:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_logpause;
+            break;
+          case 0x05:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_logrestart;
+            break;
+          case 0x06:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_ibi;
+            for (i=0; i<(sample_len - 6)/2; i++) {
+                log_entry->samples[*sample_count].u.ibi.ibi[i] = read16inc(buf, &int_offset);
+            }
+            log_entry->samples[*sample_count].u.ibi.ibi_count = (sample_len - 6)/2;
+            break;
+          case 0x07:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_ttff;
+            log_entry->samples[*sample_count].u.ttff = read16inc(buf, &int_offset);
+            break;
+          case 0x08:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_distance_source;
+            log_entry->samples[*sample_count].u.distance_source = read8inc(buf, &int_offset);
+            break;
+          case 0x09:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_lapinfo;
+            log_entry->samples[*sample_count].u.lapinfo.event_type = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.lapinfo.date_time.year = read16inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.lapinfo.date_time.month = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.lapinfo.date_time.day = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.lapinfo.date_time.hour = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.lapinfo.date_time.minute = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.lapinfo.date_time.msec = read8inc(buf, &int_offset)*1000;
+            log_entry->samples[*sample_count].u.lapinfo.duration = read32inc(buf, &int_offset)*100;
+            log_entry->samples[*sample_count].u.lapinfo.distance = read32inc(buf, &int_offset);
+            break;
+          case 0x0d:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_altitude_source;
+            log_entry->samples[*sample_count].u.altitude_source.source_type = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.altitude_source.altitude_offset = read16inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.altitude_source.pressure_offset = read16inc(buf, &int_offset);
+            break;
+          case 0x0f:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_gps_base;
+            log_entry->samples[*sample_count].u.gps_base.navvalid = read16inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.navtype = read16inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.utc_base_time.year = read16inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.utc_base_time.month = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.utc_base_time.day = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.utc_base_time.hour = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.utc_base_time.minute = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.utc_base_time.msec = read16inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.latitude = read32inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.longitude = read32inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.altitude = read32inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.speed = read16inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.heading = read16inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.ehpe = read32inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.noofsatellites = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.hdop = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_base.satellites = calloc((sample_len - 40)/4, sizeof(ambit_log_gps_satellite_t));
+            for (i=0; i<(sample_len - 40)/4; i++) {
+                log_entry->samples[*sample_count].u.gps_base.satellites[i].sv = read8inc(buf, &int_offset);
+                log_entry->samples[*sample_count].u.gps_base.satellites[i].state = read8inc(buf, &int_offset);
+                int_offset += 1;
+                log_entry->samples[*sample_count].u.gps_base.satellites[i].snr = read8inc(buf, &int_offset);
+            }
+            log_entry->samples[*sample_count].u.gps_base.satellites_count = (sample_len - 40)/4;
+            break;
+          case 0x10:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_gps_small;
+            log_entry->samples[*sample_count].u.gps_small.latitude = (int16_t)read16inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_small.longitude = (int16_t)read16inc(buf, &int_offset);
+            int_offset += 2; // Time (seconds)
+            log_entry->samples[*sample_count].u.gps_small.ehpe = read8inc(buf, &int_offset)*100;
+            log_entry->samples[*sample_count].u.gps_small.noofsatellites = read8inc(buf, &int_offset);
+            break;
+          case 0x11:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_gps_tiny;
+            log_entry->samples[*sample_count].u.gps_tiny.latitude = (int8_t)read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_tiny.longitude = (int8_t)read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.gps_tiny.unknown = read8inc(buf, &int_offset);
+            break;
+          case 0x12:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_time;
+            log_entry->samples[*sample_count].u.time.hour = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.time.minute = read8inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.time.second = read8inc(buf, &int_offset);
+            break;
+          case 0x18:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_activity;
+            log_entry->samples[*sample_count].u.activity.activitytype = read16inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.activity.custommode = read32inc(buf, &int_offset);
+            break;
+          case 0x1b:
+            log_entry->samples[*sample_count].type = ambit_log_sample_type_position;
+            log_entry->samples[*sample_count].u.position.latitude = read32inc(buf, &int_offset);
+            log_entry->samples[*sample_count].u.position.longitude = read32inc(buf, &int_offset);
+            break;
+          default:
+            printf("Found unknown episodic sample type (%02x)\n", episodic_type);
+            break;
+        }
+        ret = 1;
+        break;
+      default:
+        printf("Found unknown sample type (%02x)\n", sample_type);
+        ret = 1;
+        break;
+    }
+
+    *sample_count += ret;
+    *offset += 2 + sample_len;
+
+    return ret;
+}
+
+static int read_upto(ambit_object_t *object, uint32_t address, uint32_t length)
+{
+    uint32_t start_address = address - ((address - PMEM20_LOG_START) % PMEM20_LOG_READ_CHUNKS);
+
+    while (start_address < address + length) {
+        if (object->pmem20.prev_read != start_address) {
+            if (read_log_chunk(object, start_address, PMEM20_LOG_READ_CHUNKS, object->pmem20.buffer + (start_address - PMEM20_LOG_START)) != 0) {
+                return -1;
+            }
+            object->pmem20.prev_read = start_address;
+            object->pmem20.last_addr = start_address + PMEM20_LOG_READ_CHUNKS - 1;
+        }
+        start_address += PMEM20_LOG_READ_CHUNKS;
+    }
+
+    return 0;
+}
+
+static int read_log_chunk(ambit_object_t *object, uint32_t address, uint32_t length, uint8_t *buffer)
+{
+    int ret = -1;
+
+    uint8_t *reply = NULL;
+    size_t replylen = 0;
+
+    uint8_t send_data[8];
+    uint32_t *_address = (uint32_t*)&send_data[0];
+    uint32_t *_length = (uint32_t*)&send_data[4];
+
+    *_address = htole32(address);
+    *_length = htole32(length);
+
+    if (libambit_protocol_command(object, ambit_command_log_read, send_data, sizeof(send_data), &reply, &replylen, 0) == 0 &&
+        replylen == length + 8) {
+        memcpy(buffer, reply + 8, length);
+        ret = 0;
+    }
+
+    libambit_protocol_free(reply);
+
+    return ret;
+}
+
+static void add_time(ambit_date_time_t *intime, int32_t offset, ambit_date_time_t *outtime)
+{
+    struct timeval timeval;
+    struct tm *tm;
+
+    to_timeval(intime, &timeval);
+
+    if (offset >= 0) {
+        timeval.tv_sec += offset / 1000;
+        timeval.tv_usec += (offset % 1000)*1000;
+    }
+    else {
+        timeval.tv_sec += offset / 1000;
+        timeval.tv_usec -= (abs(offset) % 1000)*1000;
+    }
+    if (timeval.tv_usec >= 1000000) {
+        timeval.tv_sec++;
+        timeval.tv_usec -= 1000000;
+    }
+    if(timeval.tv_usec < 0) {
+        timeval.tv_sec--;
+        timeval.tv_usec += 1000000;
+    }
+
+    tm = gmtime(&timeval.tv_sec);
+    outtime->msec = tm->tm_sec * 1000 + (timeval.tv_usec / 1000);
+    outtime->minute = tm->tm_min;
+    outtime->hour = tm->tm_hour;
+    outtime->day = tm->tm_mday;
+    outtime->month = tm->tm_mon;
+    outtime->year = tm->tm_year;
+}
+
+static int is_leap(unsigned int y) {
+    y += 1900;
+    return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0);
+}
+
+static void to_timeval(ambit_date_time_t *ambit_time, struct timeval *timeval) {
+    static const unsigned ndays[2][12] = {
+        {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
+        {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
+    };
+    timeval->tv_sec = 0;
+    timeval->tv_usec = 0;
+    int i;
+
+    for (i = 70; i < ambit_time->year; ++i) {
+        timeval->tv_sec += is_leap(i) ? 366 : 365;
+    }
+
+    for (i = 0; i < ambit_time->month; ++i) {
+        timeval->tv_sec += ndays[is_leap(ambit_time->year)][i];
+    }
+    timeval->tv_sec += ambit_time->day - 1;
+    timeval->tv_sec *= 24;
+    timeval->tv_sec += ambit_time->hour;
+    timeval->tv_sec *= 60;
+    timeval->tv_sec += ambit_time->minute;
+    timeval->tv_sec *= 60;
+    timeval->tv_sec += ambit_time->msec / 1000;
+    timeval->tv_usec = (ambit_time->msec % 1000)*1000;
+}
diff --git a/src/libambit/protocol.c b/src/libambit/protocol.c
index 50ac812..95527ba 100644
--- a/src/libambit/protocol.c
+++ b/src/libambit/protocol.c
@@ -1,3 +1,24 @@
+/*
+ * (C) Copyright 2013 Emil Ljungdahl
+ *
+ * This file is part of libambit.
+ *
+ * libambit is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * Contributors:
+ *
+ */
 #include "libambit.h"
 #include "libambit_int.h"
 #include "hidapi/hidapi.h"
@@ -11,7 +32,7 @@
 /*
  * Local definitions
  */
-#define READ_TIMEOUT       1000 // ms
+#define READ_TIMEOUT       3000 // ms
 #define READ_POLL_INTERVAL 100  // ms
 #define READ_POLL_RETRY    (READ_TIMEOUT / READ_POLL_INTERVAL)
 
@@ -125,10 +146,10 @@ int libambit_protocol_command(ambit_object_t *object, uint16_t command, uint8_t
         msg_parts = le16toh(msg->parts_seq);
 
         for (i=2; ret == 0 && i<=msg_parts; i++) {
-            if (protocol_read_packet(object, buf) == 0 && msg->MP == 0x5e) {
+            if (protocol_read_packet(object, buf) == 0 && msg->MP == 0x5e && le16toh(msg->parts_seq) < msg_parts) {
                 packet_payload_len = fmin(54, reply_data_len);
                 if (reply_data != NULL) {
-                    memcpy(&(*reply_data)[dataoffset], &buf[8], packet_payload_len);
+                    memcpy(&(*reply_data)[42+(le16toh(msg->parts_seq)-1)*54], &buf[8], packet_payload_len);
                 }
                 dataoffset += packet_payload_len;
                 reply_data_len -= packet_payload_len;

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-running/openambit.git



More information about the Pkg-running-devel mailing list