File libftdi1-1.5.12+git.0684c1b.obscpio of Package libftdi1

07070100000000000081A400000000000000000000000160917B830000024B000000000000000000000000000000000000002700000000libftdi1-1.5.12+git.0684c1b/.gitignore# Normal stuff
*.o
*.a
*.so
*.lo
*.la
*.patch
*.pc
.deps/
.libs/
.kdev4/
build/

# kdevelop
*.kdevelop.pcs
*.kdevses

# Doxygen documentation
Doxyfile
Doxyfile.xml
doc/Doxyfile
doc/html
doc/man
doc/xml

# examples
examples/baud_test
examples/bitbang
examples/bitbang2
examples/bitbang_cbus
examples/bitbang_ft2232
examples/find_all
examples/find_all_pp
examples/serial_test
examples/simple

# Backup files and stuff from patches
*.orig
*.rej
*~
.*.swp

# libftdi specific
libftdi1-config

# CMake
CMakeCache.txt
cmake_install.cmake
CMakeFiles

# Misc. binaries
*.dylib
opt

# ctags
tags
07070100000001000081A400000000000000000000000160917B8300000DC0000000000000000000000000000000000000002400000000libftdi1-1.5.12+git.0684c1b/AUTHORSMain developers:

  Intra2net AG <opensource@intra2net.com>

Contributors in alphabetical order,
see Changelog for full details:

  Adam Malinowski <amalinowski75@gmail.com>
  Alain Abbas <aa@libertech.fr>
  Alex Harford <harford@gmail.com>
  Alexander Lehmann <lehmanna@in.tum.de>
  Anders Larsen <al@alarsen.net>
  Andrei Errapart <a.errapart@trenz-electronic.de>
  Andrew John Rogers <andrew@rogerstech.co.uk>
  Arnim Läuger <arnim.laeuger@gmx.net>
  Aurelien Jarno <aurelien@aurel32.net>
  Benjamin Vanheuverzwijn <bvanheu@gmail.com>
  Chris Morgan <chmorgan@gmail.com>
  Chris Zeh <chris.w.zeh@gmail.com>
  Claudio Lanconelli <claudiolanconelli@gmail.com>
  Clifford Wolf <clifford@clifford.at>
  Dan Dedrick <dan.dedrick@gmail.com>
  Daniel Kirkham <dk2@kirkham.id.au>
  David Challis <dchallis@qsimaging.com>
  Davide Michelizza <dmichelizza@gmail.com>
  Denis Sirotkin <reg.libftdi@demitel.ru>
  Diego Elio Pettenò <flameeyes@flameeyes.com>
  Emil <emil@datel.co.uk>
  Eneas U de Queiroz <cote2004-github@yahoo.com>
  Eric Schott <els6@psu.edu>
  Eugene Hutorny <eugene@hutorny.in.ua>
  Evan Nemerson <evan@coeus-group.com>
  Evgeny Sinelnikov <sin@geoft.ru>
  Fabrice Fontaine <fontaine.fabrice@gmail.com>
  Fahrzin Hemmati <fahhem@gmail.com>
  Flynn Marquardt <ftdi@flynnux.de>
  Forest Crossman <cyrozap@gmail.com>
  Frank Dana <ferdnyc@gmail.com>
  Holger Mößinger <h.moessinger@primes.de>
  Ian Abbott <abbotti@mev.co.uk>
  Jared Boone <jared@sharebrained.com>
  Jarkko Sonninen <kasper@iki.fi>
  Jean-Daniel Merkli <jdmerkli@computerscience.ch>
  Jochen Sprickerhof <jochen@sprickerhof.de>
  Joe Zbiciak <intvnut@gmail.com>
  Jon Beniston <jon@beniston.com>
  Jordan Rupprecht <rupprecht@google.com>
  Juergen Beisert <juergen.beisert@weihenstephan.org>
  Lorenz Moesenlechner <lorenz@hcilab.org>
  Marek Vavruša <marek@vavrusa.com>
  Marius Kintel <kintel@sim.no>
  Mark Hämmerling <mail@markh.de>
  Matthias Janke <janke@physi.uni-heidelberg.de>
  Matthias Kranz <matthias@hcilab.org>
  Matthias Richter <mail.to.mr@gmx.de>
  Matthijs ten Berge <m.h.tenberge@alumnus.utwente.nl>
  Max <max@koeln.ccc.de>
  Maxwell Dreytser <admin@mdtech.us>
  Michel Zou <xantares09@hotmail.com>
  Mike Frysinger <vapier.adi@gmail.com>
  Nathael Pajani <nathael.pajani@ed3l.fr>
  Nathan Fraser <ndf@undershorts.org>
  Oleg Seiljus <oseiljus@xverve.com>
  Paul Fertser <fercerpav@gmail.com>
  Pawel Jewstafjew <pawel.jewstafjew@gmail.com>
  Peter Holik <peter@holik.at>
  Raphael Assenat <raph@8d.com>
  Richard Shaw <hobbes1069@gmail.com>
  Robby McKilliam <robby.mckilliam@myriota.com>
  Robert Cox <Robert.cox@novatechweb.com>
  Robin Haberkorn <haberkorn@metratec.com>
  Rodney Sinclair <rodney@sinclairrf.com>
  Rogier Wolff <R.E.Wolff@harddisk-recovery.nl>
  Rolf Fiedler <derRolf@gmx-topmail.de>
  Roman Lapin <lampus.lapin@gmail.com>
  Salvador Eduardo Tropea <salvador@inti.gob.ar>
  Stephan Linz <linz@li-pro.net>
  Steven Turner <steven.turner@ftdichip.com>
  Tarek Heiland <tarek@illimitable.com>
  Thilo Schulz <thilo@tjps.eu>
  Thimo Eichstaedt <abc@digithi.de>
  Thomas Fischl <fischl@fundf.net>
  Thomas Klose <thomas.klose@hiperscan.com>
  Tim Ansell <mithro@mithis.com>
  Tom Saunders <trsaunders@gmail.com>
  Tomasz Wasilczyk <twasilczyk@google.com>
  Uwe Bonnes <bon@elektron.ikp.physik.tu-darmstadt.de>
  Vladimir Yakovlev <nagos@inbox.ru>
  Wilfried Holzke <libftdi@holzke.net>
  Xiaofan Chen <xiaofanc@gmail.com>
  Yegor Yefremov <yegorslists@googlemail.com>
  Yi-Shin Li <ysli@araisrobo.com>
07070100000002000081A400000000000000000000000160917B8300001FDE000000000000000000000000000000000000002B00000000libftdi1-1.5.12+git.0684c1b/CMakeLists.txt# Project
project(libftdi1 C)
set(MAJOR_VERSION 1)
set(MINOR_VERSION 5)
set(PACKAGE libftdi1)
set(VERSION_STRING ${MAJOR_VERSION}.${MINOR_VERSION})
set(VERSION ${VERSION_STRING})
set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake)

# CMake
if("${CMAKE_BUILD_TYPE}" STREQUAL "")
   set(CMAKE_BUILD_TYPE     RelWithDebInfo)
endif("${CMAKE_BUILD_TYPE}" STREQUAL "")
set(CMAKE_COLOR_MAKEFILE ON)
cmake_minimum_required(VERSION 2.6 FATAL_ERROR)

add_definitions(-Wall)

include(CMakeOptions.txt)

# Debug build
message("-- Build type: ${CMAKE_BUILD_TYPE}")
if(${CMAKE_BUILD_TYPE} STREQUAL Debug)
   add_definitions(-DDEBUG)
endif(${CMAKE_BUILD_TYPE} STREQUAL Debug)

# find libusb
find_package ( USB1 REQUIRED )
include_directories ( ${LIBUSB_INCLUDE_DIR} )

# Find Boost
if (FTDIPP OR BUILD_TESTS)
  find_package( Boost REQUIRED )
endif()

# Set components
set(CPACK_COMPONENTS_ALL sharedlibs staticlibs headers)
set(CPACK_COMPONENT_SHAREDLIBS_DISPLAY_NAME "Shared libraries")
set(CPACK_COMPONENT_STATICLIBS_DISPLAY_NAME "Static libraries")
set(CPACK_COMPONENT_HEADERS_DISPLAY_NAME "C++ Headers")

set(CPACK_COMPONENT_SHAREDLIBS_DESCRIPTION
"Shared library for general use.")
set(CPACK_COMPONENT_STATICLIBS_DESCRIPTION
"Static library, good if you want to embed libftdi1 in your application.")
set(CPACK_COMPONENT_HEADERS_DESCRIPTION
"C/C++ header files.")

set(CPACK_COMPONENT_SHAREDLIBS_GROUP "Development")
set(CPACK_COMPONENT_STATICLIBS_GROUP "Development")
set(CPACK_COMPONENT_HEADERS_GROUP    "Development")

# guess LIB_SUFFIX, don't take debian multiarch into account 
if ( NOT DEFINED LIB_SUFFIX )
  if( CMAKE_SYSTEM_NAME MATCHES "Linux"
      AND NOT CMAKE_CROSSCOMPILING
      AND NOT EXISTS "/etc/debian_version"
      AND NOT EXISTS "/etc/arch-release" )
    if ( "${CMAKE_SIZEOF_VOID_P}" EQUAL "8" )
      set ( LIB_SUFFIX 64 )
    endif ()
  endif ()
endif ()

if(NOT APPLE)
  if(CMAKE_SIZEOF_VOID_P EQUAL 4)
      SET(PACK_ARCH "")
    else(CMAKE_SIZEOF_VOID_P EQUAL 8)
      SET(PACK_ARCH .x86_64)
  endif(CMAKE_SIZEOF_VOID_P EQUAL 4)
else(NOT APPLE)
  SET(PACK_ARCH "")
endif(NOT APPLE)

# Package information
set(CPACK_PACKAGE_VERSION              ${VERSION_STRING})
set(CPACK_PACKAGE_CONTACT              "Intra2net AG <libftdi@developer.intra2net.com>")
set(CPACK_PACKAGE_DESCRIPTION          "libftdi1 library.")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY  ${CPACK_PACKAGE_DESCRIPTION}
                                       )
# Package settings
if ( UNIX )
  set(CPACK_GENERATOR                    "DEB;RPM")
  set(CPACK_CMAKE_GENERATOR              "Unix Makefiles")
  set(CPACK_PACKAGE_NAME                 ${PROJECT_NAME})
  set(CPACK_PACKAGE_FILE_NAME            ${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}${PACK_ARCH})
endif ()

if ( WIN32 )
  set ( CPACK_GENERATOR                    "NSIS" )
  set ( CPACK_CMAKE_GENERATOR              "MinGW Makefiles" )
  set ( CPACK_PACKAGE_NAME                 "${PROJECT_NAME}" )
  set ( CPACK_PACKAGE_VENDOR               "" )
  set ( CPACK_PACKAGE_INSTALL_DIRECTORY    "libftdi1" )
  set ( CPACK_PACKAGE_FILE_NAME            "${PROJECT_NAME}-${VERSION_STRING}-win32")
  set ( CPACK_NSIS_DISPLAY_NAME            "libftdi1" )
  set ( CPACK_NSIS_MODIFY_PATH             ON )
endif ()

set(CPACK_RESOURCE_FILE_LICENSE        ${CMAKE_SOURCE_DIR}/LICENSE)

set(CPACK_SOURCE_GENERATOR             TGZ)
set(CPACK_SOURCE_IGNORE_FILES          "\\\\.git;~$;build/")
set(CPACK_SOURCE_PACKAGE_FILE_NAME     ${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION})

# Subdirectories
if ( UNIX )
  set ( CPACK_SET_DESTDIR ON )
endif ()

# "make dist" target
set(ARCHIVE_NAME ${CMAKE_PROJECT_NAME}-${VERSION_STRING})
add_custom_target(dist
    COMMAND git archive --prefix=${ARCHIVE_NAME}/ HEAD
            | bzip2 > ${CMAKE_BINARY_DIR}/${ARCHIVE_NAME}.tar.bz2
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})

if ( DOCUMENTATION )
   find_package ( Doxygen REQUIRED)

   # Copy doxy.config.in
   set(top_srcdir ${CMAKE_SOURCE_DIR})
   configure_file(${CMAKE_SOURCE_DIR}/doc/Doxyfile.in ${CMAKE_BINARY_DIR}/Doxyfile )
   configure_file(${CMAKE_SOURCE_DIR}/doc/Doxyfile.xml.in ${CMAKE_BINARY_DIR}/Doxyfile.xml )

   # Run doxygen
   add_custom_command(
    OUTPUT ${CMAKE_BINARY_DIR}/doc/html/index.html
    COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/doc
    COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_BINARY_DIR}/Doxyfile
    DEPENDS ${c_headers};${c_sources};${cpp_sources};${cpp_headers}
   )

   add_custom_target(docs ALL DEPENDS ${CMAKE_BINARY_DIR}/doc/html/index.html)
endif ()

add_subdirectory(src)
if ( FTDIPP )
  project(libftdi1 C CXX)
  add_subdirectory(ftdipp)
endif ()
if ( PYTHON_BINDINGS )
add_subdirectory(python)
endif ()
if ( FTDI_EEPROM )
  add_subdirectory(ftdi_eeprom)
endif ()
if ( EXAMPLES )
  add_subdirectory(examples)
endif ()
add_subdirectory(packages)
if ( BUILD_TESTS )
  project(libftdi1 C CXX)
  add_subdirectory(test)
endif ()

# PkgConfig
set(prefix      ${CMAKE_INSTALL_PREFIX})
set(exec_prefix ${CMAKE_INSTALL_PREFIX}/bin)
set(includedir  ${CMAKE_INSTALL_PREFIX}/include/${PROJECT_NAME})

if(${UNIX})
   set(libdir      ${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX})
endif(${UNIX})
if(${WIN32})
   set(libdir      ${CMAKE_INSTALL_PREFIX}/bin)
endif(${WIN32})

configure_file(${CMAKE_SOURCE_DIR}/libftdi1.pc.in ${CMAKE_BINARY_DIR}/libftdi1.pc @ONLY)
configure_file(${CMAKE_SOURCE_DIR}/libftdipp1.pc.in ${CMAKE_BINARY_DIR}/libftdipp1.pc @ONLY)
install(FILES ${CMAKE_BINARY_DIR}/libftdi1.pc ${CMAKE_BINARY_DIR}/libftdipp1.pc
        DESTINATION lib${LIB_SUFFIX}/pkgconfig)

if (UNIX OR MINGW)
  configure_file ( libftdi1-config.in ${CMAKE_CURRENT_BINARY_DIR}/libftdi1-config @ONLY )
  install ( PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/libftdi1-config
            DESTINATION bin )
endif ()

# config script install path
if ( NOT DEFINED LIBFTDI_CMAKE_CONFIG_DIR )
  set ( LIBFTDI_CMAKE_CONFIG_DIR lib${LIB_SUFFIX}/cmake/libftdi1 )
endif ()

set ( LIBFTDI_INCLUDE_DIR ${includedir} )
set ( LIBFTDI_INCLUDE_DIRS ${LIBFTDI_INCLUDE_DIR} )
set ( LIBFTDI_LIBRARY ftdi1 )
set ( LIBFTDI_LIBRARIES ${LIBFTDI_LIBRARY} )
list ( APPEND LIBFTDI_LIBRARIES ${LIBUSB_LIBRARIES} )
set ( LIBFTDI_STATIC_LIBRARY ftdi1.a )
set ( LIBFTDI_STATIC_LIBRARIES ${LIBFTDI_STATIC_LIBRARY} )
list ( APPEND LIBFTDI_STATIC_LIBRARIES ${LIBUSB_LIBRARIES} )
if ( FTDIPP )
  set ( LIBFTDIPP_LIBRARY ftdipp1 )
  set ( LIBFTDIPP_LIBRARIES ${LIBFTDIPP_LIBRARY} )
  list ( APPEND LIBFTDIPP_LIBRARIES ${LIBUSB_LIBRARIES} )
endif ()
set ( LIBFTDI_LIBRARY_DIRS ${libdir} )
set ( LIBFTDI_ROOT_DIR ${prefix} )
set ( LIBFTDI_VERSION_STRING ${VERSION_STRING} )
set ( LIBFTDI_VERSION_MAJOR ${MAJOR_VERSION} )
set ( LIBFTDI_VERSION_MINOR ${MINOR_VERSION} )

set ( LIBFTDI_USE_FILE ${CMAKE_INSTALL_PREFIX}/${LIBFTDI_CMAKE_CONFIG_DIR}/UseLibFTDI1.cmake )

if(CMAKE_VERSION VERSION_LESS 2.8.8) 
  configure_file ( cmake/LibFTDI1Config.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/LibFTDI1Config.cmake @ONLY )
  configure_file ( cmake/LibFTDI1ConfigVersion.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/LibFTDI1ConfigVersion.cmake @ONLY )
else ()
  include(CMakePackageConfigHelpers)

  configure_package_config_file (
    cmake/LibFTDI1Config.cmake.in
    ${CMAKE_CURRENT_BINARY_DIR}/LibFTDI1Config.cmake
    INSTALL_DESTINATION ${LIBFTDI_CMAKE_CONFIG_DIR}
    PATH_VARS
      LIBFTDI_USE_FILE
      LIBFTDI_ROOT_DIR
      LIBFTDI_INCLUDE_DIR
      LIBFTDI_INCLUDE_DIRS
      LIBFTDI_LIBRARY_DIRS
    NO_CHECK_REQUIRED_COMPONENTS_MACRO
  )
  write_basic_package_version_file (
    LibFTDI1ConfigVersion.cmake 
    VERSION ${LIBFTDI_VERSION_STRING} 
    COMPATIBILITY AnyNewerVersion
  )
endif ()


install ( FILES 
            ${CMAKE_CURRENT_BINARY_DIR}/LibFTDI1Config.cmake
            ${CMAKE_CURRENT_BINARY_DIR}/LibFTDI1ConfigVersion.cmake
            cmake/UseLibFTDI1.cmake

          DESTINATION ${LIBFTDI_CMAKE_CONFIG_DIR}
        )

include(CPack)

message (STATUS "Summary of build options:

  Build static libs: ${STATICLIBS}
  Build C++ bindings: ${FTDIPP}
  Build Python bindings: ${PYTHON_BINDINGS}
  Build ftdi_eeprom: ${FTDI_EEPROM}
  Build examples: ${EXAMPLES}
  Build tests: ${BUILD_TESTS}
  Build API documentation: ${DOCUMENTATION}
")
07070100000003000081A400000000000000000000000160917B83000001E4000000000000000000000000000000000000002D00000000libftdi1-1.5.12+git.0684c1b/CMakeOptions.txtoption ( STATICLIBS "Build static libraries" ON )
option ( BUILD_TESTS "Build unit tests with Boost Unit Test framework" OFF )
option ( DOCUMENTATION "Generate API documentation with Doxygen" OFF )
option ( EXAMPLES "Build example programs" ON )
option ( FTDIPP "Build C++ binding library libftdi1++" OFF )
option ( FTDI_EEPROM "Build ftdi_eeprom" ON )
option ( PYTHON_BINDINGS "Build python bindings via swig" OFF )
option ( LINK_PYTHON_LIBRARY "Link against python libraries" OFF )
07070100000004000081A400000000000000000000000160917B830000052F000000000000000000000000000000000000003200000000libftdi1-1.5.12+git.0684c1b/COPYING-CMAKE-SCRIPTSRedistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products 
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
07070100000005000081A400000000000000000000000160917B8300004643000000000000000000000000000000000000002800000000libftdi1-1.5.12+git.0684c1b/COPYING.GPL		    GNU GENERAL PUBLIC LICENSE
		       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.)  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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  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.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

			    NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.

		     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
convey 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 2 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, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This 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.
07070100000006000081A400000000000000000000000160917B8300006327000000000000000000000000000000000000002800000000libftdi1-1.5.12+git.0684c1b/COPYING.LIB                  GNU LIBRARY GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1991 Free Software Foundation, Inc.
 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

[This is the first released version of the library GPL.  It is
 numbered 2 because it goes with version 2 of the ordinary GPL.]

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.

  This license, the Library General Public License, applies to some
specially designated Free Software Foundation software, and to any
other libraries whose authors decide to use it.  You can use it for
your libraries, 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if
you distribute copies of the library, or if you modify it.

  For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you.  You must make sure that they, too, receive or can get the source
code.  If you link a program with the library, you must provide
complete object files to the recipients so that they can relink them
with the library, after making changes to the library and recompiling
it.  And you must show them these terms so they know their rights.

  Our method of protecting your rights has two steps: (1) copyright
the library, and (2) offer you this license which gives you legal
permission to copy, distribute and/or modify the library.

  Also, for each distributor's protection, we want to make certain
that everyone understands that there is no warranty for this free
library.  If the library is modified by someone else and passed on, we
want its recipients to know that what they have is not the original
version, so that any problems introduced by others will not reflect on
the original authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that companies distributing free
software will individually obtain patent licenses, thus in effect
transforming the program into proprietary software.  To prevent this,
we have made it clear that any patent must be licensed for everyone's
free use or not licensed at all.

  Most GNU software, including some libraries, is covered by the ordinary
GNU General Public License, which was designed for utility programs.  This
license, the GNU Library General Public License, applies to certain
designated libraries.  This license is quite different from the ordinary
one; be sure to read it in full, and don't assume that anything in it is
the same as in the ordinary license.

  The reason we have a separate public license for some libraries is that
they blur the distinction we usually make between modifying or adding to a
program and simply using it.  Linking a program with a library, without
changing the library, is in some sense simply using the library, and is
analogous to running a utility program or application program.  However, in
a textual and legal sense, the linked executable is a combined work, a
derivative of the original library, and the ordinary General Public License
treats it as such.

  Because of this blurred distinction, using the ordinary General
Public License for libraries did not effectively promote software
sharing, because most developers did not use the libraries.  We
concluded that weaker conditions might promote sharing better.

  However, unrestricted linking of non-free programs would deprive the
users of those programs of all benefit from the free status of the
libraries themselves.  This Library General Public License is intended to
permit developers of non-free programs to use free libraries, while
preserving your freedom as a user of such programs to change the free
libraries that are incorporated in them.  (We have not seen how to achieve
this as regards changes in header files, but we have achieved it as regards
changes in the actual functions of the Library.)  The hope is that this
will lead to faster development of free libraries.

  The precise terms and conditions for copying, distribution and
modification follow.  Pay close attention to the difference between a
"work based on the library" and a "work that uses the library".  The
former contains code derived from the library, while the latter only
works together with the library.

  Note that it is possible for a library to be covered by the ordinary
General Public License rather than by this special one.

                  GNU LIBRARY GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License Agreement applies to any software library which
contains a notice placed by the copyright holder or other authorized
party saying it may be distributed under the terms of this Library
General Public License (also called "this License").  Each licensee is
addressed as "you".

  A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.

  The "Library", below, refers to any such software library or work
which has been distributed under these terms.  A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language.  (Hereinafter, translation is
included without limitation in the term "modification".)

  "Source code" for a work means the preferred form of the work for
making modifications to it.  For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.

  Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it).  Whether that is true depends on what the Library does
and what the program that uses the Library does.
  
  1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.

  You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.

  2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) The modified work must itself be a software library.

    b) You must cause the files modified to carry prominent notices
    stating that you changed the files and the date of any change.

    c) You must cause the whole of the work to be licensed at no
    charge to all third parties under the terms of this License.

    d) If a facility in the modified Library refers to a function or a
    table of data to be supplied by an application program that uses
    the facility, other than as an argument passed when the facility
    is invoked, then you must make a good faith effort to ensure that,
    in the event an application does not supply such function or
    table, the facility still operates, and performs whatever part of
    its purpose remains meaningful.

    (For example, a function in a library to compute square roots has
    a purpose that is entirely well-defined independent of the
    application.  Therefore, Subsection 2d requires that any
    application-supplied function or table used by this function must
    be optional: if the application does not supply it, the square
    root function must still compute square roots.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.

In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library.  To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License.  (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.)  Do not make any other change in
these notices.

  Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.

  This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.

  4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.

  If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.

  5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library".  Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.

  However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library".  The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.

  When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library.  The
threshold for this to be true is not precisely defined by law.

  If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work.  (Executables containing this object code plus portions of the
Library will still fall under Section 6.)

  Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.

  6. As an exception to the Sections above, you may also compile or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.

  You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License.  You must supply a copy of this License.  If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License.  Also, you must do one
of these things:

    a) Accompany the work with the complete corresponding
    machine-readable source code for the Library including whatever
    changes were used in the work (which must be distributed under
    Sections 1 and 2 above); and, if the work is an executable linked
    with the Library, with the complete machine-readable "work that
    uses the Library", as object code and/or source code, so that the
    user can modify the Library and then relink to produce a modified
    executable containing the modified Library.  (It is understood
    that the user who changes the contents of definitions files in the
    Library will not necessarily be able to recompile the application
    to use the modified definitions.)

    b) Accompany the work with a written offer, valid for at
    least three years, to give the same user the materials
    specified in Subsection 6a, above, for a charge no more
    than the cost of performing this distribution.

    c) If distribution of the work is made by offering access to copy
    from a designated place, offer equivalent access to copy the above
    specified materials from the same place.

    d) Verify that the user has already received a copy of these
    materials or that you have already sent this user a copy.

  For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it.  However, as a special exception,
the source code distributed need not include anything that is normally
distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.

  It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system.  Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.

  7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:

    a) Accompany the combined library with a copy of the same work
    based on the Library, uncombined with any other library
    facilities.  This must be distributed under the terms of the
    Sections above.

    b) Give prominent notice with the combined library of the fact
    that part of it is a work based on the Library, and explaining
    where to find the accompanying uncombined form of the same work.

  8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License.  Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License.  However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.

  9. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Library or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.

  10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all.  For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.

If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded.  In such case, this License incorporates the limitation as if
written in the body of this License.

  13. The Free Software Foundation may publish revised and/or new
versions of the Library 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 Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation.  If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.

  14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission.  For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this.  Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.

                            NO WARRANTY

  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.

                     END OF TERMS AND CONDITIONS

           How to Apply These Terms to Your New Libraries

  If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change.  You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).

  To apply these terms, attach the following notices to the library.  It is
safest to attach them to the start of each source file to most effectively
convey 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 library's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Also add information on how to contact you by electronic and paper mail.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the
  library `Frob' (a library for tweaking knobs) written by James Random Hacker.

  <signature of Ty Coon>, 1 April 1990
  Ty Coon, President of Vice

That's all there is to it!
07070100000007000081A400000000000000000000000160917B8300003158000000000000000000000000000000000000002600000000libftdi1-1.5.12+git.0684c1b/ChangeLogNew in 1.5 - 2020-07-07
-----------------------
* Implement tc[io]flush methods & deprecate broken purge_buffers methods

  Please check your code for ftdi_usb_purge_rx_buffer(),
  ftdi_usb_purge_tx_buffer() and ftdi_usb_purge_buffers()
  and migrate to the new ftdi_tc[io]flush() methods.

  Old code will continue to function, but you'll get
  a deprecation warning during compilation.

* Add program to test buffer flush (purge) functionality
* Add kernel driver auto attach/detach.
  See new AUTO_DETACH_REATACH_SIO_MODULE option
* Add ftdi_setflowctrl_xonxoff()
* ftdi_eeprom / eeprom handling:
  * Unify handling of all boolean eeprom flags
  * Add device release number support
  * Add channel_a_driver support for type xxR chips
  * Add support for group0 drive levels on x232H chips
  * Fix handling of high_current_drive parameter
  * Fix inverted handling of VCP driver field for TYPE_R chips
  * New --verbose option for eeprom decode operation
* Add example code for async mode
* Add SPDX license identifiers to the core library & ftdi_eeprom
* Various python SWIG wrapper improvements
* Various cmake file improvements
* Fix small bugs in error code paths

New in 1.4 - 2017-08-07
-----------------------
* New ftdi_usb_open_bus_addr() open function
* Use BM/R series baud rate computation for FT230X
* ftdi_get_error_string() now returns const char*
* C++ API: Ability to open devices with empty descriptor strings
* C++ API: Fix enumerations for buffer purge and modem controls
* small build fixes and improvements in the python examples
* ftdi_eeprom / eeprom handling:
  * New API function: ftdi_eeprom_get_strings()
  * Fix USE_SERIAL handling for 230X type chips
  * Make ftdi_read_eeprom_location() endianness independent
  * Fix flashing of FT245R

New in 1.3 - 2016-05-20
-----------------------
* Added ftdi_usb_get_strings2() to prevent automatic device close (Fahrzin Hemmati)
* Added ftdi_transfer_data_cancel() for cancellation of a submitted transfer,
  avoided resubmittion of a canceled transfer in the callbacks,
  replaced calls to libusb_handle_events with
  libusb_handle_events_timeout_completed (Eugene Hutorny)
* ftdi_eeprom / eeprom handling:
  * Add support for arbitrary user data (Salvador Eduardo Tropea)
  * Add --build-eeprom support (Salvador Eduardo Tropea)
  * Fix use_usb_version config file option (Thilo Schulz)
  * Ability to include other config files in EEPROM config file (Thilo Schulz)
  * Add external oscillator enable bit (Raphael Assenat)
  * Support channel configuration (Stephan Linz)
  * Added --device option to ftdi_eeprom to specify FTDI device (Robin Haberkorn)
  * Fixed EEPROM user-area space checks for FT232R and FT245R chips (Robin Haberkorn)
* Various improvements to CBUS handling, including the EEPROM (Robin Haberkorn)
* swig wrapper: Fix handling of binary strings in ftdi_write_data()
  for python 3 (xantares09)
* cbus python example code (Rodney Sinclair)
* ftdi_stream: fix timeout setting (Ларионов Даниил)
* Fixed typo in CBUS defines: CBUSG_DRIVE1 -> CBUSH_DRIVE1

New in 1.2 - 2014-11-21
-----------------------
* Support for FT230X devices (Uwe Bonnes)
* ftdi_usb_get_strings(): Don't try to open an already open device (Denis Sirotkin)
* Support for finding devices bricked by the Windows driver (Forest Crossman)
* cmake build system: New LibFTDI1ConfigVersion.cmake file (xantares09)
* Fix a typo in the MPSSE command CLK_BYTES_OR_LOW (Benjamin Vanheuverzwijn)
* Minor fixes for MSVC++ (Andrei Errapart)
* Various small code improvements (Florian Preinstorfer, Jochen Sprickerhof, xantares09)

New in 1.1 - 2014-02-05
-----------------------
* Fix FT232H eeprom suspend pulldown setting (Davide Michelizza)
* Fix FT232H eeprom user area size (Davide Michelizza)
* Improved mingw build (Paul Fertser and Michel Zou)
* C++ wrapper: Get/set functions for USB timeouts (Jochen Sprickerhof)
* Partial support for FT230X (Nathael Pajani)
* New API function: ftdi_eeprom_set_strings() (Nathael Pajani)
* Prevent possible segfault in ftdi_eeprom_decode() (Nathael Pajani)
* Save device release number in eeprom (Jarkko Sonninen)
* Fix "self powered" eeprom flag (Jarkko Sonninen)
* Improved python wrapper (Michel Zou)
* Many buildsystem improvements (Michel Zou and Mike Frysinger)
* See the git history for more changes and fixes

New in 1.0 - 2013-01-29
-----------------------
* Ported to libusb 1.x (initial work by Jie Zhang)
* Many eeprom handling improvements (Uwe Bonnes, Anders Larsen)
* Renamed pkconfig, library .so etc. files to "libftdi1" (Intra2net)
* ftdi_eeprom is part of libftdi now (Intra2net)

* New baudrate calculation code + unit tests (Uwe Bonnes and Intra2net)
* Improved python bindings including python3 support (Michel Zou)
* Switched completely to cmake build system (Intra2net)
* cmake: Easy libftdi discovery via find_package() (Michel Zou)
* eeprom handling now done via get()/set() functions (Uwe Bonnes)
* C++ wrapper: Fixed use-after-free in List::find_all() (Intra2net)
* Documentation updates (Xiaofan Chen)
* See the git history for more changes and fixes

New in 0.20 - 2012-03-19
------------------------
* Support for FT232H (Uwe Bonnes)
* Fixed install location of header files (Uwe Bonnes and Intra2net)
* Backported serial_test tool from libftdi 1.x (Uwe Bonnes)

New in 0.19 - 2011-05-23
------------------------
* Make kernel driver detach configurable (Thomas Klose)
* Correct ftdi_poll_modem_status() result code (Tom Saunders)
* cmake build system improvements (Evgeny Sinelnikov)
* Fix uninitialized memory access in async mode (Intra2net)
* Support for FT232R eeprom features (Hermann Kraus)
* Fix size returned by ftdi_read_data (Hermann Kraus)
* C++ wrapper: Fix infinite recursion in set_bitmode (Intra2net)
* Improvements to the python wrapper (Flynn Marquardt and Chris Zeh)

New in 0.18 - 2010-06-25
------------------------
* Add ftdi_eeprom_free() to free allocated memory in eeprom (Wilfried Holzke)
* More generic error message for the FTDI kernel driver (Intra2net)
* Honor CPPFLAGS in python wrapper build (Alexander Lehmann)
* cmake: Fix package creation on 32-bit machines (Uwe Bonnes)
* Fix swig argument constraints (Intra2net)
* Don't segfault if device is closed or ftdi context is invalid (Intra2net)
* Ability to disable build of examples / documentation (Mike Frysinger and Intra2net)
* Fix typo in python wrapper build (Mike Frysinger)
* Autoconf build system improvements (Mike Frysinger)

New in 0.17 - 2009-12-19
------------------------
* C++ wrapper: Reduced code duplication and small other changes (Intra2net)
* Deprecated old ftdi_enable_bitbang() function (Intra2net)
* New ftdi_usb_open_desc_index() function (Intra2net)
* Added baud rate test example code (Intra2net)
* New serial input example code (Jim Paris)
* Fix modem status byte filtering for USB high speed chips (Intra2net and Jim Paris)
* Add bitmode for synchronous fifo in FT2232H (Uwe Bonnes)
* Fix usb_set_configuration() call on Windows 64 (NIL)
* Fix usb index in ftdi_convert_baudrate() for FT2232H/FT4232H chips (Thimo Eichstaedt)
* Set initial baudrate on correct interface instead of always the first one (Thimo Eichstaedt)
* Call usb_set_configuration() on Windows only (Uwe Bonnes)
* 64 bit and other buildsystem fixes (Uwe Bonnes)
* Don't build --with-async-mode w/ libusb-compat-0.1 (Clifford Wolf)
* Functions for read/write of a single eeprom location (Oleg Seiljus)
* Protect against double close of usb device (Nathan Fraser)
* Fix out-of-tree-build in python wrapper (Aurelien Jarno)
* Autoconf and doxygen cleanup (Jim Paris)

New in 0.16 - 2009-05-08
------------------------
* C++ wrapper: Reopen the device after calling get_strings() in Context::open() (Marek Vavruša and Intra2net)
* C++ wrapper: Fixed an inheritance problem (Marek Vavruša and Intra2net)
* C++ wrapper: Relicensed under GPLv2 + linking exception (Marek Vavruša and Intra2net)
* Support for FT2232H and FT4232H (David Challis, Alex Harford and Intra2net)
* Support for mingw cross compile (Uwe Bonnes)
* Python bindings and minor autoconf cleanup (Tarek Heiland)
* Code cleanup in various places (Intra2net)
* Fixed ftdi_read_chipid in some cases (Matthias Richter)
* eeprom decode function and small cleanups (Marius Kintel)
* cmake system improvements (Marius Kintel and Intra2net)
* Fix compilation in -ansi -pedantic mode (Matthias Janke)

New in 0.15 - 2008-12-19
------------------------
* Full C++ wrapper. Needs boost (Marek Vavruša and Intra2net)
* cmake rules (Marek Vavruša)

New in 0.14 - 2008-09-09
------------------------
* Fixed flow control code for second FT2232 interface (Marek Vavruša)
* Ability to set flow control via one USB call (Marek Vavruša)
* 64 bit build support in the RPM spec file (Uwe Bonnes)
* Small fix to the RPM spec file (Uwe Bonnes)
* Ability to set RS232 break type (Intra2net)
* Grouped flow control and modem status code together (Intra2net)

New in 0.13 - 2008-06-13
------------------------
* Build .spec file via configure.in (Intra2net)
* Fixed "libusb-config --cflags" call (Mike Frysinger and Intra2net)
* Always set usb configuration (Mike Frysinger and Intra2net)
* Improved libusb-win32 support (Mike Frysinger)

New in 0.12 - 2008-04-16
------------------------
* Fix build of documentation for "out of tree" builds
* Fix USB config descriptor in the eeprom (Juergen Beisert)
* Ability to purge RX/TX buffers separately (Arnim Läuger)
* Setting of event and error character (Arnim Läuger)
* Poll modem status function (Arnim Läuger and Intra2net)
* Updated documentation and created AUTHORS file

New in 0.11 - 2008-03-01
------------------------
* Vala bindings helper functions (ftdi_new, ftdi_free, ftdi_list_free2) (Even Nermerson)
* Support for different EEPROM sizes (Andrew John Rogers, andrew@rogerstech.co.uk)
* Async write support. Linux only and no error handling.
  You have to enable it via --with-async-mode.
* Detection of R-type chips
* FTDIChip-ID read support (Peter Holik)

New in 0.10 - 2007-05-08
------------------------
* Examples for libftdi_usb_find_all and CBUS mode
* Fixed ftdi_list_free
* Small cosmetic changes

New in 0.9 - 2007-02-09
-----------------------
* Fixed build without doxygen
* Correct .so file library version

New in 0.8 - 2007-02-08
-----------------------
* Complete doxygen documentation and examples
* Extended FT2232C bitbang mode example code (Max)
* ftdi_usb_get_strings function to get device ID strings (Matthijs ten Berge)
* Fix ftdi_read_pins on PowerPC systems (Thomas Fischl)
* Automatically detach ftdi_sio kernel driver (Uwe Bonnes and Intra2net)
* Configurable flow control (Lorenz Moesenlechner and Matthias Kranz)

New in 0.7 - 2005-10-11
-----------------------
* Baudrate calculation fix for FT2232C (Steven Turner/FTDI)
* Find all devices by vendor/product id (Tim Ansell and Intra2net)
* Documentation updates (Tim Ansell)

New in 0.6 - 2005-04-24
-----------------------
* Set library version on .so file again
* Configurable serial line parameters (Alain Abbas)
* Improved filtering of status bytes (Evgeny Sinelnikov)
* Extended FT2232C support (Uwe Bonnes)
* Small improvement to the baudrate calculation code (Emil)
* Error handling cleanup (Rogier Wolff and Intra2net)

New in 0.5 - 2004-09-24
-----------------------
* New autoconf suite
* pkgconfig support
* Status byte filtering now works for "big" readbuffer sizes (Thanks Evgeny!)
* Open device by description and/or serial (Evgeny Sinelnikov)
* Improved error handling (Evgeny Sinelnikov)

New in 0.4 - 2004-06-15
-----------------------
* Fixed filtering of status bytes (Readbuffer size is now 64 bytes)
* FT2232C support (Steven Turner/FTDI)
* New baudrate calculation code (Ian Abbott)
* Automatic detection of chip type
* Important: ftdi_write_data now returns the bytes written
* Fixed defaults values in ftdi_eeprom_initdefaults (Jean-Daniel Merkli)
* Reset internal readbuffer offsets for reset()/purge_buffers()
* Small typo fixes (Mark Haemmerling)

New in 0.3 - 2004-03-25
-----------------------
* Improved read function which takes arbitrary input buffer sizes
  Attention: Call ftdi_deinit() on exit to free used memory
* Vastly increased read/write performance (configurable chunksize, default is 4096)
* Set/get latency timer function working (Thanks Steven Turner/FTDI)
* Increased library version because the changes require recompilation

New in 0.2 - 2004-01-03
-----------------------
* EEPROM build fix by Daniel Kirkham (Melbourne, Australia)
* Implemented basic ftdi_read_data() function
* EEPROM write fixes

New in 0.1 - 2003-06-10
-----------------------
* First public release
07070100000008000081A400000000000000000000000160917B830000044D000000000000000000000000000000000000002400000000libftdi1-1.5.12+git.0684c1b/LICENSEThe C library "libftdi1" is distributed under the
GNU Library General Public License version 2.

A copy of the GNU Library General Public License (LGPL) is included
in this distribution, in the file COPYING.LIB.

----------------------------------------------------------------------

The C++ wrapper "ftdipp1" is distributed under the GNU General
Public License version 2 (with a special exception described below).

A copy of the GNU General Public License (GPL) is included
in this distribution, in the file COPYING.GPL.

As a special exception, if other files instantiate templates or use macros
or inline functions from this file, or you compile this file and link it
with other works to produce a work based on this file, this file
does not by itself cause the resulting work to be covered
by the GNU General Public License.

However the source code for this file must still be made available
in accordance with section (3) of the GNU General Public License.

This exception does not invalidate any other reasons why a work based
on this file might be covered by the GNU General Public License.
07070100000009000081A400000000000000000000000160917B8300000880000000000000000000000000000000000000002300000000libftdi1-1.5.12+git.0684c1b/README--------------------------------------------------------------------
libftdi version 1.5
--------------------------------------------------------------------

libftdi - A library (using libusb) to talk to FTDI's UART/FIFO chips
including the popular bitbang mode.

The following chips are supported:
* FT230X
- FT4232H / FT2232H
- FT232R  / FT245R
- FT2232L / FT2232D / FT2232C
- FT232BM / FT245BM (and the BL/BQ variants)
- FT8U232AM / FT8U245AM

libftdi requires libusb 1.x.

The AUTHORS file contains a list of all the people
that made libftdi possible what it is today.

Changes
-------
* Implement tc[io]flush methods & deprecate broken purge_buffers methods

  Please check your code for ftdi_usb_purge_rx_buffer(),
  ftdi_usb_purge_tx_buffer() and ftdi_usb_purge_buffers()
  and migrate to the new ftdi_tc[io]flush() methods.

  Old code will continue to function, but you'll get
  a deprecation warning during compilation.

* Add program to test buffer flush (purge) functionality
* Add kernel driver auto attach/detach.
  See new AUTO_DETACH_REATACH_SIO_MODULE option
* Add ftdi_setflowctrl_xonxoff()
* ftdi_eeprom / eeprom handling:
  * Unify handling of all boolean eeprom flags
  * Add device release number support
  * Add channel_a_driver support for type xxR chips
  * Add support for group0 drive levels on x232H chips
  * Fix handling of high_current_drive parameter
  * Fix inverted handling of VCP driver field for TYPE_R chips
  * New --verbose option for eeprom decode operation
* Add example code for async mode
* Add SPDX license identifiers to the core library & ftdi_eeprom
* Various python SWIG wrapper improvements
* Various cmake file improvements
* Fix small bugs in error code paths

You'll find the newest version of libftdi at:
https://www.intra2net.com/en/developer/libftdi


Quick start
-----------
mkdir build
cd build

cmake -DCMAKE_INSTALL_PREFIX="/usr" ../
make
make install

More verbose build instructions are in "README.build"

--------------------------------------------------------------------
www.intra2net.com                             2003-2020 Intra2net AG
--------------------------------------------------------------------
0707010000000A000081A400000000000000000000000160917B8300000EA0000000000000000000000000000000000000002900000000libftdi1-1.5.12+git.0684c1b/README.buildHere is a short tutorial on how to build libftdi git under
Ubuntu 12.10, But it is similar on other Linux distros.

1) Install the build tools
sudo apt-get install build-essential (yum install make automake gcc gcc-c++ kernel-devel)
sudo apt-get install git-core (yum install git)
sudo apt-get install cmake (yum install cmake)
sudo apt-get install doxygen (for building documentations) (yum install doxygen)

2) Install dependencies
sudo apt-get install libusb-1.0-devel (yum install libusb-devel)
(if the system comes with older version like 1.0.8 or
earlier, it is recommended you build libusbx-1.0.14 or later).

sudo apt-get install libconfuse-dev (for ftdi-eeprom) (yum install libconfuse-devel)
sudo apt-get install swig python-dev (for python bindings) (yum install swig python-devel)
sudo apt-get install libboost-all-dev (for C++ binding and unit test) (yum install boost-devel)

3) Clone the git repository
mkdir libftdi
cd libftdi
git clone git://developer.intra2net.com/libftdi

If you are building the release tar ball, just extract the source
tar ball.

4) Build the git source and install
cd libftdi
mkdir build
cd build
cmake  -DCMAKE_INSTALL_PREFIX="/usr" ../
make
sudo make install

5) carry out some tests
cd examples

mcuee@Ubuntu1210VM:~/Desktop/build/libftdi/libftdi/build/examples$
./find_all_pp  -v 0x0403 -p 0x6001
Found devices ( VID: 0x403, PID: 0x6001 )
------------------------------------------------
FTDI (0x8730800): ftdi, usb serial converter, ftDEH51S (Open OK)
FTDI (0x8730918): FTDI, FT232R USB UART, A8007Ub5 (Open OK)

mcuee@Ubuntu1210VM:~/Desktop/build/libftdi/libftdi/build/examples$ ./eeprom
2 FTDI devices found: Only Readout on EEPROM done. Use
VID/PID/desc/serial to select device
Decoded values of device 1:
Chip type 1 ftdi_eeprom_size: 128
0x000: 00 00 03 04 01 60 00 04  a0 16 08 00 10 01 94 0a .....`.. ........
0x010: 9e 2a c8 12 0a 03 66 00  74 00 64 00 69 00 2a 03 .*....f. t.d.i.*.
0x020: 75 00 73 00 62 00 20 00  73 00 65 00 72 00 69 00 u.s.b. . s.e.r.i.
0x030: 61 00 6c 00 20 00 63 00  6f 00 6e 00 76 00 65 00 a.l. .c. o.n.v.e.
0x040: 72 00 74 00 65 00 72 00  12 03 66 00 74 00 44 00 r.t.e.r. ..f.t.D.
0x050: 45 00 48 00 35 00 31 00  53 00 02 03 00 00 00 00 E.H.5.1. S.......
0x060: 00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00 ........ ........
0x070: 00 00 00 00 00 00 00 00  00 00 00 00 01 00 16 02 ........ ........
VID:     0x0403
PID:     0x6001
Release: 0x0400
Bus Powered:  44 mA USB Remote Wake Up
Manufacturer: ftdi
Product:      usb serial converter
Serial:       ftDEH51S
Checksum      : 0216
Enable Remote Wake Up
PNP: 1
Decoded values of device 2:
Chip type 3 ftdi_eeprom_size: 128
0x000: 00 40 03 04 01 60 00 00  a0 2d 08 00 00 00 98 0a .@...`.. .-......
0x010: a2 20 c2 12 23 10 05 00  0a 03 46 00 54 00 44 00 . ..#... ..F.T.D.
0x020: 49 00 20 03 46 00 54 00  32 00 33 00 32 00 52 00 I. .F.T. 2.3.2.R.
0x030: 20 00 55 00 53 00 42 00  20 00 55 00 41 00 52 00  .U.S.B.  .U.A.R.
0x040: 54 00 12 03 41 00 38 00  30 00 30 00 37 00 55 00 T...A.8. 0.0.7.U.
0x050: 62 00 35 00 c9 bf 1c 80  00 00 00 00 00 00 00 00 b.5..... ........
0x060: 00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00 ........ ........
0x070: 00 00 00 00 00 00 00 00  00 00 00 00 00 00 0f 23 ........ .......#
0x080: 2c 04 d3 fb 00 00 c9 bf  1c 80 42 00 00 00 00 00 ,....... ..B.....
0x090: 00 00 00 00 00 00 00 00  38 41 32 52 4a 33 47 4f ........ 8A2RJ3GO
VID:     0x0403
PID:     0x6001
Release: 0x0000
Bus Powered:  90 mA USB Remote Wake Up
Manufacturer: FTDI
Product:      FT232R USB UART
Serial:       A8007Ub5
Checksum      : 230f
Internal EEPROM
Enable Remote Wake Up
PNP: 1
Channel A has Mode UART VCP
C0 Function: TXLED
C1 Function: RXLED
C2 Function: TXDEN
C3 Function: PWREN
C4 Function: SLEEP
0707010000000B000081A400000000000000000000000160917B830000076F000000000000000000000000000000000000002900000000libftdi1-1.5.12+git.0684c1b/README.mingw* How to cross compile libftdi-1.x for Windows? *
   1 - Prepare a pkg-config wrapper according to
       https://autotools.io/pkgconfig/cross-compiling.html ,
       additionally export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS and
       PKG_CONFIG_ALLOW_SYSTEM_LIBS.
   2 - Write a CMake toolchain file according to
       http://www.vtk.org/Wiki/CmakeMingw . Change the path to your future sysroot.
   3 - Get libusb sources (either by cloning the git repo or by downloading a
       tarball). Unpack, autogen.sh (when building from git), and configure like this:
       ./configure --build=`./config.guess` --host=i686-w64-mingw32 \
               --prefix=/usr --with-sysroot=$HOME/i686-w64-mingw32-root/
   4 - run
       make install DESTDIR=$HOME/i686-w64-mingw32-root/
   5 - go to libftdi-1.x source directory and run
       cmake -DCMAKE_TOOLCHAIN_FILE=~/Toolchain-mingw.cmake \
             -DCMAKE_INSTALL_PREFIX="/usr" \
             -DPKG_CONFIG_EXECUTABLE=`which i686-w64-mingw32-pkg-config`
   6 - run
       make install DESTDIR=$HOME/i686-w64-mingw32-root/

* How to run libftdi 1.x under Windows *

On 26-Jan-2014, libusbx and libusb project were merged with the release
of libusb-1.0.18 and now the project is called libusb.

libusb Windows backend will need to rely on a proper driver to run.
Please refer to the following wiki page for proper driver installation.
https://github.com/libusb/libusb/wiki/Windows#wiki-How_to_use_libusb_on_Windows

As of 26-Jan-2014, libusb Windows backend supports WinUSB,
libusb0.sys and libusbk.sys driver. However, libusb's support of
libusb0.sys and libusbk.sys is considered to be less mature than
WinUSB. Therefore, WinUSB driver installation using Zadig
is recommended.

Take note once you replace the original FTDI driver with WinUSB driver,
you can no longer use the functionality the original FTDI driver provides
(eg. Virtual Serial Port or D2XX).
0707010000000C000081A400000000000000000000000160917B830000004F000000000000000000000000000000000000002100000000libftdi1-1.5.12+git.0684c1b/TODO*** TODO for 1.0 release ***
Documentation:
- Document the new EEPROM function
0707010000000D000041ED00000000000000000000000260917B8300000000000000000000000000000000000000000000002200000000libftdi1-1.5.12+git.0684c1b/cmake0707010000000E000081A400000000000000000000000160917B8300000BB2000000000000000000000000000000000000003400000000libftdi1-1.5.12+git.0684c1b/cmake/FindConfuse.cmake# libConfuse is a configuration file parser library
# available at http://www.nongnu.org/confuse/
#
# The module defines the following variables:
#  CONFUSE_FOUND - the system has Confuse
#  CONFUSE_INCLUDE_DIR - where to find confuse.h
#  CONFUSE_INCLUDE_DIRS - confuse includes
#  CONFUSE_LIBRARY - where to find the Confuse library
#  CONFUSE_LIBRARIES - additional libraries
#  CONFUSE_ROOT_DIR - root dir (ex. /usr/local)

#=============================================================================
# Copyright 2010-2013, Julien Schueller
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met: 
# 
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer. 
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution. 
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# The views and conclusions contained in the software and documentation are those
# of the authors and should not be interpreted as representing official policies, 
# either expressed or implied, of the FreeBSD Project.
#=============================================================================


find_path ( CONFUSE_INCLUDE_DIR
  NAMES confuse.h
)

set ( CONFUSE_INCLUDE_DIRS ${CONFUSE_INCLUDE_DIR} )

find_library ( CONFUSE_LIBRARY
  NAMES confuse
)

set ( CONFUSE_LIBRARIES ${CONFUSE_LIBRARY} )


# try to guess root dir from include dir
if ( CONFUSE_INCLUDE_DIR )
  string ( REGEX REPLACE "(.*)/include.*" "\\1" CONFUSE_ROOT_DIR ${CONFUSE_INCLUDE_DIR} )
# try to guess root dir from library dir
elseif ( CONFUSE_LIBRARY )
  string ( REGEX REPLACE "(.*)/lib[/|32|64].*" "\\1" CONFUSE_ROOT_DIR ${CONFUSE_LIBRARY} )
endif ()


# handle the QUIETLY and REQUIRED arguments
include ( FindPackageHandleStandardArgs )
find_package_handle_standard_args( Confuse DEFAULT_MSG CONFUSE_LIBRARY CONFUSE_INCLUDE_DIR  )

mark_as_advanced (
  CONFUSE_LIBRARY 
  CONFUSE_LIBRARIES
  CONFUSE_INCLUDE_DIR
  CONFUSE_INCLUDE_DIRS
  CONFUSE_ROOT_DIR
)
0707010000000F000081A400000000000000000000000160917B8300000685000000000000000000000000000000000000003400000000libftdi1-1.5.12+git.0684c1b/cmake/FindLibintl.cmake# Try to find Libintl functionality
# Once done this will define
#
#  LIBINTL_FOUND - system has Libintl
#  LIBINTL_INCLUDE_DIR - Libintl include directory
#  LIBINTL_LIBRARIES - Libraries needed to use Libintl
#
# TODO: This will enable translations only if Gettext functionality is
# present in libc. Must have more robust system for release, where Gettext
# functionality can also reside in standalone Gettext library, or the one
# embedded within kdelibs (cf. gettext.m4 from Gettext source).
 
# Copyright (c) 2006, Chusslove Illich, <caslav.ilic@gmx.net>
# Copyright (c) 2007, Alexander Neundorf, <neundorf@kde.org>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
 
if(LIBINTL_INCLUDE_DIR AND LIBINTL_LIB_FOUND)
  set(Libintl_FIND_QUIETLY TRUE)
endif(LIBINTL_INCLUDE_DIR AND LIBINTL_LIB_FOUND)
 
find_path(LIBINTL_INCLUDE_DIR libintl.h)
 
set(LIBINTL_LIB_FOUND FALSE)
 
if(LIBINTL_INCLUDE_DIR)
  include(CheckFunctionExists)
  check_function_exists(dgettext LIBINTL_LIBC_HAS_DGETTEXT)
 
  if (LIBINTL_LIBC_HAS_DGETTEXT)
    set(LIBINTL_LIBRARIES)
    set(LIBINTL_LIB_FOUND TRUE)
  else (LIBINTL_LIBC_HAS_DGETTEXT)
    find_library(LIBINTL_LIBRARIES NAMES intl libintl )
    if(LIBINTL_LIBRARIES)
      set(LIBINTL_LIB_FOUND TRUE)
    endif(LIBINTL_LIBRARIES)
  endif (LIBINTL_LIBC_HAS_DGETTEXT)
 
endif(LIBINTL_INCLUDE_DIR)
 
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Libintl  DEFAULT_MSG  LIBINTL_INCLUDE_DIR  LIBINTL_LIB_FOUND)
 
mark_as_advanced(LIBINTL_INCLUDE_DIR  LIBINTL_LIBRARIES  LIBINTL_LIBC_HAS_DGETTEXT  LIBINTL_LIB_FOUND)

07070100000010000081A400000000000000000000000160917B83000004B7000000000000000000000000000000000000003100000000libftdi1-1.5.12+git.0684c1b/cmake/FindUSB1.cmake# - Try to find the freetype library
# Once done this defines
#
#  LIBUSB_FOUND - system has libusb
#  LIBUSB_INCLUDE_DIR - the libusb include directory
#  LIBUSB_LIBRARIES - Link these to use libusb

# Copyright (c) 2006, 2008  Laurent Montel, <montel@kde.org>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.


if (LIBUSB_INCLUDE_DIR AND LIBUSB_LIBRARIES)

  # in cache already
  set(LIBUSB_FOUND TRUE)

else (LIBUSB_INCLUDE_DIR AND LIBUSB_LIBRARIES)
  # use pkg-config to get the directories and then use these values
  # in the FIND_PATH() and FIND_LIBRARY() calls
  find_package(PkgConfig)
  pkg_check_modules(PC_LIBUSB libusb-1.0)

  FIND_PATH(LIBUSB_INCLUDE_DIR libusb.h
    PATH_SUFFIXES libusb-1.0
    PATHS ${PC_LIBUSB_INCLUDEDIR} ${PC_LIBUSB_INCLUDE_DIRS})

  FIND_LIBRARY(LIBUSB_LIBRARIES NAMES usb-1.0
    PATHS ${PC_LIBUSB_LIBDIR} ${PC_LIBUSB_LIBRARY_DIRS})

  include(FindPackageHandleStandardArgs)
  FIND_PACKAGE_HANDLE_STANDARD_ARGS(LIBUSB DEFAULT_MSG LIBUSB_LIBRARIES LIBUSB_INCLUDE_DIR)

  MARK_AS_ADVANCED(LIBUSB_INCLUDE_DIR LIBUSB_LIBRARIES)

endif (LIBUSB_INCLUDE_DIR AND LIBUSB_LIBRARIES)
07070100000011000081A400000000000000000000000160917B83000009F1000000000000000000000000000000000000003A00000000libftdi1-1.5.12+git.0684c1b/cmake/LibFTDI1Config.cmake.in#                                               -*- cmake -*-
#
#  LibFTDI1Config.cmake(.in)
#
#  Copyright (C) 2013 Intra2net AG and the libftdi developers
#
#  This file is part of LibFTDI.
#
#  LibFTDI is free software; you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License
#  version 2.1 as published by the Free Software Foundation;
#

# Use the following variables to compile and link against LibFTDI:
#  LIBFTDI_FOUND              - True if LibFTDI was found on your system
#  LIBFTDI_USE_FILE           - The file making LibFTDI usable
#  LIBFTDI_DEFINITIONS        - Definitions needed to build with LibFTDI
#  LIBFTDI_INCLUDE_DIRS       - Directory where ftdi.h can be found
#  LIBFTDI_INCLUDE_DIRS       - List of directories of LibFTDI and it's dependencies
#  LIBFTDI_LIBRARY            - LibFTDI library location
#  LIBFTDI_LIBRARIES          - List of libraries to link against LibFTDI library
#  LIBFTDIPP_LIBRARY          - LibFTDI C++ wrapper library location
#  LIBFTDIPP_LIBRARIES        - List of libraries to link against LibFTDI C++ wrapper
#  LIBFTDI_LIBRARY_DIRS       - List of directories containing LibFTDI' libraries
#  LIBFTDI_ROOT_DIR           - The base directory of LibFTDI
#  LIBFTDI_VERSION_STRING     - A human-readable string containing the version
#  LIBFTDI_VERSION_MAJOR      - The major version of LibFTDI
#  LIBFTDI_VERSION_MINOR      - The minor version of LibFTDI
#  LIBFTDI_VERSION_PATCH      - The patch version of LibFTDI
#  LIBFTDI_PYTHON_MODULE_PATH - Path to the python module

set ( LIBFTDI_FOUND 1 )
set ( LIBFTDI_USE_FILE     "@LIBFTDI_USE_FILE@" )

set ( LIBFTDI_DEFINITIONS  "@LIBFTDI_DEFINITIONS@" )
set ( LIBFTDI_INCLUDE_DIR  "@LIBFTDI_INCLUDE_DIR@" )
set ( LIBFTDI_INCLUDE_DIRS "@LIBFTDI_INCLUDE_DIRS@" )
set ( LIBFTDI_LIBRARY      "@LIBFTDI_LIBRARY@" )
set ( LIBFTDI_LIBRARIES    "@LIBFTDI_LIBRARIES@" )
set ( LIBFTDI_STATIC_LIBRARY      "@LIBFTDI_STATIC_LIBRARY@" )
set ( LIBFTDI_STATIC_LIBRARIES    "@LIBFTDI_STATIC_LIBRARIES@" )
set ( LIBFTDIPP_LIBRARY    "@LIBFTDIPP_LIBRARY@" )
set ( LIBFTDIPP_LIBRARIES  "@LIBFTDIPP_LIBRARIES@" )
set ( LIBFTDI_LIBRARY_DIRS "@LIBFTDI_LIBRARY_DIRS@" )
set ( LIBFTDI_ROOT_DIR     "@LIBFTDI_ROOT_DIR@" )

set ( LIBFTDI_VERSION_STRING "@LIBFTDI_VERSION_STRING@" )
set ( LIBFTDI_VERSION_MAJOR  "@LIBFTDI_VERSION_MAJOR@" )
set ( LIBFTDI_VERSION_MINOR  "@LIBFTDI_VERSION_MINOR@" )
set ( LIBFTDI_VERSION_PATCH  "@LIBFTDI_VERSION_PATCH@" )

set ( LIBFTDI_PYTHON_MODULE_PATH "@LIBFTDI_PYTHON_MODULE_PATH@" )

07070100000012000081A400000000000000000000000160917B8300000527000000000000000000000000000000000000004100000000libftdi1-1.5.12+git.0684c1b/cmake/LibFTDI1ConfigVersion.cmake.in# This is a basic version file for the Config-mode of find_package().
# It is used by write_basic_package_version_file() as input file for configure_file()
# to create a version-file which can be installed along a config.cmake file.
#
# The created file sets PACKAGE_VERSION_EXACT if the current version string and
# the requested version string are exactly the same and it sets
# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version.
# The variable CVF_VERSION must be set before calling configure_file().

set(PACKAGE_VERSION "@LIBFTDI_VERSION_STRING@")

if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}" )
  set(PACKAGE_VERSION_COMPATIBLE FALSE)
else()
  set(PACKAGE_VERSION_COMPATIBLE TRUE)
  if( "${PACKAGE_FIND_VERSION}" STREQUAL "${PACKAGE_VERSION}")
    set(PACKAGE_VERSION_EXACT TRUE)
  endif()
endif()

# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it:
if("${CMAKE_SIZEOF_VOID_P}"  STREQUAL ""  OR "8" STREQUAL "")
   return()
endif()

# check that the installed version has the same 32/64bit-ness as the one which is currently searching:
if(NOT "${CMAKE_SIZEOF_VOID_P}"  STREQUAL  "8")
   math(EXPR installedBits "8 * 8")
   set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)")
   set(PACKAGE_VERSION_UNSUITABLE TRUE)
endif()
07070100000013000081A400000000000000000000000160917B8300000080000000000000000000000000000000000000003F00000000libftdi1-1.5.12+git.0684c1b/cmake/Toolchain-Crossbuild32.cmakeset(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_C_COMPILER gcc -m32)
set(CMAKE_CXX_COMPILER g++ -m32)
set(CMAKE_FIND_ROOT_PATH /usr/lib)
07070100000014000081A400000000000000000000000160917B830000027C000000000000000000000000000000000000004300000000libftdi1-1.5.12+git.0684c1b/cmake/Toolchain-i686-w64-mingw32.cmake# the name of the target operating system
SET(CMAKE_SYSTEM_NAME Windows)

# which compilers to use for C and C++
SET(CMAKE_C_COMPILER i686-w64-mingw32-gcc)
SET(CMAKE_CXX_COMPILER i686-w64-mingw32-g++)

# here is the target environment located
SET(CMAKE_FIND_ROOT_PATH  /usr/i686-w64-mingw32 )

# adjust the default behaviour of the FIND_XXX() commands:
# search headers and libraries in the target environment, search 
# programs in the host environment
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set (CMAKE_RC_COMPILER i686-w64-mingw32-windres)
07070100000015000081A400000000000000000000000160917B8300000251000000000000000000000000000000000000003A00000000libftdi1-1.5.12+git.0684c1b/cmake/Toolchain-mingw32.cmake# the name of the target operating system
SET(CMAKE_SYSTEM_NAME Windows)

# which compilers to use for C and C++
SET(CMAKE_C_COMPILER i386-mingw32msvc-gcc)
SET(CMAKE_CXX_COMPILER i386-mingw32msvc-g++)

# here is the target environment located
SET(CMAKE_FIND_ROOT_PATH  /opt/cross/i386-mingw32msvc )

# adjust the default behaviour of the FIND_XXX() commands:
# search headers and libraries in the target environment, search 
# programs in the host environment
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
07070100000016000081A400000000000000000000000160917B8300000284000000000000000000000000000000000000004500000000libftdi1-1.5.12+git.0684c1b/cmake/Toolchain-x86_64-w64-mingw32.cmake# the name of the target operating system
SET(CMAKE_SYSTEM_NAME Windows)

# which compilers to use for C and C++
SET(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
SET(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++)

# here is the target environment located
SET(CMAKE_FIND_ROOT_PATH  /usr/x86_64-w64-mingw32 )

# adjust the default behaviour of the FIND_XXX() commands:
# search headers and libraries in the target environment, search 
# programs in the host environment
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set (CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)
07070100000017000081A400000000000000000000000160917B830000020C000000000000000000000000000000000000003400000000libftdi1-1.5.12+git.0684c1b/cmake/UseLibFTDI1.cmake#                                               -*- cmake -*-
#
#  UseLibFTDI.cmake
#
#  Copyright (C) 2013 Intra2net AG and the libftdi developers
#
#  This file is part of LibFTDI.
#
#  LibFTDI is free software; you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License
#  version 2.1 as published by the Free Software Foundation;
#


add_definitions     ( ${LIBFTDI_DEFINITIONS} )
include_directories ( ${LIBFTDI_INCLUDE_DIRS} )
link_directories    ( ${LIBFTDI_LIBRARY_DIRS} )

07070100000018000041ED00000000000000000000000260917B8300000000000000000000000000000000000000000000002000000000libftdi1-1.5.12+git.0684c1b/doc07070100000019000081A400000000000000000000000160917B83000198E3000000000000000000000000000000000000002C00000000libftdi1-1.5.12+git.0684c1b/doc/Doxyfile.in# Doxyfile 1.8.10

# This file describes the settings to be used by the documentation system
# doxygen (www.doxygen.org) for a project.
#
# All text after a double hash (##) is considered a comment and is placed in
# front of the TAG it is preceding.
#
# All text after a single hash (#) is considered a comment and will be ignored.
# The format is:
# TAG = value [value, ...]
# For lists, items can also be appended using:
# TAG += value [value, ...]
# Values that contain spaces should be placed between quotes (\" \").

#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------

# This tag specifies the encoding used for all characters in the config file
# that follow. The default is UTF-8 which is also the encoding used for all text
# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
# for the list of possible encodings.
# The default value is: UTF-8.

DOXYFILE_ENCODING      = UTF-8

# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
# double-quotes, unless you are using Doxywizard) that should identify the
# project for which the documentation is generated. This name is used in the
# title of most generated pages and in a few other places.
# The default value is: My Project.

PROJECT_NAME           = @PACKAGE@

# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
# could be handy for archiving the generated documentation or if some version
# control system is used.

PROJECT_NUMBER         = @VERSION@

# Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a
# quick idea about the purpose of the project. Keep the description short.

PROJECT_BRIEF          =

# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
# in the documentation. The maximum height of the logo should not exceed 55
# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
# the logo to the output directory.

PROJECT_LOGO           =

# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
# into which the generated documentation will be written. If a relative path is
# entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used.

OUTPUT_DIRECTORY       = doc

# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-
# directories (in 2 levels) under the output directory of each output format and
# will distribute the generated files over these directories. Enabling this
# option can be useful when feeding doxygen a huge amount of source files, where
# putting all generated files in the same directory would otherwise causes
# performance problems for the file system.
# The default value is: NO.

CREATE_SUBDIRS         = NO

# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
# characters to appear in the names of generated files. If set to NO, non-ASCII
# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
# U+3044.
# The default value is: NO.

ALLOW_UNICODE_NAMES    = NO

# The OUTPUT_LANGUAGE tag is used to specify the language in which all
# documentation generated by doxygen is written. Doxygen will use this
# information to generate all constant output in the proper language.
# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
# Ukrainian and Vietnamese.
# The default value is: English.

OUTPUT_LANGUAGE        = English

# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
# descriptions after the members that are listed in the file and class
# documentation (similar to Javadoc). Set to NO to disable this.
# The default value is: YES.

BRIEF_MEMBER_DESC      = YES

# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief
# description of a member or function before the detailed description
#
# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
# brief descriptions will be completely suppressed.
# The default value is: YES.

REPEAT_BRIEF           = YES

# This tag implements a quasi-intelligent brief description abbreviator that is
# used to form the text in various listings. Each string in this list, if found
# as the leading text of the brief description, will be stripped from the text
# and the result, after processing the whole list, is used as the annotated
# text. Otherwise, the brief description is used as-is. If left blank, the
# following values are used ($name is automatically replaced with the name of
# the entity):The $name class, The $name widget, The $name file, is, provides,
# specifies, contains, represents, a, an and the.

ABBREVIATE_BRIEF       =

# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
# doxygen will generate a detailed section even if there is only a brief
# description.
# The default value is: NO.

ALWAYS_DETAILED_SEC    = NO

# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
# inherited members of a class in the documentation of that class as if those
# members were ordinary class members. Constructors, destructors and assignment
# operators of the base classes will not be shown.
# The default value is: NO.

INLINE_INHERITED_MEMB  = NO

# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path
# before files name in the file list and in the header files. If set to NO the
# shortest path that makes the file name unique will be used
# The default value is: YES.

FULL_PATH_NAMES        = NO

# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
# Stripping is only done if one of the specified strings matches the left-hand
# part of the path. The tag can be used to show relative paths in the file list.
# If left blank the directory from which doxygen is run is used as the path to
# strip.
#
# Note that you can specify absolute paths here, but also relative paths, which
# will be relative from the directory where doxygen is started.
# This tag requires that the tag FULL_PATH_NAMES is set to YES.

STRIP_FROM_PATH        =

# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
# path mentioned in the documentation of a class, which tells the reader which
# header file to include in order to use a class. If left blank only the name of
# the header file containing the class definition is used. Otherwise one should
# specify the list of include paths that are normally passed to the compiler
# using the -I flag.

STRIP_FROM_INC_PATH    =

# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
# less readable) file names. This can be useful is your file systems doesn't
# support long names like on DOS, Mac, or CD-ROM.
# The default value is: NO.

SHORT_NAMES            = NO

# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
# first line (until the first dot) of a Javadoc-style comment as the brief
# description. If set to NO, the Javadoc-style will behave just like regular Qt-
# style comments (thus requiring an explicit @brief command for a brief
# description.)
# The default value is: NO.

JAVADOC_AUTOBRIEF      = NO

# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
# line (until the first dot) of a Qt-style comment as the brief description. If
# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
# requiring an explicit \brief command for a brief description.)
# The default value is: NO.

QT_AUTOBRIEF           = NO

# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
# a brief description. This used to be the default behavior. The new default is
# to treat a multi-line C++ comment block as a detailed description. Set this
# tag to YES if you prefer the old behavior instead.
#
# Note that setting this tag to YES also means that rational rose comments are
# not recognized any more.
# The default value is: NO.

MULTILINE_CPP_IS_BRIEF = NO

# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
# documentation from any documented member that it re-implements.
# The default value is: YES.

INHERIT_DOCS           = YES

# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new
# page for each member. If set to NO, the documentation of a member will be part
# of the file/class/namespace that contains it.
# The default value is: NO.

SEPARATE_MEMBER_PAGES  = NO

# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
# uses this value to replace tabs by spaces in code fragments.
# Minimum value: 1, maximum value: 16, default value: 4.

TAB_SIZE               = 4

# This tag can be used to specify a number of aliases that act as commands in
# the documentation. An alias has the form:
# name=value
# For example adding
# "sideeffect=@par Side Effects:\n"
# will allow you to put the command \sideeffect (or @sideeffect) in the
# documentation, which will result in a user-defined paragraph with heading
# "Side Effects:". You can put \n's in the value part of an alias to insert
# newlines.

ALIASES                =

# This tag can be used to specify a number of word-keyword mappings (TCL only).
# A mapping has the form "name=value". For example adding "class=itcl::class"
# will allow you to use the command class in the itcl::class meaning.

TCL_SUBST              =

# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
# only. Doxygen will then generate output that is more tailored for C. For
# instance, some of the names that are used will be different. The list of all
# members will be omitted, etc.
# The default value is: NO.

OPTIMIZE_OUTPUT_FOR_C  = NO

# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
# Python sources only. Doxygen will then generate output that is more tailored
# for that language. For instance, namespaces will be presented as packages,
# qualified scopes will look different, etc.
# The default value is: NO.

OPTIMIZE_OUTPUT_JAVA   = NO

# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
# sources. Doxygen will then generate output that is tailored for Fortran.
# The default value is: NO.

OPTIMIZE_FOR_FORTRAN   = NO

# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
# sources. Doxygen will then generate output that is tailored for VHDL.
# The default value is: NO.

OPTIMIZE_OUTPUT_VHDL   = NO

# Doxygen selects the parser to use depending on the extension of the files it
# parses. With this tag you can assign which parser to use for a given
# extension. Doxygen has a built-in mapping, but you can override or extend it
# using this tag. The format is ext=language, where ext is a file extension, and
# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:
# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:
# Fortran. In the later case the parser tries to guess whether the code is fixed
# or free formatted code, this is the default for Fortran type files), VHDL. For
# instance to make doxygen treat .inc files as Fortran files (default is PHP),
# and .f files as C (default is Fortran), use: inc=Fortran f=C.
#
# Note: For files without extension you can use no_extension as a placeholder.
#
# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
# the files are not read by doxygen.

EXTENSION_MAPPING      =

# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
# according to the Markdown format, which allows for more readable
# documentation. See http://daringfireball.net/projects/markdown/ for details.
# The output of markdown processing is further processed by doxygen, so you can
# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
# case of backward compatibilities issues.
# The default value is: YES.

MARKDOWN_SUPPORT       = YES

# When enabled doxygen tries to link words that correspond to documented
# classes, or namespaces to their corresponding documentation. Such a link can
# be prevented in individual cases by putting a % sign in front of the word or
# globally by setting AUTOLINK_SUPPORT to NO.
# The default value is: YES.

AUTOLINK_SUPPORT       = YES

# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
# to include (a tag file for) the STL sources as input, then you should set this
# tag to YES in order to let doxygen match functions declarations and
# definitions whose arguments contain STL classes (e.g. func(std::string);
# versus func(std::string) {}). This also make the inheritance and collaboration
# diagrams that involve STL classes more complete and accurate.
# The default value is: NO.

BUILTIN_STL_SUPPORT    = NO

# If you use Microsoft's C++/CLI language, you should set this option to YES to
# enable parsing support.
# The default value is: NO.

CPP_CLI_SUPPORT        = NO

# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
# will parse them like normal C++ but will assume all classes use public instead
# of private inheritance when no explicit protection keyword is present.
# The default value is: NO.

SIP_SUPPORT            = NO

# For Microsoft's IDL there are propget and propput attributes to indicate
# getter and setter methods for a property. Setting this option to YES will make
# doxygen to replace the get and set methods by a property in the documentation.
# This will only work if the methods are indeed getting or setting a simple
# type. If this is not the case, or you want to show the methods anyway, you
# should set this option to NO.
# The default value is: YES.

IDL_PROPERTY_SUPPORT   = YES

# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
# tag is set to YES then doxygen will reuse the documentation of the first
# member in the group (if any) for the other members of the group. By default
# all members of a group must be documented explicitly.
# The default value is: NO.

DISTRIBUTE_GROUP_DOC   = NO

# If one adds a struct or class to a group and this option is enabled, then also
# any nested class or struct is added to the same group. By default this option
# is disabled and one has to add nested compounds explicitly via \ingroup.
# The default value is: NO.

GROUP_NESTED_COMPOUNDS = NO

# Set the SUBGROUPING tag to YES to allow class member groups of the same type
# (for instance a group of public functions) to be put as a subgroup of that
# type (e.g. under the Public Functions section). Set it to NO to prevent
# subgrouping. Alternatively, this can be done per class using the
# \nosubgrouping command.
# The default value is: YES.

SUBGROUPING            = YES

# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
# are shown inside the group in which they are included (e.g. using \ingroup)
# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
# and RTF).
#
# Note that this feature does not work in combination with
# SEPARATE_MEMBER_PAGES.
# The default value is: NO.

INLINE_GROUPED_CLASSES = NO

# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
# with only public data fields or simple typedef fields will be shown inline in
# the documentation of the scope in which they are defined (i.e. file,
# namespace, or group documentation), provided this scope is documented. If set
# to NO, structs, classes, and unions are shown on a separate page (for HTML and
# Man pages) or section (for LaTeX and RTF).
# The default value is: NO.

INLINE_SIMPLE_STRUCTS  = NO

# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
# enum is documented as struct, union, or enum with the name of the typedef. So
# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
# with name TypeT. When disabled the typedef will appear as a member of a file,
# namespace, or class. And the struct will be named TypeS. This can typically be
# useful for C code in case the coding convention dictates that all compound
# types are typedef'ed and only the typedef is referenced, never the tag name.
# The default value is: NO.

TYPEDEF_HIDES_STRUCT   = NO

# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
# cache is used to resolve symbols given their name and scope. Since this can be
# an expensive process and often the same symbol appears multiple times in the
# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
# doxygen will become slower. If the cache is too large, memory is wasted. The
# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
# symbols. At the end of a run doxygen will report the cache usage and suggest
# the optimal cache size from a speed point of view.
# Minimum value: 0, maximum value: 9, default value: 0.

LOOKUP_CACHE_SIZE      = 0

#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------

# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in
# documentation are documented, even if no documentation was available. Private
# class members and static file members will be hidden unless the
# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
# Note: This will also disable the warnings about undocumented members that are
# normally produced when WARNINGS is set to YES.
# The default value is: NO.

EXTRACT_ALL            = YES

# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will
# be included in the documentation.
# The default value is: NO.

EXTRACT_PRIVATE        = NO

# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal
# scope will be included in the documentation.
# The default value is: NO.

EXTRACT_PACKAGE        = NO

# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be
# included in the documentation.
# The default value is: NO.

EXTRACT_STATIC         = NO

# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined
# locally in source files will be included in the documentation. If set to NO,
# only classes defined in header files are included. Does not have any effect
# for Java sources.
# The default value is: YES.

EXTRACT_LOCAL_CLASSES  = YES

# This flag is only useful for Objective-C code. If set to YES, local methods,
# which are defined in the implementation section but not in the interface are
# included in the documentation. If set to NO, only methods in the interface are
# included.
# The default value is: NO.

EXTRACT_LOCAL_METHODS  = NO

# If this flag is set to YES, the members of anonymous namespaces will be
# extracted and appear in the documentation as a namespace called
# 'anonymous_namespace{file}', where file will be replaced with the base name of
# the file that contains the anonymous namespace. By default anonymous namespace
# are hidden.
# The default value is: NO.

EXTRACT_ANON_NSPACES   = NO

# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
# undocumented members inside documented classes or files. If set to NO these
# members will be included in the various overviews, but no documentation
# section is generated. This option has no effect if EXTRACT_ALL is enabled.
# The default value is: NO.

HIDE_UNDOC_MEMBERS     = YES

# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
# undocumented classes that are normally visible in the class hierarchy. If set
# to NO, these classes will be included in the various overviews. This option
# has no effect if EXTRACT_ALL is enabled.
# The default value is: NO.

HIDE_UNDOC_CLASSES     = YES

# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
# (class|struct|union) declarations. If set to NO, these declarations will be
# included in the documentation.
# The default value is: NO.

HIDE_FRIEND_COMPOUNDS  = NO

# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
# documentation blocks found inside the body of a function. If set to NO, these
# blocks will be appended to the function's detailed documentation block.
# The default value is: NO.

HIDE_IN_BODY_DOCS      = NO

# The INTERNAL_DOCS tag determines if documentation that is typed after a
# \internal command is included. If the tag is set to NO then the documentation
# will be excluded. Set it to YES to include the internal documentation.
# The default value is: NO.

INTERNAL_DOCS          = NO

# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
# names in lower-case letters. If set to YES, upper-case letters are also
# allowed. This is useful if you have classes or files whose names only differ
# in case and if your file system supports case sensitive file names. Windows
# and Mac users are advised to set this option to NO.
# The default value is: system dependent.

CASE_SENSE_NAMES       = YES

# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
# their full class and namespace scopes in the documentation. If set to YES, the
# scope will be hidden.
# The default value is: NO.

HIDE_SCOPE_NAMES       = NO

# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will
# append additional text to a page's title, such as Class Reference. If set to
# YES the compound reference will be hidden.
# The default value is: NO.

HIDE_COMPOUND_REFERENCE= NO

# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
# the files that are included by a file in the documentation of that file.
# The default value is: YES.

SHOW_INCLUDE_FILES     = YES

# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
# grouped member an include statement to the documentation, telling the reader
# which file to include in order to use the member.
# The default value is: NO.

SHOW_GROUPED_MEMB_INC  = NO

# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
# files with double quotes in the documentation rather than with sharp brackets.
# The default value is: NO.

FORCE_LOCAL_INCLUDES   = NO

# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
# documentation for inline members.
# The default value is: YES.

INLINE_INFO            = YES

# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
# (detailed) documentation of file and class members alphabetically by member
# name. If set to NO, the members will appear in declaration order.
# The default value is: YES.

SORT_MEMBER_DOCS       = NO

# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
# descriptions of file, namespace and class members alphabetically by member
# name. If set to NO, the members will appear in declaration order. Note that
# this will also influence the order of the classes in the class list.
# The default value is: NO.

SORT_BRIEF_DOCS        = NO

# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
# (brief and detailed) documentation of class members so that constructors and
# destructors are listed first. If set to NO the constructors will appear in the
# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
# member documentation.
# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
# detailed member documentation.
# The default value is: NO.

SORT_MEMBERS_CTORS_1ST = NO

# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
# of group names into alphabetical order. If set to NO the group names will
# appear in their defined order.
# The default value is: NO.

SORT_GROUP_NAMES       = NO

# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
# fully-qualified names, including namespaces. If set to NO, the class list will
# be sorted only by class name, not including the namespace part.
# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
# Note: This option applies only to the class list, not to the alphabetical
# list.
# The default value is: NO.

SORT_BY_SCOPE_NAME     = NO

# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
# type resolution of all parameters of a function it will reject a match between
# the prototype and the implementation of a member function even if there is
# only one candidate or it is obvious which candidate to choose by doing a
# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
# accept a match between prototype and implementation in such cases.
# The default value is: NO.

STRICT_PROTO_MATCHING  = NO

# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo
# list. This list is created by putting \todo commands in the documentation.
# The default value is: YES.

GENERATE_TODOLIST      = YES

# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test
# list. This list is created by putting \test commands in the documentation.
# The default value is: YES.

GENERATE_TESTLIST      = YES

# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug
# list. This list is created by putting \bug commands in the documentation.
# The default value is: YES.

GENERATE_BUGLIST       = YES

# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)
# the deprecated list. This list is created by putting \deprecated commands in
# the documentation.
# The default value is: YES.

GENERATE_DEPRECATEDLIST= YES

# The ENABLED_SECTIONS tag can be used to enable conditional documentation
# sections, marked by \if <section_label> ... \endif and \cond <section_label>
# ... \endcond blocks.

ENABLED_SECTIONS       =

# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
# initial value of a variable or macro / define can have for it to appear in the
# documentation. If the initializer consists of more lines than specified here
# it will be hidden. Use a value of 0 to hide initializers completely. The
# appearance of the value of individual variables and macros / defines can be
# controlled using \showinitializer or \hideinitializer command in the
# documentation regardless of this setting.
# Minimum value: 0, maximum value: 10000, default value: 30.

MAX_INITIALIZER_LINES  = 30

# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
# the bottom of the documentation of classes and structs. If set to YES, the
# list will mention the files that were used to generate the documentation.
# The default value is: YES.

SHOW_USED_FILES        = YES

# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
# will remove the Files entry from the Quick Index and from the Folder Tree View
# (if specified).
# The default value is: YES.

SHOW_FILES             = YES

# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
# page. This will remove the Namespaces entry from the Quick Index and from the
# Folder Tree View (if specified).
# The default value is: YES.

SHOW_NAMESPACES        = YES

# The FILE_VERSION_FILTER tag can be used to specify a program or script that
# doxygen should invoke to get the current version for each file (typically from
# the version control system). Doxygen will invoke the program by executing (via
# popen()) the command command input-file, where command is the value of the
# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
# by doxygen. Whatever the program writes to standard output is used as the file
# version. For an example see the documentation.

FILE_VERSION_FILTER    =

# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
# by doxygen. The layout file controls the global structure of the generated
# output files in an output format independent way. To create the layout file
# that represents doxygen's defaults, run doxygen with the -l option. You can
# optionally specify a file name after the option, if omitted DoxygenLayout.xml
# will be used as the name of the layout file.
#
# Note that if you run doxygen from a directory containing a file called
# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
# tag is left empty.

LAYOUT_FILE            =

# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
# the reference definitions. This must be a list of .bib files. The .bib
# extension is automatically appended if omitted. This requires the bibtex tool
# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
# For LaTeX the style of the bibliography can be controlled using
# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
# search path. See also \cite for info how to create references.

CITE_BIB_FILES         =

#---------------------------------------------------------------------------
# Configuration options related to warning and progress messages
#---------------------------------------------------------------------------

# The QUIET tag can be used to turn on/off the messages that are generated to
# standard output by doxygen. If QUIET is set to YES this implies that the
# messages are off.
# The default value is: NO.

QUIET                  = YES

# The WARNINGS tag can be used to turn on/off the warning messages that are
# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES
# this implies that the warnings are on.
#
# Tip: Turn warnings on while writing the documentation.
# The default value is: YES.

WARNINGS               = YES

# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate
# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
# will automatically be disabled.
# The default value is: YES.

WARN_IF_UNDOCUMENTED   = YES

# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
# potential errors in the documentation, such as not documenting some parameters
# in a documented function, or documenting parameters that don't exist or using
# markup commands wrongly.
# The default value is: YES.

WARN_IF_DOC_ERROR      = YES

# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
# are documented, but have no documentation for their parameters or return
# value. If set to NO, doxygen will only warn about wrong or incomplete
# parameter documentation, but not about the absence of documentation.
# The default value is: NO.

WARN_NO_PARAMDOC       = NO

# The WARN_FORMAT tag determines the format of the warning messages that doxygen
# can produce. The string should contain the $file, $line, and $text tags, which
# will be replaced by the file and line number from which the warning originated
# and the warning text. Optionally the format may contain $version, which will
# be replaced by the version of the file (if it could be obtained via
# FILE_VERSION_FILTER)
# The default value is: $file:$line: $text.

WARN_FORMAT            = "$file:$line: $text"

# The WARN_LOGFILE tag can be used to specify a file to which warning and error
# messages should be written. If left blank the output is written to standard
# error (stderr).

WARN_LOGFILE           =

#---------------------------------------------------------------------------
# Configuration options related to the input files
#---------------------------------------------------------------------------

# The INPUT tag is used to specify the files and/or directories that contain
# documented source files. You may enter file names like myfile.cpp or
# directories like /usr/src/myproject. Separate the files or directories with
# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
# Note: If this tag is empty the current directory is searched.

INPUT                  = @top_srcdir@/src \
                         @top_srcdir@/ftdipp

# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
# documentation (see: http://www.gnu.org/software/libiconv) for the list of
# possible encodings.
# The default value is: UTF-8.

INPUT_ENCODING         = UTF-8

# If the value of the INPUT tag contains directories, you can use the
# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
# *.h) to filter out the source-files in the directories.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# read by doxygen.
#
# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,
# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd,
# *.vhdl, *.ucf, *.qsf, *.as and *.js.

FILE_PATTERNS          =

# The RECURSIVE tag can be used to specify whether or not subdirectories should
# be searched for input files as well.
# The default value is: NO.

RECURSIVE              = NO

# The EXCLUDE tag can be used to specify files and/or directories that should be
# excluded from the INPUT source files. This way you can easily exclude a
# subdirectory from a directory tree whose root is specified with the INPUT tag.
#
# Note that relative paths are relative to the directory from which doxygen is
# run.

EXCLUDE                =

# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded
# from the input.
# The default value is: NO.

EXCLUDE_SYMLINKS       = NO

# If the value of the INPUT tag contains directories, you can use the
# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
# certain files from those directories.
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories for example use the pattern */test/*

EXCLUDE_PATTERNS       =

# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
# (namespaces, classes, functions, etc.) that should be excluded from the
# output. The symbol name can be a fully qualified name, a word, or if the
# wildcard * is used, a substring. Examples: ANamespace, AClass,
# AClass::ANamespace, ANamespace::*Test
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories use the pattern */test/*

EXCLUDE_SYMBOLS        =

# The EXAMPLE_PATH tag can be used to specify one or more files or directories
# that contain example code fragments that are included (see the \include
# command).

EXAMPLE_PATH           = @top_srcdir@/examples

# If the value of the EXAMPLE_PATH tag contains directories, you can use the
# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
# *.h) to filter out the source-files in the directories. If left blank all
# files are included.

EXAMPLE_PATTERNS       =

# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
# searched for input files to be used with the \include or \dontinclude commands
# irrespective of the value of the RECURSIVE tag.
# The default value is: NO.

EXAMPLE_RECURSIVE      = NO

# The IMAGE_PATH tag can be used to specify one or more files or directories
# that contain images that are to be included in the documentation (see the
# \image command).

IMAGE_PATH             =

# The INPUT_FILTER tag can be used to specify a program that doxygen should
# invoke to filter for each input file. Doxygen will invoke the filter program
# by executing (via popen()) the command:
#
# <filter> <input-file>
#
# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
# name of an input file. Doxygen will then use the output that the filter
# program writes to standard output. If FILTER_PATTERNS is specified, this tag
# will be ignored.
#
# Note that the filter must not add or remove lines; it is applied before the
# code is scanned, but not when the output code is generated. If lines are added
# or removed, the anchors will not be placed correctly.

INPUT_FILTER           =

# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
# basis. Doxygen will compare the file name with each pattern and apply the
# filter if there is a match. The filters are a list of the form: pattern=filter
# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
# patterns match the file name, INPUT_FILTER is applied.

FILTER_PATTERNS        =

# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
# INPUT_FILTER) will also be used to filter the input files that are used for
# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
# The default value is: NO.

FILTER_SOURCE_FILES    = NO

# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
# it is also possible to disable source filtering for a specific pattern using
# *.ext= (so without naming a filter).
# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.

FILTER_SOURCE_PATTERNS =

# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
# is part of the input, its contents will be placed on the main page
# (index.html). This can be useful if you have a project on for instance GitHub
# and want to reuse the introduction page also for the doxygen output.

USE_MDFILE_AS_MAINPAGE =

#---------------------------------------------------------------------------
# Configuration options related to source browsing
#---------------------------------------------------------------------------

# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
# generated. Documented entities will be cross-referenced with these sources.
#
# Note: To get rid of all source code in the generated output, make sure that
# also VERBATIM_HEADERS is set to NO.
# The default value is: NO.

SOURCE_BROWSER         = YES

# Setting the INLINE_SOURCES tag to YES will include the body of functions,
# classes and enums directly into the documentation.
# The default value is: NO.

INLINE_SOURCES         = NO

# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
# special comment blocks from generated source code fragments. Normal C, C++ and
# Fortran comments will always remain visible.
# The default value is: YES.

STRIP_CODE_COMMENTS    = YES

# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
# function all documented functions referencing it will be listed.
# The default value is: NO.

REFERENCED_BY_RELATION = YES

# If the REFERENCES_RELATION tag is set to YES then for each documented function
# all documented entities called/used by that function will be listed.
# The default value is: NO.

REFERENCES_RELATION    = YES

# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
# to YES then the hyperlinks from functions in REFERENCES_RELATION and
# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
# link to the documentation.
# The default value is: YES.

REFERENCES_LINK_SOURCE = YES

# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
# source code will show a tooltip with additional information such as prototype,
# brief description and links to the definition and documentation. Since this
# will make the HTML file larger and loading of large files a bit slower, you
# can opt to disable this feature.
# The default value is: YES.
# This tag requires that the tag SOURCE_BROWSER is set to YES.

SOURCE_TOOLTIPS        = YES

# If the USE_HTAGS tag is set to YES then the references to source code will
# point to the HTML generated by the htags(1) tool instead of doxygen built-in
# source browser. The htags tool is part of GNU's global source tagging system
# (see http://www.gnu.org/software/global/global.html). You will need version
# 4.8.6 or higher.
#
# To use it do the following:
# - Install the latest version of global
# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
# - Make sure the INPUT points to the root of the source tree
# - Run doxygen as normal
#
# Doxygen will invoke htags (and that will in turn invoke gtags), so these
# tools must be available from the command line (i.e. in the search path).
#
# The result: instead of the source browser generated by doxygen, the links to
# source code will now point to the output of htags.
# The default value is: NO.
# This tag requires that the tag SOURCE_BROWSER is set to YES.

USE_HTAGS              = NO

# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
# verbatim copy of the header file for each class for which an include is
# specified. Set to NO to disable this.
# See also: Section \class.
# The default value is: YES.

VERBATIM_HEADERS       = YES

#---------------------------------------------------------------------------
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------

# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
# compounds will be generated. Enable this if the project contains a lot of
# classes, structs, unions or interfaces.
# The default value is: YES.

ALPHABETICAL_INDEX     = NO

# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
# which the alphabetical index list will be split.
# Minimum value: 1, maximum value: 20, default value: 5.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.

COLS_IN_ALPHA_INDEX    = 5

# In case all classes in a project start with a common prefix, all classes will
# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
# can be used to specify a prefix (or a list of prefixes) that should be ignored
# while generating the index headers.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.

IGNORE_PREFIX          =

#---------------------------------------------------------------------------
# Configuration options related to the HTML output
#---------------------------------------------------------------------------

# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
# The default value is: YES.

GENERATE_HTML          = YES

# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: html.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_OUTPUT            = html

# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
# generated HTML page (for example: .htm, .php, .asp).
# The default value is: .html.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_FILE_EXTENSION    = .html

# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
# each generated HTML page. If the tag is left blank doxygen will generate a
# standard header.
#
# To get valid HTML the header file that includes any scripts and style sheets
# that doxygen needs, which is dependent on the configuration options used (e.g.
# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
# default header using
# doxygen -w html new_header.html new_footer.html new_stylesheet.css
# YourConfigFile
# and then modify the file new_header.html. See also section "Doxygen usage"
# for information on how to generate the default header that doxygen normally
# uses.
# Note: The header is subject to change so you typically have to regenerate the
# default header when upgrading to a newer version of doxygen. For a description
# of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_HEADER            =

# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
# generated HTML page. If the tag is left blank doxygen will generate a standard
# footer. See HTML_HEADER for more information on how to generate a default
# footer and what special commands can be used inside the footer. See also
# section "Doxygen usage" for information on how to generate the default footer
# that doxygen normally uses.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_FOOTER            =

# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
# sheet that is used by each HTML page. It can be used to fine-tune the look of
# the HTML output. If left blank doxygen will generate a default style sheet.
# See also section "Doxygen usage" for information on how to generate the style
# sheet that doxygen normally uses.
# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
# it is more robust and this tag (HTML_STYLESHEET) will in the future become
# obsolete.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_STYLESHEET        =

# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
# cascading style sheets that are included after the standard style sheets
# created by doxygen. Using this option one can overrule certain style aspects.
# This is preferred over using HTML_STYLESHEET since it does not replace the
# standard style sheet and is therefore more robust against future updates.
# Doxygen will copy the style sheet files to the output directory.
# Note: The order of the extra style sheet files is of importance (e.g. the last
# style sheet in the list overrules the setting of the previous ones in the
# list). For an example see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_EXTRA_STYLESHEET  =

# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the HTML output directory. Note
# that these files will be copied to the base HTML output directory. Use the
# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
# files will be copied as-is; there are no commands or markers available.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_EXTRA_FILES       =

# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
# will adjust the colors in the style sheet and background images according to
# this color. Hue is specified as an angle on a colorwheel, see
# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
# purple, and 360 is red again.
# Minimum value: 0, maximum value: 359, default value: 220.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_COLORSTYLE_HUE    = 220

# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
# in the HTML output. For a value of 0 the output will use grayscales only. A
# value of 255 will produce the most vivid colors.
# Minimum value: 0, maximum value: 255, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_COLORSTYLE_SAT    = 100

# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
# luminance component of the colors in the HTML output. Values below 100
# gradually make the output lighter, whereas values above 100 make the output
# darker. The value divided by 100 is the actual gamma applied, so 80 represents
# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
# change the gamma.
# Minimum value: 40, maximum value: 240, default value: 80.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_COLORSTYLE_GAMMA  = 80

# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
# page will contain the date and time when the page was generated. Setting this
# to YES can help to show when doxygen was last run and thus if the
# documentation is up to date.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_TIMESTAMP         = YES

# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
# documentation will contain sections that can be hidden and shown after the
# page has loaded.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_DYNAMIC_SECTIONS  = NO

# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
# shown in the various tree structured indices initially; the user can expand
# and collapse entries dynamically later on. Doxygen will expand the tree to
# such a level that at most the specified number of entries are visible (unless
# a fully collapsed tree already exceeds this amount). So setting the number of
# entries 1 will produce a full collapsed tree by default. 0 is a special value
# representing an infinite number of entries and will result in a full expanded
# tree by default.
# Minimum value: 0, maximum value: 9999, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.

HTML_INDEX_NUM_ENTRIES = 100

# If the GENERATE_DOCSET tag is set to YES, additional index files will be
# generated that can be used as input for Apple's Xcode 3 integrated development
# environment (see: http://developer.apple.com/tools/xcode/), introduced with
# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
# Makefile in the HTML output directory. Running make will produce the docset in
# that directory and running make install will install the docset in
# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
# for more information.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.

GENERATE_DOCSET        = NO

# This tag determines the name of the docset feed. A documentation feed provides
# an umbrella under which multiple documentation sets from a single provider
# (such as a company or product suite) can be grouped.
# The default value is: Doxygen generated docs.
# This tag requires that the tag GENERATE_DOCSET is set to YES.

DOCSET_FEEDNAME        = "Doxygen generated docs"

# This tag specifies a string that should uniquely identify the documentation
# set bundle. This should be a reverse domain-name style string, e.g.
# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_DOCSET is set to YES.

DOCSET_BUNDLE_ID       = org.doxygen.Project

# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
# the documentation publisher. This should be a reverse domain-name style
# string, e.g. com.mycompany.MyDocSet.documentation.
# The default value is: org.doxygen.Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.

DOCSET_PUBLISHER_ID    = org.doxygen.Publisher

# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
# The default value is: Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.

DOCSET_PUBLISHER_NAME  = Publisher

# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
# Windows.
#
# The HTML Help Workshop contains a compiler that can convert all HTML output
# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
# files are now used as the Windows 98 help format, and will replace the old
# Windows help format (.hlp) on all Windows platforms in the future. Compressed
# HTML files also contain an index, a table of contents, and you can search for
# words in the documentation. The HTML workshop also contains a viewer for
# compressed HTML files.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.

GENERATE_HTMLHELP      = NO

# The CHM_FILE tag can be used to specify the file name of the resulting .chm
# file. You can add a path in front of the file if the result should not be
# written to the html output directory.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

CHM_FILE               =

# The HHC_LOCATION tag can be used to specify the location (absolute path
# including file name) of the HTML help compiler (hhc.exe). If non-empty,
# doxygen will try to run the HTML help compiler on the generated index.hhp.
# The file has to be specified with full path.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

HHC_LOCATION           =

# The GENERATE_CHI flag controls if a separate .chi index file is generated
# (YES) or that it should be included in the master .chm file (NO).
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

GENERATE_CHI           = NO

# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)
# and project file content.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

CHM_INDEX_ENCODING     =

# The BINARY_TOC flag controls whether a binary table of contents is generated
# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it
# enables the Previous and Next buttons.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

BINARY_TOC             = NO

# The TOC_EXPAND flag can be set to YES to add extra items for group members to
# the table of contents of the HTML help documentation and to the tree view.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

TOC_EXPAND             = NO

# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
# (.qch) of the generated HTML documentation.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.

GENERATE_QHP           = NO

# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
# the file name of the resulting .qch file. The path specified is relative to
# the HTML output folder.
# This tag requires that the tag GENERATE_QHP is set to YES.

QCH_FILE               =

# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
# Project output. For more information please see Qt Help Project / Namespace
# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_QHP is set to YES.

QHP_NAMESPACE          = org.doxygen.Project

# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
# Help Project output. For more information please see Qt Help Project / Virtual
# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
# folders).
# The default value is: doc.
# This tag requires that the tag GENERATE_QHP is set to YES.

QHP_VIRTUAL_FOLDER     = doc

# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
# filter to add. For more information please see Qt Help Project / Custom
# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
# filters).
# This tag requires that the tag GENERATE_QHP is set to YES.

QHP_CUST_FILTER_NAME   =

# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
# custom filter to add. For more information please see Qt Help Project / Custom
# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
# filters).
# This tag requires that the tag GENERATE_QHP is set to YES.

QHP_CUST_FILTER_ATTRS  =

# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
# project's filter section matches. Qt Help Project / Filter Attributes (see:
# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
# This tag requires that the tag GENERATE_QHP is set to YES.

QHP_SECT_FILTER_ATTRS  =

# The QHG_LOCATION tag can be used to specify the location of Qt's
# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
# generated .qhp file.
# This tag requires that the tag GENERATE_QHP is set to YES.

QHG_LOCATION           =

# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
# generated, together with the HTML files, they form an Eclipse help plugin. To
# install this plugin and make it available under the help contents menu in
# Eclipse, the contents of the directory containing the HTML and XML files needs
# to be copied into the plugins directory of eclipse. The name of the directory
# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
# After copying Eclipse needs to be restarted before the help appears.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.

GENERATE_ECLIPSEHELP   = NO

# A unique identifier for the Eclipse help plugin. When installing the plugin
# the directory name containing the HTML and XML files should also have this
# name. Each documentation set should have its own identifier.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.

ECLIPSE_DOC_ID         = org.doxygen.Project

# If you want full control over the layout of the generated HTML pages it might
# be necessary to disable the index and replace it with your own. The
# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
# of each HTML page. A value of NO enables the index and the value YES disables
# it. Since the tabs in the index contain the same information as the navigation
# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.

DISABLE_INDEX          = NO

# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
# structure should be generated to display hierarchical information. If the tag
# value is set to YES, a side panel will be generated containing a tree-like
# index structure (just like the one that is generated for HTML Help). For this
# to work a browser that supports JavaScript, DHTML, CSS and frames is required
# (i.e. any modern browser). Windows users are probably better off using the
# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can
# further fine-tune the look of the index. As an example, the default style
# sheet generated by doxygen has an example that shows how to put an image at
# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
# the same information as the tab index, you could consider setting
# DISABLE_INDEX to YES when enabling this option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.

GENERATE_TREEVIEW      = NO

# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
# doxygen will group on one line in the generated HTML documentation.
#
# Note that a value of 0 will completely suppress the enum values from appearing
# in the overview section.
# Minimum value: 0, maximum value: 20, default value: 4.
# This tag requires that the tag GENERATE_HTML is set to YES.

ENUM_VALUES_PER_LINE   = 4

# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
# to set the initial width (in pixels) of the frame in which the tree is shown.
# Minimum value: 0, maximum value: 1500, default value: 250.
# This tag requires that the tag GENERATE_HTML is set to YES.

TREEVIEW_WIDTH         = 250

# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
# external symbols imported via tag files in a separate window.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.

EXT_LINKS_IN_WINDOW    = NO

# Use this tag to change the font size of LaTeX formulas included as images in
# the HTML documentation. When you change the font size after a successful
# doxygen run you need to manually remove any form_*.png images from the HTML
# output directory to force them to be regenerated.
# Minimum value: 8, maximum value: 50, default value: 10.
# This tag requires that the tag GENERATE_HTML is set to YES.

FORMULA_FONTSIZE       = 10

# Use the FORMULA_TRANPARENT tag to determine whether or not the images
# generated for formulas are transparent PNGs. Transparent PNGs are not
# supported properly for IE 6.0, but are supported on all modern browsers.
#
# Note that when changing this option you need to delete any form_*.png files in
# the HTML output directory before the changes have effect.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.

FORMULA_TRANSPARENT    = YES

# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
# http://www.mathjax.org) which uses client side Javascript for the rendering
# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX
# installed or if you want to formulas look prettier in the HTML output. When
# enabled you may also need to install MathJax separately and configure the path
# to it using the MATHJAX_RELPATH option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.

USE_MATHJAX            = NO

# When MathJax is enabled you can set the default output format to be used for
# the MathJax output. See the MathJax site (see:
# http://docs.mathjax.org/en/latest/output.html) for more details.
# Possible values are: HTML-CSS (which is slower, but has the best
# compatibility), NativeMML (i.e. MathML) and SVG.
# The default value is: HTML-CSS.
# This tag requires that the tag USE_MATHJAX is set to YES.

MATHJAX_FORMAT         = HTML-CSS

# When MathJax is enabled you need to specify the location relative to the HTML
# output directory using the MATHJAX_RELPATH option. The destination directory
# should contain the MathJax.js script. For instance, if the mathjax directory
# is located at the same level as the HTML output directory, then
# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
# Content Delivery Network so you can quickly see the result without installing
# MathJax. However, it is strongly recommended to install a local copy of
# MathJax from http://www.mathjax.org before deployment.
# The default value is: http://cdn.mathjax.org/mathjax/latest.
# This tag requires that the tag USE_MATHJAX is set to YES.

MATHJAX_RELPATH        = http://www.mathjax.org/mathjax

# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
# extension names that should be enabled during MathJax rendering. For example
# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
# This tag requires that the tag USE_MATHJAX is set to YES.

MATHJAX_EXTENSIONS     =

# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
# of code that will be used on startup of the MathJax code. See the MathJax site
# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
# example see the documentation.
# This tag requires that the tag USE_MATHJAX is set to YES.

MATHJAX_CODEFILE       =

# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
# the HTML output. The underlying search engine uses javascript and DHTML and
# should work on any modern browser. Note that when using HTML help
# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
# there is already a search function so this one should typically be disabled.
# For large projects the javascript based search engine can be slow, then
# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
# search using the keyboard; to jump to the search box use <access key> + S
# (what the <access key> is depends on the OS and browser, but it is typically
# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
# key> to jump into the search results window, the results can be navigated
# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
# the search. The filter options can be selected when the cursor is inside the
# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
# to select a filter and <Enter> or <escape> to activate or cancel the filter
# option.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.

SEARCHENGINE           = NO

# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
# implemented using a web server instead of a web client using Javascript. There
# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
# setting. When disabled, doxygen will generate a PHP script for searching and
# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
# and searching needs to be provided by external tools. See the section
# "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.

SERVER_BASED_SEARCH    = NO

# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
# script for searching. Instead the search results are written to an XML file
# which needs to be processed by an external indexer. Doxygen will invoke an
# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
# search results.
#
# Doxygen ships with an example indexer (doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see: http://xapian.org/).
#
# See the section "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.

EXTERNAL_SEARCH        = NO

# The SEARCHENGINE_URL should point to a search engine hosted by a web server
# which will return the search results when EXTERNAL_SEARCH is enabled.
#
# Doxygen ships with an example indexer (doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see: http://xapian.org/). See the section "External Indexing and
# Searching" for details.
# This tag requires that the tag SEARCHENGINE is set to YES.

SEARCHENGINE_URL       =

# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
# search data is written to a file for indexing by an external tool. With the
# SEARCHDATA_FILE tag the name of this file can be specified.
# The default file is: searchdata.xml.
# This tag requires that the tag SEARCHENGINE is set to YES.

SEARCHDATA_FILE        = searchdata.xml

# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
# projects and redirect the results back to the right project.
# This tag requires that the tag SEARCHENGINE is set to YES.

EXTERNAL_SEARCH_ID     =

# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
# projects other than the one defined by this configuration file, but that are
# all added to the same external search index. Each project needs to have a
# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
# to a relative location where the documentation can be found. The format is:
# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
# This tag requires that the tag SEARCHENGINE is set to YES.

EXTRA_SEARCH_MAPPINGS  =

#---------------------------------------------------------------------------
# Configuration options related to the LaTeX output
#---------------------------------------------------------------------------

# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
# The default value is: YES.

GENERATE_LATEX         = NO

# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: latex.
# This tag requires that the tag GENERATE_LATEX is set to YES.

LATEX_OUTPUT           = latex

# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
# invoked.
#
# Note that when enabling USE_PDFLATEX this option is only used for generating
# bitmaps for formulas in the HTML output, but not in the Makefile that is
# written to the output directory.
# The default file is: latex.
# This tag requires that the tag GENERATE_LATEX is set to YES.

LATEX_CMD_NAME         = latex

# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
# index for LaTeX.
# The default file is: makeindex.
# This tag requires that the tag GENERATE_LATEX is set to YES.

MAKEINDEX_CMD_NAME     = makeindex

# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.

COMPACT_LATEX          = NO

# The PAPER_TYPE tag can be used to set the paper type that is used by the
# printer.
# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
# 14 inches) and executive (7.25 x 10.5 inches).
# The default value is: a4.
# This tag requires that the tag GENERATE_LATEX is set to YES.

PAPER_TYPE             = a4wide

# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
# that should be included in the LaTeX output. The package can be specified just
# by its name or with the correct syntax as to be used with the LaTeX
# \usepackage command. To get the times font for instance you can specify :
# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}
# To use the option intlimits with the amsmath package you can specify:
# EXTRA_PACKAGES=[intlimits]{amsmath}
# If left blank no extra packages will be included.
# This tag requires that the tag GENERATE_LATEX is set to YES.

EXTRA_PACKAGES         =

# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
# generated LaTeX document. The header should contain everything until the first
# chapter. If it is left blank doxygen will generate a standard header. See
# section "Doxygen usage" for information on how to let doxygen write the
# default header to a separate file.
#
# Note: Only use a user-defined header if you know what you are doing! The
# following commands have a special meaning inside the header: $title,
# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
# $projectbrief, $projectlogo. Doxygen will replace $title with the empty
# string, for the replacement values of the other commands the user is referred
# to HTML_HEADER.
# This tag requires that the tag GENERATE_LATEX is set to YES.

LATEX_HEADER           =

# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
# generated LaTeX document. The footer should contain everything after the last
# chapter. If it is left blank doxygen will generate a standard footer. See
# LATEX_HEADER for more information on how to generate a default footer and what
# special commands can be used inside the footer.
#
# Note: Only use a user-defined footer if you know what you are doing!
# This tag requires that the tag GENERATE_LATEX is set to YES.

LATEX_FOOTER           =

# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
# LaTeX style sheets that are included after the standard style sheets created
# by doxygen. Using this option one can overrule certain style aspects. Doxygen
# will copy the style sheet files to the output directory.
# Note: The order of the extra style sheet files is of importance (e.g. the last
# style sheet in the list overrules the setting of the previous ones in the
# list).
# This tag requires that the tag GENERATE_LATEX is set to YES.

LATEX_EXTRA_STYLESHEET =

# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the LATEX_OUTPUT output
# directory. Note that the files will be copied as-is; there are no commands or
# markers available.
# This tag requires that the tag GENERATE_LATEX is set to YES.

LATEX_EXTRA_FILES      =

# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
# contain links (just like the HTML output) instead of page references. This
# makes the output suitable for online browsing using a PDF viewer.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.

PDF_HYPERLINKS         = NO

# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
# the PDF file directly from the LaTeX files. Set this option to YES, to get a
# higher quality PDF documentation.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.

USE_PDFLATEX           = NO

# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
# command to the generated LaTeX files. This will instruct LaTeX to keep running
# if errors occur, instead of asking the user for help. This option is also used
# when generating formulas in HTML.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.

LATEX_BATCHMODE        = NO

# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
# index chapters (such as File Index, Compound Index, etc.) in the output.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.

LATEX_HIDE_INDICES     = NO

# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
# code with syntax highlighting in the LaTeX output.
#
# Note that which sources are shown also depends on other settings such as
# SOURCE_BROWSER.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.

LATEX_SOURCE_CODE      = NO

# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
# bibliography, e.g. plainnat, or ieeetr. See
# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
# The default value is: plain.
# This tag requires that the tag GENERATE_LATEX is set to YES.

LATEX_BIB_STYLE        = plain

# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated
# page will contain the date and time when the page was generated. Setting this
# to NO can help when comparing the output of multiple runs.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.

LATEX_TIMESTAMP        = NO

#---------------------------------------------------------------------------
# Configuration options related to the RTF output
#---------------------------------------------------------------------------

# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The
# RTF output is optimized for Word 97 and may not look too pretty with other RTF
# readers/editors.
# The default value is: NO.

GENERATE_RTF           = NO

# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: rtf.
# This tag requires that the tag GENERATE_RTF is set to YES.

RTF_OUTPUT             = rtf

# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.

COMPACT_RTF            = NO

# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
# contain hyperlink fields. The RTF file will contain links (just like the HTML
# output) instead of page references. This makes the output suitable for online
# browsing using Word or some other Word compatible readers that support those
# fields.
#
# Note: WordPad (write) and others do not support links.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.

RTF_HYPERLINKS         = NO

# Load stylesheet definitions from file. Syntax is similar to doxygen's config
# file, i.e. a series of assignments. You only have to provide replacements,
# missing definitions are set to their default value.
#
# See also section "Doxygen usage" for information on how to generate the
# default style sheet that doxygen normally uses.
# This tag requires that the tag GENERATE_RTF is set to YES.

RTF_STYLESHEET_FILE    =

# Set optional variables used in the generation of an RTF document. Syntax is
# similar to doxygen's config file. A template extensions file can be generated
# using doxygen -e rtf extensionFile.
# This tag requires that the tag GENERATE_RTF is set to YES.

RTF_EXTENSIONS_FILE    =

# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code
# with syntax highlighting in the RTF output.
#
# Note that which sources are shown also depends on other settings such as
# SOURCE_BROWSER.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.

RTF_SOURCE_CODE        = NO

#---------------------------------------------------------------------------
# Configuration options related to the man page output
#---------------------------------------------------------------------------

# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for
# classes and files.
# The default value is: NO.

GENERATE_MAN           = YES

# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it. A directory man3 will be created inside the directory specified by
# MAN_OUTPUT.
# The default directory is: man.
# This tag requires that the tag GENERATE_MAN is set to YES.

MAN_OUTPUT             = man

# The MAN_EXTENSION tag determines the extension that is added to the generated
# man pages. In case the manual section does not start with a number, the number
# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
# optional.
# The default value is: .3.
# This tag requires that the tag GENERATE_MAN is set to YES.

MAN_EXTENSION          = .3

# The MAN_SUBDIR tag determines the name of the directory created within
# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
# MAN_EXTENSION with the initial . removed.
# This tag requires that the tag GENERATE_MAN is set to YES.

MAN_SUBDIR             =

# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
# will generate one additional man file for each entity documented in the real
# man page(s). These additional files only source the real man page, but without
# them the man command would be unable to find the correct page.
# The default value is: NO.
# This tag requires that the tag GENERATE_MAN is set to YES.

MAN_LINKS              = NO

#---------------------------------------------------------------------------
# Configuration options related to the XML output
#---------------------------------------------------------------------------

# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that
# captures the structure of the code including all documentation.
# The default value is: NO.

GENERATE_XML           = NO

# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: xml.
# This tag requires that the tag GENERATE_XML is set to YES.

XML_OUTPUT             = xml

# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program
# listings (including syntax highlighting and cross-referencing information) to
# the XML output. Note that enabling this will significantly increase the size
# of the XML output.
# The default value is: YES.
# This tag requires that the tag GENERATE_XML is set to YES.

XML_PROGRAMLISTING     = YES

#---------------------------------------------------------------------------
# Configuration options related to the DOCBOOK output
#---------------------------------------------------------------------------

# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files
# that can be used to generate PDF.
# The default value is: NO.

GENERATE_DOCBOOK       = NO

# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
# front of it.
# The default directory is: docbook.
# This tag requires that the tag GENERATE_DOCBOOK is set to YES.

DOCBOOK_OUTPUT         = docbook

# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the
# program listings (including syntax highlighting and cross-referencing
# information) to the DOCBOOK output. Note that enabling this will significantly
# increase the size of the DOCBOOK output.
# The default value is: NO.
# This tag requires that the tag GENERATE_DOCBOOK is set to YES.

DOCBOOK_PROGRAMLISTING = NO

#---------------------------------------------------------------------------
# Configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------

# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
# AutoGen Definitions (see http://autogen.sf.net) file that captures the
# structure of the code including all documentation. Note that this feature is
# still experimental and incomplete at the moment.
# The default value is: NO.

GENERATE_AUTOGEN_DEF   = NO

#---------------------------------------------------------------------------
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------

# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module
# file that captures the structure of the code including all documentation.
#
# Note that this feature is still experimental and incomplete at the moment.
# The default value is: NO.

GENERATE_PERLMOD       = NO

# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary
# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
# output from the Perl module output.
# The default value is: NO.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.

PERLMOD_LATEX          = NO

# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely
# formatted so it can be parsed by a human reader. This is useful if you want to
# understand what is going on. On the other hand, if this tag is set to NO, the
# size of the Perl module output will be much smaller and Perl will parse it
# just the same.
# The default value is: YES.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.

PERLMOD_PRETTY         = YES

# The names of the make variables in the generated doxyrules.make file are
# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
# so different doxyrules.make files included by the same Makefile don't
# overwrite each other's variables.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.

PERLMOD_MAKEVAR_PREFIX =

#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------

# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all
# C-preprocessor directives found in the sources and include files.
# The default value is: YES.

ENABLE_PREPROCESSING   = YES

# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
# in the source code. If set to NO, only conditional compilation will be
# performed. Macro expansion can be done in a controlled way by setting
# EXPAND_ONLY_PREDEF to YES.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

MACRO_EXPANSION        = YES

# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
# the macro expansion is limited to the macros specified with the PREDEFINED and
# EXPAND_AS_DEFINED tags.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

EXPAND_ONLY_PREDEF     = YES

# If the SEARCH_INCLUDES tag is set to YES, the include files in the
# INCLUDE_PATH will be searched if a #include is found.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

SEARCH_INCLUDES        = YES

# The INCLUDE_PATH tag can be used to specify one or more directories that
# contain include files that are not input files but should be processed by the
# preprocessor.
# This tag requires that the tag SEARCH_INCLUDES is set to YES.

INCLUDE_PATH           =

# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
# patterns (like *.h and *.hpp) to filter out the header-files in the
# directories. If left blank, the patterns specified with FILE_PATTERNS will be
# used.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

INCLUDE_FILE_PATTERNS  =

# The PREDEFINED tag can be used to specify one or more macro names that are
# defined before the preprocessor is started (similar to the -D option of e.g.
# gcc). The argument of the tag is a list of macros of the form: name or
# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
# is assumed. To prevent a macro definition from being undefined via #undef or
# recursively expanded use the := operator instead of the = operator.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

PREDEFINED             = LIBFTDI_LINUX_ASYNC_MODE=

# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
# tag can be used to specify a list of macro names that should be expanded. The
# macro definition that is found in the sources will be used. Use the PREDEFINED
# tag if you want to use a different macro definition that overrules the
# definition found in the source code.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

EXPAND_AS_DEFINED      =

# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
# remove all references to function-like macros that are alone on a line, have
# an all uppercase name, and do not end with a semicolon. Such function macros
# are typically used for boiler-plate code, and will confuse the parser if not
# removed.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

SKIP_FUNCTION_MACROS   = YES

#---------------------------------------------------------------------------
# Configuration options related to external references
#---------------------------------------------------------------------------

# The TAGFILES tag can be used to specify one or more tag files. For each tag
# file the location of the external documentation should be added. The format of
# a tag file without this location is as follows:
# TAGFILES = file1 file2 ...
# Adding location for the tag files is done as follows:
# TAGFILES = file1=loc1 "file2 = loc2" ...
# where loc1 and loc2 can be relative or absolute paths or URLs. See the
# section "Linking to external documentation" for more information about the use
# of tag files.
# Note: Each tag file must have a unique name (where the name does NOT include
# the path). If a tag file is not located in the directory in which doxygen is
# run, you must also specify the path to the tagfile here.

TAGFILES               =

# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
# tag file that is based on the input files it reads. See section "Linking to
# external documentation" for more information about the usage of tag files.

GENERATE_TAGFILE       =

# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
# the class index. If set to NO, only the inherited external classes will be
# listed.
# The default value is: NO.

ALLEXTERNALS           = NO

# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed
# in the modules index. If set to NO, only the current project's groups will be
# listed.
# The default value is: YES.

EXTERNAL_GROUPS        = YES

# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in
# the related pages index. If set to NO, only the current project's pages will
# be listed.
# The default value is: YES.

EXTERNAL_PAGES         = YES

# The PERL_PATH should be the absolute path and name of the perl script
# interpreter (i.e. the result of 'which perl').
# The default file (with absolute path) is: /usr/bin/perl.

PERL_PATH              = /usr/bin/perl

#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------

# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram
# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
# NO turns the diagrams off. Note that this option also works with HAVE_DOT
# disabled, but it is recommended to install and use dot, since it yields more
# powerful graphs.
# The default value is: YES.

CLASS_DIAGRAMS         = YES

# You can define message sequence charts within doxygen comments using the \msc
# command. Doxygen will then run the mscgen tool (see:
# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
# documentation. The MSCGEN_PATH tag allows you to specify the directory where
# the mscgen tool resides. If left empty the tool is assumed to be found in the
# default search path.

MSCGEN_PATH            =

# You can include diagrams made with dia in doxygen documentation. Doxygen will
# then run dia to produce the diagram and insert it in the documentation. The
# DIA_PATH tag allows you to specify the directory where the dia binary resides.
# If left empty dia is assumed to be found in the default search path.

DIA_PATH               =

# If set to YES the inheritance and collaboration graphs will hide inheritance
# and usage relations if the target is undocumented or is not a class.
# The default value is: YES.

HIDE_UNDOC_RELATIONS   = YES

# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
# available from the path. This tool is part of Graphviz (see:
# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
# Bell Labs. The other options in this section have no effect if this option is
# set to NO
# The default value is: NO.

HAVE_DOT               = NO

# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
# to run in parallel. When set to 0 doxygen will base this on the number of
# processors available in the system. You can set it explicitly to a value
# larger than 0 to get control over the balance between CPU load and processing
# speed.
# Minimum value: 0, maximum value: 32, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.

DOT_NUM_THREADS        = 0

# When you want a differently looking font in the dot files that doxygen
# generates you can specify the font name using DOT_FONTNAME. You need to make
# sure dot is able to find the font, which can be done by putting it in a
# standard location or by setting the DOTFONTPATH environment variable or by
# setting DOT_FONTPATH to the directory containing the font.
# The default value is: Helvetica.
# This tag requires that the tag HAVE_DOT is set to YES.

DOT_FONTNAME           = Helvetica

# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
# dot graphs.
# Minimum value: 4, maximum value: 24, default value: 10.
# This tag requires that the tag HAVE_DOT is set to YES.

DOT_FONTSIZE           = 10

# By default doxygen will tell dot to use the default font as specified with
# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
# the path where dot can find it using this tag.
# This tag requires that the tag HAVE_DOT is set to YES.

DOT_FONTPATH           =

# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
# each documented class showing the direct and indirect inheritance relations.
# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.

CLASS_GRAPH            = YES

# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
# graph for each documented class showing the direct and indirect implementation
# dependencies (inheritance, containment, and class references variables) of the
# class with other documented classes.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.

COLLABORATION_GRAPH    = YES

# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
# groups, showing the direct groups dependencies.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.

GROUP_GRAPHS           = YES

# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and
# collaboration diagrams in a style similar to the OMG's Unified Modeling
# Language.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.

UML_LOOK               = NO

# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
# class node. If there are many fields or methods and many nodes the graph may
# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
# number of items for each type to make the size more manageable. Set this to 0
# for no limit. Note that the threshold may be exceeded by 50% before the limit
# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
# but if the number exceeds 15, the total amount of fields shown is limited to
# 10.
# Minimum value: 0, maximum value: 100, default value: 10.
# This tag requires that the tag HAVE_DOT is set to YES.

UML_LIMIT_NUM_FIELDS   = 10

# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
# collaboration graphs will show the relations between templates and their
# instances.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.

TEMPLATE_RELATIONS     = NO

# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
# YES then doxygen will generate a graph for each documented file showing the
# direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.

INCLUDE_GRAPH          = YES

# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
# set to YES then doxygen will generate a graph for each documented file showing
# the direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.

INCLUDED_BY_GRAPH      = YES

# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable call graphs for selected
# functions only using the \callgraph command. Disabling a call graph can be
# accomplished by means of the command \hidecallgraph.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.

CALL_GRAPH             = NO

# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable caller graphs for selected
# functions only using the \callergraph command. Disabling a caller graph can be
# accomplished by means of the command \hidecallergraph.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.

CALLER_GRAPH           = NO

# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
# hierarchy of all classes instead of a textual one.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.

GRAPHICAL_HIERARCHY    = YES

# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
# dependencies a directory has on other directories in a graphical way. The
# dependency relations are determined by the #include relations between the
# files in the directories.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.

DIRECTORY_GRAPH        = YES

# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
# generated by dot. For an explanation of the image formats see the section
# output formats in the documentation of the dot tool (Graphviz (see:
# http://www.graphviz.org/)).
# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
# to make the SVG files visible in IE 9+ (other browsers do not have this
# requirement).
# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo,
# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and
# png:gdiplus:gdiplus.
# The default value is: png.
# This tag requires that the tag HAVE_DOT is set to YES.

DOT_IMAGE_FORMAT       = png

# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
# enable generation of interactive SVG images that allow zooming and panning.
#
# Note that this requires a modern browser other than Internet Explorer. Tested
# and working are Firefox, Chrome, Safari, and Opera.
# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
# the SVG files visible. Older versions of IE do not have SVG support.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.

INTERACTIVE_SVG        = NO

# The DOT_PATH tag can be used to specify the path where the dot tool can be
# found. If left blank, it is assumed the dot tool can be found in the path.
# This tag requires that the tag HAVE_DOT is set to YES.

DOT_PATH               =

# The DOTFILE_DIRS tag can be used to specify one or more directories that
# contain dot files that are included in the documentation (see the \dotfile
# command).
# This tag requires that the tag HAVE_DOT is set to YES.

DOTFILE_DIRS           =

# The MSCFILE_DIRS tag can be used to specify one or more directories that
# contain msc files that are included in the documentation (see the \mscfile
# command).

MSCFILE_DIRS           =

# The DIAFILE_DIRS tag can be used to specify one or more directories that
# contain dia files that are included in the documentation (see the \diafile
# command).

DIAFILE_DIRS           =

# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
# path where java can find the plantuml.jar file. If left blank, it is assumed
# PlantUML is not used or called during a preprocessing step. Doxygen will
# generate a warning when it encounters a \startuml command in this case and
# will not generate output for the diagram.

PLANTUML_JAR_PATH      =

# When using plantuml, the specified paths are searched for files specified by
# the !include statement in a plantuml block.

PLANTUML_INCLUDE_PATH  =

# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
# that will be shown in the graph. If the number of nodes in a graph becomes
# larger than this value, doxygen will truncate the graph, which is visualized
# by representing a node as a red box. Note that doxygen if the number of direct
# children of the root node in a graph is already larger than
# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
# Minimum value: 0, maximum value: 10000, default value: 50.
# This tag requires that the tag HAVE_DOT is set to YES.

DOT_GRAPH_MAX_NODES    = 50

# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
# generated by dot. A depth value of 3 means that only nodes reachable from the
# root by following a path via at most 3 edges will be shown. Nodes that lay
# further from the root node will be omitted. Note that setting this option to 1
# or 2 may greatly reduce the computation time needed for large code bases. Also
# note that the size of a graph can be further restricted by
# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
# Minimum value: 0, maximum value: 1000, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.

MAX_DOT_GRAPH_DEPTH    = 0

# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
# background. This is disabled by default, because dot on Windows does not seem
# to support this out of the box.
#
# Warning: Depending on the platform used, enabling this option may lead to
# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
# read).
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.

DOT_TRANSPARENT        = NO

# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output
# files in one run (i.e. multiple -o and -T options on the command line). This
# makes dot run faster, but since only newer versions of dot (>1.8.10) support
# this, this feature is disabled by default.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.

DOT_MULTI_TARGETS      = NO

# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
# explaining the meaning of the various boxes and arrows in the dot generated
# graphs.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.

GENERATE_LEGEND        = YES

# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot
# files that are used to generate the various graphs.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.

DOT_CLEANUP            = YES
0707010000001A000081A400000000000000000000000160917B8300000282000000000000000000000000000000000000003000000000libftdi1-1.5.12+git.0684c1b/doc/Doxyfile.xml.in# Doxyfile 1.7.4

# xml generation only
# keep settings but shut off all other generation
@INCLUDE = Doxyfile

GENERATE_TODOLIST      = NO
GENERATE_TESTLIST      = NO
GENERATE_BUGLIST       = NO
GENERATE_DEPRECATEDLIST= NO
GENERATE_HTML          = NO
GENERATE_DOCSET        = NO
GENERATE_HTMLHELP      = NO
GENERATE_CHI           = NO
GENERATE_QHP           = NO
GENERATE_ECLIPSEHELP   = NO
GENERATE_TREEVIEW      = NO
GENERATE_LATEX         = NO
GENERATE_RTF           = NO
GENERATE_MAN           = NO
GENERATE_AUTOGEN_DEF   = NO
GENERATE_PERLMOD       = NO
GENERATE_TAGFILE       =
GENERATE_LEGEND        = NO

GENERATE_XML           = YES
0707010000001B000081A400000000000000000000000160917B8300001399000000000000000000000000000000000000003100000000libftdi1-1.5.12+git.0684c1b/doc/EEPROM-structureHere we try to document what we know about the EEPROM Structure.

Even with a 93xx66 EEPROM, at maximum 256 Bytes are used

All important things happen in the first
0x14(FT232/245), 0x16(FT2232CD), 0x18(FT232/245R) or 0x1a (FT2232H/4432H) bytes

Type   |  Use extra EEPROM space
FT2XXB |  No

Byte.BIT| TYPE_AM TYPE_BM   TYPE_2232C       TYPE_R          TYPE_2232H       TYPE_4232H
00.0    |      0       0   channel_a_type   232R/245R        channel_a_type   0
00.1    |      0       0   channel_a_type                    channel_a_type   0
00.2    |      0       0   channel_a_type   high_current     channel_a_type   0
00.3    |      0       0   channel_a_driver channel_a_driver channel_a_driver channel_a_driver
00.4    |      0       0   high_current_a   0                0                0
00.5    |      0       0   0                0                0                0
00.6    |      0       0   0                0                0                0
00.7    |      0       0   0                0                SUSPEND_DBUS7    channel_c_driver

On TYPE_R 00.0 is set for the FT245R and cleared for the FT232R
On TYPE_R 00.3 set means D2XX, on other devices VCP

01.0    |      0       0   channel_b_type                    channel_b_type   0
01.1    |      0       0   channel_b_type                    channel_b_type   0
01.2    |      0       0   channel_b_type   0                channel_b_type   0
01.3    |      0       0   channel_b_driver 0                channel_b_driver channel_b_driver
01.4    |      0       0   high_current_b   0                0                0
01.5    |      0       0   0                0                0                0
01.6    |      0       0   0                                 0                0
01.7    |      0       0   0                0                0                channel_d_driver

Fixme: Missing 4232H validation

02     | Vendor ID (VID) LSB (all)
03     | Vendor ID (VID) MSB (all)
04     | Product ID (PID) LSB (all)
05     | Product ID (PID) MSB (all)
06     | Device release number LSB (not tested on TYPE_4232H)
07     | Device release number MSB (not tested on TYPE_4232H)
       |
08.4   | Battery powered
08.5   | Remote wakeup
08.6   | Self powered: 1, bus powered: 0
08.7   | Always 1
       |
09     | Max power (mA/2)
       |
Byte.BIT| TYPE_AM TYPE_BM            TYPE_2232C         TYPE_R       TYPE_2232H        TYPE_4232H
0a.0    | 0       IsoIn              IsoIn part A       0            0                 0
0a.1    | 0       IsoOut             IsoOut part A      0            0                 0
0a.2    | 0       suspend_pull_down  suspend_pull_down               suspend_pull_down suspend_pull_down
0a.3    | 0       use_serial                                         use_serial        use_serial
0a.4    | 0       change_usb_version change_usb_version
0a.5    | 0       0                  IsoIn part B       0            0                 0
0a.6    | 0       0                  IsoOut part B      0            0                 0
0a.7    | 0 - reserved

0b      | TYPE_R Bitmask Invert, 0 else
Byte.BIT| TYPE_4232H
0b.4    | channel_a_rs485enable
0b.5    | channel_b_rs485enable
0b.6    | channel_c_rs485enable
0b.7    | channel_d_rs485enable

Byte   | TYPE_AM TYPE_BM     TYPE_2232C   TYPE_R       TYPE_2232H       TYPE_4232H
0c     | 0       USB-VER-LSB USB-VER-LSB  0            ?                ?
0d     | 0       USB-VER-MSB USB-VER-MSB  0            ?                ?
(On several FT2232H different values were observed -> The value is unused
 if change USB version is not set, so it might contain garbage)

0e     | OFFSET Vendor
0f     | Len    VENDOR

10     | Offset Product
11     | Length Product

12     | Offset Serial
13     | Length Serial

Byte.BIT| TYPE_AM TYPE_BM   TYPE_2232C   TYPE_R       TYPE_2232H       TYPE_4232H
14.3:0  | UA      UA        CHIP         CBUS[0]      AL               A
14.7:0  | UA      UA        CHIP         CBUS[1]      AH               B
15.3:0  | UA      UA        0            CBUS[2]      BL               C
15.7:0  | UA      UA        0            CBUS[3]      BH               D
16.3:0  | UA      UA        UA           CBUS[4]      0                0
16.7:0  | UA      UA        UA           0            0                0

CHIP values:
0x46: EEPROM is a 93xx46
0x56: EEPROM is a 93xx56
0x66: EEPROM is a 93xx66

17        UA      UA        UA           0            0                0
18        UA      UA        UA           VENDOR       CHIP             CHIP
19        UA      UA        UA           VENDOR       0                0

1a        UA (all)


Additional fields after the serial string:
0x00, 0x00 - reserved for "legacy port name prefix"
0x00, 0x00 - reserved for plug and play options
(Observed values with PnP == 0:
0x02 0x03 0x01 0x00)

Note: The additional fields after the serial number string
collide with the official FTDI formula from AN_121 regarding
the start of the user area:
"Start Address = the address following the last byte of SerialNumber string."
0707010000001C000081ED00000000000000000000000160917B83000000E8000000000000000000000000000000000000003300000000libftdi1-1.5.12+git.0684c1b/doc/astyle_reformat.sh#!/bin/sh
# Astyle settings used to format our source code
/usr/bin/astyle --indent=spaces=4 --indent-switches --brackets=break \
                --convert-tabs --keep-one-line-statements --keep-one-line-blocks \
                $*
0707010000001D000081A400000000000000000000000160917B830000035A000000000000000000000000000000000000003600000000libftdi1-1.5.12+git.0684c1b/doc/release-checklist.txt*** Checklist for a new libftdi release ***
- Update ChangeLog via git history:
  git log --oneline latest_release..HEAD

- Update AUTHORS via git history:
  git log --pretty=format:"%an <%ae>" latest_release..HEAD |sort -u

- Update version number in the following files:
  - CMakeLists.txt
  - README

- Run "make dist"

- Diff tarball to previous version, check if all
  important changes are in the ChangeLog

- Ensure all modifications are checked in

- Sign tarball:
  gpg2 --default-key opensource@intra2net.com --detach-sign --sign libftdi1-1.XX.tar.bz2

- Create git tag:
  - git tag -s -u 24F006F5 v1.XX
  - git tag -d latest_release ; git tag latest_release
  - git push --tags

- Website
  - Upload tarball
  - Add ChangeLog to main page
  - Update URLs in download section
  - Generate API documentation and upload it

- Announce on mailinglist
0707010000001E000041ED00000000000000000000000360917B8300000000000000000000000000000000000000000000002500000000libftdi1-1.5.12+git.0684c1b/examples0707010000001F000081A400000000000000000000000160917B830000058E000000000000000000000000000000000000003400000000libftdi1-1.5.12+git.0684c1b/examples/CMakeLists.txt# Includes
include_directories( ${CMAKE_CURRENT_SOURCE_DIR}
		${CMAKE_CURRENT_BINARY_DIR}
		)

# Targets
add_executable(simple simple.c)
add_executable(bitbang bitbang.c)
add_executable(bitbang2 bitbang2.c)
add_executable(bitbang_cbus bitbang_cbus.c)
add_executable(bitbang_ft2232 bitbang_ft2232.c)
add_executable(find_all find_all.c)
add_executable(serial_test serial_test.c)
add_executable(baud_test baud_test.c)
add_executable(stream_test stream_test.c)
add_executable(eeprom eeprom.c)
add_executable(async async.c)
if(NOT MINGW)
    add_executable(purge_test purge_test.c)
endif(NOT MINGW)

# Linkage
target_link_libraries(simple ftdi1)
target_link_libraries(bitbang ftdi1)
target_link_libraries(bitbang2 ftdi1)
target_link_libraries(bitbang_cbus ftdi1)
target_link_libraries(bitbang_ft2232 ftdi1)
target_link_libraries(find_all ftdi1)
target_link_libraries(serial_test ftdi1)
target_link_libraries(baud_test ftdi1)
target_link_libraries(stream_test ftdi1)
target_link_libraries(eeprom ftdi1)
target_link_libraries(async ftdi1)
if(NOT MINGW)
    target_link_libraries(purge_test ftdi1)
endif(NOT MINGW)

# libftdi++ examples
if( FTDIPP )
	include_directories(BEFORE ${CMAKE_SOURCE_DIR}/ftdipp
			${Boost_INCLUDE_DIRS})

	# Target
	add_executable(find_all_pp find_all_pp.cpp)

	# Linkage
	target_link_libraries(find_all_pp ftdipp1)
endif( FTDIPP )

# Source includes
include_directories(BEFORE ${CMAKE_SOURCE_DIR}/src)
07070100000020000081A400000000000000000000000160917B8300001556000000000000000000000000000000000000002D00000000libftdi1-1.5.12+git.0684c1b/examples/async.c/* Libftdi example for asynchronous read/write.

   This program is distributed under the GPL, version 2
*/

/* This program switches to MPSSE mode, and sets and then reads back
 * the high byte 3 times with three different values.
 * The expected read values are hard coded in ftdi_init
 * with 0x00, 0x55 and 0xaa
 *
 * Make sure that that nothing else drives some bit of the high byte
 * or expect a collision for a very short time and some differences
 * in the data read back.
 *
 * Result should be the same without any option or with either
 * -r or -w or -b.
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <getopt.h>
#include <ftdi.h>

int main(int argc, char **argv)
{
    struct ftdi_context *ftdi;
    int do_read = 0;
    int do_write = 0;
    int i, f, retval;

    if ((ftdi = ftdi_new()) == 0)
    {
        fprintf(stderr, "Failed to allocate ftdi structure :%s \n",
                ftdi_get_error_string(ftdi));
        return EXIT_FAILURE;
    }

    while ((i = getopt(argc, argv, "brw")) != -1)
    {
        switch (i)
        {
            case 'b':
                do_read = 1;
                do_write = 1;
                break;
            case 'r':
                do_read = 1;
                break;
            case 'w':
                do_write  = 1;
                break;
            default:
                fprintf(stderr, "usage: %s [options]\n", *argv);
                fprintf(stderr, "\t-b do synchronous read and write\n");
                fprintf(stderr, "\t-r do synchronous read\n");
                fprintf(stderr, "\t-w do synchronous write\n");
                retval = -1;
                goto done;
        }
    }

    /* Select first free interface */
    ftdi_set_interface(ftdi, INTERFACE_ANY);

    struct ftdi_device_list *devlist;
    int res;
    if ((res = ftdi_usb_find_all(ftdi, &devlist, 0, 0)) < 0)
    {
        fprintf(stderr, "No FTDI with default VID/PID found\n");
        retval =  EXIT_FAILURE;
        goto do_deinit;
    }
    if (res > 0)
    {
        int i = 1;
        f = ftdi_usb_open_dev(ftdi, devlist[0].dev);
        if (f < 0)
        {
            fprintf(stderr, "Unable to open device %d: (%s)",
                    i, ftdi_get_error_string(ftdi));
            retval = -1;
            goto do_deinit;
        }
    }
    else
    {
        fprintf(stderr, "No devices found\n");
        retval = -1;
        goto do_deinit;
    }
    ftdi_list_free(&devlist);
    int err = ftdi_tcioflush(ftdi);
    if (err != 0) {
        fprintf(stderr, "ftdi_tcioflush: %d: %s\n",
                err, ftdi_get_error_string(ftdi));
        retval = -1;
        goto do_deinit;
    }
    /* Reset MPSSE controller. */
    err = ftdi_set_bitmode(ftdi, 0,  BITMODE_RESET);
    if (err != 0) {
        fprintf(stderr, "ftdi_set_bitmode: %d: %s\n",
                err, ftdi_get_error_string(ftdi));
        retval = -1;
        goto do_deinit;
   }
    /* Enable MPSSE controller. Pin directions are set later.*/
    err = ftdi_set_bitmode(ftdi, 0, BITMODE_MPSSE);
    if (err != 0) {
        fprintf(stderr, "ftdi_set_bitmode: %d: %s\n",
                err, ftdi_get_error_string(ftdi));
        return -1;
    }
#define DATA_TO_READ 3
    uint8_t ftdi_init[] = {TCK_DIVISOR, 0x00, 0x00,
                             /* Set High byte to zero.*/
                             SET_BITS_HIGH, 0, 0xff,
                             GET_BITS_HIGH,
                             /* Set High byte to 0x55.*/
                             SET_BITS_HIGH, 0x55, 0xff,
                             GET_BITS_HIGH,
                             /* Set High byte to 0xaa.*/
                             SET_BITS_HIGH, 0xaa, 0xff,
                             GET_BITS_HIGH,
                             /* Set back to high impedance.*/
                             SET_BITS_HIGH, 0x00, 0x00 };
    struct ftdi_transfer_control *tc_read;
    struct ftdi_transfer_control *tc_write;
    uint8_t data[3];
    if (do_read) {
        tc_read = ftdi_read_data_submit(ftdi, data, DATA_TO_READ);
    }
    if (do_write) {
        tc_write = ftdi_write_data_submit(ftdi, ftdi_init, sizeof(ftdi_init));
        int transfer = ftdi_transfer_data_done(tc_write);
        if (transfer != sizeof(ftdi_init)) {
            printf("Async write failed : %d\n", transfer);
        }
    } else {
        int written = ftdi_write_data(ftdi, ftdi_init, sizeof(ftdi_init));
        if (written != sizeof(ftdi_init)) {
            printf("Sync write failed: %d\n", written);
        }
    }
    if (do_read) {
        int transfer = ftdi_transfer_data_done(tc_read);
        if (transfer != DATA_TO_READ) {
            printf("Async Read failed:%d\n", transfer);
        }
    } else {
        int index = 0;
        ftdi->usb_read_timeout = 1;
        int i = 1000; /* Fail if read did not succeed in 1 second.*/
        while (i--) {
            int res = ftdi_read_data(ftdi, data + index, 3 - index);
            if (res < 0) {
                printf("Async read failure at %d\n", index);
            } else {
                index += res;
            }
            if (res == 3) {
                break;
            }
        }
        if (i < 1) {
            printf("Async read unsuccessful\n");
        }
    }
    printf("Read %02x %02x %02x\n", data[0], data[1], data[2]);
done:
    ftdi_usb_close(ftdi);
do_deinit:
    ftdi_free(ftdi);
    return retval;
}
07070100000021000081A400000000000000000000000160917B830000193B000000000000000000000000000000000000003100000000libftdi1-1.5.12+git.0684c1b/examples/baud_test.c/* baud_test.c
 *
 * test setting the baudrate and compare it with the expected runtime
 *
 * options:
 *  -p <devicestring> defaults to "i:0x0403:0x6001" (this is the first FT232R with default id)
 *       d:<devicenode> path of bus and device-node (e.g. "003/001") within usb device tree (usually at /proc/bus/usb/)
 *       i:<vendor>:<product> first device with given vendor and product id,
 *                            ids can be decimal, octal (preceded by "0") or hex (preceded by "0x")
 *       i:<vendor>:<product>:<index> as above with index being the number of the device (starting with 0)
 *                            if there are more than one
 *       s:<vendor>:<product>:<serial> first device with given vendor id, product id and serial string
 *  -d <datasize to send in bytes>
 *  -b <baudrate> (divides by 16 if bitbang as taken from the ftdi datasheets)
 *  -m <mode to use> r: serial a: async bitbang s:sync bitbang
 *  -c <chunksize>
 *
 * (C) 2009 by Gerd v. Egidy <gerd.von.egidy@intra2net.com>
 *
 * 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 2 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.
 *
 */

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ftdi.h>

double get_prec_time()
{
    struct timeval tv;
    double res;

    gettimeofday(&tv,NULL);

    res=tv.tv_sec;
    res+=((double)tv.tv_usec/1000000);

    return res;
}

int main(int argc, char **argv)
{
    struct ftdi_context *ftdi;
    int i, t;
    unsigned char *txbuf;
    unsigned char *rxbuf;
    double start, duration, plan;
    int retval= 0;

    // default values
    int baud=9600;
    int set_baud;
    int datasize=100000;

    char default_devicedesc[] = "i:0x0403:0x6001";
    char *devicedesc=default_devicedesc;
    int txchunksize=256;
    enum ftdi_mpsse_mode test_mode=BITMODE_BITBANG;

    while ((t = getopt (argc, argv, "b:d:p:m:c:")) != -1)
    {
        switch (t)
        {
            case 'd':
                datasize = atoi (optarg);
                break;
            case 'm':
                switch (*optarg)
                {
                    case 'r':
                        // serial
                        test_mode=BITMODE_RESET;
                        break;
                    case 'a':
                        // async
                        test_mode=BITMODE_BITBANG;
                        break;
                    case 's':
                        // sync
                        test_mode=BITMODE_SYNCBB;
                        break;
                }
                break;
            case 'b':
                baud = atoi (optarg);
                break;
            case 'p':
                devicedesc=optarg;
                break;
            case 'c':
                txchunksize = atoi (optarg);
                break;
        }
    }

    txbuf=malloc(txchunksize);
    rxbuf=malloc(txchunksize);
    if (txbuf == NULL || rxbuf == NULL)
    {
        fprintf(stderr, "can't malloc\n");
        return EXIT_FAILURE;
    }

    if ((ftdi = ftdi_new()) == 0)
    {
        fprintf(stderr, "ftdi_new failed\n");
        retval = EXIT_FAILURE;
        goto done;
    }

    if (ftdi_usb_open_string(ftdi, devicedesc) < 0)
    {
        fprintf(stderr,"Can't open ftdi device: %s\n",ftdi_get_error_string(ftdi));
        retval = EXIT_FAILURE;
        goto do_deinit;
    }

    set_baud=baud;
    if (test_mode!=BITMODE_RESET)
    {
        // we do bitbang, so real baudrate / 16
        set_baud=baud/16;
    }

    ftdi_set_baudrate(ftdi,set_baud);
    printf("real baudrate used: %d\n",(test_mode==BITMODE_RESET) ? ftdi->baudrate : ftdi->baudrate*16);

    if (ftdi_set_bitmode(ftdi, 0xFF,test_mode) < 0)
    {
        fprintf(stderr,"Can't set mode: %s\n",ftdi_get_error_string(ftdi));
        retval = EXIT_FAILURE;
        goto do_close;
    }

    if (test_mode==BITMODE_RESET)
    {
        // serial 8N1: 8 data bits, 1 startbit, 1 stopbit
        plan=((double)(datasize*10))/baud;
    }
    else
    {
        // bitbang means 8 bits at once
        plan=((double)datasize)/baud;
    }

    printf("this test should take %.2f seconds\n",plan);

    // prepare data to send: 0 and 1 bits alternating (except for serial start/stopbit):
    // maybe someone wants to look at this with a scope or logic analyzer
    for (i=0; i<txchunksize; i++)
    {
        if (test_mode==BITMODE_RESET)
            txbuf[i]=0xAA;
        else
            txbuf[i]=(i%2) ? 0xff : 0;
    }

    if (ftdi_write_data_set_chunksize(ftdi, txchunksize) < 0 ||
            ftdi_read_data_set_chunksize(ftdi, txchunksize) < 0)
    {
        fprintf(stderr,"Can't set chunksize: %s\n",ftdi_get_error_string(ftdi));
        retval = EXIT_FAILURE;
        goto do_close;
    }

    if (test_mode==BITMODE_SYNCBB)
    {
        // completely clear the receive buffer before beginning
        while (ftdi_read_data(ftdi, rxbuf, txchunksize)>0);
    }

    start=get_prec_time();

    // don't wait for more data to arrive, take what we get and keep on sending
    // yes, we really would like to have libusb 1.0+ with async read/write...
    ftdi->usb_read_timeout=1;

    i=0;
    while (i < datasize)
    {
        int sendsize=txchunksize;
        if (i+sendsize > datasize)
            sendsize=datasize-i;

        if ((sendsize=ftdi_write_data(ftdi, txbuf, sendsize)) < 0)
        {
            fprintf(stderr,"write failed at %d: %s\n",
                    i, ftdi_get_error_string(ftdi));
            retval = EXIT_FAILURE;
            goto do_close;
        }

        i+=sendsize;

        if (test_mode==BITMODE_SYNCBB)
        {
            // read the same amount of data as sent
            ftdi_read_data(ftdi, rxbuf, sendsize);
        }
    }

    duration=get_prec_time()-start;
    printf("and took %.4f seconds, this is %.0f baud or factor %.3f\n",duration,(plan*baud)/duration,plan/duration);
do_close:
    ftdi_usb_close(ftdi);
do_deinit:
    ftdi_free(ftdi);
done:
    if(rxbuf)
        free(rxbuf);
    if(txbuf)
        free(txbuf);
    exit (retval);
}
07070100000022000081A400000000000000000000000160917B8300000763000000000000000000000000000000000000002F00000000libftdi1-1.5.12+git.0684c1b/examples/bitbang.c/* This program is distributed under the GPL, version 2 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ftdi.h>

int main(int argc, char **argv)
{
    struct ftdi_context *ftdi;
    int f,i;
    unsigned char buf[1];
    int retval = 0;

    if ((ftdi = ftdi_new()) == 0)
    {
        fprintf(stderr, "ftdi_new failed\n");
        return EXIT_FAILURE;
    }

    f = ftdi_usb_open(ftdi, 0x0403, 0x6001);

    if (f < 0 && f != -5)
    {
        fprintf(stderr, "unable to open ftdi device: %d (%s)\n", f, ftdi_get_error_string(ftdi));
        retval = 1;
        goto done;
    }

    printf("ftdi open succeeded: %d\n",f);

    printf("enabling bitbang mode\n");
    ftdi_set_bitmode(ftdi, 0xFF, BITMODE_BITBANG);

    usleep(3 * 1000000);

    buf[0] = 0x0;
    printf("turning everything on\n");
    f = ftdi_write_data(ftdi, buf, 1);
    if (f < 0)
    {
        fprintf(stderr,"write failed for 0x%x, error %d (%s)\n",buf[0],f, ftdi_get_error_string(ftdi));
    }

    usleep(3 * 1000000);

    buf[0] = 0xFF;
    printf("turning everything off\n");
    f = ftdi_write_data(ftdi, buf, 1);
    if (f < 0)
    {
        fprintf(stderr,"write failed for 0x%x, error %d (%s)\n",buf[0],f, ftdi_get_error_string(ftdi));
    }

    usleep(3 * 1000000);

    for (i = 0; i < 32; i++)
    {
        buf[0] =  0 | (0xFF ^ 1 << (i % 8));
        if ( i > 0 && (i % 8) == 0)
        {
            printf("\n");
        }
        printf("%02hhx ",buf[0]);
        fflush(stdout);
        f = ftdi_write_data(ftdi, buf, 1);
        if (f < 0)
        {
            fprintf(stderr,"write failed for 0x%x, error %d (%s)\n",buf[0],f, ftdi_get_error_string(ftdi));
        }
        usleep(1 * 1000000);
    }

    printf("\n");

    printf("disabling bitbang mode\n");
    ftdi_disable_bitbang(ftdi);

    ftdi_usb_close(ftdi);
done:
    ftdi_free(ftdi);

    return retval;
}
07070100000023000081A400000000000000000000000160917B83000008DD000000000000000000000000000000000000003000000000libftdi1-1.5.12+git.0684c1b/examples/bitbang2.c/* ftdi_out.c
 *
 * Output a (stream of) byte(s) in bitbang mode to the
 * ftdi245 chip that is (hopefully) attached.
 *
 * We have a little board that has a FT245BM chip and
 * the 8 outputs are connected to several different
 * things that we can turn on and off with this program.
 *
 * If you have an idea about hardware that can easily
 * interface onto an FTDI chip, I'd like to collect
 * ideas. If I find it worthwhile to make, I'll consider
 * making it, I'll even send you a prototype (against
 * cost-of-material) if you want.
 *
 * At "harddisk-recovery.nl" they have a little board that
 * controls the power to two harddrives and two fans.
 *
 * -- REW R.E.Wolff@BitWizard.nl
 *
 *
 *
 * This program was based on libftdi_example_bitbang2232.c
 * which doesn't carry an author or attribution header.
 *
 *
 * This program is distributed under the GPL, version 2.
 * Millions copies of the GPL float around the internet.
 */


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ftdi.h>

void ftdi_fatal (struct ftdi_context *ftdi, char *str)
{
    fprintf (stderr, "%s: %s\n",
             str, ftdi_get_error_string (ftdi));
    ftdi_free(ftdi);
    exit (1);
}

int main(int argc, char **argv)
{
    struct ftdi_context *ftdi;
    int i, t;
    unsigned char data;
    int delay = 100000; /* 100 thousand microseconds: 1 tenth of a second */

    while ((t = getopt (argc, argv, "d:")) != -1)
    {
        switch (t)
        {
            case 'd':
                delay = atoi (optarg);
                break;
        }
    }

    if ((ftdi = ftdi_new()) == 0)
    {
        fprintf(stderr, "ftdi_bew failed\n");
        return EXIT_FAILURE;
    }

    if (ftdi_usb_open(ftdi, 0x0403, 0x6001) < 0)
        ftdi_fatal (ftdi, "Can't open ftdi device");

    if (ftdi_set_bitmode(ftdi, 0xFF, BITMODE_BITBANG) < 0)
        ftdi_fatal (ftdi, "Can't enable bitbang");

    for (i=optind; i < argc ; i++)
    {
        sscanf (argv[i], "%x", &t);
        data = t;
        if (ftdi_write_data(ftdi, &data, 1) < 0)
        {
            fprintf(stderr,"write failed for 0x%x: %s\n",
                    data, ftdi_get_error_string(ftdi));
        }
        usleep(delay);
    }

    ftdi_usb_close(ftdi);
    ftdi_free(ftdi);
    exit (0);
}
07070100000024000081A400000000000000000000000160917B8300000A57000000000000000000000000000000000000003400000000libftdi1-1.5.12+git.0684c1b/examples/bitbang_cbus.c/*  bitbang_cbus.c

    Example to use CBUS bitbang mode of newer chipsets.
    You must enable CBUS bitbang mode in the EEPROM first.

    Thanks to Steve Brown <sbrown@ewol.com> for the
    the information how to do it.

    The top nibble controls input/output and the bottom nibble
    controls the state of the lines set to output. The datasheet isn't clear
    what happens if you set a bit in the output register when that line is
    conditioned for input. This is described in more detail
    in the FT232R bitbang app note.

    BITMASK
    CBUS Bits
    3210 3210
    xxxx xxxx
    |    |------ Output Control 0->LO, 1->HI
    |----------- Input/Output   0->Input, 1->Output

    Example:
    All pins to output with 0 bit high: 0xF1 (11110001)
    Bits 0 and 1 to input, 2 and 3 to output and masked high: 0xCC (11001100)

    The input is standard "0x" hex notation.
    A carriage return terminates the program.

    This program is distributed under the GPL, version 2
*/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <ftdi.h>

int main(void)
{
    struct ftdi_context *ftdi;
    int f;
    unsigned char buf[1];
    unsigned char bitmask;
    char input[10];

    if ((ftdi = ftdi_new()) == 0)
    {
        fprintf(stderr, "ftdi_new failed\n");
        return EXIT_FAILURE;
    }

    f = ftdi_usb_open(ftdi, 0x0403, 0x6001);
    if (f < 0 && f != -5)
    {
        fprintf(stderr, "unable to open ftdi device: %d (%s)\n", f, ftdi_get_error_string(ftdi));
        ftdi_free(ftdi);
        exit(-1);
    }
    printf("ftdi open succeeded: %d\n",f);

    while (1)
    {
        // Set bitmask from input
        char *s = fgets(input, sizeof(input) - 1, stdin);
        if (s == NULL || input[0] == '\n')
            break;
        bitmask = strtol(input, NULL, 0);
        printf("Using bitmask 0x%02x\n", bitmask);
        f = ftdi_set_bitmode(ftdi, bitmask, BITMODE_CBUS);
        if (f < 0)
        {
            fprintf(stderr, "set_bitmode failed for 0x%x, error %d (%s)\n", bitmask, f, ftdi_get_error_string(ftdi));
            ftdi_usb_close(ftdi);
            ftdi_free(ftdi);
            exit(-1);
        }

        // read CBUS
        f = ftdi_read_pins(ftdi, &buf[0]);
        if (f < 0)
        {
            fprintf(stderr, "read_pins failed, error %d (%s)\n", f, ftdi_get_error_string(ftdi));
            ftdi_usb_close(ftdi);
            ftdi_free(ftdi);
            exit(-1);
        }
        printf("Read returned 0x%01x\n", buf[0] & 0x0f);
    }
    printf("disabling bitbang mode\n");
    ftdi_disable_bitbang(ftdi);

    ftdi_usb_close(ftdi);
    ftdi_free(ftdi);

    return 0;
}
07070100000025000081A400000000000000000000000160917B83000004BC000000000000000000000000000000000000004900000000libftdi1-1.5.12+git.0684c1b/examples/bitbang_cbus_eeprom_for_windows.ept[Basic Details]
Device Type=6
VID PID Type=0
USB VID=0403
USB PID=6001
[USB Power Options]
Bus Powered=1
Self Powered=0
Max Bus Power=44
[USB Serial Number Control]
Prefix=FT
Use Fixed Serial Number=0
Fixed Serial Number=FTDECZJT
[USB Remote WakeUp]
Enable Remote WakeUp=1
[Windows Plug and Play]
Enable Plug and Play=0
[USB String Descriptors]
Manufacturer=FTDI
Product=USB Serial Converter
[Programming Options]
Only Program Blank Devices=0
[BM Device Specific Options]
USB Version Number=1
Disable Serial Number=0
IO Pin Pull Down in Suspend=0
[Dual Device Specific Options A]
RS 232 mode=1
245 FIFO mode=0
245 CPU FIFO mode=0
OPTO Isolate mode=1
High Current Drive=0
[Dual Device Specific Options B]
RS 232 mode=1
245 FIFO mode=0
245 CPU FIFO mode=0
OPTO Isolate mode=0
High Current Drive=0
[Dual Device Driver Options A]
Virtual Com Port Driver=1
D2XX Driver=0
[Dual Device Driver Options B]
Virtual Com Port Driver=1
D2XX Driver=0
[R Device Specific Options]
Invert TXD=0
Invert RXD=0
Invert RTS#=0
Invert CTS#=0
Invert DTR#=0
Invert DSR#=0
Invert DCD#=0
Invert RI#=0
C0 Signal=10
C1 Signal=10
C2 Signal=10
C3 Signal=10
C4 Signal=5
Enable Ext Osc=0
High Current I/O=0
Load D2XX Driver=0
In EndPoint Size=0
07070100000026000081A400000000000000000000000160917B8300000C29000000000000000000000000000000000000003600000000libftdi1-1.5.12+git.0684c1b/examples/bitbang_ft2232.c/* bitbang_ft2232.c

   Output some flickering in bitbang mode to the FT2232

   Thanks to max@koeln.ccc.de for fixing and extending
   the example for the second channel.

   This program is distributed under the GPL, version 2
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ftdi.h>

int main(int argc, char **argv)
{
    struct ftdi_context *ftdi, *ftdi2;
    unsigned char buf[1];
    int f,i;

    // Init 1. channel
    if ((ftdi = ftdi_new()) == 0)
    {
        fprintf(stderr, "ftdi_new failed\n");
        return EXIT_FAILURE;
    }

    ftdi_set_interface(ftdi, INTERFACE_A);
    f = ftdi_usb_open(ftdi, 0x0403, 0x6001);
    if (f < 0 && f != -5)
    {
        fprintf(stderr, "unable to open ftdi device: %d (%s)\n", f, ftdi_get_error_string(ftdi));
        ftdi_free(ftdi);
        exit(-1);
    }
    printf("ftdi open succeeded(channel 1): %d\n",f);

    printf("enabling bitbang mode(channel 1)\n");
    ftdi_set_bitmode(ftdi, 0xFF, BITMODE_BITBANG);

    // Init 2. channel
    if ((ftdi2 = ftdi_new()) == 0)
    {
        fprintf(stderr, "ftdi_new failed\n");
        return EXIT_FAILURE;
    }
    ftdi_set_interface(ftdi2, INTERFACE_B);
    f = ftdi_usb_open(ftdi2, 0x0403, 0x6001);
    if (f < 0 && f != -5)
    {
        fprintf(stderr, "unable to open ftdi device: %d (%s)\n", f, ftdi_get_error_string(ftdi2));
        ftdi_free(ftdi2);
        exit(-1);
    }
    printf("ftdi open succeeded(channel 2): %d\n",f);

    printf("enabling bitbang mode (channel 2)\n");
    ftdi_set_bitmode(ftdi2, 0xFF, BITMODE_BITBANG);

    // Write data
    printf("startloop\n");
    for (i = 0; i < 23; i++)
    {
        buf[0] =  0x1;
        printf("porta: %02i: 0x%02x \n",i,buf[0]);
        f = ftdi_write_data(ftdi, buf, 1);
        if (f < 0)
            fprintf(stderr,"write failed on channel 1 for 0x%x, error %d (%s)\n", buf[0], f, ftdi_get_error_string(ftdi));
        usleep(1 * 1000000);

        buf[0] =  0x2;
        printf("porta: %02i: 0x%02x \n",i,buf[0]);
        f = ftdi_write_data(ftdi, buf, 1);
        if (f < 0)
            fprintf(stderr,"write failed on channel 1 for 0x%x, error %d (%s)\n", buf[0], f, ftdi_get_error_string(ftdi));
        usleep(1 * 1000000);

        buf[0] =  0x1;
        printf("portb: %02i: 0x%02x \n",i,buf[0]);
        f = ftdi_write_data(ftdi2, buf, 1);
        if (f < 0)
            fprintf(stderr,"write failed on channel 2 for 0x%x, error %d (%s)\n", buf[0], f, ftdi_get_error_string(ftdi2));
        usleep(1 * 1000000);

        buf[0] =  0x2;
        printf("portb: %02i: 0x%02x \n",i,buf[0]);
        f = ftdi_write_data(ftdi2, buf, 1);
        if (f < 0)
            fprintf(stderr,"write failed on channel 2 for 0x%x, error %d (%s)\n", buf[0], f, ftdi_get_error_string(ftdi2));
        usleep(1 * 1000000);
    }
    printf("\n");

    printf("disabling bitbang mode(channel 1)\n");
    ftdi_disable_bitbang(ftdi);
    ftdi_usb_close(ftdi);
    ftdi_free(ftdi);

    printf("disabling bitbang mode(channel 2)\n");
    ftdi_disable_bitbang(ftdi2);
    ftdi_usb_close(ftdi2);
    ftdi_free(ftdi2);

    return 0;
}
07070100000027000041ED00000000000000000000000260917B8300000000000000000000000000000000000000000000003300000000libftdi1-1.5.12+git.0684c1b/examples/cmake_example07070100000028000081A400000000000000000000000160917B8300000127000000000000000000000000000000000000004200000000libftdi1-1.5.12+git.0684c1b/examples/cmake_example/CMakeLists.txtcmake_minimum_required ( VERSION 2.8 )

project ( example C )

find_package ( LibFTDI1 NO_MODULE REQUIRED )
include ( ${LIBFTDI_USE_FILE} )

add_executable ( example main.c )
target_link_libraries( example ${LIBFTDI_LIBRARIES} )

install ( TARGETS example
          DESTINATION bin )
          
07070100000029000081A400000000000000000000000160917B8300000169000000000000000000000000000000000000003A00000000libftdi1-1.5.12+git.0684c1b/examples/cmake_example/main.c/* main.c

   Example for ftdi_new()

   This program is distributed under the GPL, version 2
*/

#include <stdio.h>
#include <stdlib.h>
#include <ftdi.h>

int main(void)
{
  struct ftdi_context *ftdi;
  int retval = EXIT_SUCCESS;

  if ((ftdi = ftdi_new()) == 0)
  {
    fprintf(stderr, "ftdi_new failed\n");
    return EXIT_FAILURE;
  }
  
  return retval;
}
0707010000002A000081A400000000000000000000000160917B8300002372000000000000000000000000000000000000002E00000000libftdi1-1.5.12+git.0684c1b/examples/eeprom.c/* LIBFTDI EEPROM access example

   This program is distributed under the GPL, version 2
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <getopt.h>
#include <ftdi.h>

int read_decode_eeprom(struct ftdi_context *ftdi)
{
    int i, j, f;
    int value;
    int size;
    unsigned char buf[256];

    f = ftdi_read_eeprom(ftdi);
    if (f < 0)
    {
        fprintf(stderr, "ftdi_read_eeprom: %d (%s)\n",
                f, ftdi_get_error_string(ftdi));
        return -1;
    }


    ftdi_get_eeprom_value(ftdi, CHIP_SIZE, & value);
    if (value <0)
    {
        fprintf(stderr, "No EEPROM found or EEPROM empty\n");
        fprintf(stderr, "On empty EEPROM, use -w option to write default values\n");
        return -1;
    }
    fprintf(stderr, "Chip type %d ftdi_eeprom_size: %d\n", ftdi->type, value);
    if (ftdi->type == TYPE_R)
        size = 0xa0;
    else
        size = value;
    ftdi_get_eeprom_buf(ftdi, buf, size);
    for (i=0; i < size; i += 16)
    {
        fprintf(stdout,"0x%03x:", i);

        for (j = 0; j< 8; j++)
            fprintf(stdout," %02x", buf[i+j]);
        fprintf(stdout," ");
        for (; j< 16; j++)
            fprintf(stdout," %02x", buf[i+j]);
        fprintf(stdout," ");
        for (j = 0; j< 8; j++)
            fprintf(stdout,"%c", isprint(buf[i+j])?buf[i+j]:'.');
        fprintf(stdout," ");
        for (; j< 16; j++)
            fprintf(stdout,"%c", isprint(buf[i+j])?buf[i+j]:'.');
        fprintf(stdout,"\n");
    }

    f = ftdi_eeprom_decode(ftdi, 1);
    if (f < 0)
    {
        fprintf(stderr, "ftdi_eeprom_decode: %d (%s)\n",
                f, ftdi_get_error_string(ftdi));
        return -1;
    }
    return 0;
}

int main(int argc, char **argv)
{
    struct ftdi_context *ftdi;
    int f, i;
    int vid = 0;
    int pid = 0;
    char const *desc    = 0;
    char const *serial  = 0;
    int erase = 0;
    int use_defaults = 0;
    int large_chip = 0;
    int do_write = 0;
    int retval = 0;
    int value;

    if ((ftdi = ftdi_new()) == 0)
    {
        fprintf(stderr, "Failed to allocate ftdi structure :%s \n",
                ftdi_get_error_string(ftdi));
        return EXIT_FAILURE;
    }

    while ((i = getopt(argc, argv, "d::ev:p:l:P:S:w")) != -1)
    {
        switch (i)
        {
            case 'd':
                use_defaults = 1;
                if (optarg)
                    large_chip = 0x66;
                break;
            case 'e':
                erase = 1;
                break;
            case 'v':
                vid = strtoul(optarg, NULL, 0);
                break;
            case 'p':
                pid = strtoul(optarg, NULL, 0);
                break;
            case 'P':
                desc = optarg;
                break;
            case 'S':
                serial = optarg;
                break;
            case 'w':
                do_write  = 1;
                break;
            default:
                fprintf(stderr, "usage: %s [options]\n", *argv);
                fprintf(stderr, "\t-d[num] Work with default valuesfor 128 Byte "
                        "EEPROM or for 256 Byte EEPROM if some [num] is given\n");
                fprintf(stderr, "\t-w write\n");
                fprintf(stderr, "\t-e erase\n");
                fprintf(stderr, "\t-v verbose decoding\n");
                fprintf(stderr, "\t-p <number> Search for device with PID == number\n");
                fprintf(stderr, "\t-v <number> Search for device with VID == number\n");
                fprintf(stderr, "\t-P <string? Search for device with given "
                        "product description\n");
                fprintf(stderr, "\t-S <string? Search for device with given "
                        "serial number\n");
                retval = -1;
                goto done;
        }
    }

    // Select first interface
    ftdi_set_interface(ftdi, INTERFACE_ANY);

    if (!vid && !pid && desc == NULL && serial == NULL)
    {
        struct ftdi_device_list *devlist, *curdev;
        int res;
        if ((res = ftdi_usb_find_all(ftdi, &devlist, 0, 0)) < 0)
        {
            fprintf(stderr, "No FTDI with default VID/PID found\n");
            retval =  EXIT_FAILURE;
            goto do_deinit;
        }
        if (res > 1)
        {
            int i = 1;
            fprintf(stderr, "%d FTDI devices found: Only Readout on EEPROM done. ",res);
            fprintf(stderr, "Use VID/PID/desc/serial to select device\n");
            for (curdev = devlist; curdev != NULL; curdev= curdev->next, i++)
            {
                f = ftdi_usb_open_dev(ftdi,  curdev->dev);
                if (f<0)
                {
                    fprintf(stderr, "Unable to open device %d: (%s)",
                            i, ftdi_get_error_string(ftdi));
                    continue;
                }
                fprintf(stderr, "Decoded values of device %d:\n", i);
                read_decode_eeprom(ftdi);
                ftdi_usb_close(ftdi);
            }
            ftdi_list_free(&devlist);
            retval = EXIT_SUCCESS;
            goto do_deinit;
        }
        else if (res == 1)
        {
            f = ftdi_usb_open_dev(ftdi,  devlist[0].dev);
            if (f<0)
            {
                fprintf(stderr, "Unable to open device %d: (%s)",
                        i, ftdi_get_error_string(ftdi));
            }
        }
        else
        {
            fprintf(stderr, "No devices found\n");
            f = 0;
        }
        ftdi_list_free(&devlist);
    }
    else
    {
        // Open device
        f = ftdi_usb_open_desc(ftdi, vid, pid, desc, serial);
        if (f < 0)
        {
            fprintf(stderr, "Device VID 0x%04x PID 0x%04x", vid, pid);
            if (desc)
                fprintf(stderr, " Desc %s", desc);
            if (serial)
                fprintf(stderr, " Serial %s", serial);
            fprintf(stderr, "\n");
            fprintf(stderr, "unable to open ftdi device: %d (%s)\n",
                    f, ftdi_get_error_string(ftdi));
            
            retval = -1;
            goto done;
        }
    }
    if (erase)
    {
        f = ftdi_erase_eeprom(ftdi); /* needed to determine EEPROM chip type */
        if (f < 0)
        {
            fprintf(stderr, "Erase failed: %s",
                    ftdi_get_error_string(ftdi));
            retval =  -2;
            goto done;
        }
        if (ftdi_get_eeprom_value(ftdi, CHIP_TYPE, & value) <0)
        {
            fprintf(stderr, "ftdi_get_eeprom_value: %d (%s)\n",
                    f, ftdi_get_error_string(ftdi));
        }
        if (value == -1)
            fprintf(stderr, "No EEPROM\n");
        else if (value == 0)
            fprintf(stderr, "Internal EEPROM\n");
        else
            fprintf(stderr, "Found 93x%02x\n", value);
        retval = 0;
        goto done;
    }

    if (use_defaults)
    {
        ftdi_eeprom_initdefaults(ftdi, NULL, NULL, NULL);
        if (ftdi_set_eeprom_value(ftdi, MAX_POWER, 500) <0)
        {
            fprintf(stderr, "ftdi_set_eeprom_value: %d (%s)\n",
                    f, ftdi_get_error_string(ftdi));
        }
        if (large_chip)
            if (ftdi_set_eeprom_value(ftdi, CHIP_TYPE, 0x66) <0)
            {
                fprintf(stderr, "ftdi_set_eeprom_value: %d (%s)\n",
                        f, ftdi_get_error_string(ftdi));
            }
        f=(ftdi_eeprom_build(ftdi));
        if (f < 0)
        {
            fprintf(stderr, "ftdi_eeprom_build: %d (%s)\n",
                    f, ftdi_get_error_string(ftdi));
            retval = -1;
            goto done;
        }
    }
    else if (do_write)
    {
        ftdi_eeprom_initdefaults(ftdi, NULL, NULL, NULL);
        f = ftdi_erase_eeprom(ftdi);
        if (ftdi_set_eeprom_value(ftdi, MAX_POWER, 500) <0)
        {
            fprintf(stderr, "ftdi_set_eeprom_value: %d (%s)\n",
                    f, ftdi_get_error_string(ftdi));
        }
        f = ftdi_erase_eeprom(ftdi);/* needed to determine EEPROM chip type */
        if (ftdi_get_eeprom_value(ftdi, CHIP_TYPE, & value) <0)
        {
            fprintf(stderr, "ftdi_get_eeprom_value: %d (%s)\n",
                    f, ftdi_get_error_string(ftdi));
        }
        if (value == -1)
            fprintf(stderr, "No EEPROM\n");
        else if (value == 0)
            fprintf(stderr, "Internal EEPROM\n");
        else
            fprintf(stderr, "Found 93x%02x\n", value);
        f=(ftdi_eeprom_build(ftdi));
        if (f < 0)
        {
            fprintf(stderr, "Erase failed: %s",
                    ftdi_get_error_string(ftdi));
            retval = -2;
            goto done;
        }
        f = ftdi_write_eeprom(ftdi);
        {
            fprintf(stderr, "ftdi_eeprom_decode: %d (%s)\n",
                    f, ftdi_get_error_string(ftdi));
            retval = 1;
            goto done;
        }
    }
    retval = read_decode_eeprom(ftdi);
done:
    ftdi_usb_close(ftdi);
do_deinit:
    ftdi_free(ftdi);
    return retval;
}
0707010000002B000081A400000000000000000000000160917B8300000562000000000000000000000000000000000000003000000000libftdi1-1.5.12+git.0684c1b/examples/find_all.c/* find_all.c

   Example for ftdi_usb_find_all()

   This program is distributed under the GPL, version 2
*/

#include <stdio.h>
#include <stdlib.h>
#include <ftdi.h>

int main(void)
{
    int ret, i;
    struct ftdi_context *ftdi;
    struct ftdi_device_list *devlist, *curdev;
    char manufacturer[128], description[128];
    int retval = EXIT_SUCCESS;

    if ((ftdi = ftdi_new()) == 0)
    {
        fprintf(stderr, "ftdi_new failed\n");
        return EXIT_FAILURE;
    }

    if ((ret = ftdi_usb_find_all(ftdi, &devlist, 0, 0)) < 0)
    {
        fprintf(stderr, "ftdi_usb_find_all failed: %d (%s)\n", ret, ftdi_get_error_string(ftdi));
        retval =  EXIT_FAILURE;
        goto do_deinit;
    }

    printf("Number of FTDI devices found: %d\n", ret);

    i = 0;
    for (curdev = devlist; curdev != NULL; i++)
    {
        printf("Checking device: %d\n", i);
        if ((ret = ftdi_usb_get_strings(ftdi, curdev->dev, manufacturer, 128, description, 128, NULL, 0)) < 0)
        {
            fprintf(stderr, "ftdi_usb_get_strings failed: %d (%s)\n", ret, ftdi_get_error_string(ftdi));
            retval = EXIT_FAILURE;
            goto done;
        }
        printf("Manufacturer: %s, Description: %s\n\n", manufacturer, description);
        curdev = curdev->next;
    }
done:
    ftdi_list_free(&devlist);
do_deinit:
    ftdi_free(ftdi);

    return retval;
}
0707010000002C000081A400000000000000000000000160917B830000069F000000000000000000000000000000000000003500000000libftdi1-1.5.12+git.0684c1b/examples/find_all_pp.cpp/* final_all_pp.cpp

   Simple libftdi-cpp usage

   This program is distributed under the GPL, version 2
*/

#include "ftdi.hpp"
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
using namespace Ftdi;

int main(int argc, char **argv)
{
    // Show help
    if (argc > 1)
    {
        if (strcmp(argv[1],"-h") == 0 || strcmp(argv[1],"--help") == 0)
        {
            std::cout << "Usage: " << argv[0] << " [-v VENDOR_ID] [-p PRODUCT_ID]" << std::endl;
            return EXIT_SUCCESS;
        }
    }

    // Parse args
    int vid = 0x0403, pid = 0x6010, tmp = 0;
    for (int i = 0; i < (argc - 1); i++)
    {
        if (strcmp(argv[i], "-v") == 0)
            if ((tmp = strtol(argv[++i], 0, 16)) >= 0)
                vid = tmp;

        if (strcmp(argv[i], "-p") == 0)
            if ((tmp = strtol(argv[++i], 0, 16)) >= 0)
                pid = tmp;
    }

    // Print header
    std::cout << std::hex << std::showbase
    << "Found devices ( VID: " << vid << ", PID: " << pid << " )"
    << std::endl
    << "------------------------------------------------"
    << std::endl << std::dec;

    // Print whole list
    Context context;
    List* list = List::find_all(context, vid, pid);
    for (List::iterator it = list->begin(); it != list->end(); it++)
    {
        std::cout << "FTDI (" << &*it << "): "
        << it->vendor() << ", "
        << it->description() << ", "
        << it->serial();

        // Open test
        if(it->open() == 0)
           std::cout << " (Open OK)";
        else
           std::cout << " (Open FAILED)";

        it->close();

        std::cout << std::endl;

    }

    delete list;

    return EXIT_SUCCESS;
}
0707010000002D000081A400000000000000000000000160917B8300004959000000000000000000000000000000000000003200000000libftdi1-1.5.12+git.0684c1b/examples/purge_test.c/* purge_test.c
 *
 * Test for purge TX/RX functions.
 *
 * The chip must be wired to loop TX data to RX data (loopback).
 *
 * This program works with "standard" linux drivers and the FTDI1 library.
 *
 * Usage: purge_test [-b baud] [-i interface] [-n msg-size] [-N note] device-specifier
 *   See usage below for more information on command usage.
 *
 * This program works well with the FT4231H which is newer and has large
 * FIFOs. This program does not work well with FT232, either pre or post
 * switching the SIO_RESET_PURGE_TX/SIO_RESET_PURGE_RX values.
 *
 * This needs testing with other devices, which I do not have.
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <signal.h>
#include <errno.h>
/* Prevent deprecated messages when building library */
#define _FTDI_DISABLE_DEPRECATED
#include <ftdi.h>

#include <termios.h>		// For baudcodes & linux UARTs
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


static struct ftdi_context *ftdi = NULL;
static int dev_fd = -1;
static char * dev_string = NULL;
static int latency_specified = 0;
static int latency = 5;
static int baud = 9600;
static int baud_code = -1;
static enum ftdi_interface interface = INTERFACE_A;
static int msg_size = 80;
static int broken_purge_test = 0;

static const int latency_min = 2;
static const int latency_max = 255;

static volatile long long usec_test_start;



static int ascii2int(const char * str, const char * pgm_name);
static int baud_2_baud_code(int baud);
static long int char_cnt_2_usec(int char_count);
static long int drain();
static int flush(int queue_selector);
static long long int get_time_usec();

static const int flushQueueSelector[] = {
    TCIFLUSH, TCOFLUSH, TCIOFLUSH }; /* See /usr/include/bits/termios.h */
static const char * flushTestName[] = {
  "Input-only", "Output-only", "Input+Output" };
static const char * expected[] = {
    "last portion of message",
    "first portion of message",
    "mid-message characters",
};


static const char * chip_types[] = {
    "am",
    "bm",
    "2232C",
    "R",
    "2232H",
    "4232H",
    "232H",
    "230X",
};

#ifndef ARRAY_SIZE
#  define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
#endif



/**********************************************************************
 */
static void
usage(const char *argv0)
{
   fprintf(stderr,
           "Usage: %s [options...] device-specifier\n"
           "Flush test for UARTS.\n"
	   " with loopback connector\n"
           "    [-b baud]        baud rate (e.g., 300, 600, 1200, ...230400)\n"
           "    [-i {a|b|c|d}]   FTDI interface for chips which have multiple UARTS\n"
	   "    [-l latency]     Latency (%d..%d)\n"
           "    [-n msg-size]    Number of bytes in test message\n"
           "    [-N note]        Note for the output\n"
	   "    [-P]             Use broken libftdi1 purge methods (over new flush)\n"
           "\n"
           "    device-specifier String specifying the UART.  If the first character\n"
	   "                     is the '/' character, the program assumes a Linux UART\n"
	   "                     is to be tested and the string would be something like\n"
	   "                     '/dev/ttyS0' or '/dev/ttyUSB0'. Otherwise, the program\n"
	   "                     assumes an FTDI device is being tested with the FTDI1\n"
	   "                     library. The device-specifier must be a string\n"
	   "                     accepted by the ftdi_usb_open_string function. An\n"
	   "                     example would be 'i:0x0403:0x6011[:index]'.\n"
	   "\n"
	   "NOTE: To function correctly, this program requires a loopback connector\n"
	   "      attached to the UART under test.\n"
           "\n"
           "Adapted from stream_test.c 2018. Eric Schott <els6@psu.edu>\n"
           "Copyright (C) 2009 Micah Dowty <micah@navi.cx>\n"
           "Adapted for use with libftdi (C) 2010 Uwe Bonnes <bon@elektron.ikp.physik.tu-darmstadt.de>\n",
           argv0, latency_min, latency_max);
   exit(1);
}


/**********************************************************************
 */
int main(int argc, char **argv)
{
    int c, i;
    int option_index;
    int test;
    unsigned char * msg;
    unsigned char * retMsg;
    char * note = NULL;
    char * note_default = NULL;
    size_t retMsgSize;
    long int msg_xmit_time_us;
    static struct option long_options[] = {{NULL},};

    while ((c = getopt_long(argc, argv, "n:b:i:l:N:P", long_options, &option_index)) !=- 1)
        switch (c)
        {
        case -1:
            break;
        case 'b':
            baud = ascii2int(optarg, argv[0]);
            break;
        case 'i':
            if (optarg == NULL || strlen(optarg) != 1)
                usage(argv[0]);
            switch (optarg[0])
            {
            case 'a':
            case 'A':
                interface = INTERFACE_A;
                break;

            case 'b':
            case 'B':
                interface = INTERFACE_B;
                break;

            case 'c':
            case 'C':
                interface = INTERFACE_C;
                break;

            case 'd':
            case 'D':
                interface = INTERFACE_D;
                break;

            default:
                usage(argv[0]);
            }
            break;
        case 'l':
            latency = ascii2int(optarg, argv[0]);
            if (latency < latency_min || latency > latency_max)
            {
	      fprintf(stderr, "latency [-l] must be an integer in the range %d..%d\n",
			latency_min, latency_max);
                usage(argv[0]);
            }
	    latency_specified = 1;
            break;
        case 'n':
            msg_size = ascii2int(optarg, argv[0]);
            if (msg_size < 1)
            {
                fprintf(stderr, "msg-size [-n] must be an integer greater than 0\n");
                usage(argv[0]);
            }
            break;
        case 'N':
            note = optarg;
            break;
	case 'P':
	    broken_purge_test = 1;
	    break;
        default:
            usage(argv[0]);
        }

    if (optind == argc)
        usage(argv[0]);

    if (optind == argc - 1)
    {
        // Exactly one extra argument- a dump file
        dev_string = argv[optind];
    }
    else if (optind < argc)
    {
        // Too many extra args
        usage(argv[0]);
    }

    baud_code = baud_2_baud_code(baud);
    if (baud_code < 1)
    {
        fprintf(stderr, "Invalid baud [-b]\n");
        usage(argv[0]);
    }

    if (dev_string[0] == '/')
    {
        struct termios termios;

	if (latency_specified) {
	  fprintf(stderr, "Latency (-l) option not support on this device; ignored\n");
	}

	if (broken_purge_test) {
	  fprintf(stderr, "Broken-purge (-P) option not support with Linux kernel driver\n");
	  return EXIT_FAILURE;
	}

        dev_fd = open(dev_string, O_NOCTTY | O_RDWR);
        if (dev_fd < 0)
        {
            fprintf(stderr, "Error opening Linux device \"%s\": %s\n",
                    dev_string, strerror(errno));
            return EXIT_FAILURE;
        }

        if (! isatty(dev_fd))
        {
            fprintf(stderr, "Not a TTY device: \"%s\"\n", dev_string);
            return EXIT_FAILURE;
        }

        if (tcgetattr(dev_fd, &termios) == -1)
        {
            fprintf(stderr, "Error getting TTY attributes for \"%s\": %s\n",
                    dev_string, strerror(errno));
            return EXIT_FAILURE;
        }

	note_default = "Linux kernel driver";

        cfmakeraw(&termios);

        termios.c_cflag &=
            ~(CSTOPB | CRTSCTS);

        termios.c_cflag &= ~CSIZE;
        termios.c_cflag |= CS8;

        cfsetspeed(&termios, baud_code);

        termios.c_cflag |=
            CLOCAL;

        termios.c_cc[VMIN] = 1;	// Character at a time input
        termios.c_cc[VTIME] = 0;	// with blocking

        if (tcsetattr(dev_fd, TCSAFLUSH, &termios) == -1) {
            fprintf(stderr, "Error setting TTY attributes for \"%s\": %s\n", 
                    dev_string, strerror(errno));
            return EXIT_FAILURE;
        }
    }
    else
    {

        if ((ftdi = ftdi_new()) == 0)
        {
            fprintf(stderr, "ftdi_new failed\n");
            return EXIT_FAILURE;
        }

        if (ftdi_set_interface(ftdi, interface) < 0)
        {
            fprintf(stderr, "ftdi_set_interface failed\n");
            ftdi_free(ftdi);
            return EXIT_FAILURE;
        }

        if (ftdi_usb_open_string(ftdi, dev_string) < 0)
        {
            fprintf(stderr,"Error opening ftdi device \"%s\": %s\n", dev_string,
                    ftdi_get_error_string(ftdi));
            ftdi_free(ftdi);
            return EXIT_FAILURE;
        }

	if(ftdi_set_latency_timer(ftdi, (unsigned char) latency))
	{
	    if (latency_specified &&
                (ftdi->type == TYPE_AM || ftdi->type == TYPE_232H)) {
	        fprintf(stderr, "Latency (-l) option not support on this device; ignored\n");
	    } else if (ftdi->type != TYPE_AM && ftdi->type != TYPE_232H) {
                fprintf(stderr,"Error setting latency for ftdi device \"%s\" (%d): %s\n",
                        dev_string, ftdi->type, ftdi_get_error_string(ftdi));
                ftdi_free(ftdi);
                return EXIT_FAILURE;
            }
	}

        if (ftdi_set_line_property2(ftdi, BITS_8, STOP_BIT_1, NONE, BREAK_OFF) < 0)
        {
            fprintf(stderr,"Error setting line properties ftdi device \"%s\": %s\n", dev_string,
                    ftdi_get_error_string(ftdi));
            ftdi_free(ftdi);
            return EXIT_FAILURE;
        }

        if (ftdi_set_baudrate(ftdi, baud) < 0)
        {
            fprintf(stderr,"Error setting baud rate for ftdi device \"%s\": %s\n", dev_string,
                    ftdi_get_error_string(ftdi));
            ftdi_free(ftdi);
            return EXIT_FAILURE;
        }

        if (ftdi_setflowctrl(ftdi, SIO_DISABLE_FLOW_CTRL))
        {
            fprintf(stderr,"Error setting flow control for ftdi device \"%s\": %s\n", dev_string,
                    ftdi_get_error_string(ftdi));
            ftdi_free(ftdi);
            return EXIT_FAILURE;
        }

	if (broken_purge_test)
	    note_default = "libftdi w/ deprecated purge";
	else
	    note_default = "libftdi w/ new flush methods";
    }

    printf("Purge (tcflush) test for device %s\n", dev_string);
    printf("Note: %s\n", (note ? note : note_default));

    if (dev_fd < 0)
    {
        if (ftdi->type >0 && ftdi->type < ARRAY_SIZE(chip_types))
            printf("FTDI chip type is %d (%s)\n",
                   ftdi->type, chip_types[ftdi->type]);
        else
            printf("FTDI chip type is %d (unknown)\n", ftdi->type);
    }

    printf("# purge_test" );
    for (c = 1; c < argc; ++c)
    {
        const char *p = argv[c];
        while (*p != '\0')
        {
            if (*p == ' ')
                break;
            ++p;
        }
        if (*p == ' ')
            printf(" '%s'", argv[c]);
        else
            printf(" %s", argv[c]);
    }
    printf("\n");

    msg_xmit_time_us = char_cnt_2_usec(msg_size);
    printf("%d chars at %d baud takes about %.0f ms to transmit\n", msg_size,
           baud, msg_xmit_time_us * .001);

    msg = malloc(msg_size + 1);
    if (msg == NULL)
    {
        fprintf(stderr, "Could not allocate send message buffer\n");
        return EXIT_FAILURE;
    }

    {
        char dataChar = '0' + ((get_time_usec() / 1000) % 31);
        char next = 'A';
        for (i = 0; i < msg_size; ++i) {
            if (dataChar == '`')
            {
                msg[i] = next++;
                ++dataChar;
            }
            else
                msg[i] = dataChar++;

            if (dataChar > 'z') {
                dataChar = '`';
            }
        }
        msg[msg_size] = '\0';
    }

    printf("TX Message is \"%s\"\n", msg);

    retMsgSize = 2 * msg_size;
    retMsg = malloc(retMsgSize);
    if (retMsg == NULL)
    {
        fprintf(stderr, "Could not allocate received message buffer\n");
        return EXIT_FAILURE;
    }

    flush(TCIOFLUSH);

    for (test = 0; test <= 2; ++test)
    {
        long long usec_delay;
        long long usec_to_now;
        int rc;

        printf("\n********  Test purge %s; expect %s  ********\n"
	       "  --              Flushing UART\n",
               flushTestName[test], expected[test]);
        flush(TCIOFLUSH);
        usleep(msg_xmit_time_us);
        flush(TCIOFLUSH);
        usleep(100000);

        usec_test_start = get_time_usec();
        if (dev_fd >= 0)
            rc = write(dev_fd, msg, msg_size);
        else
            rc = ftdi_write_data(ftdi, msg, msg_size);

        if (rc != msg_size)
        {
            fprintf(stderr, "Data write was short: %d: %s\n",
                    rc, ftdi_get_error_string(ftdi));
            exit(1);
        }
        usec_to_now = get_time_usec() - usec_test_start;
        usec_delay = msg_xmit_time_us / 2 - usec_to_now;
        if (usec_delay < 0)
            usec_delay = 0;
        printf("  -- %9.1f ms Write completes; delaying to TX midpoint (%.1f ms)\n", 
               usec_to_now * .001, usec_delay * .001);
        if (usec_delay > 0)
            usleep(usec_delay);

        printf("  -- %9.1f ms Issuing %s flush (purge)\n", 
               (get_time_usec() - usec_test_start) * .001,
               flushTestName[test]);
        flush(flushQueueSelector[test]);

        printf("  -- %9.1f ms Calling drain to wait for transmit to complete\n", 
               (get_time_usec() - usec_test_start) * .001);
        drain();

        usec_to_now = get_time_usec() - usec_test_start;

        /* If input only flush, check drain time. */
        if (flushQueueSelector[test] == TCIFLUSH &&
            usec_to_now < (msg_xmit_time_us * 90ll) / 100ll)
        {
            usec_delay = (msg_xmit_time_us * 110ll) / 100ll - usec_to_now;
            printf("  -- %9.1f ms Drain() completed too early; expected at least %.1f ms\n"
                   "                  Delaying for %.1f ms\n", 
                   usec_to_now * .001,
                   ((msg_xmit_time_us * 90ll) / 100ll) * .001,
                   usec_delay * .001);
            usleep(usec_delay);
        }
        else
	{
            printf("  -- %9.1f ms Drain() reports completed; timing OK; delaying for 4 bytes\n", 
                   (get_time_usec() - usec_test_start) * .001);
            usleep(char_cnt_2_usec(4));
        }

        printf("  -- %9.1f ms Reading data.\n",
               (get_time_usec() - usec_test_start) * .001);
        if (dev_fd >= 0)
            rc = read(dev_fd, retMsg, retMsgSize);
        else
            rc = ftdi_read_data(ftdi, retMsg, retMsgSize - 1);

        usec_to_now = get_time_usec() - usec_test_start;
        if (rc < 0)
        {
            fprintf(stderr, "  -- %9.1f ms Read returned error %s\n",
                    usec_to_now * .001,
                    (dev_fd >= 0 ? strerror(errno) : ftdi_get_error_string(ftdi)));
            exit(1);
        }
        retMsg[rc] = '\0';
        printf("  -- %9.1f ms Read returns %d bytes; msg: \"%s\"\n",
               usec_to_now * .001, rc, retMsg);

        usleep(char_cnt_2_usec(10));

    }


    if (dev_fd >= 0)
    {
        close(dev_fd);
    }
    else
    {
        ftdi_usb_close(ftdi);
        ftdi_free(ftdi);
    }

    exit (0);
}

/**********************************************************************
 */
static int ascii2int(const char * str, const char * pgm_name)
{
    int rc;
    char * endptr;
    if (str == NULL || strlen(str) == 0)
        usage(pgm_name);
    rc = strtol(str, &endptr, 10);
    if (endptr == str || *endptr != '\0')
        usage(pgm_name);
    return rc;
}


/**********************************************************************
 */
static struct Baud_Table {
	int32_t baud, baud_code;
} baud_table [] =
{
	{ 50,     B50     },
	{ 75,     B75     },
	{ 110,    B110    },
	{ 134,    B134    },
	{ 150,    B150    },
	{ 200,    B200    },
	{ 300,    B300    },
	{ 600,    B600    },
	{ 1200,   B1200   },
	{ 1800,   B1800   },
	{ 2400,   B2400   },
	{ 4800,   B4800   },
	{ 9600,   B9600   },
	{ 19200,  B19200  },
	{ 38400,  B38400  },
	{ 57600,  B57600  },
	{ 115200, B115200 },
	{ 230400, B230400 },
	{ -1,     -1,     }
};

/**********************************************************************
 */
static int baud_2_baud_code(int baud)
{
    struct Baud_Table *p;

    for (p = baud_table ; p->baud != -1; ++p) {
        if (p->baud == baud)
            break;
    }
    return p->baud_code;
}


static long int char_cnt_2_usec(int char_count)
{
    long long bits = 8 + 1 + 1;                 /* Number of bits in each character */
    bits *= (char_count == 0 ? 1 : char_count); /* Total number of bits */
    bits *= 1000000;                            /* Convert to us */
    lldiv_t parts = lldiv(bits, baud);          /* Number of us for message */
    return (parts.quot + 1);
}


static long int drain()
{
    long int rc = 0;
    long long start_time = get_time_usec();
    if (dev_fd >= 0)
        rc = tcdrain(dev_fd);
    else
    {
        long int sleep_interval = char_cnt_2_usec(10);
        while (1) {
            unsigned short modem_status = 0;
            int rc = ftdi_poll_modem_status(ftdi, &modem_status);
            if (rc < 0)
                return -1;
            if (modem_status & (1 << (6 + 8))) {
                break;
            }
            usleep(sleep_interval);
        }
    }
    if (rc < 0)
        return rc;
    usleep(char_cnt_2_usec(2));
    return get_time_usec() - start_time;
}


static int flush(int queue_selector)
{
    int rc;
    if (dev_fd >= 0)
        rc = tcflush(dev_fd, queue_selector);
    else if (! broken_purge_test)
    {
        switch (queue_selector) {

        case TCIOFLUSH:
            rc = ftdi_tcioflush(ftdi);
            break;

        case TCIFLUSH:
            rc = ftdi_tciflush(ftdi);
            break;

        case TCOFLUSH:
            rc = ftdi_tcoflush(ftdi);
            break;

        default:
            errno = EINVAL;
            return -1;
        }
    }
    else
    {
        switch (queue_selector) {

        case TCIOFLUSH:
            rc = ftdi_usb_purge_buffers(ftdi);
            break;

        case TCIFLUSH:
            rc = ftdi_usb_purge_rx_buffer(ftdi);
            break;

        case TCOFLUSH:
            rc = ftdi_usb_purge_tx_buffer(ftdi);
            break;

        default:
            errno = EINVAL;
            return -1;
        }
    }

    return rc;
}


static long long int get_time_usec()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000000ll + tv.tv_usec;
}
0707010000002E000081A400000000000000000000000160917B8300001241000000000000000000000000000000000000003300000000libftdi1-1.5.12+git.0684c1b/examples/serial_test.c/* serial_test.c

   Read/write data via serial I/O

   This program is distributed under the GPL, version 2
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <signal.h>
#include <ftdi.h>

static int exitRequested = 0;
/*
 * sigintHandler --
 *
 *    SIGINT handler, so we can gracefully exit when the user hits ctrl-C.
 */
static void
sigintHandler(int signum)
{
    exitRequested = 1;
}

int main(int argc, char **argv)
{
    struct ftdi_context *ftdi;
    unsigned char buf[1024];
    int f = 0, i;
    int vid = 0x403;
    int pid = 0;
    int baudrate = 115200;
    int interface = INTERFACE_ANY;
    int do_write = 0;
    unsigned int pattern = 0xffff;
    int retval = EXIT_FAILURE;

    while ((i = getopt(argc, argv, "i:v:p:b:w::")) != -1)
    {
        switch (i)
        {
            case 'i': // 0=ANY, 1=A, 2=B, 3=C, 4=D
                interface = strtoul(optarg, NULL, 0);
                break;
            case 'v':
                vid = strtoul(optarg, NULL, 0);
                break;
            case 'p':
                pid = strtoul(optarg, NULL, 0);
                break;
            case 'b':
                baudrate = strtoul(optarg, NULL, 0);
                break;
            case 'w':
                do_write = 1;
                if (optarg)
                    pattern = strtoul(optarg, NULL, 0);
                if (pattern > 0xff)
                {
                    fprintf(stderr, "Please provide a 8 bit pattern\n");
                    exit(-1);
                }
                break;
            default:
                fprintf(stderr, "usage: %s [-i interface] [-v vid] [-p pid] [-b baudrate] [-w [pattern]]\n", *argv);
                exit(-1);
        }
    }

    // Init
    if ((ftdi = ftdi_new()) == 0)
    {
        fprintf(stderr, "ftdi_new failed\n");
        return EXIT_FAILURE;
    }

    if (!vid && !pid && (interface == INTERFACE_ANY))
    {
        ftdi_set_interface(ftdi, INTERFACE_ANY);
        struct ftdi_device_list *devlist;
        int res;
        if ((res = ftdi_usb_find_all(ftdi, &devlist, 0, 0)) < 0)
        {
            fprintf(stderr, "No FTDI with default VID/PID found\n");
            goto do_deinit;
        }
        if (res == 1)
        {
            f = ftdi_usb_open_dev(ftdi,  devlist[0].dev);
            if (f<0)
            {
                fprintf(stderr, "Unable to open device %d: (%s)",
                        i, ftdi_get_error_string(ftdi));
            }
        }
        ftdi_list_free(&devlist);
        if (res > 1)
        {
            fprintf(stderr, "%d Devices found, please select Device with VID/PID\n", res);
            /* TODO: List Devices*/
            goto do_deinit;
        }
        if (res == 0)
        {
            fprintf(stderr, "No Devices found with default VID/PID\n");
            goto do_deinit;
        }
    }
    else
    {
        // Select interface
        ftdi_set_interface(ftdi, interface);
        
        // Open device
        f = ftdi_usb_open(ftdi, vid, pid);
    }
    if (f < 0)
    {
        fprintf(stderr, "unable to open ftdi device: %d (%s)\n", f, ftdi_get_error_string(ftdi));
        exit(-1);
    }

    // Set baudrate
    f = ftdi_set_baudrate(ftdi, baudrate);
    if (f < 0)
    {
        fprintf(stderr, "unable to set baudrate: %d (%s)\n", f, ftdi_get_error_string(ftdi));
        exit(-1);
    }
    
    /* Set line parameters
     *
     * TODO: Make these parameters settable from the command line
     *
     * Parameters are chosen that sending a continuous stream of 0x55 
     * should give a square wave
     *
     */
    f = ftdi_set_line_property(ftdi, 8, STOP_BIT_1, NONE);
    if (f < 0)
    {
        fprintf(stderr, "unable to set line parameters: %d (%s)\n", f, ftdi_get_error_string(ftdi));
        exit(-1);
    }
    
    if (do_write)
        for(i=0; i<1024; i++)
            buf[i] = pattern;

    signal(SIGINT, sigintHandler);
    while (!exitRequested)
    {
        if (do_write)
            f = ftdi_write_data(ftdi, buf, 
                                (baudrate/512 >sizeof(buf))?sizeof(buf):
                                (baudrate/512)?baudrate/512:1);
        else
            f = ftdi_read_data(ftdi, buf, sizeof(buf));
        if (f<0)
            usleep(1 * 1000000);
        else if(f> 0 && !do_write)
        {
            fprintf(stderr, "read %d bytes\n", f);
            fwrite(buf, f, 1, stdout);
            fflush(stderr);
            fflush(stdout);
        }
    }
    signal(SIGINT, SIG_DFL);
    retval =  EXIT_SUCCESS;
            
    ftdi_usb_close(ftdi);
    do_deinit:
    ftdi_free(ftdi);

    return retval;
}
0707010000002F000081A400000000000000000000000160917B830000053E000000000000000000000000000000000000002E00000000libftdi1-1.5.12+git.0684c1b/examples/simple.c/* simple.c

   Simple libftdi usage example

   This program is distributed under the GPL, version 2
*/

#include <stdio.h>
#include <stdlib.h>
#include <ftdi.h>

int main(void)
{
    int ret;
    struct ftdi_context *ftdi;
    struct ftdi_version_info version;
    if ((ftdi = ftdi_new()) == 0)
   {
        fprintf(stderr, "ftdi_new failed\n");
        return EXIT_FAILURE;
    }

    version = ftdi_get_library_version();
    printf("Initialized libftdi %s (major: %d, minor: %d, micro: %d, snapshot ver: %s)\n",
        version.version_str, version.major, version.minor, version.micro,
        version.snapshot_str);

    if ((ret = ftdi_usb_open(ftdi, 0x0403, 0x6001)) < 0)
    {
        fprintf(stderr, "unable to open ftdi device: %d (%s)\n", ret, ftdi_get_error_string(ftdi));
        ftdi_free(ftdi);
        return EXIT_FAILURE;
    }

    // Read out FTDIChip-ID of R type chips
    if (ftdi->type == TYPE_R)
    {
        unsigned int chipid;
        printf("ftdi_read_chipid: %d\n", ftdi_read_chipid(ftdi, &chipid));
        printf("FTDI chipid: %X\n", chipid);
    }

    if ((ret = ftdi_usb_close(ftdi)) < 0)
    {
        fprintf(stderr, "unable to close ftdi device: %d (%s)\n", ret, ftdi_get_error_string(ftdi));
        ftdi_free(ftdi);
        return EXIT_FAILURE;
    }

    ftdi_free(ftdi);

    return EXIT_SUCCESS;
}
07070100000030000081A400000000000000000000000160917B8300002866000000000000000000000000000000000000003300000000libftdi1-1.5.12+git.0684c1b/examples/stream_test.c/* stream_test.c
 *
 * Test reading  from FT2232H in synchronous FIFO mode.
 *
 * The FT2232H must supply data due to an appropriate circuit
 *
 * To check for skipped block with appended code, 
 *     a structure as follows is assumed
 * 1* uint32_t num (incremented in 0x4000 steps)
 * 3* uint32_t dont_care
 *
 * After start, data will be read in streaming until the program is aborted
 * Progress information will be printed out
 * If a filename is given on the command line, the data read will be
 * written to that file
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <signal.h>
#include <errno.h>
#include <ftdi.h>
void check_outfile(char *);

static FILE *outputFile;

static int check = 1;
static int exitRequested = 0;
/*
 * sigintHandler --
 *
 *    SIGINT handler, so we can gracefully exit when the user hits ctrl-C.
 */

static void
sigintHandler(int signum)
{
   exitRequested = 1;
}

static void
usage(const char *argv0)
{
   fprintf(stderr,
           "Usage: %s [options...] \n"
           "Test streaming read from FT2232H\n"
           "[-P string] only look for product with given string\n"
           "[-n] don't check for special block structure\n"
           "\n"
           "If some filename is given, write data read to that file\n"
           "Progress information is printed each second\n"
           "Abort with ^C\n"
           "\n"
           "Options:\n"
           "\n"
           "Copyright (C) 2009 Micah Dowty <micah@navi.cx>\n"
           "Adapted for use with libftdi (C) 2010 Uwe Bonnes <bon@elektron.ikp.physik.tu-darmstadt.de>\n",
           argv0);
   exit(1);
}

static uint32_t start = 0;
static uint32_t offset = 0;
static uint64_t blocks = 0;
static uint32_t skips = 0;
static uint32_t n_err = 0;
static int
readCallback(uint8_t *buffer, int length, FTDIProgressInfo *progress, void *userdata)
{
   if (length)
   {
       if (check)
       {
           int i,rem;
           uint32_t num;
           for (i= offset; i<length-16; i+=16)
           {
               num = *(uint32_t*) (buffer+i);
               if (start && (num != start +0x4000))
               {
                   uint32_t delta = ((num-start)/0x4000)-1;
                   fprintf(stderr, "Skip %7d blocks from 0x%08x to 0x%08x at blocks %10llu\n",
                           delta, start -0x4000, num, (unsigned long long)blocks);
                   n_err++;
                   skips += delta;
               }
               blocks ++;
               start = num;
           }
           rem = length -i;
           if (rem >3)
           {
               num = *(uint32_t*) (buffer+i);
               if (start && (num != start +0x4000))
               {
                   uint32_t delta = ((num-start)/0x4000)-1;
                   fprintf(stderr, "Skip %7d blocks from 0x%08x to 0x%08x at blocks %10llu\n",
                           delta, start -0x4000, num, (unsigned long long) blocks);
                   n_err++;
                   skips += delta;
               }
               start = num;
           }
           else if (rem)
               start += 0x4000;
           if (rem != 0)
           {
               blocks ++;
               offset = 16-rem;
           }
       }
       if (outputFile)
       {
           if (fwrite(buffer, length, 1, outputFile) != 1)
           {
               perror("Write error");
               return 1;
           }
       }
   }
   if (progress)
   {
       fprintf(stderr, "%10.02fs total time %9.3f MiB captured %7.1f kB/s curr rate %7.1f kB/s totalrate %d dropouts\n",
               progress->totalTime,
               progress->current.totalBytes / (1024.0 * 1024.0),
               progress->currentRate / 1024.0,
               progress->totalRate / 1024.0,
               n_err);
   }
   return exitRequested ? 1 : 0;
}

int main(int argc, char **argv)
{
   struct ftdi_context *ftdi;
   int err, c;
   FILE *of = NULL;
   char const *outfile  = 0;
   outputFile =0;
   exitRequested = 0;
   char *descstring = NULL;
   int option_index;
   static struct option long_options[] = {{NULL},};

   while ((c = getopt_long(argc, argv, "P:n", long_options, &option_index)) !=- 1)
       switch (c) 
       {
       case -1:
           break;
       case 'P':
           descstring = optarg;
           break;
       case 'n':
           check = 0;
           break;
       default:
           usage(argv[0]);
       }
   
   if (optind == argc - 1)
   {
       // Exactly one extra argument- a dump file
       outfile = argv[optind];
   }
   else if (optind < argc)
   {
       // Too many extra args
       usage(argv[0]);
   }
   
   if ((ftdi = ftdi_new()) == 0)
   {
       fprintf(stderr, "ftdi_new failed\n");
       return EXIT_FAILURE;
   }
   
   if (ftdi_set_interface(ftdi, INTERFACE_A) < 0)
   {
       fprintf(stderr, "ftdi_set_interface failed\n");
       ftdi_free(ftdi);
       return EXIT_FAILURE;
   }
   
   if (ftdi_usb_open_desc(ftdi, 0x0403, 0x6010, descstring, NULL) < 0)
   {
       fprintf(stderr,"Can't open ftdi device: %s\n",ftdi_get_error_string(ftdi));
       ftdi_free(ftdi);
       return EXIT_FAILURE;
   }
   
   /* A timeout value of 1 results in may skipped blocks */
   if(ftdi_set_latency_timer(ftdi, 2))
   {
       fprintf(stderr,"Can't set latency, Error %s\n",ftdi_get_error_string(ftdi));
       ftdi_usb_close(ftdi);
       ftdi_free(ftdi);
       return EXIT_FAILURE;
   }
   
/*   if(ftdi_usb_purge_rx_buffer(ftdi) < 0)
   {
       fprintf(stderr,"Can't rx purge\n",ftdi_get_error_string(ftdi));
       return EXIT_FAILURE;
       }*/
   if (outfile)
       if ((of = fopen(outfile,"w+")) == 0)
           fprintf(stderr,"Can't open logfile %s, Error %s\n", outfile, strerror(errno));
   if (of)
       if (setvbuf(of, NULL, _IOFBF , 1<<16) == 0)
           outputFile = of;
   signal(SIGINT, sigintHandler);
   
   err = ftdi_readstream(ftdi, readCallback, NULL, 8, 256);
   if (err < 0 && !exitRequested)
       exit(1);
   
   if (outputFile) {
       fclose(outputFile);
       outputFile = NULL;
   }
   fprintf(stderr, "Capture ended.\n");
   
   if (ftdi_set_bitmode(ftdi,  0xff, BITMODE_RESET) < 0)
   {
       fprintf(stderr,"Can't set synchronous fifo mode, Error %s\n",ftdi_get_error_string(ftdi));
       ftdi_usb_close(ftdi);
       ftdi_free(ftdi);
       return EXIT_FAILURE;
   }
   ftdi_usb_close(ftdi);
   ftdi_free(ftdi);
   signal(SIGINT, SIG_DFL);
   if (check && outfile)
   {
       if ((outputFile = fopen(outfile,"r")) == 0)
       {
           fprintf(stderr,"Can't open logfile %s, Error %s\n", outfile, strerror(errno));
           ftdi_usb_close(ftdi);
           ftdi_free(ftdi);
           return EXIT_FAILURE;
       }
       check_outfile(descstring);
       fclose(outputFile);
   }
   else if (check)
       fprintf(stderr,"%d errors of %llu blocks (%Le), %d (%Le) blocks skipped\n",
               n_err, (unsigned long long) blocks, (long double)n_err/(long double) blocks,
               skips, (long double)skips/(long double) blocks);
   exit (0);
}

void check_outfile(char *descstring)
{
    if(strcmp(descstring,"FT2232HTEST") == 0)
    {
       char buf0[1024];
       char buf1[1024];
       char bufr[1024];
       char *pa, *pb, *pc;
       unsigned int num_lines = 0, line_num = 1;
       int err_count = 0;
       unsigned int num_start, num_end;

       pa = buf0;
       pb = buf1;
       pc = buf0;
       if(fgets(pa, 1023, outputFile) == NULL)
       {
           fprintf(stderr,"Empty output file\n");
           return;
       }
       while(fgets(pb, 1023, outputFile) != NULL)
       {
           num_lines++;
           unsigned int num_save = num_start;
           if( sscanf(pa,"%6u%94s%6u",&num_start, bufr,&num_end) !=3)
           {
               fprintf(stdout,"Format doesn't match at line %8d \"%s",
                       num_lines, pa);
               err_count++;
               line_num = num_save +2;
           }
           else
           {
               if ((num_start+1)%100000 != num_end)
               {
                   if (err_count < 20)
                       fprintf(stdout,"Malformed line %d \"%s\"\n", 
                               num_lines, pa);
                   err_count++;
               }
               else if(num_start != line_num)
               {
                   if (err_count < 20)
                       fprintf(stdout,"Skipping from %d to %d\n", 
                               line_num, num_start);
                   err_count++;
                  
               }
               line_num = num_end;
           }
           pa = pb;
           pb = pc;
           pc = pa;
       }
       if(err_count)
           fprintf(stdout,"\n%d errors of %d data sets %f\n", err_count, num_lines, (double) err_count/(double)num_lines);
       else
           fprintf(stdout,"No errors for %d lines\n",num_lines);
   }
    else if(strcmp(descstring,"LLBBC10") == 0)
    { 
        uint32_t block0[4];
        uint32_t block1[4];
        uint32_t *pa = block0;
        uint32_t *pb = block1;
        uint32_t *pc = block0;
        uint32_t start= 0;
        uint32_t nread = 0;
        int n_shown = 0;
        int n_errors = 0;
        if (fread(pa, sizeof(uint32_t), 4,outputFile) < 4)
        {
            fprintf(stderr,"Empty result file\n");
            return;
        }
        while(fread(pb, sizeof(uint32_t), 4,outputFile) != 0)
        {
            blocks++;
            nread =  pa[0];
            if(start>0 && (nread != start))
            {
                if(n_shown < 30)
                {
                    fprintf(stderr, "Skip %7d blocks from 0x%08x to 0x%08x at blocks %10llu \n",
                            (nread-start)/0x4000, start -0x4000, nread, (unsigned long long) blocks);
                    n_shown ++;
                }
                n_errors++;
            }
            else if (n_shown >0) 
                n_shown--; 
            start = nread + 0x4000;
            pa = pb;
            pb = pc;
            pc = pa;
        }
        if(n_errors)
            fprintf(stderr, "%d blocks wrong from %llu blocks read\n",
                    n_errors, (unsigned long long) blocks);
        else
            fprintf(stderr, "%llu blocks all fine\n", (unsigned long long) blocks);
    }
}
07070100000031000041ED00000000000000000000000260917B8300000000000000000000000000000000000000000000002800000000libftdi1-1.5.12+git.0684c1b/ftdi_eeprom07070100000032000081A400000000000000000000000160917B8300000500000000000000000000000000000000000000003700000000libftdi1-1.5.12+git.0684c1b/ftdi_eeprom/CMakeLists.txtfind_package ( Confuse REQUIRED )
find_package ( Libintl )

# determine docdir
include(GNUInstallDirs)
if(NOT CMAKE_INSTALL_DOCDIR)
  if(WIN32)
    set(CMAKE_INSTALL_DOCDIR .)
  else(WIN32)
    set(CMAKE_INSTALL_DOCDIR ${CMAKE_INSTALL_DATAROOTDIR}/doc/${PROJECT_NAME})
  endif(WIN32)
endif(NOT CMAKE_INSTALL_DOCDIR)

message(STATUS "Building ftdi_eeprom")

include_directories ( ${CONFUSE_INCLUDE_DIRS} )
list ( APPEND libs ${CONFUSE_LIBRARIES} )

if ( LIBINTL_FOUND )
  include_directories ( ${LIBINTL_INCLUDE_DIR} )
  list ( APPEND libs ${LIBINTL_LIBRARIES} )
endif ()


# Version defines
set ( EEPROM_MAJOR_VERSION 0 )
set ( EEPROM_MINOR_VERSION 17 )
set ( EEPROM_VERSION_STRING ${EEPROM_MAJOR_VERSION}.${EEPROM_MINOR_VERSION} )

include_directories ( BEFORE ${CMAKE_SOURCE_DIR}/src )
include_directories ( BEFORE ${CMAKE_CURRENT_BINARY_DIR} )

configure_file(
               ftdi_eeprom_version.h.in
              ${CMAKE_CURRENT_BINARY_DIR}/ftdi_eeprom_version.h
)

add_executable ( ftdi_eeprom main.c )
target_link_libraries ( ftdi_eeprom ftdi1 ${CONFUSE_LIBRARIES} )
if ( LIBINTL_FOUND )
  target_link_libraries ( ftdi_eeprom ${LIBINTL_LIBRARIES} )
endif ()
install ( TARGETS ftdi_eeprom DESTINATION bin )
install ( FILES example.conf DESTINATION ${CMAKE_INSTALL_DOCDIR} )
07070100000033000081A400000000000000000000000160917B8300001C8F000000000000000000000000000000000000003500000000libftdi1-1.5.12+git.0684c1b/ftdi_eeprom/example.conf#see http://developer.intra2net.com/git/?p=libftdi;a=blob;f=src/ftdi.c
#and http://developer.intra2net.com/git/?p=libftdi;a=blob;f=src/ftdi.h
#and http://developer.intra2net.com/git/?p=libftdi;a=tree;f=ftdi_eeprom
#and http://developer.intra2net.com/git/?p=libftdi;a=blob;f=ftdi_eeprom/example.conf
#and http://developer.intra2net.com/git/?p=libftdi;a=blob;f=ftdi_eeprom/main.c

############
# Filename #
############
filename=eeprom.new 									# Filename of the EE file to be generated. Leave empty to skip file writing
#flash_raw=false										# Boolean: 

## Include another config file?
#include

############
#   IDs    #
############
vendor_id="0x0403"      								# Integer: Vendor ID. FT245R factory default 0x0403
product_id="0x6001"     								# Integer: Product ID. FT245R factory default 0x6001

##############################
# Device and Serial Strings  #
##############################
manufacturer="ACME Inc"      							# String: Manufacturer. FT245R factory default FTDI
product="USB Serial Converter" 							# String: Product. FT245R factory default FT245R USB FIFO
serial="08-15"    							   			# String: Serial"number". FT245R factory default (sample chip) A9082P2B
use_serial=true 										# Boolean: Use the serial number string

############
# Options  #
############
max_power=500   										# Integer: Max. power consumption: value * 2 mA(?). Use 0 if self_powered = true. FT245R factory default 90
self_powered=false 										# Boolean: Turn this off for bus powered
remote_wakeup=true 										# Boolean: Turn this on for remote wakeup feature

# Normally you don't have to change one of these flags
#in_is_isochronous=false								# Boolean: In Endpoint is Isochronous
#out_is_isochronous=false								# Boolean: Out Endpoint is Isochronous
#suspend_pull_downs=false								# Boolean: Enable suspend pull downs for lower power
#change_usb_version=false								# Boolean: Change USB Version
#usb_version=0x00										# Integer: Only used when change_usb_version is enabled

#default_pid=0x6001										# Integer: Default Pid.

#eeprom_type											# Integer: Chip Type / EEPROM Type. Corresponds to ftdi_chip_type struct in ftdi.h
#high_current=false										# Boolean: High Current Drive

##Type_R chips
# Only used on FT-R chips (when omitted, use chip defaults)
# Possible values correspond to enum ftdi_cbus_func in ftdi.h and strings are defined in function parse_cbus in ftdi_eeprom/main.c
# Values in the struct are (see current ftid.h for an up to date list):
# CBUS_TXDEN = 0, CBUS_PWREN = 1, CBUS_RXLED = 2, CBUS_TXLED = 3, CBUS_TXRXLED = 4, CBUS_SLEEP = 5, CBUS_CLK48 = 6, CBUS_CLK24 = 7, CBUS_CLK12 = 8, CBUS_CLK6 =  9, CBUS_IOMODE = 0xa, CBUS_BB_WR = 0xb, CBUS_BB_RD = 0xc
# Strings to be used here are: 
# "TXDEN", "PWREN", "RXLED", "TXLED", "TXRXLED", "SLEEP", "CLK48", "CLK24", "CLK12", "CLK6", "IOMODE", "BB_WR", "BB_RD"
cbus0=TXLED  											# String parsed to integer: FT245R factory default TXLED
cbus1=RXLED  											# String parsed to integer: FT245R factory default RXLED
cbus2=TXDEN  											# String parsed to integer: FT245R factory default TXDEN
cbus3=PWREN  											# String parsed to integer: FT245R factory default PWREN
cbus4=SLEEP  											# String parsed to integer: FT245R factory default SLEEP

## Only used on FT232H chips (when omitted, use chip defaults)
# Possible values correspond to enum ftdi_cbush_func in ftdi.h and strings are defined in function parse_cbush in ftdi_eeprom/main.c.
# Values are (see current ftid.h for an up to date list):
# CBUSH_TRISTATE = 0, CBUSH_TXLED = 1, CBUSH_RXLED = 2, CBUSH_TXRXLED = 3, CBUSH_PWREN = 4, CBUSH_SLEEP = 5, CBUSH_DRIVE_0 = 6, CBUSH_DRIVE1 = 7, CBUSH_IOMODE = 8, CBUSH_TXDEN =  9,     CBUSH_CLK30 = 10, CBUSH_CLK15 = 11, CBUSH_CLK7_5 = 12
# Strings to be used in this config file are:
# "TRISTATE", "TXLED", "RXLED", "TXRXLED", "PWREN", "SLEEP", "DRIVE_0", "DRIVE1", "IOMODE", "TXDEN", "CLK30", "CLK15", "CLK7_5"
##Type_232H Chips			
#cbush0=TRISTATE										# String parsed to integer:
#cbush1=TRISTATE										# String parsed to integer: 
#cbush2=TRISTATE										# String parsed to integer: 
#cbush3=TRISTATE										# String parsed to integer:
#cbush4=TRISTATE										# String parsed to integer: 
#cbush5=TRISTATE										# String parsed to integer:
#cbush6=TRISTATE										# String parsed to integer:
#cbush7=TRISTATE										# String parsed to integer:
#cbush8=TRISTATE										# String parsed to integer: 
#cbush9=TRISTATE										# String parsed to integer:
# Group Drive
# Strings to be used in this config file are:
# "4MA", "8MA", "12MA", "16MA"
#group0_drive											# Integer: 

# Only used on FT230X chips (when omitted, use chip defaults)
# Possible values correspond to enum ftdi_cbusx_func in ftdi.h and strings are defined in function parse_cbusx in ftdi_eeprom/main.c.
# Values are (see current ftid.h for an up to date list):
# CBUSX_TRISTATE = 0, CBUSX_TXLED = 1, CBUSX_RXLED = 2, CBUSX_TXRXLED = 3, CBUSX_PWREN = 4, CBUSX_SLEEP = 5, CBUSX_DRIVE_0 = 6, CBUSX_DRIVE1 = 7, CBUSX_IOMODE = 8, CBUSX_TXDEN =  9,     CBUSX_CLK24 = 10, CBUSX_CLK12 = 11, CBUSX_CLK6 = 12, CBUSX_BAT_DETECT = 13, CBUSX_BAT_DETECT_NEG = 14, CBUSX_I2C_TXE = 15, CBUSX_I2C_RXF = 16, CBUSX_VBUS_SENSE = 17, CBUSX_BB_WR = 18, CBUSX_BB_RD = 19, CBUSX_TIME_STAMP = 20, CBUSX_AWAKE = 21
# Strings to be used in this config file are: 
# "TRISTATE", "TXLED", "RXLED", "TXRXLED", "PWREN", "SLEEP", "DRIVE_0", "DRIVE1", "IOMODE", "TXDEN", "CLK24", "CLK12", "CLK6", "BAT_DETECT", "BAT_DETECT_NEG", "I2C_TXE", "I2C_RXF", "VBUS_SENSE", "BB_WR", "BB_RD", "TIME_STAMP", "AWAKE"
#cbusx0=TXDEN											# String parsed to integer: 
#cbusx1=RXLED											# String parsed to integer:
#cbusx2=TXLED											# String parsed to integer:
#cbusx3=SLEEP											# String parsed to integer:

########
# Misc #
########

## Pin Configuration
#invert_txd												# Boolean: Invert TXD signal
#invert_rxd												# Boolean: Invert RXD signal
#invert_rts												# Boolean: Invert RTS signal
#invert_cts												# Boolean: Invert CTS signal
#invert_dtr												# Boolean: Invert DTR signal
#invert_dsr												# Boolean: Invert DSR signal
#invert_dcd												# Boolean: Invert DCD signal
#invert_ri												# Boolean: Invert RI signal

## Channel Types and Drivers
# Possible values are (see current ftid.h (Interface Mode macros) and ftdi.c "channel_mode" for an up to date list). They are parsed in fucntion parse_chtype in ftdi_eeprom/main.c.
# (from ftid.h): UART= 0x0, FIFO = 0x1, OPTO = 0x2, CPU = 0x4, FT1284 = 0x8, RS485 = 0x10
# (from ftdi.c): UART = 0x0, FIOF = 0x1, CPU = 0x2, OPTO = 0x3, FT1284 = 0x3
# Strings to be used in this config file are: 
# "UART", "FIFO", "OPTO", "CPU", "FT1284"
cha_type=FIFO											# String parsed to integer:
#chb_type												# String parsed to integer:

cha_vcp=false											# Boolean:
#chb_vcp=false											# Boolean:
#chc_vcp=false											# Boolean:
#chd_vcp=false											# Boolean:
#cha_rs485												# Boolean:
#chb_rs485												# Boolean:
#chc_rs485												# Boolean:
#chd_rs485												# Boolean:

## Include user defined binary data into the the eeprom at address?
#user_data_addr											# Integer:
#user_data_file											# String: Filename of the data file to be used


07070100000034000081A400000000000000000000000160917B83000000E7000000000000000000000000000000000000004100000000libftdi1-1.5.12+git.0684c1b/ftdi_eeprom/ftdi_eeprom_version.h.in#ifndef _FTDI_EEPROM_VERSION_H
#define _FTDI_EEPROM_VERSION_H

#define EEPROM_MAJOR_VERSION @EEPROM_MAJOR_VERSION@
#define EEPROM_MINOR_VERSION @EEPROM_MINOR_VERSION@
#define EEPROM_VERSION_STRING "@EEPROM_VERSION_STRING@"

#endif
07070100000035000081A400000000000000000000000160917B8300005CED000000000000000000000000000000000000002F00000000libftdi1-1.5.12+git.0684c1b/ftdi_eeprom/main.c/***************************************************************************
                             main.c  -  description
                           -------------------
    begin                : Mon Apr  7 12:05:22 CEST 2003
    copyright            : (C) 2003-2020 by Intra2net AG and the libftdi developers
    email                : opensource@intra2net.com
    SPDX-License-Identifier: GPL-2.0-only
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License version 2 as     *
 *   published by the Free Software Foundation.                            *
 *                                                                         *
 ***************************************************************************/

/*
 TODO:
    - Merge Uwe's eeprom tool. Current features:
        - Init eeprom defaults based upon eeprom type
        - Read -> Already there
        - Write -> Already there
        - Erase -> Already there
        - Decode on stdout
        - Ability to find device by PID/VID, product name or serial

 TODO nice-to-have:
    - Out-of-the-box compatibility with FTDI's eeprom tool configuration files
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>

#include <confuse.h>
#include <libusb.h>
#include <ftdi.h>
#include <ftdi_eeprom_version.h>

static int parse_cbus(cfg_t *cfg, cfg_opt_t *opt, const char *value, void *result)
{
    static const char* options[] =
    {
        "TXDEN", "PWREN", "RXLED", "TXLED", "TXRXLED", "SLEEP", "CLK48",
        "CLK24", "CLK12", "CLK6", "IOMODE", "BB_WR", "BB_RD"
    };

    int i;
    for (i=0; i<sizeof(options)/sizeof(*options); i++)
    {
        if (!(strcmp(options[i], value)))
        {
            *(int *)result = i;
            return 0;
        }
    }

    cfg_error(cfg, "Invalid %s option '%s'", cfg_opt_name(opt), value);
    return -1;
}

static int parse_group0_drive(cfg_t *cfg, cfg_opt_t *opt, const char *value, void *result)
{
    static const char* options[] =
    {
        "4MA", "8MA", "12MA", "16MA"
    };

    int i;
    for (i=0; i<sizeof(options)/sizeof(*options); i++)
    {
        if (!(strcasecmp(options[i], value)))
        {
            *(int *)result = i;
            return 0;
        }
    }

    cfg_error(cfg, "Invalid %s option '%s'", cfg_opt_name(opt), value);
    return -1;
}

static int parse_cbush(cfg_t *cfg, cfg_opt_t *opt, const char *value, void *result)
{
    static const char* options[] =
    {
        "TRISTATE", "TXLED", "RXLED", "TXRXLED", "PWREN", "SLEEP",
        "DRIVE_0", "DRIVE1", "IOMODE", "TXDEN", "CLK30", "CLK15", "CLK7_5"
    };

    int i;
    for (i=0; i<sizeof(options)/sizeof(*options); i++)
    {
        if (!(strcmp(options[i], value)))
        {
            *(int *)result = i;
            return 0;
        }
    }

    cfg_error(cfg, "Invalid %s option '%s'", cfg_opt_name(opt), value);
    return -1;
}

static int parse_cbusx(cfg_t *cfg, cfg_opt_t *opt, const char *value, void *result)
{
    static const char* options[] =
    {
        "TRISTATE", "TXLED", "RXLED", "TXRXLED", "PWREN", "SLEEP",
        "DRIVE_0", "DRIVE1", "IOMODE", "TXDEN", "CLK24", "CLK12",
        "CLK6", "BAT_DETECT", "BAT_DETECT_NEG", "I2C_TXE", "I2C_RXF", "VBUS_SENSE",
        "BB_WR", "BB_RD", "TIME_STAMP", "AWAKE"
    };

    int i;
    for (i=0; i<sizeof(options)/sizeof(*options); i++)
    {
        if (!(strcmp(options[i], value)))
        {
            *(int *)result = i;
            return 0;
        }
    }

    cfg_error(cfg, "Invalid %s option '%s'", cfg_opt_name(opt), value);
    return -1;
}

static int parse_chtype(cfg_t *cfg, cfg_opt_t *opt, const char *value, void *result)
{
    static const struct
    {
        char* key;
	int   opt;
    } options[] =
    {
        { "UART",   CHANNEL_IS_UART },
        { "FIFO",   CHANNEL_IS_FIFO },
        { "OPTO",   CHANNEL_IS_OPTO },
        { "CPU",    CHANNEL_IS_CPU },
        { "FT1284", CHANNEL_IS_FT1284}
    };

    int i;
    for (i=0; i<sizeof(options)/sizeof(*options); i++)
    {
        if (!(strcmp(options[i].key, value)))
        {
            *(int *)result = options[i].opt;
            return 0;
        }
    }

    cfg_error(cfg, "Invalid %s option '%s'", cfg_opt_name(opt), value);
    return -1;
}

/**
 * @brief Set eeprom value
 *
 * \param ftdi pointer to ftdi_context
 * \param value_name Enum of the value to set
 * \param value Value to set
 *
 * Function will abort the program on error
 **/
static void eeprom_set_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int value)
{
    if (ftdi_set_eeprom_value(ftdi, value_name, value) < 0)
    {
        printf("Unable to set eeprom value %d: %s. Aborting\n", value_name, ftdi_get_error_string(ftdi));
        exit (-1);
    }
}

/**
 * @brief Get eeprom value
 *
 * \param ftdi pointer to ftdi_context
 * \param value_name Enum of the value to get
 * \param value Value to get
 *
 * Function will abort the program on error
 **/
static void eeprom_get_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int *value)
{
    if (ftdi_get_eeprom_value(ftdi, value_name, value) < 0)
    {
        printf("Unable to get eeprom value %d: %s. Aborting\n", value_name, ftdi_get_error_string(ftdi));
        exit (-1);
    }
}

static void usage(const char *program)
{
    fprintf(stderr, "Syntax: %s [...options...] <config-file>\n", program);
    fprintf(stderr, "Valid Options:\n");
    fprintf(stderr, "--device <description>  Specify device to open by description string. One of:\n");
    fprintf(stderr, "         d:<device node>\n");
    fprintf(stderr, "         i:<vendor>:<product>\n");
    fprintf(stderr, "         i:<vendor>:<product>:<index>\n");
    fprintf(stderr, "         s:<vendor>:<product>:<serial>\n");
    fprintf(stderr, "--read-eeprom           Read eeprom and write to -filename- from config-file\n");
    fprintf(stderr, "--build-eeprom          Build eeprom image\n");
    fprintf(stderr, "--erase-eeprom          Erase eeprom\n");
    fprintf(stderr, "--flash-eeprom          Flash eeprom\n");
    fprintf(stderr, "--verbose               Print more information\n");
}

int main(int argc, char *argv[])
{
    /*
    configuration options
    */
    cfg_opt_t opts[] =
    {
        CFG_INT("vendor_id", 0, 0),
        CFG_INT("product_id", 0, 0),
        CFG_INT("release_number", -1, 0),
        CFG_BOOL("self_powered", cfg_true, 0),
        CFG_BOOL("remote_wakeup", cfg_true, 0),
        CFG_BOOL("in_is_isochronous", cfg_false, 0),
        CFG_BOOL("out_is_isochronous", cfg_false, 0),
        CFG_BOOL("suspend_pull_downs", cfg_false, 0),
        CFG_BOOL("use_serial", cfg_false, 0),
        CFG_BOOL("change_usb_version", cfg_false, 0),
        CFG_INT("usb_version", 0, 0),
        CFG_INT("default_pid", 0x6001, 0),
        CFG_INT("max_power", 0, 0),
        CFG_STR("manufacturer", "Acme Inc.", 0),
        CFG_STR("product", "USB Serial Converter", 0),
        CFG_STR("serial", "08-15", 0),
        CFG_INT("eeprom_type", 0x00, 0),
        CFG_STR("filename", "", 0),
        CFG_BOOL("flash_raw", cfg_false, 0),
        CFG_BOOL("high_current", cfg_false, 0),
        CFG_INT_CB("cbus0", -1, 0, parse_cbus),
        CFG_INT_CB("cbus1", -1, 0, parse_cbus),
        CFG_INT_CB("cbus2", -1, 0, parse_cbus),
        CFG_INT_CB("cbus3", -1, 0, parse_cbus),
        CFG_INT_CB("cbus4", -1, 0, parse_cbus),
        CFG_INT_CB("cbush0", -1, 0, parse_cbush),
        CFG_INT_CB("cbush1", -1, 0, parse_cbush),
        CFG_INT_CB("cbush2", -1, 0, parse_cbush),
        CFG_INT_CB("cbush3", -1, 0, parse_cbush),
        CFG_INT_CB("cbush4", -1, 0, parse_cbush),
        CFG_INT_CB("cbush5", -1, 0, parse_cbush),
        CFG_INT_CB("cbush6", -1, 0, parse_cbush),
        CFG_INT_CB("cbush7", -1, 0, parse_cbush),
        CFG_INT_CB("cbush8", -1, 0, parse_cbush),
        CFG_INT_CB("cbush9", -1, 0, parse_cbush),
        CFG_INT_CB("cbusx0", -1, 0, parse_cbusx),
        CFG_INT_CB("cbusx1", -1, 0, parse_cbusx),
        CFG_INT_CB("cbusx2", -1, 0, parse_cbusx),
        CFG_INT_CB("cbusx3", -1, 0, parse_cbusx),
        CFG_INT_CB("group0_drive", -1, 0, parse_group0_drive),
        CFG_BOOL("invert_txd", cfg_false, 0),
        CFG_BOOL("invert_rxd", cfg_false, 0),
        CFG_BOOL("invert_rts", cfg_false, 0),
        CFG_BOOL("invert_cts", cfg_false, 0),
        CFG_BOOL("invert_dtr", cfg_false, 0),
        CFG_BOOL("invert_dsr", cfg_false, 0),
        CFG_BOOL("invert_dcd", cfg_false, 0),
        CFG_BOOL("invert_ri", cfg_false, 0),
        CFG_INT_CB("cha_type", -1, 0, parse_chtype),
        CFG_INT_CB("chb_type", -1, 0, parse_chtype),
        CFG_BOOL("cha_vcp", cfg_true, 0),
        CFG_BOOL("chb_vcp", cfg_true, 0),
        CFG_BOOL("chc_vcp", cfg_true, 0),
        CFG_BOOL("chd_vcp", cfg_true, 0),
        CFG_BOOL("cha_rs485", cfg_false, 0),
        CFG_BOOL("chb_rs485", cfg_false, 0),
        CFG_BOOL("chc_rs485", cfg_false, 0),
        CFG_BOOL("chd_rs485", cfg_false, 0),
        CFG_FUNC("include", &cfg_include),
        CFG_INT("user_data_addr", 0x18, 0),
        CFG_STR("user_data_file", "", 0),
        CFG_END()
    };
    cfg_t *cfg;

    /*
    normal variables
    */
    enum {
        COMMAND_READ = 1,
        COMMAND_ERASE,
        COMMAND_FLASH,
        COMMAND_BUILD
    } command = 0;
    const char *cfg_filename = NULL;
    const char *device_description = NULL;
    const char *user_data_file = NULL;
    char *user_data_buffer = NULL;

    const int max_eeprom_size = 256;
    int my_eeprom_size = 0;
    unsigned char *eeprom_buf = NULL;
    char *filename;
    int size_check;
    int i;
    FILE *fp;

    int verbose=0;

    struct ftdi_context *ftdi = NULL;

    printf("\nFTDI eeprom generator v%s\n", EEPROM_VERSION_STRING);
    printf ("(c) Intra2net AG and the libftdi developers <opensource@intra2net.com>\n");

    for (i = 1; i < argc; i++) {
        if (*argv[i] != '-')
        {
            cfg_filename = argv[i];
        }
        else if (!strcmp(argv[i], "--device"))
        {
            if (i+1 >= argc)
            {
                usage(argv[0]);
                exit(-1);
            }
            device_description = argv[++i];
        }
        else if (!strcmp(argv[i], "--read-eeprom"))
        {
            command = COMMAND_READ;
        }
        else if (!strcmp(argv[i], "--erase-eeprom"))
        {
            command = COMMAND_ERASE;
        }
        else if (!strcmp(argv[i], "--flash-eeprom"))
        {
            command = COMMAND_FLASH;
        }
        else if (!strcmp(argv[i], "--build-eeprom"))
        {
            command = COMMAND_BUILD;
        }
        else if (!strcmp(argv[i], "--verbose"))
        {
            verbose = 1;
        }
        else
        {
            usage(argv[0]);
            exit(-1);
        }
    }

    if (!cfg_filename)
    {
        usage(argv[0]);
        exit(-1);
    }

    if ((fp = fopen(cfg_filename, "r")) == NULL)
    {
        printf ("Can't open configuration file\n");
        exit (-1);
    }
    fclose (fp);

    cfg = cfg_init(opts, 0);
    cfg_parse(cfg, cfg_filename);
    filename = cfg_getstr(cfg, "filename");

    if (cfg_getbool(cfg, "self_powered") && cfg_getint(cfg, "max_power") > 0)
        printf("Hint: Self powered devices should have a max_power setting of 0.\n");

    if ((ftdi = ftdi_new()) == 0)
    {
        fprintf(stderr, "Failed to allocate ftdi structure :%s \n",
                ftdi_get_error_string(ftdi));
        return EXIT_FAILURE;
    }

    if (device_description != NULL)
    {
        i = ftdi_usb_open_string(ftdi, device_description);

        if (i != 0)
        {
            printf("Unable to find FTDI device with description: %s\n",
                   device_description);
            printf("Error code: %d (%s)\n", i, ftdi_get_error_string(ftdi));
            exit (-1);
        }
    }
    else if (command > 0)
    {
        int vendor_id = cfg_getint(cfg, "vendor_id");
        int product_id = cfg_getint(cfg, "product_id");

        i = ftdi_usb_open(ftdi, vendor_id, product_id);

        if (i != 0)
        {
            int default_pid = cfg_getint(cfg, "default_pid");
            printf("Unable to find FTDI devices under given vendor/product id: 0x%X/0x%X\n", vendor_id, product_id);
            printf("Error code: %d (%s)\n", i, ftdi_get_error_string(ftdi));
            printf("Retrying with default FTDI pid=%#04x.\n", default_pid);

            i = ftdi_usb_open(ftdi, 0x0403, default_pid);
            if (i != 0)
            {
                printf("Error: %s\n", ftdi->error_str);
                exit (-1);
            }
        }
    }
    ftdi_eeprom_initdefaults (ftdi, cfg_getstr(cfg, "manufacturer"),
                              cfg_getstr(cfg, "product"),
                              cfg_getstr(cfg, "serial"));

    printf("FTDI read eeprom: %d\n", ftdi_read_eeprom(ftdi));
    eeprom_get_value(ftdi, CHIP_SIZE, &my_eeprom_size);
    printf("EEPROM size: %d\n", my_eeprom_size);

    if (command == COMMAND_READ)
    {
        ftdi_eeprom_decode(ftdi, verbose);

        eeprom_buf = malloc(my_eeprom_size);
        ftdi_get_eeprom_buf(ftdi, eeprom_buf, my_eeprom_size);

        if (eeprom_buf == NULL)
        {
            fprintf(stderr, "Malloc failed, aborting\n");
            goto cleanup;
        }
        if (filename != NULL && strlen(filename) > 0)
        {
            FILE *fp = fopen (filename, "wb");
            
            if(fp)
            {
                fwrite(eeprom_buf, 1, my_eeprom_size, fp);
                fclose(fp);
            }
            else
                fprintf(stderr, "Could not open output file %s: %s\n", filename, strerror(errno));
        }
        else
        {
            printf("Warning: Not writing eeprom, you must supply a valid filename\n");
        }

        goto cleanup;
    }

    eeprom_set_value(ftdi, VENDOR_ID, cfg_getint(cfg, "vendor_id"));
    eeprom_set_value(ftdi, PRODUCT_ID, cfg_getint(cfg, "product_id"));

    if (cfg_getint(cfg, "release_number") != -1) {
        eeprom_set_value(ftdi, RELEASE_NUMBER, cfg_getint(cfg, "release_number"));
    }

    eeprom_set_value(ftdi, SELF_POWERED, cfg_getbool(cfg, "self_powered"));
    eeprom_set_value(ftdi, REMOTE_WAKEUP, cfg_getbool(cfg, "remote_wakeup"));
    eeprom_set_value(ftdi, MAX_POWER, cfg_getint(cfg, "max_power"));

    eeprom_set_value(ftdi, IN_IS_ISOCHRONOUS, cfg_getbool(cfg, "in_is_isochronous"));
    eeprom_set_value(ftdi, OUT_IS_ISOCHRONOUS, cfg_getbool(cfg, "out_is_isochronous"));
    eeprom_set_value(ftdi, SUSPEND_PULL_DOWNS, cfg_getbool(cfg, "suspend_pull_downs"));

    eeprom_set_value(ftdi, USE_SERIAL, cfg_getbool(cfg, "use_serial"));
    eeprom_set_value(ftdi, USE_USB_VERSION, cfg_getbool(cfg, "change_usb_version"));
    eeprom_set_value(ftdi, USB_VERSION, cfg_getint(cfg, "usb_version"));
    eeprom_set_value(ftdi, CHIP_TYPE, cfg_getint(cfg, "eeprom_type"));

    eeprom_set_value(ftdi, HIGH_CURRENT, cfg_getbool(cfg, "high_current"));

    if (ftdi->type == TYPE_R)
    {
        if (cfg_getint(cfg, "cbus0") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_0, cfg_getint(cfg, "cbus0"));
        if (cfg_getint(cfg, "cbus1") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_1, cfg_getint(cfg, "cbus1"));
        if (cfg_getint(cfg, "cbus2") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_2, cfg_getint(cfg, "cbus2"));
        if (cfg_getint(cfg, "cbus3") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_3, cfg_getint(cfg, "cbus3"));
        if (cfg_getint(cfg, "cbus4") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_4, cfg_getint(cfg, "cbus4"));
    }
    else if (ftdi->type == TYPE_232H)
    {
        if (cfg_getint(cfg, "cbush0") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_0, cfg_getint(cfg, "cbush0"));
        if (cfg_getint(cfg, "cbush1") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_1, cfg_getint(cfg, "cbush1"));
        if (cfg_getint(cfg, "cbush2") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_2, cfg_getint(cfg, "cbush2"));
        if (cfg_getint(cfg, "cbush3") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_3, cfg_getint(cfg, "cbush3"));
        if (cfg_getint(cfg, "cbush4") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_4, cfg_getint(cfg, "cbush4"));
        if (cfg_getint(cfg, "cbush5") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_5, cfg_getint(cfg, "cbush5"));
        if (cfg_getint(cfg, "cbush6") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_6, cfg_getint(cfg, "cbush6"));
        if (cfg_getint(cfg, "cbush7") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_7, cfg_getint(cfg, "cbush7"));
        if (cfg_getint(cfg, "cbush8") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_8, cfg_getint(cfg, "cbush8"));
        if (cfg_getint(cfg, "cbush9") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_9, cfg_getint(cfg, "cbush9"));
        if (cfg_getint(cfg, "group0_drive") != -1)
            eeprom_set_value(ftdi, GROUP0_DRIVE, cfg_getint(cfg, "group0_drive"));
    }
    else if (ftdi->type == TYPE_230X)
    {
        if (cfg_getint(cfg, "cbusx0") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_0, cfg_getint(cfg, "cbusx0"));
        if (cfg_getint(cfg, "cbusx1") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_1, cfg_getint(cfg, "cbusx1"));
        if (cfg_getint(cfg, "cbusx2") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_2, cfg_getint(cfg, "cbusx2"));
        if (cfg_getint(cfg, "cbusx3") != -1)
            eeprom_set_value(ftdi, CBUS_FUNCTION_3, cfg_getint(cfg, "cbusx3"));
    }

    int invert = 0;
    if (cfg_getbool(cfg, "invert_rxd")) invert |= INVERT_RXD;
    if (cfg_getbool(cfg, "invert_txd")) invert |= INVERT_TXD;
    if (cfg_getbool(cfg, "invert_rts")) invert |= INVERT_RTS;
    if (cfg_getbool(cfg, "invert_cts")) invert |= INVERT_CTS;
    if (cfg_getbool(cfg, "invert_dtr")) invert |= INVERT_DTR;
    if (cfg_getbool(cfg, "invert_dsr")) invert |= INVERT_DSR;
    if (cfg_getbool(cfg, "invert_dcd")) invert |= INVERT_DCD;
    if (cfg_getbool(cfg, "invert_ri")) invert |= INVERT_RI;
    eeprom_set_value(ftdi, INVERT, invert);

    if (cfg_getint(cfg, "cha_type") != -1)
        eeprom_set_value(ftdi, CHANNEL_A_TYPE, cfg_getint(cfg, "cha_type"));
    if (cfg_getint(cfg, "chb_type") != -1)
        eeprom_set_value(ftdi, CHANNEL_B_TYPE, cfg_getint(cfg, "chb_type"));

    eeprom_set_value(ftdi, CHANNEL_A_DRIVER,
                     cfg_getbool(cfg, "cha_vcp") ? DRIVER_VCP : 0);
    eeprom_set_value(ftdi, CHANNEL_B_DRIVER,
                     cfg_getbool(cfg, "chb_vcp") ? DRIVER_VCP : 0);
    eeprom_set_value(ftdi, CHANNEL_C_DRIVER,
                     cfg_getbool(cfg, "chc_vcp") ? DRIVER_VCP : 0);
    eeprom_set_value(ftdi, CHANNEL_D_DRIVER,
                     cfg_getbool(cfg, "chd_vcp") ? DRIVER_VCP : 0);

    eeprom_set_value(ftdi, CHANNEL_A_RS485, cfg_getbool(cfg, "cha_rs485"));
    eeprom_set_value(ftdi, CHANNEL_B_RS485, cfg_getbool(cfg, "chb_rs485"));
    eeprom_set_value(ftdi, CHANNEL_C_RS485, cfg_getbool(cfg, "chc_rs485"));
    eeprom_set_value(ftdi, CHANNEL_D_RS485, cfg_getbool(cfg, "chd_rs485"));

    /* Arbitrary user data */
    eeprom_set_value(ftdi, USER_DATA_ADDR, cfg_getint(cfg, "user_data_addr"));
    user_data_file = cfg_getstr(cfg, "user_data_file");
    if (user_data_file && strlen(user_data_file) > 0)
    {
        int data_size;
        struct stat st;

        printf("User data file: %s\n", user_data_file);
        /* Allocate a buffer for the user data */
        user_data_buffer = (char *)malloc(max_eeprom_size);
        if (user_data_buffer == NULL)
        {
            fprintf(stderr, "Malloc failed, aborting\n");
            goto cleanup;
        }

        if (stat(user_data_file, &st))
        {
            printf ("Can't stat user data file %s.\n", user_data_file);
            exit (-1);
        }
        if (st.st_size > max_eeprom_size)
            printf("Warning: %s is too big, only reading %d bytes\n",
                   user_data_file, max_eeprom_size);
        /* Read the user data file, no more than max_eeprom_size bytes */
        FILE *fp = fopen(user_data_file, "rb");
        if (fp == NULL)
        {
            printf ("Can't open user data file %s.\n", user_data_file);
            exit (-1);
        }
        data_size = fread(user_data_buffer, 1, max_eeprom_size, fp);
        fclose(fp);
        if (data_size < 1)
        {
            printf ("Can't read user data file %s.\n", user_data_file);
            exit (-1);
        }
        printf("User data size: %d\n", data_size);

        ftdi_set_eeprom_user_data(ftdi, user_data_buffer, data_size);
    }


    if (command == COMMAND_ERASE)
    {
        printf("FTDI erase eeprom: %d\n", ftdi_erase_eeprom(ftdi));
    }

    size_check = ftdi_eeprom_build(ftdi);
    eeprom_get_value(ftdi, CHIP_SIZE, &my_eeprom_size);

    if (size_check == -1)
    {
        printf ("Sorry, the eeprom can only contain %d bytes.\n", my_eeprom_size);
        goto cleanup;
    }
    else if (size_check < 0)
    {
        printf ("ftdi_eeprom_build(): error: %d\n", size_check);
        goto cleanup;
    }
    else
    {
        printf ("Used eeprom space: %d bytes\n", my_eeprom_size-size_check);
    }

    if (command == COMMAND_FLASH)
    {
        if (cfg_getbool(cfg, "flash_raw"))
        {
            if (filename != NULL && strlen(filename) > 0)
            {
                eeprom_buf = malloc(max_eeprom_size);
                FILE *fp = fopen(filename, "rb");
                if (fp == NULL)
                {
                    printf ("Can't open eeprom file %s.\n", filename);
                    exit (-1);
                }
                my_eeprom_size = fread(eeprom_buf, 1, max_eeprom_size, fp);
                fclose(fp);
                if (my_eeprom_size < 128)
                {
                    printf ("Can't read eeprom file %s.\n", filename);
                    exit (-1);
                }

                printf("Flashing raw eeprom from file %s (%d bytes)\n",
                       filename, my_eeprom_size);

                ftdi_set_eeprom_buf(ftdi, eeprom_buf, my_eeprom_size);
            } else
            {
                printf ("ERROR: flash_raw mode enabled, but no eeprom filename "
                        "given in config file.\n");
                exit (-1);
            }
        }
        printf ("FTDI write eeprom: %d\n", ftdi_write_eeprom(ftdi));
        libusb_reset_device(ftdi->usb_dev);
    }

    // Write to file?
    if (filename != NULL && strlen(filename) > 0 && !cfg_getbool(cfg, "flash_raw"))
    {
        fp = fopen(filename, "w");
        if (fp == NULL)
        {
            printf ("Can't write eeprom file.\n");
            exit (-1);
        }
        else
            printf ("Writing to file: %s\n", filename);

        if (eeprom_buf == NULL)
            eeprom_buf = malloc(my_eeprom_size);
        ftdi_get_eeprom_buf(ftdi, eeprom_buf, my_eeprom_size);

        fwrite(eeprom_buf, my_eeprom_size, 1, fp);
        fclose(fp);
    }

cleanup:
    if (eeprom_buf)
        free(eeprom_buf);
    if (user_data_buffer)
        free(user_data_buffer);
    if (command > 0)
    {
        printf("FTDI close: %d\n", ftdi_usb_close(ftdi));
    }

    ftdi_deinit (ftdi);
    ftdi_free (ftdi);

    cfg_free(cfg);

    printf("\n");
    return 0;
}
07070100000036000041ED00000000000000000000000260917B8300000000000000000000000000000000000000000000002300000000libftdi1-1.5.12+git.0684c1b/ftdipp07070100000037000081A400000000000000000000000160917B83000005A0000000000000000000000000000000000000003200000000libftdi1-1.5.12+git.0684c1b/ftdipp/CMakeLists.txt# vim: ts=2:sw=2:sts=2

# Targets
set(cpp_sources ${CMAKE_CURRENT_SOURCE_DIR}/ftdi.cpp CACHE INTERNAL "List of cpp sources" )
set(cpp_headers ${CMAKE_CURRENT_SOURCE_DIR}/ftdi.hpp CACHE INTERNAL "List of cpp headers" )

# Includes
include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR}
	${CMAKE_CURRENT_SOURCE_DIR}
	${CMAKE_SOURCE_DIR}/src)

include_directories(${Boost_INCLUDE_DIRS})

# Shared library
add_library(ftdipp1 SHARED ${cpp_sources})

math(EXPR VERSION_FIXUP "${MAJOR_VERSION} + 1")    # Compatibility with previous releases
set_target_properties(ftdipp1 PROPERTIES VERSION ${VERSION_FIXUP}.${MINOR_VERSION}.0 SOVERSION 3)

# Prevent clobbering each other during the build
set_target_properties(ftdipp1 PROPERTIES CLEAN_DIRECT_OUTPUT 1)

# Dependencies
target_link_libraries(ftdipp1 ftdi1 ${LIBUSB_LIBRARIES} ${BOOST_LIBRARIES})

install ( TARGETS ftdipp1
					RUNTIME DESTINATION bin
					LIBRARY DESTINATION lib${LIB_SUFFIX}
					ARCHIVE DESTINATION lib${LIB_SUFFIX}
				)

# Static library
if ( STATICLIBS )
	add_library(ftdipp1-static STATIC ${cpp_sources})
	set_target_properties(ftdipp1-static PROPERTIES OUTPUT_NAME "ftdipp1")
	set_target_properties(ftdipp1-static PROPERTIES CLEAN_DIRECT_OUTPUT 1)

	install ( TARGETS ftdipp1-static
						ARCHIVE DESTINATION lib${LIB_SUFFIX}
						COMPONENT staticlibs
					)
endif ()

install ( FILES ${cpp_headers}
					DESTINATION include/${PROJECT_NAME}
					COMPONENT headers
				)
07070100000038000081A400000000000000000000000160917B83000038F3000000000000000000000000000000000000002C00000000libftdi1-1.5.12+git.0684c1b/ftdipp/ftdi.cpp/***************************************************************************
                          ftdi.cpp  -  C++ wrapper for libftdi
                             -------------------
    begin                : Mon Oct 13 2008
    copyright            : (C) 2008-2020 by Marek Vavruša / libftdi developers
    email                : opensource@intra2net.com and marek@vavrusa.com
 ***************************************************************************/
/*
Copyright (C) 2008-2017 by Marek Vavruša / libftdi developers

The software in this package is distributed under the GNU General
Public License version 2 (with a special exception described below).

A copy of GNU General Public License (GPL) is included in this distribution,
in the file COPYING.GPL.

As a special exception, if other files instantiate templates or use macros
or inline functions from this file, or you compile this file and link it
with other works to produce a work based on this file, this file
does not by itself cause the resulting work to be covered
by the GNU General Public License.

However the source code for this file must still be made available
in accordance with section (3) of the GNU General Public License.

This exception does not invalidate any other reasons why a work based
on this file might be covered by the GNU General Public License.
*/
#include <libusb.h>
#define _FTDI_DISABLE_DEPRECATED
#include "ftdi.hpp"
#include "ftdi_i.h"
#include "ftdi.h"

namespace Ftdi
{

class Context::Private
{
public:
    Private()
            : open(false), ftdi(0), dev(0)
    {
        ftdi = ftdi_new();
    }

    ~Private()
    {
        if (open)
            ftdi_usb_close(ftdi);

        ftdi_free(ftdi);
    }

    bool open;

    struct ftdi_context* ftdi;
    struct libusb_device* dev;

    std::string vendor;
    std::string description;
    std::string serial;
};

/*! \brief Constructor.
 */
Context::Context()
        : d( new Private() )
{
}

/*! \brief Destructor.
 */
Context::~Context()
{
}

bool Context::is_open()
{
    return d->open;
}

int Context::open(int vendor, int product)
{
    // Open device
    int ret = ftdi_usb_open(d->ftdi, vendor, product);

    if (ret < 0)
       return ret;

    return get_strings_and_reopen(false,false,false);
}

int Context::open(int vendor, int product, const std::string& description, const std::string& serial, unsigned int index)
{
    // translate empty strings to NULL
    // -> do not use them to find the device (vs. require an empty string to be set in the EEPROM)
    const char* c_description=NULL;
    const char* c_serial=NULL;
    if (!description.empty())
        c_description=description.c_str();
    if (!serial.empty())
        c_serial=serial.c_str();

    int ret = ftdi_usb_open_desc_index(d->ftdi, vendor, product, c_description, c_serial, index);

    if (ret < 0)
       return ret;

    return get_strings_and_reopen(false,!description.empty(),!serial.empty());
}

int Context::open(const std::string& description)
{
    int ret = ftdi_usb_open_string(d->ftdi, description.c_str());

    if (ret < 0)
       return ret;

    return get_strings_and_reopen(false,true,false);
}

int Context::open(struct libusb_device *dev)
{
    if (dev != 0)
        d->dev = dev;

    if (d->dev == 0)
        return -1;

    return get_strings_and_reopen();
}

int Context::close()
{
    d->open = false;
    d->dev = 0;
    return ftdi_usb_close(d->ftdi);
}

int Context::reset()
{
    return ftdi_usb_reset(d->ftdi);
}

int Context::flush(int mask)
{
    int ret;

    switch (mask & (Input | Output)) {
    case Input:
        ret = ftdi_usb_purge_rx_buffer(d->ftdi);
        break;

    case Output:
        ret = ftdi_usb_purge_tx_buffer(d->ftdi);
        break;

    case Input | Output:
        ret = ftdi_usb_purge_buffers(d->ftdi);
        break;

    default:
        // Emulate behavior of previous version.
        ret = 1;
        break;
    }

    return ret;
}

int Context::tcflush(int mask)
{
    int ret;

    switch (mask & (Input | Output)) {
    case Input:
        ret = ftdi_tciflush(d->ftdi);
        break;

    case Output:
        ret = ftdi_tcoflush(d->ftdi);
        break;

    case Input | Output:
        ret = ftdi_tcioflush(d->ftdi);
        break;

    default:
        // Emulate behavior of previous version.
        ret = 1;
        break;
    }

    return ret;
}

int Context::set_interface(enum ftdi_interface interface)
{
    return ftdi_set_interface(d->ftdi, interface);
}

void Context::set_usb_device(struct libusb_device_handle *dev)
{
    ftdi_set_usbdev(d->ftdi, dev);
    d->dev = libusb_get_device(dev);
}

int Context::set_baud_rate(int baudrate)
{
    return ftdi_set_baudrate(d->ftdi, baudrate);
}

int Context::set_line_property(enum ftdi_bits_type bits, enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
{
    return ftdi_set_line_property(d->ftdi, bits, sbit, parity);
}

int Context::set_line_property(enum ftdi_bits_type bits, enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity, enum ftdi_break_type break_type)
{
    return ftdi_set_line_property2(d->ftdi, bits, sbit, parity, break_type);
}

int Context::get_usb_read_timeout() const
{
    return d->ftdi->usb_read_timeout;
}

void Context::set_usb_read_timeout(int usb_read_timeout)
{
    d->ftdi->usb_read_timeout = usb_read_timeout;
}

int Context::get_usb_write_timeout() const
{
    return d->ftdi->usb_write_timeout;
}

void Context::set_usb_write_timeout(int usb_write_timeout)
{
    d->ftdi->usb_write_timeout = usb_write_timeout;
}

int Context::read(unsigned char *buf, int size)
{
    return ftdi_read_data(d->ftdi, buf, size);
}

int Context::set_read_chunk_size(unsigned int chunksize)
{
    return ftdi_read_data_set_chunksize(d->ftdi, chunksize);
}

int Context::read_chunk_size()
{
    unsigned chunk = -1;
    if (ftdi_read_data_get_chunksize(d->ftdi, &chunk) < 0)
        return -1;

    return chunk;
}

int Context::write(const unsigned char *buf, int size)
{
    return ftdi_write_data(d->ftdi, buf, size);
}

int Context::set_write_chunk_size(unsigned int chunksize)
{
    return ftdi_write_data_set_chunksize(d->ftdi, chunksize);
}

int Context::write_chunk_size()
{
    unsigned chunk = -1;
    if (ftdi_write_data_get_chunksize(d->ftdi, &chunk) < 0)
        return -1;

    return chunk;
}

int Context::set_flow_control(int flowctrl)
{
    return ftdi_setflowctrl(d->ftdi, flowctrl);
}

int Context::set_modem_control(int mask)
{
    int dtr = 0, rts = 0;

    if (mask & Dtr)
        dtr = 1;
    if (mask & Rts)
        rts = 1;

    return ftdi_setdtr_rts(d->ftdi, dtr, rts);
}

int Context::set_dtr(bool state)
{
    return ftdi_setdtr(d->ftdi, state);
}

int Context::set_rts(bool state)
{
    return ftdi_setrts(d->ftdi, state);
}

int Context::set_latency(unsigned char latency)
{
    return ftdi_set_latency_timer(d->ftdi, latency);
}

unsigned Context::latency()
{
    unsigned char latency = 0;
    ftdi_get_latency_timer(d->ftdi, &latency);
    return latency;
}

unsigned short Context::poll_modem_status()
{
    unsigned short status = 0;
    ftdi_poll_modem_status(d->ftdi, &status);
    return status;
}

int Context::set_event_char(unsigned char eventch, unsigned char enable)
{
    return ftdi_set_event_char(d->ftdi, eventch, enable);
}

int Context::set_error_char(unsigned char errorch, unsigned char enable)
{
    return ftdi_set_error_char(d->ftdi, errorch, enable);
}

int Context::set_bitmode(unsigned char bitmask, unsigned char mode)
{
    return ftdi_set_bitmode(d->ftdi, bitmask, mode);
}

int Context::set_bitmode(unsigned char bitmask, enum ftdi_mpsse_mode mode)
{
    return ftdi_set_bitmode(d->ftdi, bitmask, mode);
}

int Context::bitbang_disable()
{
    return ftdi_disable_bitbang(d->ftdi);
}

int Context::read_pins(unsigned char *pins)
{
    return ftdi_read_pins(d->ftdi, pins);
}

const char* Context::error_string()
{
    return ftdi_get_error_string(d->ftdi);
}

int Context::get_strings(bool vendor, bool description, bool serial)
{
    // Prepare buffers
    char ivendor[512], idesc[512], iserial[512];

    int ret = ftdi_usb_get_strings(d->ftdi, d->dev, vendor?ivendor:NULL, 512, description?idesc:NULL, 512, serial?iserial:NULL, 512);

    if (ret < 0)
        return -1;

    d->vendor = ivendor;
    d->description = idesc;
    d->serial = iserial;

    return 1;
}

int Context::get_strings_and_reopen(bool vendor, bool description, bool serial)
{
    int ret = 0;

    if(vendor || description || serial)
    {
        if (d->dev == 0)
        {
            d->dev = libusb_get_device(d->ftdi->usb_dev);
        }

        // Get device strings (closes device)
        ret=get_strings(vendor, description, serial);
        if (ret < 0)
        {
            d->open = 0;
            return ret;
        }

        // Reattach device
        ret = ftdi_usb_open_dev(d->ftdi, d->dev);
        d->open = (ret >= 0);
    }

    return ret;
}

/*! \brief Device strings properties.
 */
const std::string& Context::vendor()
{
    if(d->vendor.empty())
        get_strings_and_reopen(true,false,false);
    return d->vendor;
}

/*! \brief Device strings properties.
 */
const std::string& Context::description()
{
    if(d->description.empty())
        get_strings_and_reopen(false,true,false);
    return d->description;
}

/*! \brief Device strings properties.
 */
const std::string& Context::serial()
{
    if(d->serial.empty())
        get_strings_and_reopen(false,false,true);
    return d->serial;
}

void Context::set_context(struct ftdi_context* context)
{
    ftdi_free(d->ftdi);
    d->ftdi = context;
}

void Context::set_usb_device(struct libusb_device *dev)
{
    d->dev = dev;
}

struct ftdi_context* Context::context()
{
    return d->ftdi;
}

class Eeprom::Private
{
public:
    Private()
            : context(0)
    {}

    struct ftdi_eeprom eeprom;
    struct ftdi_context* context;
};

Eeprom::Eeprom(Context* parent)
        : d ( new Private() )
{
    d->context = parent->context();
}

Eeprom::~Eeprom()
{
}

int Eeprom::init_defaults(char* manufacturer, char *product, char * serial)
{
    return ftdi_eeprom_initdefaults(d->context, manufacturer, product, serial);
}

int Eeprom::chip_id(unsigned int *chipid)
{
    return ftdi_read_chipid(d->context, chipid);
}

int Eeprom::build(unsigned char *output)
{
    return ftdi_eeprom_build(d->context);
}

int Eeprom::read(unsigned char *eeprom)
{
    return ftdi_read_eeprom(d->context);
}

int Eeprom::write(unsigned char *eeprom)
{
    return ftdi_write_eeprom(d->context);
}

int Eeprom::read_location(int eeprom_addr, unsigned short *eeprom_val)
{
    return ftdi_read_eeprom_location(d->context, eeprom_addr, eeprom_val);
}

int Eeprom::write_location(int eeprom_addr, unsigned short eeprom_val)
{
    return ftdi_write_eeprom_location(d->context, eeprom_addr, eeprom_val);
}

int Eeprom::erase()
{
    return ftdi_erase_eeprom(d->context);
}

class List::Private
{
public:
    Private(struct ftdi_device_list* _devlist)
            : devlist(_devlist)
    {}

    ~Private()
    {
        if(devlist)
            ftdi_list_free(&devlist);
    }

    std::list<Context> list;
    struct ftdi_device_list* devlist;
};

List::List(struct ftdi_device_list* devlist)
        : d( new Private(devlist) )
{
    if (devlist != 0)
    {
        // Iterate list
        for (; devlist != 0; devlist = devlist->next)
        {
            Context c;
            c.set_usb_device(devlist->dev);
            c.get_strings();
            d->list.push_back(c);
        }
    }
}

List::~List()
{
}

/**
* Return begin iterator for accessing the contained list elements
* @return Iterator
*/
List::iterator List::begin()
{
    return d->list.begin();
}

/**
* Return end iterator for accessing the contained list elements
* @return Iterator
*/
List::iterator List::end()
{
    return d->list.end();
}

/**
* Return begin iterator for accessing the contained list elements
* @return Const iterator
*/
List::const_iterator List::begin() const
{
    return d->list.begin();
}

/**
* Return end iterator for accessing the contained list elements
* @return Const iterator
*/
List::const_iterator List::end() const
{
    return d->list.end();
}

/**
* Return begin reverse iterator for accessing the contained list elements
* @return Reverse iterator
*/
List::reverse_iterator List::rbegin()
{
    return d->list.rbegin();
}

/**
* Return end reverse iterator for accessing the contained list elements
* @return Reverse iterator
*/
List::reverse_iterator List::rend()
{
    return d->list.rend();
}

/**
* Return begin reverse iterator for accessing the contained list elements
* @return Const reverse iterator
*/
List::const_reverse_iterator List::rbegin() const
{
    return d->list.rbegin();
}

/**
* Return end reverse iterator for accessing the contained list elements
* @return Const reverse iterator
*/
List::const_reverse_iterator List::rend() const
{
    return d->list.rend();

}

/**
* Get number of elements stored in the list
* @return Number of elements
*/
List::ListType::size_type List::size() const
{
    return d->list.size();
}

/**
* Check if list is empty
* @return True if empty, false otherwise
*/
bool List::empty() const
{
    return d->list.empty();
}

/**
 * Removes all elements. Invalidates all iterators.
 * Do it in a non-throwing way and also make
 * sure we really free the allocated memory.
 */
void List::clear()
{
    ListType().swap(d->list);

    // Free device list
    if (d->devlist)
    {
        ftdi_list_free(&d->devlist);
        d->devlist = 0;
    }
}

/**
 * Appends a copy of the element as the new last element.
 * @param element Value to copy and append
*/
void List::push_back(const Context& element)
{
    d->list.push_back(element);
}

/**
 * Adds a copy of the element as the new first element.
 * @param element Value to copy and add
*/
void List::push_front(const Context& element)
{
    d->list.push_front(element);
}

/**
 * Erase one element pointed by iterator
 * @param pos Element to erase
 * @return Position of the following element (or end())
*/
List::iterator List::erase(iterator pos)
{
    return d->list.erase(pos);
}

/**
 * Erase a range of elements
 * @param beg Begin of range
 * @param end End of range
 * @return Position of the element after the erased range (or end())
*/
List::iterator List::erase(iterator beg, iterator end)
{
    return d->list.erase(beg, end);
}

List* List::find_all(Context &context, int vendor, int product)
{
    struct ftdi_device_list* dlist = 0;
    ftdi_usb_find_all(context.context(), &dlist, vendor, product);
    return new List(dlist);
}

}
07070100000039000081A400000000000000000000000160917B83000019AE000000000000000000000000000000000000002C00000000libftdi1-1.5.12+git.0684c1b/ftdipp/ftdi.hpp/***************************************************************************
                          ftdi.hpp  -  C++ wrapper for libftdi
                             -------------------
    begin                : Mon Oct 13 2008
    copyright            : (C) 2008-2020 by Marek Vavruša and libftdi developers
    email                : opensource@intra2net.com and marek@vavrusa.com
 ***************************************************************************/
/*
Copyright (C) 2008-2017 by Marek Vavruša and libftdi developers

The software in this package is distributed under the GNU General
Public License version 2 (with a special exception described below).

A copy of GNU General Public License (GPL) is included in this distribution,
in the file COPYING.GPL.

As a special exception, if other files instantiate templates or use macros
or inline functions from this file, or you compile this file and link it
with other works to produce a work based on this file, this file
does not by itself cause the resulting work to be covered
by the GNU General Public License.

However the source code for this file must still be made available
in accordance with section (3) of the GNU General Public License.

This exception does not invalidate any other reasons why a work based
on this file might be covered by the GNU General Public License.
*/
#ifndef __libftdi_hpp__
#define __libftdi_hpp__

#include <list>
#include <string>
#include <boost/shared_ptr.hpp>
#include <ftdi.h>

namespace Ftdi
{

/* Forward declarations*/
class List;
class Eeprom;

/*! \brief FTDI device context.
 * Represents single FTDI device context.
 */
class Context
{
    /* Friends */
    friend class Eeprom;
    friend class List;

public:
    /*! \brief Direction flags for flush().
     */
    enum Direction
    {
        Input = 0x2,
        Output = 0x1,
    };

    /*! \brief Modem control flags.
     */
    enum ModemCtl
    {
        Dtr = 0x2,
        Rts = 0x1,
    };

    /* Constructor, Destructor */
    Context();
    ~Context();

    /* Properties */
    Eeprom* eeprom();
    const std::string& vendor();
    const std::string& description();
    const std::string& serial();

    /* Device manipulators */
    bool is_open();
    int open(struct libusb_device *dev = 0);
    int open(int vendor, int product);
    int open(int vendor, int product, const std::string& description, const std::string& serial = std::string(), unsigned int index=0);
    int open(const std::string& description);
    int close();
    int reset();
    int DEPRECATED(flush)(int mask = Input|Output);
    int tcflush(int mask = Input|Output);
    int set_interface(enum ftdi_interface interface);
    void set_usb_device(struct libusb_device_handle *dev);

    /* Line manipulators */
    int set_baud_rate(int baudrate);
    int set_line_property(enum ftdi_bits_type bits, enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity);
    int set_line_property(enum ftdi_bits_type bits, enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity, enum ftdi_break_type break_type);
    int get_usb_read_timeout() const;
    void set_usb_read_timeout(int usb_read_timeout);
    int get_usb_write_timeout() const;
    void set_usb_write_timeout(int usb_write_timeout);

    /* I/O */
    int read(unsigned char *buf, int size);
    int write(const unsigned char *buf, int size);
    int set_read_chunk_size(unsigned int chunksize);
    int set_write_chunk_size(unsigned int chunksize);
    int read_chunk_size();
    int write_chunk_size();

    /* Async IO
    TODO: should wrap?
    int writeAsync(const unsigned char *buf, int size);
    void asyncComplete(int wait_for_more);
    */

    /* Flow control */
    int set_event_char(unsigned char eventch, unsigned char enable);
    int set_error_char(unsigned char errorch, unsigned char enable);
    int set_flow_control(int flowctrl);
    int set_modem_control(int mask = Dtr|Rts);
    int set_latency(unsigned char latency);
    int set_dtr(bool state);
    int set_rts(bool state);

    unsigned short poll_modem_status();
    unsigned latency();

    /* BitBang mode */
    int set_bitmode(unsigned char bitmask, unsigned char mode);
    int set_bitmode(unsigned char bitmask, enum ftdi_mpsse_mode mode);
    int bitbang_disable();
    int read_pins(unsigned char *pins);

    /* Misc */
    const char* error_string();

protected:
    int get_strings(bool vendor=true, bool description=true, bool serial=true);
    int get_strings_and_reopen(bool vendor=true, bool description=true, bool serial=true);

    /* Properties */
    struct ftdi_context* context();
    void set_context(struct ftdi_context* context);
    void set_usb_device(struct libusb_device *dev);

private:
    class Private;
    boost::shared_ptr<Private> d;
};

/*! \brief Device EEPROM.
 */
class Eeprom
{
public:
    Eeprom(Context* parent);
    ~Eeprom();

    int init_defaults(char *manufacturer, char* product, char * serial);
    int chip_id(unsigned int *chipid);
    int build(unsigned char *output);

    int read(unsigned char *eeprom);
    int write(unsigned char *eeprom);
    int read_location(int eeprom_addr, unsigned short *eeprom_val);
    int write_location(int eeprom_addr, unsigned short eeprom_val);
    int erase();

private:
    class Private;
    boost::shared_ptr<Private> d;
};

/*! \brief Device list.
 */
class List
{
public:
    List(struct ftdi_device_list* devlist = 0);
    ~List();

    static List* find_all(Context &context, int vendor, int product);

    /// List type storing "Context" objects
    typedef std::list<Context> ListType;
    /// Iterator type for the container
    typedef ListType::iterator iterator;
    /// Const iterator type for the container
    typedef ListType::const_iterator const_iterator;
    /// Reverse iterator type for the container
    typedef ListType::reverse_iterator reverse_iterator;
    /// Const reverse iterator type for the container
    typedef ListType::const_reverse_iterator const_reverse_iterator;

    iterator begin();
    iterator end();
    const_iterator begin() const;
    const_iterator end() const;

    reverse_iterator rbegin();
    reverse_iterator rend();
    const_reverse_iterator rbegin() const;
    const_reverse_iterator rend() const;

    ListType::size_type size() const;
    bool empty() const;
    void clear();

    void push_back(const Context& element);
    void push_front(const Context& element);

    iterator erase(iterator pos);
    iterator erase(iterator beg, iterator end);

private:
    class Private;
    boost::shared_ptr<Private> d;
};

}

#endif
0707010000003A000081A400000000000000000000000160917B8300000034000000000000000000000000000000000000002E00000000libftdi1-1.5.12+git.0684c1b/libftdi-1.0.kdev4[Project]
Manager=KDevCMakeManager
Name=libftdi-1.0
0707010000003B000081A400000000000000000000000160917B83000002CC000000000000000000000000000000000000002800000000libftdi1-1.5.12+git.0684c1b/libftdi.lnt// PC-Lint 9.00 settings
--iz:\usr\include\libusb-1.0
--i../src
--i../ftdipp

-emacro(527, ftdi_error_return)     // ignore "unreachable code"
-emacro(717, ftdi_error_return)

-epu // Pointer to unsigned/signed of the same type is ok

+fie // Allow enum to int conversion

-ecall(534, usb_close)              // silence ignored return value from usb_close

// Disable bogus BOOST warnings
-emacro(58,BOOST_ASSERT)
-emacro(506, BOOST_FOREACH)
-emacro(666, BOOST_FOREACH)
-esym(666, BOOST_FOREACH)
-emacro(1023, BOOST_FOREACH)
-emacro(1793, BOOST_FOREACH)
-esym(665, BOOST_FOREACH)
-e123

// Don't complain we are running with -wlib(0)
// as the boost headers can't be parsed properly
-estring(686, -wlib(0))
-wlib(0)
0707010000003C000081A400000000000000000000000160917B83000004EE000000000000000000000000000000000000002F00000000libftdi1-1.5.12+git.0684c1b/libftdi1-config.in#!/bin/sh

prefix=@prefix@
exec_prefix=@exec_prefix@
exec_prefix_set=no

usage()
{
	cat <<EOF
Usage: libftdi1-config [OPTIONS] [LIBRARIES]
Options:
	[--prefix[=DIR]]
	[--exec-prefix[=DIR]]
	[--version]
	[--libs]
	[--cflags]
EOF
	exit $1
}

if test $# -eq 0; then
	usage 1 1>&2
fi

while test $# -gt 0; do
  case "$1" in
  -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
  *) optarg= ;;
  esac

  case $1 in
    --prefix=*)
      prefix=$optarg
      if test $exec_prefix_set = no ; then
        exec_prefix=$optarg
      fi
      ;;
    --prefix)
      echo_prefix=yes
      ;;
    --exec-prefix=*)
      exec_prefix=$optarg
      exec_prefix_set=yes
      ;;
    --exec-prefix)
      echo_exec_prefix=yes
      ;;
    --version)
      echo @VERSION@
      exit 0
      ;;
    --cflags)
      if test "@includedir@" != /usr/include ; then
        includes="-I@includedir@"
      fi
      echo_cflags=yes
      ;;
    --libs)
      echo_libs=yes
      ;;
    *)
      usage 1 1>&2
      ;;
  esac
  shift
done

if test "$echo_prefix" = "yes"; then
	echo $prefix
fi
if test "$echo_exec_prefix" = "yes"; then
	echo $exec_prefix
fi
if test "$echo_cflags" = "yes"; then
	echo $includes
fi
if test "$echo_libs" = "yes"; then
	echo -L@libdir@ -lftdi1 @LIBS@
fi
0707010000003D000081A400000000000000000000000160917B8300000100000000000000000000000000000000000000002B00000000libftdi1-1.5.12+git.0684c1b/libftdi1.pc.inprefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@

Name: libftdi1
Description: Library to program and control the FTDI USB controller
Requires: libusb-1.0
Version: @VERSION@
Libs: -L${libdir} -lftdi1
Cflags: -I${includedir}
0707010000003E000081A400000000000000000000000160917B83000000E4000000000000000000000000000000000000002D00000000libftdi1-1.5.12+git.0684c1b/libftdipp1.pc.inprefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@

Name: libftdipp1
Description: C++ wrapper for libftdi1
Requires: libftdi1
Version: @VERSION@
Libs: -L${libdir} -lftdipp1
Cflags: -I${includedir}
0707010000003F000041ED00000000000000000000000260917B8300000000000000000000000000000000000000000000002500000000libftdi1-1.5.12+git.0684c1b/packages07070100000040000081A400000000000000000000000160917B8300000344000000000000000000000000000000000000003600000000libftdi1-1.5.12+git.0684c1b/packages/99-libftdi.rules# FTDI Devices: FT232BM/L/Q, FT245BM/L/Q, FT232RL/Q, FT245RL/Q, VNC1L with VDPS Firmware
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", MODE="0664", GROUP="plugdev"

# FTDI Devices: FT2232C/D/L, FT2232HL/Q
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6010", MODE="0664", GROUP="plugdev"

# FTDI Devices: FT4232HL/Q
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6011", MODE="0664", GROUP="plugdev"

# FTDI Devices: FT232H
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6014", MODE="0664", GROUP="plugdev"

# FTDI Devices: FT230X
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6015", MODE="0664", GROUP="plugdev"
07070100000041000081A400000000000000000000000160917B83000002B8000000000000000000000000000000000000003400000000libftdi1-1.5.12+git.0684c1b/packages/CMakeLists.txt# Debian
if("${PACKAGE}" STREQUAL "Debian")

   # Settings
   set(REVISION                           0)
   set(CPACK_GENERATOR                    "DEB" PARENT_SCOPE)
   set(CPACK_PACKAGE_VERSION              ${CPACK_PACKAGE_VERSION}-${REVISION} PARENT_SCOPE)

   # Dependencies
   set(CPACK_DEBIAN_PACKAGE_DEPENDS       "libusb-1.0-0" PARENT_SCOPE)
   set(DEBIAN_PACKAGE_BUILDS_DEPENDS      "cmake, libusb2-dev" PARENT_SCOPE)

   # Bundles
   message("-- Installing udev rules to /etc/udev/rules.d")
   install(FILES 99-libftdi.rules
           DESTINATION /etc/udev/rules.d)

endif("${PACKAGE}" STREQUAL "Debian")

# General RPM rules
set(CPACK_RPM_PACKAGE_DEPENDS       "libusb1" PARENT_SCOPE)
07070100000042000041ED00000000000000000000000360917B8300000000000000000000000000000000000000000000002300000000libftdi1-1.5.12+git.0684c1b/python07070100000043000081A400000000000000000000000160917B8300000D00000000000000000000000000000000000000003200000000libftdi1-1.5.12+git.0684c1b/python/CMakeLists.txt# swig_add_library behavior changed in cmake 3.13 to no longer set
# SWIG_MODULE_<target>_REAL_NAME, so restore the old behavior.
if ( POLICY CMP0078 )
  cmake_policy( SET CMP0078 OLD )
endif ()

# workaround for cmake bug #0013449
if ( NOT DEFINED CMAKE_FIND_ROOT_PATH OR NOT CMAKE_VERSION VERSION_LESS 3.0.0 )
  find_package ( SWIG REQUIRED )
else ()
  find_program ( SWIG_EXECUTABLE NAMES swig2.0 swig )
  if ( SWIG_EXECUTABLE )
    set ( SWIG_USE_FILE ${CMAKE_ROOT}/Modules/UseSWIG.cmake )
    set ( SWIG_FOUND TRUE )
  endif ()
endif ()
find_package ( PythonInterp REQUIRED )
find_package ( PythonLibs REQUIRED )

include ( UseSWIG )
include_directories ( BEFORE ${CMAKE_SOURCE_DIR}/src )
include_directories ( ${PYTHON_INCLUDE_DIRS} )
link_directories ( ${CMAKE_CURRENT_BINARY_DIR}/../src )

if ( DOCUMENTATION )
  set(CMAKE_SWIG_FLAGS -DDOXYGEN=${DOXYGEN_FOUND})
  # manually add dependency for new cmake / swig versions
  set_property(SOURCE ftdi1.i PROPERTY DEPENDS ftdi1_doc.i)
endif()
if(NOT CMAKE_VERSION VERSION_LESS 3.8.0)
  swig_add_library ( ftdi1 LANGUAGE python SOURCES ftdi1.i )
else ()
  swig_add_module ( ftdi1 python ftdi1.i )
endif()
swig_link_libraries ( ftdi1 ftdi1 )

if ( LINK_PYTHON_LIBRARY )
  swig_link_libraries ( ftdi1 ${PYTHON_LIBRARIES} )
elseif( APPLE )
  set_target_properties ( ${SWIG_MODULE_ftdi1_REAL_NAME} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup" )
endif ()

set_target_properties ( ${SWIG_MODULE_ftdi1_REAL_NAME} PROPERTIES NO_SONAME ON )

execute_process ( COMMAND ${PYTHON_EXECUTABLE} -c "from distutils import sysconfig; print( sysconfig.get_python_lib( plat_specific=True, prefix='${CMAKE_INSTALL_PREFIX}' ) )"
                  OUTPUT_VARIABLE _ABS_PYTHON_MODULE_PATH
                  OUTPUT_STRIP_TRAILING_WHITESPACE )

get_filename_component ( _ABS_PYTHON_MODULE_PATH ${_ABS_PYTHON_MODULE_PATH} ABSOLUTE )
file ( RELATIVE_PATH _REL_PYTHON_MODULE_PATH ${CMAKE_INSTALL_PREFIX} ${_ABS_PYTHON_MODULE_PATH} )

set ( PYTHON_MODULE_PATH ${_REL_PYTHON_MODULE_PATH} )

install ( FILES ${CMAKE_CURRENT_BINARY_DIR}/ftdi1.py DESTINATION ${PYTHON_MODULE_PATH} )
install ( TARGETS ${SWIG_MODULE_ftdi1_REAL_NAME} LIBRARY DESTINATION ${PYTHON_MODULE_PATH} )

if ( DOCUMENTATION )
    # Run doxygen to only generate the xml
    add_custom_command ( OUTPUT ${CMAKE_BINARY_DIR}/doc/xml/ftdi_8c.xml
        COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/doc
        COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_BINARY_DIR}/Doxyfile.xml
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
        DEPENDS ${c_headers};${c_sources};${cpp_sources};${cpp_headers}
    )

    # generate .i from doxygen .xml
    add_custom_command ( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/ftdi1_doc.i
        COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/doxy2swig.py -n
            ${CMAKE_BINARY_DIR}/doc/xml/ftdi_8c.xml
            ${CMAKE_CURRENT_BINARY_DIR}/ftdi1_doc.i
        DEPENDS ${CMAKE_BINARY_DIR}/doc/xml/ftdi_8c.xml
    )
    add_custom_target ( doc_i DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/ftdi1_doc.i )
    add_dependencies( ${SWIG_MODULE_ftdi1_REAL_NAME} doc_i )

endif ()

set ( LIBFTDI_PYTHON_MODULE_PATH ${CMAKE_INSTALL_PREFIX}/${PYTHON_MODULE_PATH} )
set ( LIBFTDI_PYTHON_MODULE_PATH ${LIBFTDI_PYTHON_MODULE_PATH} PARENT_SCOPE ) # for ftdiconfig.cmake

add_subdirectory ( examples )
07070100000044000081A400000000000000000000000160917B8300003BC1000000000000000000000000000000000000003000000000libftdi1-1.5.12+git.0684c1b/python/doxy2swig.py#!/usr/bin/env python
"""Doxygen XML to SWIG docstring converter.

Usage:

  doxy2swig.py [options] input.xml output.i

Converts Doxygen generated XML files into a file containing docstrings
that can be used by SWIG-1.3.x.  Note that you need to get SWIG
version > 1.3.23 or use Robin Dunn's docstring patch to be able to use
the resulting output.

input.xml is your doxygen generated XML file and output.i is where the
output will be written (the file will be clobbered).

"""
#
#
# This code is implemented using Mark Pilgrim's code as a guideline:
#   http://www.faqs.org/docs/diveintopython/kgp_divein.html
#
# Author: Prabhu Ramachandran
# License: BSD style
#
# Thanks:
#   Johan Hake:  the include_function_definition feature
#   Bill Spotz:  bug reports and testing.
#   Sebastian Henschel:   Misc. enhancements.
#
#

from xml.dom import minidom
import re
import textwrap
import sys
import os.path
import optparse


def my_open_read(source):
    if hasattr(source, "read"):
        return source
    else:
        return open(source)


def my_open_write(dest):
    if hasattr(dest, "write"):
        return dest
    else:
        return open(dest, 'w')


class Doxy2SWIG:

    """Converts Doxygen generated XML files into a file containing
    docstrings that can be used by SWIG-1.3.x that have support for
    feature("docstring").  Once the data is parsed it is stored in
    self.pieces.

    """

    def __init__(self, src, include_function_definition=True, quiet=False):
        """Initialize the instance given a source object.  `src` can
        be a file or filename.  If you do not want to include function
        definitions from doxygen then set
        `include_function_definition` to `False`.  This is handy since
        this allows you to use the swig generated function definition
        using %feature("autodoc", [0,1]).

        """
        f = my_open_read(src)
        self.my_dir = os.path.dirname(f.name)
        self.xmldoc = minidom.parse(f).documentElement
        f.close()

        self.pieces = []
        self.pieces.append('\n// File: %s\n' %
                           os.path.basename(f.name))

        self.space_re = re.compile(r'\s+')
        self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)')
        self.multi = 0
        self.ignores = ['inheritancegraph', 'param', 'listofallmembers',
                        'innerclass', 'name', 'declname', 'incdepgraph',
                        'invincdepgraph', 'programlisting', 'type',
                        'references', 'referencedby', 'location',
                        'collaborationgraph', 'reimplements',
                        'reimplementedby', 'derivedcompoundref',
                        'basecompoundref']
        #self.generics = []
        self.include_function_definition = include_function_definition
        if not include_function_definition:
            self.ignores.append('argsstring')

        self.quiet = quiet

    def generate(self):
        """Parses the file set in the initialization.  The resulting
        data is stored in `self.pieces`.

        """
        self.parse(self.xmldoc)

    def parse(self, node):
        """Parse a given node.  This function in turn calls the
        `parse_<nodeType>` functions which handle the respective
        nodes.

        """
        pm = getattr(self, "parse_%s" % node.__class__.__name__)
        pm(node)

    def parse_Document(self, node):
        self.parse(node.documentElement)

    def parse_Text(self, node):
        txt = node.data
        txt = txt.replace('\\', r'\\\\')
        txt = txt.replace('"', r'\"')
        # ignore pure whitespace
        m = self.space_re.match(txt)
        if m and len(m.group()) == len(txt):
            pass
        else:
            self.add_text(textwrap.fill(txt, break_long_words=False))

    def parse_Element(self, node):
        """Parse an `ELEMENT_NODE`.  This calls specific
        `do_<tagName>` handers for different elements.  If no handler
        is available the `generic_parse` method is called.  All
        tagNames specified in `self.ignores` are simply ignored.

        """
        name = node.tagName
        ignores = self.ignores
        if name in ignores:
            return
        attr = "do_%s" % name
        if hasattr(self, attr):
            handlerMethod = getattr(self, attr)
            handlerMethod(node)
        else:
            self.generic_parse(node)
            #if name not in self.generics: self.generics.append(name)

    def parse_Comment(self, node):
        """Parse a `COMMENT_NODE`.  This does nothing for now."""
        return

    def add_text(self, value):
        """Adds text corresponding to `value` into `self.pieces`."""
        if isinstance(value, (list, tuple)):
            self.pieces.extend(value)
        else:
            self.pieces.append(value)

    def get_specific_nodes(self, node, names):
        """Given a node and a sequence of strings in `names`, return a
        dictionary containing the names as keys and child
        `ELEMENT_NODEs`, that have a `tagName` equal to the name.

        """
        nodes = [(x.tagName, x) for x in node.childNodes
                 if x.nodeType == x.ELEMENT_NODE and
                 x.tagName in names]
        return dict(nodes)

    def generic_parse(self, node, pad=0):
        """A Generic parser for arbitrary tags in a node.

        Parameters:

         - node:  A node in the DOM.
         - pad: `int` (default: 0)

           If 0 the node data is not padded with newlines.  If 1 it
           appends a newline after parsing the childNodes.  If 2 it
           pads before and after the nodes are processed.  Defaults to
           0.

        """
        npiece = 0
        if pad:
            npiece = len(self.pieces)
            if pad == 2:
                self.add_text('\n')
        for n in node.childNodes:
            self.parse(n)
        if pad:
            if len(self.pieces) > npiece:
                self.add_text('\n')

    def space_parse(self, node):
        self.add_text(' ')
        self.generic_parse(node)

    do_ref = space_parse
    do_emphasis = space_parse
    do_bold = space_parse
    do_computeroutput = space_parse
    do_formula = space_parse

    def do_compoundname(self, node):
        self.add_text('\n\n')
        data = node.firstChild.data
        self.add_text('%%feature("docstring") %s "\n' % data)

    def do_compounddef(self, node):
        kind = node.attributes['kind'].value
        if kind in ('class', 'struct'):
            prot = node.attributes['prot'].value
            if prot != 'public':
                return
            names = ('compoundname', 'briefdescription',
                     'detaileddescription', 'includes')
            first = self.get_specific_nodes(node, names)
            for n in names:
                if first.has_key(n):
                    self.parse(first[n])
            self.add_text(['";', '\n'])
            for n in node.childNodes:
                if n not in first.values():
                    self.parse(n)
        elif kind in ('file', 'namespace'):
            nodes = node.getElementsByTagName('sectiondef')
            for n in nodes:
                self.parse(n)

    def do_includes(self, node):
        self.add_text('C++ includes: ')
        self.generic_parse(node, pad=1)

    def do_parameterlist(self, node):
        text = 'unknown'
        for key, val in node.attributes.items():
            if key == 'kind':
                if val == 'param':
                    text = 'Parameters'
                elif val == 'exception':
                    text = 'Exceptions'
                elif val == 'retval':
                    text = 'Returns'
                else:
                    text = val
                break
        self.add_text(['\n', '\n', text, ':', '\n'])
        self.generic_parse(node, pad=1)

    def do_para(self, node):
        self.add_text('\n')
        self.generic_parse(node, pad=1)

    def do_parametername(self, node):
        self.add_text('\n')
        try:
            data = node.firstChild.data
        except AttributeError:  # perhaps a <ref> tag in it
            data = node.firstChild.firstChild.data
        if data.find('Exception') != -1:
            self.add_text(data)
        else:
            self.add_text("%s: " % data)

    def do_parameterdefinition(self, node):
        self.generic_parse(node, pad=1)

    def do_detaileddescription(self, node):
        self.generic_parse(node, pad=1)

    def do_briefdescription(self, node):
        self.generic_parse(node, pad=1)

    def do_memberdef(self, node):
        prot = node.attributes['prot'].value
        id = node.attributes['id'].value
        kind = node.attributes['kind'].value
        tmp = node.parentNode.parentNode.parentNode
        compdef = tmp.getElementsByTagName('compounddef')[0]
        cdef_kind = compdef.attributes['kind'].value

        if prot == 'public':
            first = self.get_specific_nodes(node, ('definition', 'name'))
            name = first['name'].firstChild.data
            if name[:8] == 'operator':  # Don't handle operators yet.
                return

            if not 'definition' in first or \
                   kind in ['variable', 'typedef']:
                return

            if self.include_function_definition:
                defn = first['definition'].firstChild.data
            else:
                defn = ""
            self.add_text('\n')
            self.add_text('%feature("docstring") ')

            anc = node.parentNode.parentNode
            if cdef_kind in ('file', 'namespace'):
                ns_node = anc.getElementsByTagName('innernamespace')
                if not ns_node and cdef_kind == 'namespace':
                    ns_node = anc.getElementsByTagName('compoundname')
                if ns_node:
                    ns = ns_node[0].firstChild.data
                    self.add_text(' %s::%s "\n%s' % (ns, name, defn))
                else:
                    self.add_text(' %s "\n%s' % (name, defn))
            elif cdef_kind in ('class', 'struct'):
                # Get the full function name.
                anc_node = anc.getElementsByTagName('compoundname')
                cname = anc_node[0].firstChild.data
                self.add_text(' %s::%s "\n%s' % (cname, name, defn))

            for n in node.childNodes:
                if n not in first.values():
                    self.parse(n)
            self.add_text(['";', '\n'])

    def do_definition(self, node):
        data = node.firstChild.data
        self.add_text('%s "\n%s' % (data, data))

    def do_sectiondef(self, node):
        kind = node.attributes['kind'].value
        if kind in ('public-func', 'func', 'user-defined', ''):
            self.generic_parse(node)

    def do_header(self, node):
        """For a user defined section def a header field is present
        which should not be printed as such, so we comment it in the
        output."""
        data = node.firstChild.data
        self.add_text('\n/*\n %s \n*/\n' % data)
        # If our immediate sibling is a 'description' node then we
        # should comment that out also and remove it from the parent
        # node's children.
        parent = node.parentNode
        idx = parent.childNodes.index(node)
        if len(parent.childNodes) >= idx + 2:
            nd = parent.childNodes[idx + 2]
            if nd.nodeName == 'description':
                nd = parent.removeChild(nd)
                self.add_text('\n/*')
                self.generic_parse(nd)
                self.add_text('\n*/\n')

    def do_simplesect(self, node):
        kind = node.attributes['kind'].value
        if kind in ('date', 'rcs', 'version'):
            pass
        elif kind == 'warning':
            self.add_text(['\n', 'WARNING: '])
            self.generic_parse(node)
        elif kind == 'see':
            self.add_text('\n')
            self.add_text('See: ')
            self.generic_parse(node)
        else:
            self.generic_parse(node)

    def do_argsstring(self, node):
        self.generic_parse(node, pad=1)

    def do_member(self, node):
        kind = node.attributes['kind'].value
        refid = node.attributes['refid'].value
        if kind == 'function' and refid[:9] == 'namespace':
            self.generic_parse(node)

    def do_doxygenindex(self, node):
        self.multi = 1
        comps = node.getElementsByTagName('compound')
        for c in comps:
            refid = c.attributes['refid'].value
            fname = refid + '.xml'
            if not os.path.exists(fname):
                fname = os.path.join(self.my_dir,  fname)
            if not self.quiet:
                print("parsing file: %s" % fname)
            p = Doxy2SWIG(fname, self.include_function_definition, self.quiet)
            p.generate()
            self.pieces.extend(self.clean_pieces(p.pieces))

    def write(self, fname):
        o = my_open_write(fname)
        if self.multi:
            o.write("".join(self.pieces))
        else:
            o.write("".join(self.clean_pieces(self.pieces)))
        o.close()

    def clean_pieces(self, pieces):
        """Cleans the list of strings given as `pieces`.  It replaces
        multiple newlines by a maximum of 2 and returns a new list.
        It also wraps the paragraphs nicely.

        """
        ret = []
        count = 0
        for i in pieces:
            if i == '\n':
                count = count + 1
            else:
                if i == '";':
                    if count:
                        ret.append('\n')
                elif count > 2:
                    ret.append('\n\n')
                elif count:
                    ret.append('\n' * count)
                count = 0
                ret.append(i)

        _data = "".join(ret)
        ret = []
        for i in _data.split('\n\n'):
            if i == 'Parameters:' or i == 'Exceptions:' or i == 'Returns:':
                ret.extend([i, '\n' + '-' * len(i), '\n\n'])
            elif i.find('// File:') > -1:  # leave comments alone.
                ret.extend([i, '\n'])
            else:
                _tmp = textwrap.fill(i.strip(), break_long_words=False)
                _tmp = self.lead_spc.sub(r'\1"\2', _tmp)
                ret.extend([_tmp, '\n\n'])
        return ret


def convert(input, output, include_function_definition=True, quiet=False):
    p = Doxy2SWIG(input, include_function_definition, quiet)
    p.generate()
    p.write(output)


def main():
    usage = __doc__
    parser = optparse.OptionParser(usage)
    parser.add_option("-n", '--no-function-definition',
                      action='store_true',
                      default=False,
                      dest='func_def',
                      help='do not include doxygen function definitions')
    parser.add_option("-q", '--quiet',
                      action='store_true',
                      default=False,
                      dest='quiet',
                      help='be quiet and minimize output')

    options, args = parser.parse_args()
    if len(args) != 2:
        parser.error("error: no input and output specified")

    convert(args[0], args[1], not options.func_def, options.quiet)


if __name__ == '__main__':
    main()
07070100000045000041ED00000000000000000000000260917B8300000000000000000000000000000000000000000000002C00000000libftdi1-1.5.12+git.0684c1b/python/examples07070100000046000081A400000000000000000000000160917B830000009E000000000000000000000000000000000000003B00000000libftdi1-1.5.12+git.0684c1b/python/examples/CMakeLists.txtinstall ( FILES simple.py complete.py cbus.py
          DESTINATION share/libftdi/examples
          PERMISSIONS OWNER_READ GROUP_READ WORLD_READ 
        )

07070100000047000081A400000000000000000000000160917B8300001603000000000000000000000000000000000000003400000000libftdi1-1.5.12+git.0684c1b/python/examples/cbus.py#!/usr/bin/python2
"""
Copyright 2015, Sinclair R.F., Inc.

This program is distributed under the GPL, version 2.

Demonstrate how to configure the FT230X USB UART bridge as follows:
  max_power     500 mA
  CBUS3         Drive 1 (accommodate PCB error)
"""

import sys

# Need to install libftdi for the following to work (see README.txt)
import ftdi1 as ftdi

# Define class for displaying errors.
class ErrorMsg(Exception):
  def __init__(self,message):
    self.message = message
  def __str__(self):
    return self.message

# Function to convert CBUSX values to human-readable strings
def cbush_string(value):
  if value == ftdi.CBUSX_AWAKE:
    return 'AWAKE'
  if value == ftdi.CBUSX_BAT_DETECT:
    return 'BAT_DETECT'
  if value == ftdi.CBUSX_BAT_DETECT_NEG:
    return 'BAT_DETECT_NEG'
  if value == ftdi.CBUSX_BB_RD:
    return 'BB_RD'
  if value == ftdi.CBUSX_BB_WR:
    return 'BB_WR'
  if value == ftdi.CBUSX_CLK24:
    return 'CLK24'
  if value == ftdi.CBUSX_CLK12:
    return 'CLK12'
  if value == ftdi.CBUSX_CLK6:
    return 'CLK6'
  if value == ftdi.CBUSX_DRIVE_0:
    return 'DRIVE_0'
  if value == ftdi.CBUSX_DRIVE1:
    return 'DRIVE_1'
  if value == ftdi.CBUSX_I2C_RXF:
    return 'I2C_RXF'
  if value == ftdi.CBUSX_I2C_TXE:
    return 'I2C_TXE'
  if value == ftdi.CBUSX_IOMODE:
    return 'IOMODE'
  if value == ftdi.CBUSX_PWREN:
    return 'PWREN'
  if value == ftdi.CBUSX_RXLED:
    return 'RXLED'
  if value == ftdi.CBUSX_SLEEP:
    return 'SLEEP'
  if value == ftdi.CBUSX_TIME_STAMP:
    return 'TIME_STAMP'
  if value == ftdi.CBUSX_TRISTATE:
    return 'TRISTATE'
  if value == ftdi.CBUSX_TXDEN:
    return 'TXDEN'
  if value == ftdi.CBUSX_TXLED:
    return 'TXLED'
  if value == ftdi.CBUSX_TXRXLED:
    return 'TXRXLED'
  if value == ftdi.CBUSX_VBUS_SENSE:
    return 'VBUS_SENSE'
  return 'UNKNOWN'

# Surround the program with a try ... except clause.
try:

  # Allocate and inialize an ftdi context.
  ftdic = ftdi.new()
  if ftdic == 0:
    raise ErrorMsg('ftdi.new() failed')

  # List all the FT230X devices.
  nDevices, devlist = ftdi.usb_find_all(ftdic, 0x0403, 0x6015)
  if nDevices < 0:
    raise ErrorMsg('ftdi.usb_find_all error = %s' % ftdi.get_error_string(ftdic))
  elif nDevices == 0:
    raise ErrorMsg('No FT230X devices found')
  elif nDevices != 1:
    raise ErrorMsg('More than one FT230X device found')

  # Display the identified single FT230X device.
  ret, manufacturer, description, serial = ftdi.usb_get_strings(ftdic, devlist.dev)
  if ret < 0:
    raise ErrorMsg('ftdi.usb_get_strings error = %s' % ftdi.get_error_string(ftdic))
  print 'manufacturer="%s" description="%s" serial="%s"' % (manufacturer, description, serial)

  # Open the identified single FT230X device.
  ret = ftdi.usb_open_desc(ftdic, 0x0403, 0x6015, description, serial)
  if ret < 0:
    raise ErrorMsg('ftdi.usb_open_desc error = %s' % ftdi.get_error_string(ftdic))

  # Read the chip id.
  ret, chipid = ftdi.read_chipid(ftdic)
  if ret < 0:
    raise ErrorMsg('ftdi.read_chipid error = %s' % ftdi.get_error_string(ftdic))
  print 'chip id=0x%08X' % (chipid % 2**32)

  # Read the EEPROM
  ret = ftdi.read_eeprom(ftdic)
  if ret < 0:
    raise ErrorMsg('ftdi.read_eeprom error = %s' % ftdi.get_error_string(ftdic))

  # Get a read-only copy of the EEPROM
  if True:
    eeprom_size = ftdic.eeprom.size
    ret, eeprom_buf = ftdi.get_eeprom_buf(ftdic, eeprom_size)
    if ret < 0:
      raise ErrorMsg('ftdi.get_eeprom_buf error = %s' % ftdi.get_error_string(ftdic))
    for i in range(0,eeprom_size,16):
      sys.stdout.write('%04x:  ' % i)
      for j in range(16):
        sys.stdout.write('%02x ' % ord(eeprom_buf[i+j]))
        if j in (7,15,):
          sys.stdout.write(' ')
      for j in range(16):
        x = eeprom_buf[i+j]
        if 32 <= ord(x) <= 0x7E:
          sys.stdout.write(x)
        else:
          sys.stdout.write('.')
      sys.stdout.write('\n')

  # Read and display the EEPROM (in human readable format)
  ret = ftdi.eeprom_decode(ftdic, 1)
  if ret < 0:
    raise ErrorMsg('ftdi.eeprom_decode error = %s' % ftdi.get_error_string(ftdic))

  # Set the maximum power to 500mA.
  print 'initial max_power = %dmA' % ftdic.eeprom.max_power
  ftdic.eeprom.max_power = 500
  print 'new max_power = %dmA' % ftdic.eeprom.max_power

  # Set CBUS3 to DRIVE_1 (the board needs to be reworked to use PWREN# and BCD#)
  ret, value = ftdi.get_eeprom_value(ftdic,ftdi.CBUS_FUNCTION_3)
  if ret < 0:
    raise ErrorMsg('ftdi.get_eeprom_value error = %s' % ftdi.get_error_string(ftdic))
  print 'initial CBUS3 = %d (%s)' % (value,cbush_string(value),)
  ret = ftdi.set_eeprom_value(ftdic,ftdi.CBUS_FUNCTION_3,ftdi.CBUSX_DRIVE1)
  if ret < 0:
    raise ErrorMsg('ftdi.set_eeprom_value error = %s' % ftdi.get_error_string(ftdic))
  ret, value = ftdi.get_eeprom_value(ftdic,ftdi.CBUS_FUNCTION_3)
  if ret < 0:
    raise ErrorMsg('ftdi.get_eeprom_value error = %s' % ftdi.get_error_string(ftdic))
  print 'new CBUS3 = %d (%s)' % (value,cbush_string(value),)

  # Write the new EEPROM settings.
  if False:
    ret = ftdi.eeprom_build(ftdic)
    if ret < 0:
      raise ErrorMsg('ftdi.eeprom_build error = %s' % ftdi.get_error_string(ftdic))
    ret = ftdi.write_eeprom(ftdic)
    if ret < 0:
      raise ErrorMsg('ftdi.write_eeprom error = %s' % ftdi.get_error_string(ftdic))
    print 'EEPROM write succeeded'
  else:
    print 'EEPROM write not attempted'

  # Close the ftdi context.
  ret = ftdi.usb_close(ftdic)
  if ret < 0:
    raise ErrorMsg('ftdi.usb_close error = %s' % ftdi.get_error_string(ftdic))

except ErrorMsg, msg:
  print >> sys.stderr, 'FATAL ERROR:  ' + str(msg)
  exit(1)
07070100000048000081A400000000000000000000000160917B8300000B3D000000000000000000000000000000000000003800000000libftdi1-1.5.12+git.0684c1b/python/examples/complete.py#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Python example program.

Complete program to demonstrate the usage
of the swig generated python wrapper

You need to build and install the wrapper first"""

import os
import sys
import ftdi1 as ftdi
import time

# version
print ('version: %s\n' % ftdi.__version__)

# initialize
ftdic = ftdi.new()
if ftdic == 0:
    print('new failed: %d' % ret)
    os._exit(1)

# try to list ftdi devices 0x6010 or 0x6001
ret, devlist = ftdi.usb_find_all(ftdic, 0x0403, 0x6010)
if ret <= 0:
    ret, devlist = ftdi.usb_find_all(ftdic, 0x0403, 0x6001)

if ret < 0:
    print('ftdi_usb_find_all failed: %d (%s)' %
          (ret, ftdi.get_error_string(ftdic)))
    os._exit(1)
print('devices: %d' % ret)
curnode = devlist
i = 0
while(curnode != None):
    ret, manufacturer, description, serial = ftdi.usb_get_strings(
        ftdic, curnode.dev)
    if ret < 0:
        print('ftdi_usb_get_strings failed: %d (%s)' %
              (ret, ftdi.get_error_string(ftdic)))
        os._exit(1)
    print('#%d: manufacturer="%s" description="%s" serial="%s"\n' %
          (i, manufacturer, description, serial))
    curnode = curnode.next
    i += 1

# open usb
ret = ftdi.usb_open(ftdic, 0x0403, 0x6001)
if ret < 0:
    print('unable to open ftdi device: %d (%s)' %
          (ret, ftdi.get_error_string(ftdic)))
    os._exit(1)


# bitbang
ret = ftdi.set_bitmode(ftdic, 0xff, ftdi.BITMODE_BITBANG)
if ret < 0:
    print('Cannot enable bitbang')
    os._exit(1)
print('turning everything on')
ftdi.write_data(ftdic, chr(0xff), 1)
time.sleep(1)
print('turning everything off\n')
ftdi.write_data(ftdic, chr(0x00), 1)
time.sleep(1)
for i in range(8):
    val = 2 ** i
    print('enabling bit #%d (0x%02x)' % (i, val))
    ftdi.write_data(ftdic, chr(val), 1)
    time.sleep(1)
ftdi.disable_bitbang(ftdic)
print('')


# read pins
ret, pins = ftdi.read_pins(ftdic)
if (ret == 0):
    if sys.version_info[0] < 3:  # python 2
        pins = ord(pins)
    else:
        pins = pins[0]
    print('pins: 0x%x' % pins)


# read chip id
ret, chipid = ftdi.read_chipid(ftdic)
if (ret == 0):
    print('chip id: %x\n' % chipid)


# read eeprom
eeprom_addr = 1
ret, eeprom_val = ftdi.read_eeprom_location(ftdic, eeprom_addr)
if (ret == 0):
    print('eeprom @ %d: 0x%04x\n' % (eeprom_addr, eeprom_val))

print('eeprom:')
ret = ftdi.read_eeprom(ftdic)
size = 128
ret, eeprom = ftdi.get_eeprom_buf(ftdic, size)
if (ret == 0):
    for i in range(size):
        octet = eeprom[i]
        if sys.version_info[0] < 3:  # python 2
            octet = ord(octet)
        sys.stdout.write('%02x ' % octet)
        if (i % 8 == 7):
            print('')
print('')

# close usb
ret = ftdi.usb_close(ftdic)
if ret < 0:
    print('unable to close ftdi device: %d (%s)' %
          (ret, ftdi.get_error_string(ftdic)))
    os._exit(1)

print ('device closed')
ftdi.free(ftdic)
07070100000049000081A400000000000000000000000160917B8300000373000000000000000000000000000000000000003600000000libftdi1-1.5.12+git.0684c1b/python/examples/simple.py#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Python example program.

Small program to demonstrate the usage
of the swig generated python wrapper

You need to build and install the wrapper first"""

import ftdi1 as ftdi


def main():
    """Main program"""
    context = ftdi.new()

    version_info = ftdi.get_library_version()
    print("[FTDI version] major: %d, minor: %d, micro: %d"
          ", version_str: %s, snapshot_str: %s" %
         (version_info.major, version_info.minor, version_info.micro,
          version_info.version_str, version_info.snapshot_str))

    # try to open an ftdi 0x6010 or 0x6001
    ret = ftdi.usb_open(context, 0x0403, 0x6010)
    if ret < 0:
        ret = ftdi.usb_open(context, 0x0403, 0x6001)

    print("ftdi.usb_open(): %d" % ret)
    print("ftdi.set_baudrate(): %d" % ftdi.set_baudrate(context, 9600))

    ftdi.free(context)

main()
0707010000004A000081A400000000000000000000000160917B8300001BA2000000000000000000000000000000000000002B00000000libftdi1-1.5.12+git.0684c1b/python/ftdi1.i/* File: ftdi1.i */

%module(docstring="Python interface to libftdi1") ftdi1
%feature("autodoc","1");

#ifdef DOXYGEN
%include "ftdi1_doc.i"
#endif

%{
#include "Python.h"

inline PyObject* charp2str(const char *v_, long len)
{
#if PY_MAJOR_VERSION >= 3
  return PyBytes_FromStringAndSize(v_, len);
#else
  return PyString_FromStringAndSize(v_, len);
#endif
}

char * str2charp_size(PyObject* pyObj, int * size)
{
  char * v_ = 0;
  Py_ssize_t len = 0;
#if PY_MAJOR_VERSION >= 3
  PyBytes_AsStringAndSize(pyObj, &v_, &len);
#else
  PyString_AsStringAndSize(pyObj, &v_, &len);
#endif
  *size = len;
  return v_;
}
%}

%include <typemaps.i>
%include <cstring.i>

%typemap(in) unsigned char* = char*;

%immutable ftdi_version_info::version_str;
%immutable ftdi_version_info::snapshot_str;

%rename("%(strip:[ftdi_])s") "";

%newobject ftdi_new;
%typemap(newfree) struct ftdi_context *ftdi "ftdi_free($1);";
%delobject ftdi_free;

%define ftdi_usb_find_all_docstring
"usb_find_all(context, vendor, product) -> (return_code, devlist)"
%enddef
%feature("autodoc", ftdi_usb_find_all_docstring) ftdi_usb_find_all;
%typemap(in,numinputs=0) SWIGTYPE** OUTPUT ($*ltype temp) %{ $1 = &temp; %}
%typemap(argout) SWIGTYPE** OUTPUT %{ $result = SWIG_Python_AppendOutput($result, SWIG_NewPointerObj((void*)*$1,$*descriptor,0)); %}
%apply SWIGTYPE** OUTPUT { struct ftdi_device_list **devlist };
    int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist,
                          int vendor, int product);
%clear struct ftdi_device_list **devlist;

%define ftdi_usb_get_strings_docstring
"usb_get_strings(context, device) -> (return_code, manufacturer, description, serial)"
%enddef
%feature("autodoc", ftdi_usb_get_strings_docstring) ftdi_usb_get_strings;
%feature("autodoc", ftdi_usb_get_strings_docstring) ftdi_usb_get_strings2;
%feature("autodoc", ftdi_usb_get_strings_docstring) ftdi_eeprom_get_strings;
%apply char *OUTPUT { char * manufacturer, char * description, char * serial };
%cstring_bounded_output( char * manufacturer, 256 );
%cstring_bounded_output( char * description, 256 );
%cstring_bounded_output( char * product, 256 );
%cstring_bounded_output( char * serial, 256 );
%typemap(default,noblock=1) int mnf_len, int desc_len, int product_len, int serial_len { $1 = 256; }
    int ftdi_usb_get_strings(struct ftdi_context *ftdi, struct libusb_device *dev,
                             char * manufacturer, int mnf_len,
                             char * description, int desc_len,
                             char * serial, int serial_len);
    int ftdi_usb_get_strings2(struct ftdi_context *ftdi, struct libusb_device *dev,
                              char * manufacturer, int mnf_len,
                              char * description, int desc_len,
                              char * serial, int serial_len);
    int ftdi_eeprom_get_strings(struct ftdi_context *ftdi,
                                char *manufacturer, int mnf_len,
                                char *product, int product_len,
                                char *serial, int serial_len);

%clear char * manufacturer, char * description, char * serial;
%clear char * product;
%clear int mnf_len, int desc_len, int product_len, int serial_len;

%define ftdi_read_data_docstring
"read_data(context) -> (return_code, buf)"
%enddef
%feature("autodoc", ftdi_read_data_docstring) ftdi_read_data;
%typemap(in,numinputs=1) (unsigned char *buf, int size) %{ $2 = PyInt_AsLong($input);$1 = (unsigned char*)malloc($2*sizeof(char)); %}
%typemap(argout) (unsigned char *buf, int size) %{
        if(result<0)
                $2=0;
        $result = SWIG_Python_AppendOutput($result, charp2str((char*)$1, $2));
        free($1);
%}
    int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size);
%clear (unsigned char *buf, int size);

%define ftdi_write_data_docstring
"write_data(context, data) -> return_code"
%enddef
%feature("autodoc", ftdi_write_data_docstring) ftdi_write_data;
%typemap(in,numinputs=1) (const unsigned char *buf, int size) %{ $1 = (unsigned char*)str2charp_size($input, &$2); %}
    int ftdi_write_data(struct ftdi_context *ftdi, const unsigned char *buf, int size);
%clear (const unsigned char *buf, int size);

%apply int *OUTPUT { unsigned int *chunksize };
    int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize);
    int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize);
%clear unsigned int *chunksize;

%define ftdi_read_pins_docstring
"read_pins(context) -> (return_code, pins)"
%enddef
%feature("autodoc", ftdi_read_pins_docstring) ftdi_read_pins;
%typemap(in,numinputs=0) unsigned char *pins ($*ltype temp) %{ $1 = &temp; %}
%typemap(argout) (unsigned char *pins) %{ $result = SWIG_Python_AppendOutput($result, charp2str((char*)$1, 1)); %}
    int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins);
%clear unsigned char *pins;

%typemap(in,numinputs=0) unsigned char *latency ($*ltype temp) %{ $1 = &temp; %}
%typemap(argout) (unsigned char *latency) %{ $result = SWIG_Python_AppendOutput($result, charp2str((char*)$1, 1)); %}
    int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency);
%clear unsigned char *latency;

%apply short *OUTPUT { unsigned short *status };
    int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status);
%clear unsigned short *status;

%apply int *OUTPUT { int* value };
    int ftdi_get_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int* value);
%clear int* value;

%typemap(in,numinputs=1) (unsigned char *buf, int size) %{ $2 = PyInt_AsLong($input);$1 = (unsigned char*)malloc($2*sizeof(char)); %}
%typemap(argout) (unsigned char *buf, int size) %{
        if(result<0)
                $2=0;
        $result = SWIG_Python_AppendOutput($result, charp2str((char*)$1, $2));
        free($1);
%}
    int ftdi_get_eeprom_buf(struct ftdi_context *ftdi, unsigned char * buf, int size);
%clear (unsigned char *buf, int size);

%define ftdi_read_eeprom_location_docstring
"read_eeprom_location(context, eeprom_addr) -> (return_code, eeprom_val)"
%enddef
%feature("autodoc", ftdi_read_eeprom_location_docstring) ftdi_read_eeprom_location;
%apply short *OUTPUT { unsigned short *eeprom_val };
    int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val);
%clear unsigned short *eeprom_val;

%define ftdi_read_eeprom_docstring
"read_eeprom(context) -> (return_code, eeprom)"
%enddef
%feature("autodoc", ftdi_read_eeprom_docstring) ftdi_read_eeprom;

%define ftdi_read_chipid_docstring
"ftdi_read_chipid(context) -> (return_code, chipid)"
%enddef
%feature("autodoc", ftdi_read_chipid_docstring) ftdi_read_chipid;
%apply int *OUTPUT { unsigned int *chipid };
    int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid);
%clear unsigned int *chipid;

%include ftdi.h
%{
#include <ftdi.h>
%}

%include ftdi_i.h
%{
#include <ftdi_i.h>
%}

%pythoncode %{
__version__ = get_library_version().version_str
%}
0707010000004B000041ED00000000000000000000000260917B8300000000000000000000000000000000000000000000002000000000libftdi1-1.5.12+git.0684c1b/src0707010000004C000081A400000000000000000000000160917B83000007B4000000000000000000000000000000000000002F00000000libftdi1-1.5.12+git.0684c1b/src/CMakeLists.txt# Includes
include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR}
                     ${CMAKE_CURRENT_SOURCE_DIR}
                     )

# Version information
set(SNAPSHOT_VERSION "unknown")
execute_process(COMMAND git describe
                OUTPUT_VARIABLE GIT_DESCRIBE_OUTPUT
                RESULT_VARIABLE GIT_DESCRIBE_RESULT
                OUTPUT_STRIP_TRAILING_WHITESPACE
                )
if(${GIT_DESCRIBE_RESULT} STREQUAL 0)
  set(SNAPSHOT_VERSION ${GIT_DESCRIBE_OUTPUT})
endif ()
message(STATUS "Detected git snapshot version: ${SNAPSHOT_VERSION}")

configure_file(ftdi_version_i.h.in "${CMAKE_CURRENT_BINARY_DIR}/ftdi_version_i.h" @ONLY)

# Targets
set(c_sources     ${CMAKE_CURRENT_SOURCE_DIR}/ftdi.c ${CMAKE_CURRENT_SOURCE_DIR}/ftdi_stream.c CACHE INTERNAL "List of c sources" )
set(c_headers     ${CMAKE_CURRENT_SOURCE_DIR}/ftdi.h CACHE INTERNAL "List of c headers" )

add_library(ftdi1 SHARED ${c_sources})

math(EXPR VERSION_FIXUP "${MAJOR_VERSION} + 1")    # Compatibility with previous releases
set_target_properties(ftdi1 PROPERTIES VERSION ${VERSION_FIXUP}.${MINOR_VERSION}.0 SOVERSION 2)
# Prevent clobbering each other during the build
set_target_properties ( ftdi1 PROPERTIES CLEAN_DIRECT_OUTPUT 1 )


# Dependencies
target_link_libraries(ftdi1 ${LIBUSB_LIBRARIES})

install ( TARGETS ftdi1
          RUNTIME DESTINATION bin
          LIBRARY DESTINATION lib${LIB_SUFFIX}
          ARCHIVE DESTINATION lib${LIB_SUFFIX}
        )

if ( STATICLIBS )
  add_library(ftdi1-static STATIC ${c_sources})
  target_link_libraries(ftdi1-static ${LIBUSB_LIBRARIES})
  set_target_properties(ftdi1-static PROPERTIES OUTPUT_NAME "ftdi1")
  set_target_properties(ftdi1-static PROPERTIES CLEAN_DIRECT_OUTPUT 1)
  install ( TARGETS ftdi1-static
            ARCHIVE DESTINATION lib${LIB_SUFFIX}
            COMPONENT staticlibs
          )
endif ()

install ( FILES ${c_headers}
          DESTINATION include/${PROJECT_NAME}
          COMPONENT headers
        )
0707010000004D000081A400000000000000000000000160917B8300025A8F000000000000000000000000000000000000002700000000libftdi1-1.5.12+git.0684c1b/src/ftdi.c/***************************************************************************
                          ftdi.c  -  description
                             -------------------
    begin                : Fri Apr 4 2003
    copyright            : (C) 2003-2020 by Intra2net AG and the libftdi developers
    email                : opensource@intra2net.com
    SPDX-License-Identifier: LGPL-2.1-only
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License           *
 *   version 2.1 as published by the Free Software Foundation;             *
 *                                                                         *
 ***************************************************************************/

/**
    \mainpage libftdi API documentation

    Library to talk to FTDI chips. You find the latest versions of libftdi at
    https://www.intra2net.com/en/developer/libftdi/

    The library is easy to use. Have a look at this short example:
    \include simple.c

    More examples can be found in the "examples" directory.
*/
/** \addtogroup libftdi */
/* @{ */

#include <libusb.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

#include "ftdi_i.h"
/* Prevent deprecated messages when building library */
#define _FTDI_DISABLE_DEPRECATED
#include "ftdi.h"
#include "ftdi_version_i.h"

#define ftdi_error_return(code, str) do {  \
        if ( ftdi )                        \
            ftdi->error_str = str;         \
        else                               \
            fprintf(stderr, str);          \
        return code;                       \
   } while(0);

#define ftdi_error_return_free_device_list(code, str, devs) do {    \
        libusb_free_device_list(devs,1);   \
        ftdi->error_str = str;             \
        return code;                       \
   } while(0);


/**
    Internal function to close usb device pointer.
    Sets ftdi->usb_dev to NULL.
    \internal

    \param ftdi pointer to ftdi_context

    \retval none
*/
static void ftdi_usb_close_internal (struct ftdi_context *ftdi)
{
    if (ftdi && ftdi->usb_dev)
    {
        libusb_close (ftdi->usb_dev);
        ftdi->usb_dev = NULL;
        if(ftdi->eeprom)
            ftdi->eeprom->initialized_for_connected_device = 0;
    }
}

/**
    Initializes a ftdi_context.

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: couldn't allocate read buffer
    \retval -2: couldn't allocate struct  buffer
    \retval -3: libusb_init() failed

    \remark This should be called before all functions
*/
int ftdi_init(struct ftdi_context *ftdi)
{
    struct ftdi_eeprom* eeprom;
    ftdi->usb_ctx = NULL;
    ftdi->usb_dev = NULL;
    ftdi->usb_read_timeout = 5000;
    ftdi->usb_write_timeout = 5000;

    ftdi->type = TYPE_BM;    /* chip type */
    ftdi->baudrate = -1;
    ftdi->bitbang_enabled = 0;  /* 0: normal mode 1: any of the bitbang modes enabled */

    ftdi->readbuffer = NULL;
    ftdi->readbuffer_offset = 0;
    ftdi->readbuffer_remaining = 0;
    ftdi->writebuffer_chunksize = 4096;
    ftdi->max_packet_size = 0;
    ftdi->error_str = NULL;
    ftdi->module_detach_mode = AUTO_DETACH_SIO_MODULE;

    if (libusb_init(&ftdi->usb_ctx) < 0)
        ftdi_error_return(-3, "libusb_init() failed");

    ftdi_set_interface(ftdi, INTERFACE_ANY);
    ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode  */

    eeprom = (struct ftdi_eeprom *)malloc(sizeof(struct ftdi_eeprom));
    if (eeprom == 0)
        ftdi_error_return(-2, "Can't malloc struct ftdi_eeprom");
    memset(eeprom, 0, sizeof(struct ftdi_eeprom));
    ftdi->eeprom = eeprom;

    /* All fine. Now allocate the readbuffer */
    return ftdi_read_data_set_chunksize(ftdi, 4096);
}

/**
    Allocate and initialize a new ftdi_context

    \return a pointer to a new ftdi_context, or NULL on failure
*/
struct ftdi_context *ftdi_new(void)
{
    struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));

    if (ftdi == NULL)
    {
        return NULL;
    }

    if (ftdi_init(ftdi) != 0)
    {
        free(ftdi);
        return NULL;
    }

    return ftdi;
}

/**
    Open selected channels on a chip, otherwise use first channel.

    \param ftdi pointer to ftdi_context
    \param interface Interface to use for FT2232C/2232H/4232H chips.

    \retval  0: all fine
    \retval -1: unknown interface
    \retval -2: USB device unavailable
    \retval -3: Device already open, interface can't be set in that state
*/
int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
{
    if (ftdi == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (ftdi->usb_dev != NULL)
    {
        int check_interface = interface;
        if (check_interface == INTERFACE_ANY)
            check_interface = INTERFACE_A;

        if (ftdi->index != check_interface)
            ftdi_error_return(-3, "Interface can not be changed on an already open device");
    }

    switch (interface)
    {
        case INTERFACE_ANY:
        case INTERFACE_A:
            ftdi->interface = 0;
            ftdi->index     = INTERFACE_A;
            ftdi->in_ep     = 0x02;
            ftdi->out_ep    = 0x81;
            break;
        case INTERFACE_B:
            ftdi->interface = 1;
            ftdi->index     = INTERFACE_B;
            ftdi->in_ep     = 0x04;
            ftdi->out_ep    = 0x83;
            break;
        case INTERFACE_C:
            ftdi->interface = 2;
            ftdi->index     = INTERFACE_C;
            ftdi->in_ep     = 0x06;
            ftdi->out_ep    = 0x85;
            break;
        case INTERFACE_D:
            ftdi->interface = 3;
            ftdi->index     = INTERFACE_D;
            ftdi->in_ep     = 0x08;
            ftdi->out_ep    = 0x87;
            break;
        default:
            ftdi_error_return(-1, "Unknown interface");
    }
    return 0;
}

/**
    Deinitializes a ftdi_context.

    \param ftdi pointer to ftdi_context
*/
void ftdi_deinit(struct ftdi_context *ftdi)
{
    if (ftdi == NULL)
        return;

    ftdi_usb_close_internal (ftdi);

    if (ftdi->readbuffer != NULL)
    {
        free(ftdi->readbuffer);
        ftdi->readbuffer = NULL;
    }

    if (ftdi->eeprom != NULL)
    {
        if (ftdi->eeprom->manufacturer != 0)
        {
            free(ftdi->eeprom->manufacturer);
            ftdi->eeprom->manufacturer = 0;
        }
        if (ftdi->eeprom->product != 0)
        {
            free(ftdi->eeprom->product);
            ftdi->eeprom->product = 0;
        }
        if (ftdi->eeprom->serial != 0)
        {
            free(ftdi->eeprom->serial);
            ftdi->eeprom->serial = 0;
        }
        free(ftdi->eeprom);
        ftdi->eeprom = NULL;
    }

    if (ftdi->usb_ctx)
    {
        libusb_exit(ftdi->usb_ctx);
        ftdi->usb_ctx = NULL;
    }
}

/**
    Deinitialize and free an ftdi_context.

    \param ftdi pointer to ftdi_context
*/
void ftdi_free(struct ftdi_context *ftdi)
{
    ftdi_deinit(ftdi);
    free(ftdi);
}

/**
    Use an already open libusb device.

    \param ftdi pointer to ftdi_context
    \param usb libusb libusb_device_handle to use
*/
void ftdi_set_usbdev (struct ftdi_context *ftdi, libusb_device_handle *usb)
{
    if (ftdi == NULL)
        return;

    ftdi->usb_dev = usb;
}

/**
 * @brief Get libftdi library version
 *
 * @return ftdi_version_info Library version information
 **/
struct ftdi_version_info ftdi_get_library_version(void)
{
    struct ftdi_version_info ver;

    ver.major = FTDI_MAJOR_VERSION;
    ver.minor = FTDI_MINOR_VERSION;
    ver.micro = FTDI_MICRO_VERSION;
    ver.version_str = FTDI_VERSION_STRING;
    ver.snapshot_str = FTDI_SNAPSHOT_VERSION;

    return ver;
}

/**
    Finds all ftdi devices with given VID:PID on the usb bus. Creates a new
    ftdi_device_list which needs to be deallocated by ftdi_list_free() after
    use.  With VID:PID 0:0, search for the default devices
    (0x403:0x6001, 0x403:0x6010, 0x403:0x6011, 0x403:0x6014, 0x403:0x6015)

    \param ftdi pointer to ftdi_context
    \param devlist Pointer where to store list of found devices
    \param vendor Vendor ID to search for
    \param product Product ID to search for

    \retval >0: number of devices found
    \retval -3: out of memory
    \retval -5: libusb_get_device_list() failed
    \retval -6: libusb_get_device_descriptor() failed
*/
int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
{
    struct ftdi_device_list **curdev;
    libusb_device *dev;
    libusb_device **devs;
    int count = 0;
    int i = 0;

    if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
        ftdi_error_return(-5, "libusb_get_device_list() failed");

    curdev = devlist;
    *curdev = NULL;

    while ((dev = devs[i++]) != NULL)
    {
        struct libusb_device_descriptor desc;

        if (libusb_get_device_descriptor(dev, &desc) < 0)
            ftdi_error_return_free_device_list(-6, "libusb_get_device_descriptor() failed", devs);

        if (((vendor || product) &&
                desc.idVendor == vendor && desc.idProduct == product) ||
                (!(vendor || product) &&
                 (desc.idVendor == 0x403) && (desc.idProduct == 0x6001 || desc.idProduct == 0x6010
                                              || desc.idProduct == 0x6011 || desc.idProduct == 0x6014
                                              || desc.idProduct == 0x6015)))
        {
            *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
            if (!*curdev)
                ftdi_error_return_free_device_list(-3, "out of memory", devs);

            (*curdev)->next = NULL;
            (*curdev)->dev = dev;
            libusb_ref_device(dev);
            curdev = &(*curdev)->next;
            count++;
        }
    }
    libusb_free_device_list(devs,1);
    return count;
}

/**
    Frees a usb device list.

    \param devlist USB device list created by ftdi_usb_find_all()
*/
void ftdi_list_free(struct ftdi_device_list **devlist)
{
    struct ftdi_device_list *curdev, *next;

    for (curdev = *devlist; curdev != NULL;)
    {
        next = curdev->next;
        libusb_unref_device(curdev->dev);
        free(curdev);
        curdev = next;
    }

    *devlist = NULL;
}

/**
    Frees a usb device list.

    \param devlist USB device list created by ftdi_usb_find_all()
*/
void ftdi_list_free2(struct ftdi_device_list *devlist)
{
    ftdi_list_free(&devlist);
}

/**
    Return device ID strings from the usb device.

    The parameters manufacturer, description and serial may be NULL
    or pointer to buffers to store the fetched strings.

    \note Use this function only in combination with ftdi_usb_find_all()
          as it closes the internal "usb_dev" after use.

    \param ftdi pointer to ftdi_context
    \param dev libusb usb_dev to use
    \param manufacturer Store manufacturer string here if not NULL
    \param mnf_len Buffer size of manufacturer string
    \param description Store product description string here if not NULL
    \param desc_len Buffer size of product description string
    \param serial Store serial string here if not NULL
    \param serial_len Buffer size of serial string

    \retval   0: all fine
    \retval  -1: wrong arguments
    \retval  -4: unable to open device
    \retval  -7: get product manufacturer failed
    \retval  -8: get product description failed
    \retval  -9: get serial number failed
    \retval -11: libusb_get_device_descriptor() failed
*/
int ftdi_usb_get_strings(struct ftdi_context *ftdi,
                         struct libusb_device *dev,
                         char *manufacturer, int mnf_len,
                         char *description, int desc_len,
                         char *serial, int serial_len)
{
    int ret;

    if ((ftdi==NULL) || (dev==NULL))
        return -1;

    if (ftdi->usb_dev == NULL && libusb_open(dev, &ftdi->usb_dev) < 0)
        ftdi_error_return(-4, "libusb_open() failed");

    // ftdi->usb_dev will not be NULL when entering ftdi_usb_get_strings2(), so
    // it won't be closed either. This allows us to close it whether we actually
    // called libusb_open() up above or not. This matches the expected behavior
    // (and note) for ftdi_usb_get_strings().
    ret = ftdi_usb_get_strings2(ftdi, dev,
                                manufacturer, mnf_len,
                                description, desc_len,
                                serial, serial_len);

    // only close it if it was successful, as all other return codes close
    // before returning already.
    if (ret == 0)
        ftdi_usb_close_internal(ftdi);

    return ret;
}

/**
    Return device ID strings from the usb device.

    The parameters manufacturer, description and serial may be NULL
    or pointer to buffers to store the fetched strings.

    \note The old function ftdi_usb_get_strings() always closes the device.
          This version only closes the device if it was opened by it.

    \param ftdi pointer to ftdi_context
    \param dev libusb usb_dev to use
    \param manufacturer Store manufacturer string here if not NULL
    \param mnf_len Buffer size of manufacturer string
    \param description Store product description string here if not NULL
    \param desc_len Buffer size of product description string
    \param serial Store serial string here if not NULL
    \param serial_len Buffer size of serial string

    \retval   0: all fine
    \retval  -1: wrong arguments
    \retval  -4: unable to open device
    \retval  -7: get product manufacturer failed
    \retval  -8: get product description failed
    \retval  -9: get serial number failed
    \retval -11: libusb_get_device_descriptor() failed
*/
int ftdi_usb_get_strings2(struct ftdi_context *ftdi, struct libusb_device *dev,
                          char *manufacturer, int mnf_len,
                          char *description, int desc_len,
                          char *serial, int serial_len)
{
    struct libusb_device_descriptor desc;
    char need_open;

    if ((ftdi==NULL) || (dev==NULL))
        return -1;

    need_open = (ftdi->usb_dev == NULL);
    if (need_open && libusb_open(dev, &ftdi->usb_dev) < 0)
        ftdi_error_return(-4, "libusb_open() failed");

    if (libusb_get_device_descriptor(dev, &desc) < 0)
        ftdi_error_return(-11, "libusb_get_device_descriptor() failed");

    if (manufacturer != NULL && mnf_len > 0)
    {
        if (desc.iManufacturer == 0)
        {
            manufacturer[0] = '\0';
        }
        else if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iManufacturer, (unsigned char *)manufacturer, mnf_len) < 0)
        {
            ftdi_usb_close_internal (ftdi);
            ftdi_error_return(-7, "libusb_get_string_descriptor_ascii() failed");
        }
    }

    if (description != NULL && desc_len > 0)
    {
        if (desc.iProduct == 0)
        {
            description[0] = '\0';
        }
        else if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)description, desc_len) < 0)
        {
            ftdi_usb_close_internal (ftdi);
            ftdi_error_return(-8, "libusb_get_string_descriptor_ascii() failed");
        }
    }

    if (serial != NULL && serial_len > 0)
    {
        if (desc.iSerialNumber == 0)
        {
            serial[0] = '\0';
        }
        else if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)serial, serial_len) < 0)
        {
            ftdi_usb_close_internal (ftdi);
            ftdi_error_return(-9, "libusb_get_string_descriptor_ascii() failed");
        }
    }

    if (need_open)
        ftdi_usb_close_internal (ftdi);

    return 0;
}

/**
 * Internal function to determine the maximum packet size.
 * \param ftdi pointer to ftdi_context
 * \param dev libusb usb_dev to use
 * \retval Maximum packet size for this device
 */
static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, libusb_device *dev)
{
    struct libusb_device_descriptor desc;
    struct libusb_config_descriptor *config0;
    unsigned int packet_size;

    // Sanity check
    if (ftdi == NULL || dev == NULL)
        return 64;

    // Determine maximum packet size. Init with default value.
    // New hi-speed devices from FTDI use a packet size of 512 bytes
    // but could be connected to a normal speed USB hub -> 64 bytes packet size.
    if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H || ftdi->type == TYPE_232H)
        packet_size = 512;
    else
        packet_size = 64;

    if (libusb_get_device_descriptor(dev, &desc) < 0)
        return packet_size;

    if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
        return packet_size;

    if (desc.bNumConfigurations > 0)
    {
        if (ftdi->interface < config0->bNumInterfaces)
        {
            struct libusb_interface interface = config0->interface[ftdi->interface];
            if (interface.num_altsetting > 0)
            {
                struct libusb_interface_descriptor descriptor = interface.altsetting[0];
                if (descriptor.bNumEndpoints > 0)
                {
                    packet_size = descriptor.endpoint[0].wMaxPacketSize;
                }
            }
        }
    }

    libusb_free_config_descriptor (config0);
    return packet_size;
}

/**
    Opens a ftdi device given by an usb_device.

    \param ftdi pointer to ftdi_context
    \param dev libusb usb_dev to use

    \retval  0: all fine
    \retval -3: unable to config device
    \retval -4: unable to open device
    \retval -5: unable to claim device
    \retval -6: reset failed
    \retval -7: set baudrate failed
    \retval -8: ftdi context invalid
    \retval -9: libusb_get_device_descriptor() failed
    \retval -10: libusb_get_config_descriptor() failed
    \retval -11: libusb_detach_kernel_driver() failed
    \retval -12: libusb_get_configuration() failed
*/
int ftdi_usb_open_dev(struct ftdi_context *ftdi, libusb_device *dev)
{
    struct libusb_device_descriptor desc;
    struct libusb_config_descriptor *config0;
    int cfg, cfg0, detach_errno = 0;

    if (ftdi == NULL)
        ftdi_error_return(-8, "ftdi context invalid");

    if (libusb_open(dev, &ftdi->usb_dev) < 0)
        ftdi_error_return(-4, "libusb_open() failed");

    if (libusb_get_device_descriptor(dev, &desc) < 0)
        ftdi_error_return(-9, "libusb_get_device_descriptor() failed");

    if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
        ftdi_error_return(-10, "libusb_get_config_descriptor() failed");
    cfg0 = config0->bConfigurationValue;
    libusb_free_config_descriptor (config0);

    // Try to detach ftdi_sio kernel module.
    //
    // The return code is kept in a separate variable and only parsed
    // if usb_set_configuration() or usb_claim_interface() fails as the
    // detach operation might be denied and everything still works fine.
    // Likely scenario is a static ftdi_sio kernel module.
    if (ftdi->module_detach_mode == AUTO_DETACH_SIO_MODULE)
    {
        if (libusb_detach_kernel_driver(ftdi->usb_dev, ftdi->interface) !=0)
            detach_errno = errno;
    }
    else if (ftdi->module_detach_mode == AUTO_DETACH_REATACH_SIO_MODULE)
    {
        if (libusb_set_auto_detach_kernel_driver(ftdi->usb_dev, 1) != LIBUSB_SUCCESS)
            detach_errno = errno;
    }

    if (libusb_get_configuration (ftdi->usb_dev, &cfg) < 0)
        ftdi_error_return(-12, "libusb_get_configuration () failed");
    // set configuration (needed especially for windows)
    // tolerate EBUSY: one device with one configuration, but two interfaces
    //    and libftdi sessions to both interfaces (e.g. FT2232)
    if (desc.bNumConfigurations > 0 && cfg != cfg0)
    {
        if (libusb_set_configuration(ftdi->usb_dev, cfg0) < 0)
        {
            ftdi_usb_close_internal (ftdi);
            if (detach_errno == EPERM)
            {
                ftdi_error_return(-8, "inappropriate permissions on device!");
            }
            else
            {
                ftdi_error_return(-3, "unable to set usb configuration. Make sure the default FTDI driver is not in use");
            }
        }
    }

    if (libusb_claim_interface(ftdi->usb_dev, ftdi->interface) < 0)
    {
        ftdi_usb_close_internal (ftdi);
        if (detach_errno == EPERM)
        {
            ftdi_error_return(-8, "inappropriate permissions on device!");
        }
        else
        {
            ftdi_error_return(-5, "unable to claim usb device. Make sure the default FTDI driver is not in use");
        }
    }

    if (ftdi_usb_reset (ftdi) != 0)
    {
        ftdi_usb_close_internal (ftdi);
        ftdi_error_return(-6, "ftdi_usb_reset failed");
    }

    // Try to guess chip type
    // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
    if (desc.bcdDevice == 0x400 || (desc.bcdDevice == 0x200
                                    && desc.iSerialNumber == 0))
        ftdi->type = TYPE_BM;
    else if (desc.bcdDevice == 0x200)
        ftdi->type = TYPE_AM;
    else if (desc.bcdDevice == 0x500)
        ftdi->type = TYPE_2232C;
    else if (desc.bcdDevice == 0x600)
        ftdi->type = TYPE_R;
    else if (desc.bcdDevice == 0x700)
        ftdi->type = TYPE_2232H;
    else if (desc.bcdDevice == 0x800)
        ftdi->type = TYPE_4232H;
    else if (desc.bcdDevice == 0x900)
        ftdi->type = TYPE_232H;
    else if (desc.bcdDevice == 0x1000)
        ftdi->type = TYPE_230X;

    // Determine maximum packet size
    ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);

    if (ftdi_set_baudrate (ftdi, 9600) != 0)
    {
        ftdi_usb_close_internal (ftdi);
        ftdi_error_return(-7, "set baudrate failed");
    }

    ftdi_error_return(0, "all fine");
}

/**
    Opens the first device with a given vendor and product ids.

    \param ftdi pointer to ftdi_context
    \param vendor Vendor ID
    \param product Product ID

    \retval same as ftdi_usb_open_desc()
*/
int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
{
    return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
}

/**
    Opens the first device with a given, vendor id, product id,
    description and serial.

    \param ftdi pointer to ftdi_context
    \param vendor Vendor ID
    \param product Product ID
    \param description Description to search for. Use NULL if not needed.
    \param serial Serial to search for. Use NULL if not needed.

    \retval  0: all fine
    \retval -3: usb device not found
    \retval -4: unable to open device
    \retval -5: unable to claim device
    \retval -6: reset failed
    \retval -7: set baudrate failed
    \retval -8: get product description failed
    \retval -9: get serial number failed
    \retval -12: libusb_get_device_list() failed
    \retval -13: libusb_get_device_descriptor() failed
*/
int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
                       const char* description, const char* serial)
{
    return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
}

/**
    Opens the index-th device with a given, vendor id, product id,
    description and serial.

    \param ftdi pointer to ftdi_context
    \param vendor Vendor ID
    \param product Product ID
    \param description Description to search for. Use NULL if not needed.
    \param serial Serial to search for. Use NULL if not needed.
    \param index Number of matching device to open if there are more than one, starts with 0.

    \retval  0: all fine
    \retval -1: usb_find_busses() failed
    \retval -2: usb_find_devices() failed
    \retval -3: usb device not found
    \retval -4: unable to open device
    \retval -5: unable to claim device
    \retval -6: reset failed
    \retval -7: set baudrate failed
    \retval -8: get product description failed
    \retval -9: get serial number failed
    \retval -10: unable to close device
    \retval -11: ftdi context invalid
    \retval -12: libusb_get_device_list() failed
*/
int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
                             const char* description, const char* serial, unsigned int index)
{
    libusb_device *dev;
    libusb_device **devs;
    char string[256];
    int i = 0;

    if (ftdi == NULL)
        ftdi_error_return(-11, "ftdi context invalid");

    if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
        ftdi_error_return(-12, "libusb_get_device_list() failed");

    while ((dev = devs[i++]) != NULL)
    {
        struct libusb_device_descriptor desc;
        int res;

        if (libusb_get_device_descriptor(dev, &desc) < 0)
            ftdi_error_return_free_device_list(-13, "libusb_get_device_descriptor() failed", devs);

        if (desc.idVendor == vendor && desc.idProduct == product)
        {
            if (libusb_open(dev, &ftdi->usb_dev) < 0)
                ftdi_error_return_free_device_list(-4, "usb_open() failed", devs);

            if (description != NULL)
            {
                if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)string, sizeof(string)) < 0)
                {
                    ftdi_usb_close_internal (ftdi);
                    ftdi_error_return_free_device_list(-8, "unable to fetch product description", devs);
                }
                if (strncmp(string, description, sizeof(string)) != 0)
                {
                    ftdi_usb_close_internal (ftdi);
                    continue;
                }
            }
            if (serial != NULL)
            {
                if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)string, sizeof(string)) < 0)
                {
                    ftdi_usb_close_internal (ftdi);
                    ftdi_error_return_free_device_list(-9, "unable to fetch serial number", devs);
                }
                if (strncmp(string, serial, sizeof(string)) != 0)
                {
                    ftdi_usb_close_internal (ftdi);
                    continue;
                }
            }

            ftdi_usb_close_internal (ftdi);

            if (index > 0)
            {
                index--;
                continue;
            }

            res = ftdi_usb_open_dev(ftdi, dev);
            libusb_free_device_list(devs,1);
            return res;
        }
    }

    // device not found
    ftdi_error_return_free_device_list(-3, "device not found", devs);
}

/**
    Opens the device at a given USB bus and device address.

    \param ftdi pointer to ftdi_context
    \param bus Bus number
    \param addr Device address

    \retval  0: all fine
    \retval -1: usb_find_busses() failed
    \retval -2: usb_find_devices() failed
    \retval -3: usb device not found
    \retval -4: unable to open device
    \retval -5: unable to claim device
    \retval -6: reset failed
    \retval -7: set baudrate failed
    \retval -8: get product description failed
    \retval -9: get serial number failed
    \retval -10: unable to close device
    \retval -11: ftdi context invalid
    \retval -12: libusb_get_device_list() failed
*/
int ftdi_usb_open_bus_addr(struct ftdi_context *ftdi, uint8_t bus, uint8_t addr)
{
    libusb_device *dev;
    libusb_device **devs;
    int i = 0;

    if (ftdi == NULL)
        ftdi_error_return(-11, "ftdi context invalid");

    if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
        ftdi_error_return(-12, "libusb_get_device_list() failed");

    while ((dev = devs[i++]) != NULL)
    {
        if (libusb_get_bus_number(dev) == bus && libusb_get_device_address(dev) == addr)
        {
            int res;
            res = ftdi_usb_open_dev(ftdi, dev);
            libusb_free_device_list(devs,1);
            return res;
        }
    }

    // device not found
    ftdi_error_return_free_device_list(-3, "device not found", devs);
}

/**
    Opens the ftdi-device described by a description-string.
    Intended to be used for parsing a device-description given as commandline argument.

    \param ftdi pointer to ftdi_context
    \param description NULL-terminated description-string, using this format:
        \li <tt>d:\<devicenode></tt> path of bus and device-node (e.g. "003/001") within usb device tree (usually at /proc/bus/usb/)
        \li <tt>i:\<vendor>:\<product></tt> first device with given vendor and product id, ids can be decimal, octal (preceded by "0") or hex (preceded by "0x")
        \li <tt>i:\<vendor>:\<product>:\<index></tt> as above with index being the number of the device (starting with 0) if there are more than one
        \li <tt>s:\<vendor>:\<product>:\<serial></tt> first device with given vendor id, product id and serial string

    \note The description format may be extended in later versions.

    \retval  0: all fine
    \retval -2: libusb_get_device_list() failed
    \retval -3: usb device not found
    \retval -4: unable to open device
    \retval -5: unable to claim device
    \retval -6: reset failed
    \retval -7: set baudrate failed
    \retval -8: get product description failed
    \retval -9: get serial number failed
    \retval -10: unable to close device
    \retval -11: illegal description format
    \retval -12: ftdi context invalid
*/
int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
{
    if (ftdi == NULL)
        ftdi_error_return(-12, "ftdi context invalid");

    if (description[0] == 0 || description[1] != ':')
        ftdi_error_return(-11, "illegal description format");

    if (description[0] == 'd')
    {
        libusb_device *dev;
        libusb_device **devs;
        unsigned int bus_number, device_address;
        int i = 0;

        if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
            ftdi_error_return(-2, "libusb_get_device_list() failed");

        /* XXX: This doesn't handle symlinks/odd paths/etc... */
        if (sscanf (description + 2, "%u/%u", &bus_number, &device_address) != 2)
            ftdi_error_return_free_device_list(-11, "illegal description format", devs);

        while ((dev = devs[i++]) != NULL)
        {
            int ret;
            if (bus_number == libusb_get_bus_number (dev)
                    && device_address == libusb_get_device_address (dev))
            {
                ret = ftdi_usb_open_dev(ftdi, dev);
                libusb_free_device_list(devs,1);
                return ret;
            }
        }

        // device not found
        ftdi_error_return_free_device_list(-3, "device not found", devs);
    }
    else if (description[0] == 'i' || description[0] == 's')
    {
        unsigned int vendor;
        unsigned int product;
        unsigned int index=0;
        const char *serial=NULL;
        const char *startp, *endp;

        errno=0;
        startp=description+2;
        vendor=strtoul((char*)startp,(char**)&endp,0);
        if (*endp != ':' || endp == startp || errno != 0)
            ftdi_error_return(-11, "illegal description format");

        startp=endp+1;
        product=strtoul((char*)startp,(char**)&endp,0);
        if (endp == startp || errno != 0)
            ftdi_error_return(-11, "illegal description format");

        if (description[0] == 'i' && *endp != 0)
        {
            /* optional index field in i-mode */
            if (*endp != ':')
                ftdi_error_return(-11, "illegal description format");

            startp=endp+1;
            index=strtoul((char*)startp,(char**)&endp,0);
            if (*endp != 0 || endp == startp || errno != 0)
                ftdi_error_return(-11, "illegal description format");
        }
        if (description[0] == 's')
        {
            if (*endp != ':')
                ftdi_error_return(-11, "illegal description format");

            /* rest of the description is the serial */
            serial=endp+1;
        }

        return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
    }
    else
    {
        ftdi_error_return(-11, "illegal description format");
    }
}

/**
    Resets the ftdi device.

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: FTDI reset failed
    \retval -2: USB device unavailable
*/
int ftdi_usb_reset(struct ftdi_context *ftdi)
{
    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_RESET_REQUEST, SIO_RESET_SIO,
                                ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1,"FTDI reset failed");

    // Invalidate data in the readbuffer
    ftdi->readbuffer_offset = 0;
    ftdi->readbuffer_remaining = 0;

    return 0;
}

/**
    Clears the read buffer on the chip and the internal read buffer.
    This is the correct behavior for an RX flush.

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: read buffer purge failed
    \retval -2: USB device unavailable
*/
int ftdi_tciflush(struct ftdi_context *ftdi)
{
    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_RESET_REQUEST, SIO_TCIFLUSH,
                                ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "FTDI purge of RX buffer failed");

    // Invalidate data in the readbuffer
    ftdi->readbuffer_offset = 0;
    ftdi->readbuffer_remaining = 0;

    return 0;
}


/**
    Clears the write buffer on the chip and the internal read buffer.
    This is incorrect behavior for an RX flush.

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: write buffer purge failed
    \retval -2: USB device unavailable

    \deprecated Use \ref ftdi_tciflush(struct ftdi_context *ftdi)
*/
int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
{
    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
                                ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "FTDI purge of RX buffer failed");

    // Invalidate data in the readbuffer
    ftdi->readbuffer_offset = 0;
    ftdi->readbuffer_remaining = 0;

    return 0;
}

/**
    Clears the write buffer on the chip.
    This is correct behavior for a TX flush.

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: write buffer purge failed
    \retval -2: USB device unavailable
*/
int ftdi_tcoflush(struct ftdi_context *ftdi)
{
    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_RESET_REQUEST, SIO_TCOFLUSH,
                                ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "FTDI purge of TX buffer failed");

    return 0;
}


/**
    Clears the read buffer on the chip.
    This is incorrect behavior for a TX flush.

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: read buffer purge failed
    \retval -2: USB device unavailable

    \deprecated Use \ref ftdi_tcoflush(struct ftdi_context *ftdi)
*/
int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
{
    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
                                ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "FTDI purge of TX buffer failed");

    return 0;
}

/**
    Clears the RX and TX FIFOs on the chip and the internal read buffer.
    This is correct behavior for both RX and TX flush.

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: read buffer purge failed
    \retval -2: write buffer purge failed
    \retval -3: USB device unavailable
*/
int ftdi_tcioflush(struct ftdi_context *ftdi)
{
    int result;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-3, "USB device unavailable");

    result = ftdi_tcoflush(ftdi);
    if (result < 0)
        return -1;

    result = ftdi_tciflush(ftdi);
    if (result < 0)
        return -2;

    return 0;
}

/**
    Clears the buffers on the chip and the internal read buffer.
    While coded incorrectly, the result is satisfactory.

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: read buffer purge failed
    \retval -2: write buffer purge failed
    \retval -3: USB device unavailable

    \deprecated Use \ref ftdi_tcioflush(struct ftdi_context *ftdi)
*/
int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
{
    int result;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-3, "USB device unavailable");

    result = ftdi_usb_purge_rx_buffer(ftdi);
    if (result < 0)
        return -1;

    result = ftdi_usb_purge_tx_buffer(ftdi);
    if (result < 0)
        return -2;

    return 0;
}



/**
    Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: usb_release failed
    \retval -3: ftdi context invalid
*/
int ftdi_usb_close(struct ftdi_context *ftdi)
{
    int rtn = 0;

    if (ftdi == NULL)
        ftdi_error_return(-3, "ftdi context invalid");

    if (ftdi->usb_dev != NULL)
        if (libusb_release_interface(ftdi->usb_dev, ftdi->interface) < 0)
            rtn = -1;

    ftdi_usb_close_internal (ftdi);

    return rtn;
}

/*  ftdi_to_clkbits_AM For the AM device, convert a requested baudrate
                    to encoded divisor and the achievable baudrate
    Function is only used internally
    \internal

    See AN120
   clk/1   -> 0
   clk/1.5 -> 1
   clk/2   -> 2
   From /2, 0.125/ 0.25 and 0.5 steps may be taken
   The fractional part has frac_code encoding
*/
static int ftdi_to_clkbits_AM(int baudrate, unsigned long *encoded_divisor)

{
    static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
    static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
    static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
    int divisor, best_divisor, best_baud, best_baud_diff;
    int i;
    divisor = 24000000 / baudrate;

    // Round down to supported fraction (AM only)
    divisor -= am_adjust_dn[divisor & 7];

    // Try this divisor and the one above it (because division rounds down)
    best_divisor = 0;
    best_baud = 0;
    best_baud_diff = 0;
    for (i = 0; i < 2; i++)
    {
        int try_divisor = divisor + i;
        int baud_estimate;
        int baud_diff;

        // Round up to supported divisor value
        if (try_divisor <= 8)
        {
            // Round up to minimum supported divisor
            try_divisor = 8;
        }
        else if (divisor < 16)
        {
            // AM doesn't support divisors 9 through 15 inclusive
            try_divisor = 16;
        }
        else
        {
            // Round up to supported fraction (AM only)
            try_divisor += am_adjust_up[try_divisor & 7];
            if (try_divisor > 0x1FFF8)
            {
                // Round down to maximum supported divisor value (for AM)
                try_divisor = 0x1FFF8;
            }
        }
        // Get estimated baud rate (to nearest integer)
        baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
        // Get absolute difference from requested baud rate
        if (baud_estimate < baudrate)
        {
            baud_diff = baudrate - baud_estimate;
        }
        else
        {
            baud_diff = baud_estimate - baudrate;
        }
        if (i == 0 || baud_diff < best_baud_diff)
        {
            // Closest to requested baud rate so far
            best_divisor = try_divisor;
            best_baud = baud_estimate;
            best_baud_diff = baud_diff;
            if (baud_diff == 0)
            {
                // Spot on! No point trying
                break;
            }
        }
    }
    // Encode the best divisor value
    *encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
    // Deal with special cases for encoded value
    if (*encoded_divisor == 1)
    {
        *encoded_divisor = 0;    // 3000000 baud
    }
    else if (*encoded_divisor == 0x4001)
    {
        *encoded_divisor = 1;    // 2000000 baud (BM only)
    }
    return best_baud;
}

/*  ftdi_to_clkbits Convert a requested baudrate for a given system clock  and predivisor
                    to encoded divisor and the achievable baudrate
    Function is only used internally
    \internal

    See AN120
   clk/1   -> 0
   clk/1.5 -> 1
   clk/2   -> 2
   From /2, 0.125 steps may be taken.
   The fractional part has frac_code encoding

   value[13:0] of value is the divisor
   index[9] mean 12 MHz Base(120 MHz/10) rate versus 3 MHz (48 MHz/16) else

   H Type have all features above with
   {index[8],value[15:14]} is the encoded subdivisor

   FT232R, FT2232 and FT232BM have no option for 12 MHz and with
   {index[0],value[15:14]} is the encoded subdivisor

   AM Type chips have only four fractional subdivisors at value[15:14]
   for subdivisors 0, 0.5, 0.25, 0.125
*/
static int ftdi_to_clkbits(int baudrate, int clk, int clk_div, unsigned long *encoded_divisor)
{
    static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
    int best_baud = 0;
    int divisor, best_divisor;
    if (baudrate >=  clk/clk_div)
    {
        *encoded_divisor = 0;
        best_baud = clk/clk_div;
    }
    else if (baudrate >=  clk/(clk_div + clk_div/2))
    {
        *encoded_divisor = 1;
        best_baud = clk/(clk_div + clk_div/2);
    }
    else if (baudrate >=  clk/(2*clk_div))
    {
        *encoded_divisor = 2;
        best_baud = clk/(2*clk_div);
    }
    else
    {
        /* We divide by 16 to have 3 fractional bits and one bit for rounding */
        divisor = clk*16/clk_div / baudrate;
        if (divisor & 1) /* Decide if to round up or down*/
            best_divisor = divisor /2 +1;
        else
            best_divisor = divisor/2;
        if(best_divisor > 0x20000)
            best_divisor = 0x1ffff;
        best_baud = clk*16/clk_div/best_divisor;
        if (best_baud & 1) /* Decide if to round up or down*/
            best_baud = best_baud /2 +1;
        else
            best_baud = best_baud /2;
        *encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 0x7] << 14);
    }
    return best_baud;
}
/**
    ftdi_convert_baudrate returns nearest supported baud rate to that requested.
    Function is only used internally
    \internal
*/
static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
                                 unsigned short *value, unsigned short *index)
{
    int best_baud;
    unsigned long encoded_divisor;

    if (baudrate <= 0)
    {
        // Return error
        return -1;
    }

#define H_CLK 120000000
#define C_CLK  48000000
    if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H) || (ftdi->type == TYPE_232H))
    {
        if(baudrate*10 > H_CLK /0x3fff)
        {
            /* On H Devices, use 12 000 000 Baudrate when possible
               We have a 14 bit divisor, a 1 bit divisor switch (10 or 16)
               three fractional bits and a 120 MHz clock
               Assume AN_120 "Sub-integer divisors between 0 and 2 are not allowed" holds for
               DIV/10 CLK too, so /1, /1.5 and /2 can be handled the same*/
            best_baud = ftdi_to_clkbits(baudrate, H_CLK, 10, &encoded_divisor);
            encoded_divisor |= 0x20000; /* switch on CLK/10*/
        }
        else
            best_baud = ftdi_to_clkbits(baudrate, C_CLK, 16, &encoded_divisor);
    }
    else if ((ftdi->type == TYPE_BM) || (ftdi->type == TYPE_2232C) || (ftdi->type == TYPE_R) || (ftdi->type == TYPE_230X))
    {
        best_baud = ftdi_to_clkbits(baudrate, C_CLK, 16, &encoded_divisor);
    }
    else
    {
        best_baud = ftdi_to_clkbits_AM(baudrate, &encoded_divisor);
    }
    // Split into "value" and "index" values
    *value = (unsigned short)(encoded_divisor & 0xFFFF);
    if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H || ftdi->type == TYPE_232H)
    {
        *index = (unsigned short)(encoded_divisor >> 8);
        *index &= 0xFF00;
        *index |= ftdi->index;
    }
    else
        *index = (unsigned short)(encoded_divisor >> 16);

    // Return the nearest baud rate
    return best_baud;
}

/**
 * @brief Wrapper function to export ftdi_convert_baudrate() to the unit test
 * Do not use, it's only for the unit test framework
 **/
int convert_baudrate_UT_export(int baudrate, struct ftdi_context *ftdi,
                               unsigned short *value, unsigned short *index)
{
    return ftdi_convert_baudrate(baudrate, ftdi, value, index);
}

/**
    Sets the chip baud rate

    \param ftdi pointer to ftdi_context
    \param baudrate baud rate to set

    \retval  0: all fine
    \retval -1: invalid baudrate
    \retval -2: setting baudrate failed
    \retval -3: USB device unavailable
*/
int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
{
    unsigned short value, index;
    int actual_baudrate;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-3, "USB device unavailable");

    if (ftdi->bitbang_enabled)
    {
        baudrate = baudrate*4;
    }

    actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
    if (actual_baudrate <= 0)
        ftdi_error_return (-1, "Silly baudrate <= 0.");

    // Check within tolerance (about 5%)
    if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
            || ((actual_baudrate < baudrate)
                ? (actual_baudrate * 21 < baudrate * 20)
                : (baudrate * 21 < actual_baudrate * 20)))
        ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_SET_BAUDRATE_REQUEST, value,
                                index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return (-2, "Setting new baudrate failed");

    ftdi->baudrate = baudrate;
    return 0;
}

/**
    Set (RS232) line characteristics.
    The break type can only be set via ftdi_set_line_property2()
    and defaults to "off".

    \param ftdi pointer to ftdi_context
    \param bits Number of bits
    \param sbit Number of stop bits
    \param parity Parity mode

    \retval  0: all fine
    \retval -1: Setting line property failed
*/
int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
                           enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
{
    return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
}

/**
    Set (RS232) line characteristics

    \param ftdi pointer to ftdi_context
    \param bits Number of bits
    \param sbit Number of stop bits
    \param parity Parity mode
    \param break_type Break type

    \retval  0: all fine
    \retval -1: Setting line property failed
    \retval -2: USB device unavailable
*/
int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
                            enum ftdi_break_type break_type)
{
    unsigned short value = bits;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    switch (parity)
    {
        case NONE:
            value |= (0x00 << 8);
            break;
        case ODD:
            value |= (0x01 << 8);
            break;
        case EVEN:
            value |= (0x02 << 8);
            break;
        case MARK:
            value |= (0x03 << 8);
            break;
        case SPACE:
            value |= (0x04 << 8);
            break;
    }

    switch (sbit)
    {
        case STOP_BIT_1:
            value |= (0x00 << 11);
            break;
        case STOP_BIT_15:
            value |= (0x01 << 11);
            break;
        case STOP_BIT_2:
            value |= (0x02 << 11);
            break;
    }

    switch (break_type)
    {
        case BREAK_OFF:
            value |= (0x00 << 14);
            break;
        case BREAK_ON:
            value |= (0x01 << 14);
            break;
    }

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_SET_DATA_REQUEST, value,
                                ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return (-1, "Setting new line property failed");

    return 0;
}

/**
    Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip

    \param ftdi pointer to ftdi_context
    \param buf Buffer with the data
    \param size Size of the buffer

    \retval -666: USB device unavailable
    \retval <0: error code from usb_bulk_write()
    \retval >0: number of bytes written
*/
int ftdi_write_data(struct ftdi_context *ftdi, const unsigned char *buf, int size)
{
    int offset = 0;
    int actual_length;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-666, "USB device unavailable");

    while (offset < size)
    {
        int write_size = ftdi->writebuffer_chunksize;

        if (offset+write_size > size)
            write_size = size-offset;

        if (libusb_bulk_transfer(ftdi->usb_dev, ftdi->in_ep, (unsigned char *)buf+offset, write_size, &actual_length, ftdi->usb_write_timeout) < 0)
            ftdi_error_return(-1, "usb bulk write failed");

        offset += actual_length;
    }

    return offset;
}

static void LIBUSB_CALL ftdi_read_data_cb(struct libusb_transfer *transfer)
{
    struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
    struct ftdi_context *ftdi = tc->ftdi;
    int packet_size, actual_length, num_of_chunks, chunk_remains, i, ret;

    packet_size = ftdi->max_packet_size;

    actual_length = transfer->actual_length;

    if (actual_length > 2)
    {
        // skip FTDI status bytes.
        // Maybe stored in the future to enable modem use
        num_of_chunks = actual_length / packet_size;
        chunk_remains = actual_length % packet_size;
        //printf("actual_length = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", actual_length, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);

        ftdi->readbuffer_offset += 2;
        actual_length -= 2;

        if (actual_length > packet_size - 2)
        {
            for (i = 1; i < num_of_chunks; i++)
                memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
                         ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
                         packet_size - 2);
            if (chunk_remains > 2)
            {
                memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
                         ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
                         chunk_remains-2);
                actual_length -= 2*num_of_chunks;
            }
            else
                actual_length -= 2*(num_of_chunks-1)+chunk_remains;
        }

        if (actual_length > 0)
        {
            // data still fits in buf?
            if (tc->offset + actual_length <= tc->size)
            {
                memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, actual_length);
                //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
                tc->offset += actual_length;

                ftdi->readbuffer_offset = 0;
                ftdi->readbuffer_remaining = 0;

                /* Did we read exactly the right amount of bytes? */
                if (tc->offset == tc->size)
                {
                    //printf("read_data exact rem %d offset %d\n",
                    //ftdi->readbuffer_remaining, offset);
                    tc->completed = 1;
                    return;
                }
            }
            else
            {
                // only copy part of the data or size <= readbuffer_chunksize
                int part_size = tc->size - tc->offset;
                memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, part_size);
                tc->offset += part_size;

                ftdi->readbuffer_offset += part_size;
                ftdi->readbuffer_remaining = actual_length - part_size;

                /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
                part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
                tc->completed = 1;
                return;
            }
        }
    }

    if (transfer->status == LIBUSB_TRANSFER_CANCELLED)
        tc->completed = LIBUSB_TRANSFER_CANCELLED;
    else
    {
        ret = libusb_submit_transfer (transfer);
        if (ret < 0)
            tc->completed = 1;
    }
}


static void LIBUSB_CALL ftdi_write_data_cb(struct libusb_transfer *transfer)
{
    struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
    struct ftdi_context *ftdi = tc->ftdi;

    tc->offset += transfer->actual_length;

    if (tc->offset == tc->size)
    {
        tc->completed = 1;
    }
    else
    {
        int write_size = ftdi->writebuffer_chunksize;
        int ret;

        if (tc->offset + write_size > tc->size)
            write_size = tc->size - tc->offset;

        transfer->length = write_size;
        transfer->buffer = tc->buf + tc->offset;

        if (transfer->status == LIBUSB_TRANSFER_CANCELLED)
            tc->completed = LIBUSB_TRANSFER_CANCELLED;
        else
        {
            ret = libusb_submit_transfer (transfer);
            if (ret < 0)
                tc->completed = 1;
        }
    }
}


/**
    Writes data to the chip. Does not wait for completion of the transfer
    nor does it make sure that the transfer was successful.

    Use libusb 1.0 asynchronous API.

    \param ftdi pointer to ftdi_context
    \param buf Buffer with the data
    \param size Size of the buffer

    \retval NULL: Some error happens when submit transfer
    \retval !NULL: Pointer to a ftdi_transfer_control
*/

struct ftdi_transfer_control *ftdi_write_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
{
    struct ftdi_transfer_control *tc;
    struct libusb_transfer *transfer;
    int write_size, ret;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        return NULL;

    tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
    if (!tc)
        return NULL;

    transfer = libusb_alloc_transfer(0);
    if (!transfer)
    {
        free(tc);
        return NULL;
    }

    tc->ftdi = ftdi;
    tc->completed = 0;
    tc->buf = buf;
    tc->size = size;
    tc->offset = 0;

    if (size < (int)ftdi->writebuffer_chunksize)
        write_size = size;
    else
        write_size = ftdi->writebuffer_chunksize;

    libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->in_ep, buf,
                              write_size, ftdi_write_data_cb, tc,
                              ftdi->usb_write_timeout);
    transfer->type = LIBUSB_TRANSFER_TYPE_BULK;

    ret = libusb_submit_transfer(transfer);
    if (ret < 0)
    {
        libusb_free_transfer(transfer);
        free(tc);
        return NULL;
    }
    tc->transfer = transfer;

    return tc;
}

/**
    Reads data from the chip. Does not wait for completion of the transfer
    nor does it make sure that the transfer was successful.

    Use libusb 1.0 asynchronous API.

    \param ftdi pointer to ftdi_context
    \param buf Buffer with the data
    \param size Size of the buffer

    \retval NULL: Some error happens when submit transfer
    \retval !NULL: Pointer to a ftdi_transfer_control
*/

struct ftdi_transfer_control *ftdi_read_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
{
    struct ftdi_transfer_control *tc;
    struct libusb_transfer *transfer;
    int ret;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        return NULL;

    tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
    if (!tc)
        return NULL;

    tc->ftdi = ftdi;
    tc->buf = buf;
    tc->size = size;

    if (size <= (int)ftdi->readbuffer_remaining)
    {
        memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);

        // Fix offsets
        ftdi->readbuffer_remaining -= size;
        ftdi->readbuffer_offset += size;

        /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */

        tc->completed = 1;
        tc->offset = size;
        tc->transfer = NULL;
        return tc;
    }

    tc->completed = 0;
    if (ftdi->readbuffer_remaining != 0)
    {
        memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);

        tc->offset = ftdi->readbuffer_remaining;
    }
    else
        tc->offset = 0;

    transfer = libusb_alloc_transfer(0);
    if (!transfer)
    {
        free (tc);
        return NULL;
    }

    ftdi->readbuffer_remaining = 0;
    ftdi->readbuffer_offset = 0;

    libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi_read_data_cb, tc, ftdi->usb_read_timeout);
    transfer->type = LIBUSB_TRANSFER_TYPE_BULK;

    ret = libusb_submit_transfer(transfer);
    if (ret < 0)
    {
        libusb_free_transfer(transfer);
        free (tc);
        return NULL;
    }
    tc->transfer = transfer;

    return tc;
}

/**
    Wait for completion of the transfer.

    Use libusb 1.0 asynchronous API.

    \param tc pointer to ftdi_transfer_control

    \retval < 0: Some error happens
    \retval >= 0: Data size transferred
*/

int ftdi_transfer_data_done(struct ftdi_transfer_control *tc)
{
    int ret;
    struct timeval to = { 0, 0 };
    while (!tc->completed)
    {
        ret = libusb_handle_events_timeout_completed(tc->ftdi->usb_ctx,
                &to, &tc->completed);
        if (ret < 0)
        {
            if (ret == LIBUSB_ERROR_INTERRUPTED)
                continue;
            libusb_cancel_transfer(tc->transfer);
            while (!tc->completed)
                if (libusb_handle_events_timeout_completed(tc->ftdi->usb_ctx,
                        &to, &tc->completed) < 0)
                    break;
            libusb_free_transfer(tc->transfer);
            free (tc);
            return ret;
        }
    }

    ret = tc->offset;
    /**
     * tc->transfer could be NULL if "(size <= ftdi->readbuffer_remaining)"
     * at ftdi_read_data_submit(). Therefore, we need to check it here.
     **/
    if (tc->transfer)
    {
        if (tc->transfer->status != LIBUSB_TRANSFER_COMPLETED)
            ret = -1;
        libusb_free_transfer(tc->transfer);
    }
    free(tc);
    return ret;
}

/**
    Cancel transfer and wait for completion.

    Use libusb 1.0 asynchronous API.

    \param tc pointer to ftdi_transfer_control
    \param to pointer to timeout value or NULL for infinite
*/

void ftdi_transfer_data_cancel(struct ftdi_transfer_control *tc,
                               struct timeval * to)
{
    struct timeval tv = { 0, 0 };

    if (!tc->completed && tc->transfer != NULL)
    {
        if (to == NULL)
            to = &tv;

        libusb_cancel_transfer(tc->transfer);
        while (!tc->completed)
        {
            if (libusb_handle_events_timeout_completed(tc->ftdi->usb_ctx, to, &tc->completed) < 0)
                break;
        }
    }

    if (tc->transfer)
        libusb_free_transfer(tc->transfer);

    free (tc);
}

/**
    Configure write buffer chunk size.
    Default is 4096.

    \param ftdi pointer to ftdi_context
    \param chunksize Chunk size

    \retval 0: all fine
    \retval -1: ftdi context invalid
*/
int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
{
    if (ftdi == NULL)
        ftdi_error_return(-1, "ftdi context invalid");

    ftdi->writebuffer_chunksize = chunksize;
    return 0;
}

/**
    Get write buffer chunk size.

    \param ftdi pointer to ftdi_context
    \param chunksize Pointer to store chunk size in

    \retval 0: all fine
    \retval -1: ftdi context invalid
*/
int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
{
    if (ftdi == NULL)
        ftdi_error_return(-1, "ftdi context invalid");

    *chunksize = ftdi->writebuffer_chunksize;
    return 0;
}

/**
    Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.

    Automatically strips the two modem status bytes transferred during every read.

    \param ftdi pointer to ftdi_context
    \param buf Buffer to store data in
    \param size Size of the buffer

    \retval -666: USB device unavailable
    \retval <0: error code from libusb_bulk_transfer()
    \retval  0: no data was available
    \retval >0: number of bytes read

*/
int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
{
    int offset = 0, ret, i, num_of_chunks, chunk_remains;
    int packet_size;
    int actual_length = 1;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-666, "USB device unavailable");

    // Packet size sanity check (avoid division by zero)
    packet_size = ftdi->max_packet_size;
    if (packet_size == 0)
        ftdi_error_return(-1, "max_packet_size is bogus (zero)");

    // everything we want is still in the readbuffer?
    if (size <= (int)ftdi->readbuffer_remaining)
    {
        memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);

        // Fix offsets
        ftdi->readbuffer_remaining -= size;
        ftdi->readbuffer_offset += size;

        /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */

        return size;
    }
    // something still in the readbuffer, but not enough to satisfy 'size'?
    if (ftdi->readbuffer_remaining != 0)
    {
        memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);

        // Fix offset
        offset += ftdi->readbuffer_remaining;
    }
    // do the actual USB read
    while (offset < size && actual_length > 0)
    {
        ftdi->readbuffer_remaining = 0;
        ftdi->readbuffer_offset = 0;
        /* returns how much received */
        ret = libusb_bulk_transfer (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, &actual_length, ftdi->usb_read_timeout);
        if (ret < 0)
            ftdi_error_return(ret, "usb bulk read failed");

        if (actual_length > 2)
        {
            // skip FTDI status bytes.
            // Maybe stored in the future to enable modem use
            num_of_chunks = actual_length / packet_size;
            chunk_remains = actual_length % packet_size;
            //printf("actual_length = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", actual_length, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);

            ftdi->readbuffer_offset += 2;
            actual_length -= 2;

            if (actual_length > packet_size - 2)
            {
                for (i = 1; i < num_of_chunks; i++)
                    memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
                             ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
                             packet_size - 2);
                if (chunk_remains > 2)
                {
                    memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
                             ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
                             chunk_remains-2);
                    actual_length -= 2*num_of_chunks;
                }
                else
                    actual_length -= 2*(num_of_chunks-1)+chunk_remains;
            }
        }
        else if (actual_length <= 2)
        {
            // no more data to read?
            return offset;
        }
        if (actual_length > 0)
        {
            // data still fits in buf?
            if (offset+actual_length <= size)
            {
                memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, actual_length);
                //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
                offset += actual_length;

                /* Did we read exactly the right amount of bytes? */
                if (offset == size)
                    //printf("read_data exact rem %d offset %d\n",
                    //ftdi->readbuffer_remaining, offset);
                    return offset;
            }
            else
            {
                // only copy part of the data or size <= readbuffer_chunksize
                int part_size = size-offset;
                memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);

                ftdi->readbuffer_offset += part_size;
                ftdi->readbuffer_remaining = actual_length-part_size;
                offset += part_size;

                /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
                part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */

                return offset;
            }
        }
    }
    // never reached
    return -127;
}

/**
    Configure read buffer chunk size.
    Default is 4096.

    Automatically reallocates the buffer.

    \param ftdi pointer to ftdi_context
    \param chunksize Chunk size

    \retval 0: all fine
    \retval -1: ftdi context invalid
*/
int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
{
    unsigned char *new_buf;

    if (ftdi == NULL)
        ftdi_error_return(-1, "ftdi context invalid");

    // Invalidate all remaining data
    ftdi->readbuffer_offset = 0;
    ftdi->readbuffer_remaining = 0;
#ifdef __linux__
    /* We can't set readbuffer_chunksize larger than MAX_BULK_BUFFER_LENGTH,
       which is defined in libusb-1.0.  Otherwise, each USB read request will
       be divided into multiple URBs.  This will cause issues on Linux kernel
       older than 2.6.32.  */
    if (chunksize > 16384)
        chunksize = 16384;
#endif

    if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
        ftdi_error_return(-1, "out of memory for readbuffer");

    ftdi->readbuffer = new_buf;
    ftdi->readbuffer_chunksize = chunksize;

    return 0;
}

/**
    Get read buffer chunk size.

    \param ftdi pointer to ftdi_context
    \param chunksize Pointer to store chunk size in

    \retval 0: all fine
    \retval -1: FTDI context invalid
*/
int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
{
    if (ftdi == NULL)
        ftdi_error_return(-1, "FTDI context invalid");

    *chunksize = ftdi->readbuffer_chunksize;
    return 0;
}

/**
    Enable/disable bitbang modes.

    \param ftdi pointer to ftdi_context
    \param bitmask Bitmask to configure lines.
           HIGH/ON value configures a line as output.
    \param mode Bitbang mode: use the values defined in \ref ftdi_mpsse_mode

    \retval  0: all fine
    \retval -1: can't enable bitbang mode
    \retval -2: USB device unavailable
*/
int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
{
    unsigned short usb_val;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    usb_val = bitmask; // low byte: bitmask
    usb_val |= (mode << 8);
    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a BM/2232C type chip?");

    ftdi->bitbang_mode = mode;
    ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
    return 0;
}

/**
    Disable bitbang mode.

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: can't disable bitbang mode
    \retval -2: USB device unavailable
*/
int ftdi_disable_bitbang(struct ftdi_context *ftdi)
{
    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");

    ftdi->bitbang_enabled = 0;
    return 0;
}


/**
    Directly read pin state, circumventing the read buffer. Useful for bitbang mode.

    \param ftdi pointer to ftdi_context
    \param pins Pointer to store pins into

    \retval  0: all fine
    \retval -1: read pins failed
    \retval -2: USB device unavailable
*/
int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
{
    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_PINS_REQUEST, 0, ftdi->index, (unsigned char *)pins, 1, ftdi->usb_read_timeout) != 1)
        ftdi_error_return(-1, "read pins failed");

    return 0;
}

/**
    Set latency timer

    The FTDI chip keeps data in the internal buffer for a specific
    amount of time if the buffer is not full yet to decrease
    load on the usb bus.

    \param ftdi pointer to ftdi_context
    \param latency Value between 1 and 255

    \retval  0: all fine
    \retval -1: latency out of range
    \retval -2: unable to set latency timer
    \retval -3: USB device unavailable
*/
int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
{
    unsigned short usb_val;

    if (latency < 1)
        ftdi_error_return(-1, "latency out of range. Only valid for 1-255");

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-3, "USB device unavailable");

    usb_val = latency;
    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_LATENCY_TIMER_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-2, "unable to set latency timer");

    return 0;
}

/**
    Get latency timer

    \param ftdi pointer to ftdi_context
    \param latency Pointer to store latency value in

    \retval  0: all fine
    \retval -1: unable to get latency timer
    \retval -2: USB device unavailable
*/
int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
{
    unsigned short usb_val;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_GET_LATENCY_TIMER_REQUEST, 0, ftdi->index, (unsigned char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
        ftdi_error_return(-1, "reading latency timer failed");

    *latency = (unsigned char)usb_val;
    return 0;
}

/**
    Poll modem status information

    This function allows the retrieve the two status bytes of the device.
    The device sends these bytes also as a header for each read access
    where they are discarded by ftdi_read_data(). The chip generates
    the two stripped status bytes in the absence of data every 40 ms.

    Layout of the first byte:
    - B0..B3 - must be 0
    - B4       Clear to send (CTS)
                 0 = inactive
                 1 = active
    - B5       Data set ready (DTS)
                 0 = inactive
                 1 = active
    - B6       Ring indicator (RI)
                 0 = inactive
                 1 = active
    - B7       Receive line signal detect (RLSD)
                 0 = inactive
                 1 = active

    Layout of the second byte:
    - B0       Data ready (DR)
    - B1       Overrun error (OE)
    - B2       Parity error (PE)
    - B3       Framing error (FE)
    - B4       Break interrupt (BI)
    - B5       Transmitter holding register (THRE)
    - B6       Transmitter empty (TEMT)
    - B7       Error in RCVR FIFO

    \param ftdi pointer to ftdi_context
    \param status Pointer to store status information in. Must be two bytes.

    \retval  0: all fine
    \retval -1: unable to retrieve status information
    \retval -2: USB device unavailable
*/
int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
{
    char usb_val[2];

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_POLL_MODEM_STATUS_REQUEST, 0, ftdi->index, (unsigned char *)usb_val, 2, ftdi->usb_read_timeout) != 2)
        ftdi_error_return(-1, "getting modem status failed");

    *status = (usb_val[1] << 8) | (usb_val[0] & 0xFF);

    return 0;
}

/**
    Set flowcontrol for ftdi chip

    Note: Do not use this function to enable XON/XOFF mode, use ftdi_setflowctrl_xonxoff() instead.

    \param ftdi pointer to ftdi_context
    \param flowctrl flow control to use. should be
           SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS

    \retval  0: all fine
    \retval -1: set flow control failed
    \retval -2: USB device unavailable
*/
int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
{
    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
                                NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "set flow control failed");

    return 0;
}

/**
    Set XON/XOFF flowcontrol for ftdi chip

    \param ftdi pointer to ftdi_context
    \param xon character code used to resume transmission
    \param xoff character code used to pause transmission

    \retval  0: all fine
    \retval -1: set flow control failed
    \retval -2: USB device unavailable
*/
int ftdi_setflowctrl_xonxoff(struct ftdi_context *ftdi, unsigned char xon, unsigned char xoff)
{
    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    uint16_t xonxoff = xon | (xoff << 8);
    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_SET_FLOW_CTRL_REQUEST, xonxoff, (SIO_XON_XOFF_HS | ftdi->index),
                                NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "set flow control failed");

    return 0;
}

/**
    Set dtr line

    \param ftdi pointer to ftdi_context
    \param state state to set line to (1 or 0)

    \retval  0: all fine
    \retval -1: set dtr failed
    \retval -2: USB device unavailable
*/
int ftdi_setdtr(struct ftdi_context *ftdi, int state)
{
    unsigned short usb_val;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (state)
        usb_val = SIO_SET_DTR_HIGH;
    else
        usb_val = SIO_SET_DTR_LOW;

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
                                NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "set dtr failed");

    return 0;
}

/**
    Set rts line

    \param ftdi pointer to ftdi_context
    \param state state to set line to (1 or 0)

    \retval  0: all fine
    \retval -1: set rts failed
    \retval -2: USB device unavailable
*/
int ftdi_setrts(struct ftdi_context *ftdi, int state)
{
    unsigned short usb_val;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (state)
        usb_val = SIO_SET_RTS_HIGH;
    else
        usb_val = SIO_SET_RTS_LOW;

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
                                NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "set of rts failed");

    return 0;
}

/**
    Set dtr and rts line in one pass

    \param ftdi pointer to ftdi_context
    \param dtr  DTR state to set line to (1 or 0)
    \param rts  RTS state to set line to (1 or 0)

    \retval  0: all fine
    \retval -1: set dtr/rts failed
    \retval -2: USB device unavailable
 */
int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
{
    unsigned short usb_val;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (dtr)
        usb_val = SIO_SET_DTR_HIGH;
    else
        usb_val = SIO_SET_DTR_LOW;

    if (rts)
        usb_val |= SIO_SET_RTS_HIGH;
    else
        usb_val |= SIO_SET_RTS_LOW;

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
                                NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "set of rts/dtr failed");

    return 0;
}

/**
    Set the special event character

    \param ftdi pointer to ftdi_context
    \param eventch Event character
    \param enable 0 to disable the event character, non-zero otherwise

    \retval  0: all fine
    \retval -1: unable to set event character
    \retval -2: USB device unavailable
*/
int ftdi_set_event_char(struct ftdi_context *ftdi,
                        unsigned char eventch, unsigned char enable)
{
    unsigned short usb_val;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    usb_val = eventch;
    if (enable)
        usb_val |= 1 << 8;

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_EVENT_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "setting event character failed");

    return 0;
}

/**
    Set error character

    \param ftdi pointer to ftdi_context
    \param errorch Error character
    \param enable 0 to disable the error character, non-zero otherwise

    \retval  0: all fine
    \retval -1: unable to set error character
    \retval -2: USB device unavailable
*/
int ftdi_set_error_char(struct ftdi_context *ftdi,
                        unsigned char errorch, unsigned char enable)
{
    unsigned short usb_val;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    usb_val = errorch;
    if (enable)
        usb_val |= 1 << 8;

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_ERROR_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "setting error character failed");

    return 0;
}

/**
    Init eeprom with default values for the connected device
    \param ftdi pointer to ftdi_context
    \param manufacturer String to use as Manufacturer
    \param product String to use as Product description
    \param serial String to use as Serial number description

    \retval  0: all fine
    \retval -1: No struct ftdi_context
    \retval -2: No struct ftdi_eeprom
    \retval -3: No connected device or device not yet opened
*/
int ftdi_eeprom_initdefaults(struct ftdi_context *ftdi, const char * manufacturer,
                             const char * product, const char * serial)
{
    struct ftdi_eeprom *eeprom;

    if (ftdi == NULL)
        ftdi_error_return(-1, "No struct ftdi_context");

    if (ftdi->eeprom == NULL)
        ftdi_error_return(-2,"No struct ftdi_eeprom");

    eeprom = ftdi->eeprom;
    memset(eeprom, 0, sizeof(struct ftdi_eeprom));

    if (ftdi->usb_dev == NULL)
        ftdi_error_return(-3, "No connected device or device not yet opened");

    eeprom->vendor_id = 0x0403;
    eeprom->use_serial = (serial != NULL);
    if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM) ||
            (ftdi->type == TYPE_R))
        eeprom->product_id = 0x6001;
    else if (ftdi->type == TYPE_4232H)
        eeprom->product_id = 0x6011;
    else if (ftdi->type == TYPE_232H)
        eeprom->product_id = 0x6014;
    else if (ftdi->type == TYPE_230X)
        eeprom->product_id = 0x6015;
    else
        eeprom->product_id = 0x6010;

    if (ftdi->type == TYPE_AM)
        eeprom->usb_version = 0x0101;
    else
        eeprom->usb_version = 0x0200;
    eeprom->max_power = 100;

    if (eeprom->manufacturer)
        free (eeprom->manufacturer);
    eeprom->manufacturer = NULL;
    if (manufacturer)
    {
        eeprom->manufacturer = (char *)malloc(strlen(manufacturer)+1);
        if (eeprom->manufacturer)
            strcpy(eeprom->manufacturer, manufacturer);
    }

    if (eeprom->product)
        free (eeprom->product);
    eeprom->product = NULL;
    if(product)
    {
        eeprom->product = (char *)malloc(strlen(product)+1);
        if (eeprom->product)
            strcpy(eeprom->product, product);
    }
    else
    {
        const char* default_product;
        switch(ftdi->type)
        {
            case TYPE_AM:    default_product = "AM"; break;
            case TYPE_BM:    default_product = "BM"; break;
            case TYPE_2232C: default_product = "Dual RS232"; break;
            case TYPE_R:     default_product = "FT232R USB UART"; break;
            case TYPE_2232H: default_product = "Dual RS232-HS"; break;
            case TYPE_4232H: default_product = "FT4232H"; break;
            case TYPE_232H:  default_product = "Single-RS232-HS"; break;
            case TYPE_230X:  default_product = "FT230X Basic UART"; break;
            default:
                ftdi_error_return(-3, "Unknown chip type");
        }
        eeprom->product = (char *)malloc(strlen(default_product) +1);
        if (eeprom->product)
            strcpy(eeprom->product, default_product);
    }

    if (eeprom->serial)
        free (eeprom->serial);
    eeprom->serial = NULL;
    if (serial)
    {
        eeprom->serial = (char *)malloc(strlen(serial)+1);
        if (eeprom->serial)
            strcpy(eeprom->serial, serial);
    }

    if (ftdi->type == TYPE_R)
    {
        eeprom->max_power = 90;
        eeprom->size = 0x80;
        eeprom->cbus_function[0] = CBUS_TXLED;
        eeprom->cbus_function[1] = CBUS_RXLED;
        eeprom->cbus_function[2] = CBUS_TXDEN;
        eeprom->cbus_function[3] = CBUS_PWREN;
        eeprom->cbus_function[4] = CBUS_SLEEP;
    }
    else if (ftdi->type == TYPE_230X)
    {
        eeprom->max_power = 90;
        eeprom->size = 0x100;
        eeprom->cbus_function[0] = CBUSX_TXDEN;
        eeprom->cbus_function[1] = CBUSX_RXLED;
        eeprom->cbus_function[2] = CBUSX_TXLED;
        eeprom->cbus_function[3] = CBUSX_SLEEP;
    }
    else
    {
        if(ftdi->type == TYPE_232H)
        {
            int i;
            for (i=0; i<10; i++)
                eeprom->cbus_function[i] = CBUSH_TRISTATE;
        }
        eeprom->size = -1;
    }
    switch (ftdi->type)
    {
        case TYPE_AM:
            eeprom->release_number = 0x0200;
            break;
        case TYPE_BM:
            eeprom->release_number = 0x0400;
            break;
        case TYPE_2232C:
            eeprom->release_number = 0x0500;
            break;
        case TYPE_R:
            eeprom->release_number = 0x0600;
            break;
        case TYPE_2232H:
            eeprom->release_number = 0x0700;
            break;
        case TYPE_4232H:
            eeprom->release_number = 0x0800;
            break;
        case TYPE_232H:
            eeprom->release_number = 0x0900;
            break;
        case TYPE_230X:
            eeprom->release_number = 0x1000;
            break;
        default:
            eeprom->release_number = 0x00;
    }
    return 0;
}

int ftdi_eeprom_set_strings(struct ftdi_context *ftdi, const char * manufacturer,
                            const char * product, const char * serial)
{
    struct ftdi_eeprom *eeprom;

    if (ftdi == NULL)
        ftdi_error_return(-1, "No struct ftdi_context");

    if (ftdi->eeprom == NULL)
        ftdi_error_return(-2,"No struct ftdi_eeprom");

    eeprom = ftdi->eeprom;

    if (ftdi->usb_dev == NULL)
        ftdi_error_return(-3, "No connected device or device not yet opened");

    if (manufacturer)
    {
        if (eeprom->manufacturer)
            free (eeprom->manufacturer);
        eeprom->manufacturer = (char *)malloc(strlen(manufacturer)+1);
        if (eeprom->manufacturer)
            strcpy(eeprom->manufacturer, manufacturer);
    }

    if(product)
    {
        if (eeprom->product)
            free (eeprom->product);
        eeprom->product = (char *)malloc(strlen(product)+1);
        if (eeprom->product)
            strcpy(eeprom->product, product);
    }

    if (serial)
    {
        if (eeprom->serial)
            free (eeprom->serial);
        eeprom->serial = (char *)malloc(strlen(serial)+1);
        if (eeprom->serial)
        {
            strcpy(eeprom->serial, serial);
            eeprom->use_serial = 1;
        }
    }
    return 0;
}

/**
    Return device ID strings from the eeprom. Device needs to be connected.

    The parameters manufacturer, description and serial may be NULL
    or pointer to buffers to store the fetched strings.

    \param ftdi pointer to ftdi_context
    \param manufacturer Store manufacturer string here if not NULL
    \param mnf_len Buffer size of manufacturer string
    \param product Store product description string here if not NULL
    \param prod_len Buffer size of product description string
    \param serial Store serial string here if not NULL
    \param serial_len Buffer size of serial string

    \retval   0: all fine
    \retval  -1: ftdi context invalid
    \retval  -2: ftdi eeprom buffer invalid
*/
int ftdi_eeprom_get_strings(struct ftdi_context *ftdi,
                            char *manufacturer, int mnf_len,
                            char *product, int prod_len,
                            char *serial, int serial_len)
{
    struct ftdi_eeprom *eeprom;

    if (ftdi == NULL)
        ftdi_error_return(-1, "No struct ftdi_context");
    if (ftdi->eeprom == NULL)
        ftdi_error_return(-2, "No struct ftdi_eeprom");

    eeprom = ftdi->eeprom;

    if (manufacturer)
    {
        strncpy(manufacturer, eeprom->manufacturer, mnf_len);
        if (mnf_len > 0)
            manufacturer[mnf_len - 1] = '\0';
    }

    if (product)
    {
        strncpy(product, eeprom->product, prod_len);
        if (prod_len > 0)
            product[prod_len - 1] = '\0';
    }

    if (serial)
    {
        strncpy(serial, eeprom->serial, serial_len);
        if (serial_len > 0)
            serial[serial_len - 1] = '\0';
    }

    return 0;
}

/*FTD2XX doesn't check for values not fitting in the ACBUS Signal options*/
void set_ft232h_cbus(struct ftdi_eeprom *eeprom, unsigned char * output)
{
    int i;
    for(i=0; i<5; i++)
    {
        int mode_low, mode_high;
        if (eeprom->cbus_function[2*i]> CBUSH_CLK7_5)
            mode_low = CBUSH_TRISTATE;
        else
            mode_low = eeprom->cbus_function[2*i];
        if (eeprom->cbus_function[2*i+1]> CBUSH_CLK7_5)
            mode_high = CBUSH_TRISTATE;
        else
            mode_high = eeprom->cbus_function[2*i+1];

        output[0x18+i] = (mode_high <<4) | mode_low;
    }
}
/* Return the bits for the encoded EEPROM Structure of a requested Mode
 *
 */
static unsigned char type2bit(unsigned char type, enum ftdi_chip_type chip)
{
    switch (chip)
    {
        case TYPE_2232H:
        case TYPE_2232C:
        {
            switch (type)
            {
                case CHANNEL_IS_UART: return 0;
                case CHANNEL_IS_FIFO: return 0x01;
                case CHANNEL_IS_OPTO: return 0x02;
                case CHANNEL_IS_CPU : return 0x04;
                default: return 0;
            }
        }
        case TYPE_232H:
        {
            switch (type)
            {
                case CHANNEL_IS_UART   : return 0;
                case CHANNEL_IS_FIFO   : return 0x01;
                case CHANNEL_IS_OPTO   : return 0x02;
                case CHANNEL_IS_CPU    : return 0x04;
                case CHANNEL_IS_FT1284 : return 0x08;
                default: return 0;
            }
        }
        case TYPE_R:
        {
            switch (type)
            {
                case CHANNEL_IS_UART   : return 0;
                case CHANNEL_IS_FIFO   : return 0x01;
                default: return 0;
            }
        }
        case TYPE_230X: /* FT230X is only UART */
        default: return 0;
    }
    return 0;
}

/**
    Build binary buffer from ftdi_eeprom structure.
    Output is suitable for ftdi_write_eeprom().

    \param ftdi pointer to ftdi_context

    \retval >=0: size of eeprom user area in bytes
    \retval -1: eeprom size (128 bytes) exceeded by custom strings
    \retval -2: Invalid eeprom or ftdi pointer
    \retval -3: Invalid cbus function setting     (FIXME: Not in the code?)
    \retval -4: Chip doesn't support invert       (FIXME: Not in the code?)
    \retval -5: Chip doesn't support high current drive         (FIXME: Not in the code?)
    \retval -6: No connected EEPROM or EEPROM Type unknown
*/
int ftdi_eeprom_build(struct ftdi_context *ftdi)
{
    unsigned char i, j, eeprom_size_mask;
    unsigned short checksum, value;
    unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
    int user_area_size, free_start, free_end;
    struct ftdi_eeprom *eeprom;
    unsigned char * output;

    if (ftdi == NULL)
        ftdi_error_return(-2,"No context");
    if (ftdi->eeprom == NULL)
        ftdi_error_return(-2,"No eeprom structure");

    eeprom= ftdi->eeprom;
    output = eeprom->buf;

    if (eeprom->chip == -1)
        ftdi_error_return(-6,"No connected EEPROM or EEPROM type unknown");

    if (eeprom->size == -1)
    {
        if ((eeprom->chip == 0x56) || (eeprom->chip == 0x66))
            eeprom->size = 0x100;
        else
            eeprom->size = 0x80;
    }

    if (eeprom->manufacturer != NULL)
        manufacturer_size = strlen(eeprom->manufacturer);
    if (eeprom->product != NULL)
        product_size = strlen(eeprom->product);
    if (eeprom->serial != NULL)
        serial_size = strlen(eeprom->serial);

    // eeprom size check
    switch (ftdi->type)
    {
        case TYPE_AM:
        case TYPE_BM:
        case TYPE_R:
            user_area_size = 96;    // base size for strings (total of 48 characters)
            break;
        case TYPE_2232C:
            user_area_size = 90;     // two extra config bytes and 4 bytes PnP stuff
            break;
        case TYPE_230X:
            user_area_size = 88;     // four extra config bytes + 4 bytes PnP stuff
            break;
        case TYPE_2232H:            // six extra config bytes + 4 bytes PnP stuff
        case TYPE_4232H:
            user_area_size = 86;
            break;
        case TYPE_232H:
            user_area_size = 80;
            break;
        default:
            user_area_size = 0;
            break;
    }
    user_area_size  -= (manufacturer_size + product_size + serial_size) * 2;

    if (user_area_size < 0)
        ftdi_error_return(-1,"eeprom size exceeded");

    // empty eeprom
    if (ftdi->type == TYPE_230X)
    {
        /* FT230X have a reserved section in the middle of the MTP,
           which cannot be written to, but must be included in the checksum */
        memset(ftdi->eeprom->buf, 0, 0x80);
        memset((ftdi->eeprom->buf + 0xa0), 0, (FTDI_MAX_EEPROM_SIZE - 0xa0));
    }
    else
    {
        memset(ftdi->eeprom->buf, 0, FTDI_MAX_EEPROM_SIZE);
    }

    // Bytes and Bits set for all Types

    // Addr 02: Vendor ID
    output[0x02] = eeprom->vendor_id;
    output[0x03] = eeprom->vendor_id >> 8;

    // Addr 04: Product ID
    output[0x04] = eeprom->product_id;
    output[0x05] = eeprom->product_id >> 8;

    // Addr 06: Device release number (0400h for BM features)
    output[0x06] = eeprom->release_number;
    output[0x07] = eeprom->release_number >> 8;

    // Addr 08: Config descriptor
    // Bit 7: always 1
    // Bit 6: 1 if this device is self powered, 0 if bus powered
    // Bit 5: 1 if this device uses remote wakeup
    // Bit 4-0: reserved - 0
    j = 0x80;
    if (eeprom->self_powered)
        j |= 0x40;
    if (eeprom->remote_wakeup)
        j |= 0x20;
    output[0x08] = j;

    // Addr 09: Max power consumption: max power = value * 2 mA
    output[0x09] = eeprom->max_power / MAX_POWER_MILLIAMP_PER_UNIT;

    if ((ftdi->type != TYPE_AM) && (ftdi->type != TYPE_230X))
    {
        // Addr 0A: Chip configuration
        // Bit 7: 0 - reserved
        // Bit 6: 0 - reserved
        // Bit 5: 0 - reserved
        // Bit 4: 1 - Change USB version
        // Bit 3: 1 - Use the serial number string
        // Bit 2: 1 - Enable suspend pull downs for lower power
        // Bit 1: 1 - Out EndPoint is Isochronous
        // Bit 0: 1 - In EndPoint is Isochronous
        //
        j = 0;
        if (eeprom->in_is_isochronous)
            j = j | 1;
        if (eeprom->out_is_isochronous)
            j = j | 2;
        output[0x0A] = j;
    }

    // Dynamic content
    // Strings start at 0x94 (TYPE_AM, TYPE_BM)
    // 0x96 (TYPE_2232C), 0x98 (TYPE_R) and 0x9a (TYPE_x232H)
    // 0xa0 (TYPE_232H)
    i = 0;
    switch (ftdi->type)
    {
        case TYPE_2232H:
        case TYPE_4232H:
            i += 2;
			/* Fall through*/
        case TYPE_R:
            i += 2;
			/* Fall through*/
        case TYPE_2232C:
            i += 2;
			/* Fall through*/
        case TYPE_AM:
        case TYPE_BM:
            i += 0x94;
            break;
        case TYPE_232H:
        case TYPE_230X:
            i = 0xa0;
            break;
    }
    /* Wrap around 0x80 for 128 byte EEPROMS (Internale and 93x46) */
    eeprom_size_mask = eeprom->size -1;
    free_end = i & eeprom_size_mask;

    // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
    // Addr 0F: Length of manufacturer string
    // Output manufacturer
    output[0x0E] = i;  // calculate offset
    output[i & eeprom_size_mask] = manufacturer_size*2 + 2, i++;
    output[i & eeprom_size_mask] = 0x03, i++; // type: string
    for (j = 0; j < manufacturer_size; j++)
    {
        output[i & eeprom_size_mask] = eeprom->manufacturer[j], i++;
        output[i & eeprom_size_mask] = 0x00, i++;
    }
    output[0x0F] = manufacturer_size*2 + 2;

    // Addr 10: Offset of the product string + 0x80, calculated later
    // Addr 11: Length of product string
    output[0x10] = i | 0x80;  // calculate offset
    output[i & eeprom_size_mask] = product_size*2 + 2, i++;
    output[i & eeprom_size_mask] = 0x03, i++;
    for (j = 0; j < product_size; j++)
    {
        output[i & eeprom_size_mask] = eeprom->product[j], i++;
        output[i & eeprom_size_mask] = 0x00, i++;
    }
    output[0x11] = product_size*2 + 2;

    if (eeprom->use_serial) {
        // Addr 12: Offset of the serial string + 0x80, calculated later
        // Addr 13: Length of serial string
        output[0x12] = i | 0x80; // calculate offset
        output[i & eeprom_size_mask] = serial_size*2 + 2, i++;
        output[i & eeprom_size_mask] = 0x03, i++;
        for (j = 0; j < serial_size; j++)
        {
            output[i & eeprom_size_mask] = eeprom->serial[j], i++;
            output[i & eeprom_size_mask] = 0x00, i++;
        }
        output[0x13] = serial_size*2 + 2;
    }

    // Legacy port name and PnP fields for FT2232 and newer chips
    // It doesn't appear when written with FT_Prog for FT4232H chip.
    if (ftdi->type > TYPE_BM && ftdi->type != TYPE_4232H)
    {
        output[i & eeprom_size_mask] = 0x02; /* as seen when written with FTD2XX */
        i++;
        output[i & eeprom_size_mask] = 0x03; /* as seen when written with FTD2XX */
        i++;
        output[i & eeprom_size_mask] = eeprom->is_not_pnp; /* as seen when written with FTD2XX */
        i++;
    }

    if (ftdi->type > TYPE_AM) /* use_serial not used in AM devices */
    {
        if (eeprom->use_serial)
            output[0x0A] |= USE_SERIAL_NUM;
        else
            output[0x0A] &= ~USE_SERIAL_NUM;
    }

    /* Bytes and Bits specific to (some) types
       Write linear, as this allows easier fixing*/
    switch (ftdi->type)
    {
        case TYPE_AM:
            break;
        case TYPE_BM:
            output[0x0C] = eeprom->usb_version & 0xff;
            output[0x0D] = (eeprom->usb_version>>8) & 0xff;
            if (eeprom->use_usb_version)
                output[0x0A] |= USE_USB_VERSION_BIT;
            else
                output[0x0A] &= ~USE_USB_VERSION_BIT;

            break;
        case TYPE_2232C:

            output[0x00] = type2bit(eeprom->channel_a_type, TYPE_2232C);
            if (eeprom->channel_a_driver)
                output[0x00] |= DRIVER_VCP;
            else
                output[0x00] &= ~DRIVER_VCP;

            if (eeprom->high_current_a)
                output[0x00] |= HIGH_CURRENT_DRIVE;
            else
                output[0x00] &= ~HIGH_CURRENT_DRIVE;

            output[0x01] = type2bit(eeprom->channel_b_type, TYPE_2232C);
            if (eeprom->channel_b_driver)
                output[0x01] |= DRIVER_VCP;
            else
                output[0x01] &= ~DRIVER_VCP;

            if (eeprom->high_current_b)
                output[0x01] |= HIGH_CURRENT_DRIVE;
            else
                output[0x01] &= ~HIGH_CURRENT_DRIVE;

            if (eeprom->in_is_isochronous)
                output[0x0A] |= 0x1;
            else
                output[0x0A] &= ~0x1;
            if (eeprom->out_is_isochronous)
                output[0x0A] |= 0x2;
            else
                output[0x0A] &= ~0x2;
            if (eeprom->suspend_pull_downs)
                output[0x0A] |= 0x4;
            else
                output[0x0A] &= ~0x4;
            if (eeprom->use_usb_version)
                output[0x0A] |= USE_USB_VERSION_BIT;
            else
                output[0x0A] &= ~USE_USB_VERSION_BIT;

            output[0x0C] = eeprom->usb_version & 0xff;
            output[0x0D] = (eeprom->usb_version>>8) & 0xff;
            output[0x14] = eeprom->chip;
            break;
        case TYPE_R:
            output[0x00] = type2bit(eeprom->channel_a_type, TYPE_R);
            if (eeprom->high_current)
                output[0x00] |= HIGH_CURRENT_DRIVE_R;

            /* Field is inverted for TYPE_R: Bit 00.3 set to 1 is D2XX, VCP is 0 */
            if (eeprom->channel_a_driver)
                output[0x00] &= ~DRIVER_VCP;
            else
                output[0x00] |= DRIVER_VCP;

            if (eeprom->external_oscillator)
                output[0x00] |= 0x02;
            output[0x01] = 0x40; /* Hard coded Endpoint Size*/

            if (eeprom->suspend_pull_downs)
                output[0x0A] |= 0x4;
            else
                output[0x0A] &= ~0x4;
            output[0x0B] = eeprom->invert;
            output[0x0C] = eeprom->usb_version & 0xff;
            output[0x0D] = (eeprom->usb_version>>8) & 0xff;

            if (eeprom->cbus_function[0] > CBUS_BB_RD)
                output[0x14] = CBUS_TXLED;
            else
                output[0x14] = eeprom->cbus_function[0];

            if (eeprom->cbus_function[1] > CBUS_BB_RD)
                output[0x14] |= CBUS_RXLED<<4;
            else
                output[0x14] |= eeprom->cbus_function[1]<<4;

            if (eeprom->cbus_function[2] > CBUS_BB_RD)
                output[0x15] = CBUS_TXDEN;
            else
                output[0x15] = eeprom->cbus_function[2];

            if (eeprom->cbus_function[3] > CBUS_BB_RD)
                output[0x15] |= CBUS_PWREN<<4;
            else
                output[0x15] |= eeprom->cbus_function[3]<<4;

            if (eeprom->cbus_function[4] > CBUS_CLK6)
                output[0x16] = CBUS_SLEEP;
            else
                output[0x16] = eeprom->cbus_function[4];
            break;
        case TYPE_2232H:
            output[0x00] = type2bit(eeprom->channel_a_type, TYPE_2232H);
            if (eeprom->channel_a_driver)
                output[0x00] |= DRIVER_VCP;
            else
                output[0x00] &= ~DRIVER_VCP;

            output[0x01] = type2bit(eeprom->channel_b_type, TYPE_2232H);
            if (eeprom->channel_b_driver)
                output[0x01] |= DRIVER_VCP;
            else
                output[0x01] &= ~DRIVER_VCP;

            if (eeprom->suspend_dbus7)
                output[0x01] |= SUSPEND_DBUS7_BIT;
            else
                output[0x01] &= ~SUSPEND_DBUS7_BIT;

            if (eeprom->suspend_pull_downs)
                output[0x0A] |= 0x4;
            else
                output[0x0A] &= ~0x4;

            if (eeprom->group0_drive > DRIVE_16MA)
                output[0x0c] |= DRIVE_16MA;
            else
                output[0x0c] |= eeprom->group0_drive;
            if (eeprom->group0_schmitt)
                output[0x0c] |= IS_SCHMITT;
            if (eeprom->group0_slew)
                output[0x0c] |= SLOW_SLEW;

            if (eeprom->group1_drive > DRIVE_16MA)
                output[0x0c] |= DRIVE_16MA<<4;
            else
                output[0x0c] |= eeprom->group1_drive<<4;
            if (eeprom->group1_schmitt)
                output[0x0c] |= IS_SCHMITT<<4;
            if (eeprom->group1_slew)
                output[0x0c] |= SLOW_SLEW<<4;

            if (eeprom->group2_drive > DRIVE_16MA)
                output[0x0d] |= DRIVE_16MA;
            else
                output[0x0d] |= eeprom->group2_drive;
            if (eeprom->group2_schmitt)
                output[0x0d] |= IS_SCHMITT;
            if (eeprom->group2_slew)
                output[0x0d] |= SLOW_SLEW;

            if (eeprom->group3_drive > DRIVE_16MA)
                output[0x0d] |= DRIVE_16MA<<4;
            else
                output[0x0d] |= eeprom->group3_drive<<4;
            if (eeprom->group3_schmitt)
                output[0x0d] |= IS_SCHMITT<<4;
            if (eeprom->group3_slew)
                output[0x0d] |= SLOW_SLEW<<4;

            output[0x18] = eeprom->chip;

            break;
        case TYPE_4232H:
            if (eeprom->channel_a_driver)
                output[0x00] |= DRIVER_VCP;
            else
                output[0x00] &= ~DRIVER_VCP;
            if (eeprom->channel_b_driver)
                output[0x01] |= DRIVER_VCP;
            else
                output[0x01] &= ~DRIVER_VCP;
            if (eeprom->channel_c_driver)
                output[0x00] |= (DRIVER_VCP << 4);
            else
                output[0x00] &= ~(DRIVER_VCP << 4);
            if (eeprom->channel_d_driver)
                output[0x01] |= (DRIVER_VCP << 4);
            else
                output[0x01] &= ~(DRIVER_VCP << 4);

            if (eeprom->suspend_pull_downs)
                output[0x0a] |= 0x4;
            else
                output[0x0a] &= ~0x4;

            if (eeprom->channel_a_rs485enable)
                output[0x0b] |= CHANNEL_IS_RS485 << 0;
            else
                output[0x0b] &= ~(CHANNEL_IS_RS485 << 0);
            if (eeprom->channel_b_rs485enable)
                output[0x0b] |= CHANNEL_IS_RS485 << 1;
            else
                output[0x0b] &= ~(CHANNEL_IS_RS485 << 1);
            if (eeprom->channel_c_rs485enable)
                output[0x0b] |= CHANNEL_IS_RS485 << 2;
            else
                output[0x0b] &= ~(CHANNEL_IS_RS485 << 2);
            if (eeprom->channel_d_rs485enable)
                output[0x0b] |= CHANNEL_IS_RS485 << 3;
            else
                output[0x0b] &= ~(CHANNEL_IS_RS485 << 3);

            if (eeprom->group0_drive > DRIVE_16MA)
                output[0x0c] |= DRIVE_16MA;
            else
                output[0x0c] |= eeprom->group0_drive;
            if (eeprom->group0_schmitt)
                output[0x0c] |= IS_SCHMITT;
            if (eeprom->group0_slew)
                output[0x0c] |= SLOW_SLEW;

            if (eeprom->group1_drive > DRIVE_16MA)
                output[0x0c] |= DRIVE_16MA<<4;
            else
                output[0x0c] |= eeprom->group1_drive<<4;
            if (eeprom->group1_schmitt)
                output[0x0c] |= IS_SCHMITT<<4;
            if (eeprom->group1_slew)
                output[0x0c] |= SLOW_SLEW<<4;

            if (eeprom->group2_drive > DRIVE_16MA)
                output[0x0d] |= DRIVE_16MA;
            else
                output[0x0d] |= eeprom->group2_drive;
            if (eeprom->group2_schmitt)
                output[0x0d] |= IS_SCHMITT;
            if (eeprom->group2_slew)
                output[0x0d] |= SLOW_SLEW;

            if (eeprom->group3_drive > DRIVE_16MA)
                output[0x0d] |= DRIVE_16MA<<4;
            else
                output[0x0d] |= eeprom->group3_drive<<4;
            if (eeprom->group3_schmitt)
                output[0x0d] |= IS_SCHMITT<<4;
            if (eeprom->group3_slew)
                output[0x0d] |= SLOW_SLEW<<4;

            output[0x18] = eeprom->chip;

            break;
        case TYPE_232H:
            output[0x00] = type2bit(eeprom->channel_a_type, TYPE_232H);
            if (eeprom->channel_a_driver)
                output[0x00] |= DRIVER_VCPH;
            else
                output[0x00] &= ~DRIVER_VCPH;

            if (eeprom->powersave)
                output[0x01] |= POWER_SAVE_DISABLE_H;
            else
                output[0x01] &= ~POWER_SAVE_DISABLE_H;

            if (eeprom->suspend_pull_downs)
                output[0x0a] |= 0x4;
            else
                output[0x0a] &= ~0x4;

            if (eeprom->clock_polarity)
                output[0x01] |= FT1284_CLK_IDLE_STATE;
            else
                output[0x01] &= ~FT1284_CLK_IDLE_STATE;
            if (eeprom->data_order)
                output[0x01] |= FT1284_DATA_LSB;
            else
                output[0x01] &= ~FT1284_DATA_LSB;
            if (eeprom->flow_control)
                output[0x01] |= FT1284_FLOW_CONTROL;
            else
                output[0x01] &= ~FT1284_FLOW_CONTROL;

            if (eeprom->group0_drive > DRIVE_16MA)
                output[0x0c] |= DRIVE_16MA;
            else
                output[0x0c] |= eeprom->group0_drive;
            if (eeprom->group0_schmitt)
                output[0x0c] |= IS_SCHMITT;
            if (eeprom->group0_slew)
                output[0x0c] |= SLOW_SLEW;

            if (eeprom->group1_drive > DRIVE_16MA)
                output[0x0d] |= DRIVE_16MA;
            else
                output[0x0d] |= eeprom->group1_drive;
            if (eeprom->group1_schmitt)
                output[0x0d] |= IS_SCHMITT;
            if (eeprom->group1_slew)
                output[0x0d] |= SLOW_SLEW;

            set_ft232h_cbus(eeprom, output);

            output[0x1e] = eeprom->chip;
            /* FIXME: Build FT232H specific EEPROM settings */
            break;
        case TYPE_230X:
            output[0x00] = 0x80; /* Actually, leave the default value */
            /*FIXME: Make DBUS & CBUS Control configurable*/
            output[0x0c] = 0;    /* DBUS drive 4mA, CBUS drive 4 mA like factory default */
            for (j = 0; j <= 6; j++)
            {
                output[0x1a + j] = eeprom->cbus_function[j];
            }
            output[0x0b] = eeprom->invert;
            break;
    }

    /* First address without use */
    free_start = 0;
    switch (ftdi->type)
    {
        case TYPE_230X:
            free_start += 2;
			/* Fall through*/
        case TYPE_232H:
            free_start += 6;
			/* Fall through*/
        case TYPE_2232H:
        case TYPE_4232H:
            free_start += 2;
			/* Fall through*/
        case TYPE_R:
            free_start += 2;
			/* Fall through*/
        case TYPE_2232C:
            free_start++;
			/* Fall through*/
        case TYPE_AM:
        case TYPE_BM:
            free_start += 0x14;
    }

    /* Arbitrary user data */
    if (eeprom->user_data && eeprom->user_data_size >= 0)
    {
        if (eeprom->user_data_addr < free_start)
            fprintf(stderr,"Warning, user data starts inside the generated data!\n");
        if (eeprom->user_data_addr + eeprom->user_data_size >= free_end)
            fprintf(stderr,"Warning, user data overlaps the strings area!\n");
        if (eeprom->user_data_addr + eeprom->user_data_size > eeprom->size)
            ftdi_error_return(-1,"eeprom size exceeded");
        memcpy(output + eeprom->user_data_addr, eeprom->user_data, eeprom->user_data_size);
    }

    // calculate checksum
    checksum = 0xAAAA;

    for (i = 0; i < eeprom->size/2-1; i++)
    {
        if ((ftdi->type == TYPE_230X) && (i == 0x12))
        {
            /* FT230X has a user section in the MTP which is not part of the checksum */
            i = 0x40;
        }
        if ((ftdi->type == TYPE_230X) && (i >=  0x40) && (i < 0x50)) {
            uint16_t data;
            if (ftdi_read_eeprom_location(ftdi, i, &data)) {
                fprintf(stderr, "Reading Factory Configuration Data failed\n");
                i = 0x50;
            }
            value = data;
        }
        else {
            value = output[i*2];
            value += output[(i*2)+1] << 8;
        }
        checksum = value^checksum;
        checksum = (checksum << 1) | (checksum >> 15);
    }

    output[eeprom->size-2] = checksum;
    output[eeprom->size-1] = checksum >> 8;

    eeprom->initialized_for_connected_device = 1;
    return user_area_size;
}
/* Decode the encoded EEPROM field for the FTDI Mode into a value for the abstracted
 * EEPROM structure
 *
 * FTD2XX doesn't allow to set multiple bits in the interface mode bitfield, and so do we
 */
static unsigned char bit2type(unsigned char bits)
{
    switch (bits)
    {
        case   0: return CHANNEL_IS_UART;
        case   1: return CHANNEL_IS_FIFO;
        case   2: return CHANNEL_IS_OPTO;
        case   4: return CHANNEL_IS_CPU;
        case   8: return CHANNEL_IS_FT1284;
        default:
            fprintf(stderr," Unexpected value %d for Hardware Interface type\n",
                    bits);
    }
    return 0;
}
/* Decode 230X / 232R type chips invert bits
 * Prints directly to stdout.
*/
static void print_inverted_bits(int invert)
{
    const char *r_bits[] = {"TXD","RXD","RTS","CTS","DTR","DSR","DCD","RI"};
    int i;

    fprintf(stdout,"Inverted bits:");
    for (i=0; i<8; i++)
        if ((invert & (1<<i)) == (1<<i))
            fprintf(stdout," %s",r_bits[i]);

    fprintf(stdout,"\n");
}
/**
   Decode binary EEPROM image into an ftdi_eeprom structure.

   For FT-X devices use AN_201 FT-X MTP memory Configuration to decode.

   \param ftdi pointer to ftdi_context
   \param verbose Decode EEPROM on stdout

   \retval 0: all fine
   \retval -1: something went wrong

   FIXME: How to pass size? How to handle size field in ftdi_eeprom?
   FIXME: Strings are malloc'ed here and should be freed somewhere
*/
int ftdi_eeprom_decode(struct ftdi_context *ftdi, int verbose)
{
    int i, j;
    unsigned short checksum, eeprom_checksum, value;
    unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
    int eeprom_size;
    struct ftdi_eeprom *eeprom;
    unsigned char *buf = NULL;

    if (ftdi == NULL)
        ftdi_error_return(-1,"No context");
    if (ftdi->eeprom == NULL)
        ftdi_error_return(-1,"No eeprom structure");

    eeprom = ftdi->eeprom;
    eeprom_size = eeprom->size;
    buf = ftdi->eeprom->buf;

    // Addr 02: Vendor ID
    eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);

    // Addr 04: Product ID
    eeprom->product_id = buf[0x04] + (buf[0x05] << 8);

    // Addr 06: Device release number
    eeprom->release_number = buf[0x06] + (buf[0x07]<<8);

    // Addr 08: Config descriptor
    // Bit 7: always 1
    // Bit 6: 1 if this device is self powered, 0 if bus powered
    // Bit 5: 1 if this device uses remote wakeup
    eeprom->self_powered = !!(buf[0x08] & 0x40);
    eeprom->remote_wakeup = !!(buf[0x08] & 0x20);

    // Addr 09: Max power consumption: max power = value * 2 mA
    eeprom->max_power = MAX_POWER_MILLIAMP_PER_UNIT * buf[0x09];

    // Addr 0A: Chip configuration
    // Bit 7: 0 - reserved
    // Bit 6: 0 - reserved
    // Bit 5: 0 - reserved
    // Bit 4: 1 - Change USB version on BM and 2232C
    // Bit 3: 1 - Use the serial number string
    // Bit 2: 1 - Enable suspend pull downs for lower power
    // Bit 1: 1 - Out EndPoint is Isochronous
    // Bit 0: 1 - In EndPoint is Isochronous
    //
    eeprom->in_is_isochronous  = !!(buf[0x0A]&0x01);
    eeprom->out_is_isochronous = !!(buf[0x0A]&0x02);
    eeprom->suspend_pull_downs = !!(buf[0x0A]&0x04);
    eeprom->use_serial         = !!(buf[0x0A] & USE_SERIAL_NUM);
    eeprom->use_usb_version    = !!(buf[0x0A] & USE_USB_VERSION_BIT);

    // Addr 0C: USB version low byte when 0x0A
    // Addr 0D: USB version high byte when 0x0A
    eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);

    // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
    // Addr 0F: Length of manufacturer string
    manufacturer_size = buf[0x0F]/2;
    if (eeprom->manufacturer)
        free(eeprom->manufacturer);
    if (manufacturer_size > 0)
    {
        eeprom->manufacturer = (char *)malloc(manufacturer_size);
        if (eeprom->manufacturer)
        {
            // Decode manufacturer
            i = buf[0x0E] & (eeprom_size -1); // offset
            for (j=0; j<manufacturer_size-1; j++)
            {
                eeprom->manufacturer[j] = buf[2*j+i+2];
            }
            eeprom->manufacturer[j] = '\0';
        }
    }
    else eeprom->manufacturer = NULL;

    // Addr 10: Offset of the product string + 0x80, calculated later
    // Addr 11: Length of product string
    if (eeprom->product)
        free(eeprom->product);
    product_size = buf[0x11]/2;
    if (product_size > 0)
    {
        eeprom->product = (char *)malloc(product_size);
        if (eeprom->product)
        {
            // Decode product name
            i = buf[0x10] & (eeprom_size -1); // offset
            for (j=0; j<product_size-1; j++)
            {
                eeprom->product[j] = buf[2*j+i+2];
            }
            eeprom->product[j] = '\0';
        }
    }
    else eeprom->product = NULL;

    // Addr 12: Offset of the serial string + 0x80, calculated later
    // Addr 13: Length of serial string
    if (eeprom->serial)
        free(eeprom->serial);
    serial_size = buf[0x13]/2;
    if (serial_size > 0)
    {
        eeprom->serial = (char *)malloc(serial_size);
        if (eeprom->serial)
        {
            // Decode serial
            i = buf[0x12] & (eeprom_size -1); // offset
            for (j=0; j<serial_size-1; j++)
            {
                eeprom->serial[j] = buf[2*j+i+2];
            }
            eeprom->serial[j] = '\0';
        }
    }
    else eeprom->serial = NULL;

    // verify checksum
    checksum = 0xAAAA;

    for (i = 0; i < eeprom_size/2-1; i++)
    {
        if ((ftdi->type == TYPE_230X) && (i == 0x12))
        {
            /* FT230X has a user section in the MTP which is not part of the checksum */
            i = 0x40;
        }
        value = buf[i*2];
        value += buf[(i*2)+1] << 8;

        checksum = value^checksum;
        checksum = (checksum << 1) | (checksum >> 15);
    }

    eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);

    if (eeprom_checksum != checksum)
    {
        fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
        ftdi_error_return(-1,"EEPROM checksum error");
    }

    eeprom->channel_a_type   = 0;
    if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM))
    {
        eeprom->chip = -1;
    }
    else if (ftdi->type == TYPE_2232C)
    {
        eeprom->channel_a_type   = bit2type(buf[0x00] & 0x7);
        eeprom->channel_a_driver = !!(buf[0x00] & DRIVER_VCP);
        eeprom->high_current_a   = !!(buf[0x00] & HIGH_CURRENT_DRIVE);
        eeprom->channel_b_type   = buf[0x01] & 0x7;
        eeprom->channel_b_driver = !!(buf[0x01] & DRIVER_VCP);
        eeprom->high_current_b   = !!(buf[0x01] & HIGH_CURRENT_DRIVE);
        eeprom->chip = buf[0x14];
    }
    else if (ftdi->type == TYPE_R)
    {
        /* TYPE_R flags D2XX, not VCP as all others */
        eeprom->channel_a_driver = !(buf[0x00] & DRIVER_VCP);               /* note: inverted flag, use a single NOT */
        eeprom->high_current     = !!(buf[0x00] & HIGH_CURRENT_DRIVE_R);
        eeprom->external_oscillator = !!(buf[0x00] & 0x02);
        if ( (buf[0x01]&0x40) != 0x40)
            fprintf(stderr,
                    "TYPE_R EEPROM byte[0x01] Bit 6 unexpected Endpoint size."
                    " If this happened with the\n"
                    " EEPROM programmed by FTDI tools, please report "
                    "to libftdi@developer.intra2net.com\n");

        eeprom->chip = buf[0x16];
        // Addr 0B: Invert data lines
        // Works only on FT232R, not FT245R, but no way to distinguish
        eeprom->invert = buf[0x0B];                                         /* note: not a bitflag */
        // Addr 14: CBUS function: CBUS0, CBUS1
        // Addr 15: CBUS function: CBUS2, CBUS3
        // Addr 16: CBUS function: CBUS5
        eeprom->cbus_function[0] = buf[0x14] & 0x0f;
        eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
        eeprom->cbus_function[2] = buf[0x15] & 0x0f;
        eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
        eeprom->cbus_function[4] = buf[0x16] & 0x0f;
    }
    else if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H))
    {
        eeprom->channel_a_driver = !!(buf[0x00] & DRIVER_VCP);
        eeprom->channel_b_driver = !!(buf[0x01] & DRIVER_VCP);

        if (ftdi->type == TYPE_2232H)
        {
            eeprom->channel_a_type   = bit2type(buf[0x00] & 0x7);
            eeprom->channel_b_type   = bit2type(buf[0x01] & 0x7);
            eeprom->suspend_dbus7    = !!(buf[0x01] & SUSPEND_DBUS7_BIT);
        }
        else
        {
            eeprom->channel_c_driver = !!((buf[0x00] >> 4) & DRIVER_VCP);
            eeprom->channel_d_driver = !!((buf[0x01] >> 4) & DRIVER_VCP);
            eeprom->channel_a_rs485enable = !!(buf[0x0b] & (CHANNEL_IS_RS485 << 0));
            eeprom->channel_b_rs485enable = !!(buf[0x0b] & (CHANNEL_IS_RS485 << 1));
            eeprom->channel_c_rs485enable = !!(buf[0x0b] & (CHANNEL_IS_RS485 << 2));
            eeprom->channel_d_rs485enable = !!(buf[0x0b] & (CHANNEL_IS_RS485 << 3));
        }

        eeprom->chip = buf[0x18];
        eeprom->group0_drive   = buf[0x0c]       & DRIVE_16MA;              /* not a bitflag */
        eeprom->group0_schmitt = !!(buf[0x0c]       & IS_SCHMITT);
        eeprom->group0_slew    = !!(buf[0x0c]       & SLOW_SLEW);
        eeprom->group1_drive   = (buf[0x0c] >> 4) & DRIVE_16MA;             /* not a bitflag */
        eeprom->group1_schmitt = !!((buf[0x0c] >> 4) & IS_SCHMITT);
        eeprom->group1_slew    = !!((buf[0x0c] >> 4) & SLOW_SLEW);
        eeprom->group2_drive   = buf[0x0d]       & DRIVE_16MA;              /* not a bitflag */
        eeprom->group2_schmitt = !!(buf[0x0d]       & IS_SCHMITT);
        eeprom->group2_slew    = !!(buf[0x0d]       & SLOW_SLEW);
        eeprom->group3_drive   = (buf[0x0d] >> 4) & DRIVE_16MA;             /* not a bitflag */
        eeprom->group3_schmitt = !!((buf[0x0d] >> 4) & IS_SCHMITT);
        eeprom->group3_slew    = !!((buf[0x0d] >> 4) & SLOW_SLEW);
    }
    else if (ftdi->type == TYPE_232H)
    {
        eeprom->channel_a_type   = buf[0x00] & 0xf;
        eeprom->channel_a_driver = !!(buf[0x00] & DRIVER_VCPH);
        eeprom->clock_polarity =  !!(buf[0x01]       & FT1284_CLK_IDLE_STATE);
        eeprom->data_order     =  !!(buf[0x01]       & FT1284_DATA_LSB);
        eeprom->flow_control   =  !!(buf[0x01]       & FT1284_FLOW_CONTROL);
        eeprom->powersave      =  !!(buf[0x01]       & POWER_SAVE_DISABLE_H);
        eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;             /* not a bitflag */
        eeprom->group0_schmitt =  !!(buf[0x0c]       & IS_SCHMITT);
        eeprom->group0_slew    =  !!(buf[0x0c]       & SLOW_SLEW);
        eeprom->group1_drive   =  buf[0x0d]       & DRIVE_16MA;             /* not a bitflag */
        eeprom->group1_schmitt =  !!(buf[0x0d]       & IS_SCHMITT);
        eeprom->group1_slew    =  !!(buf[0x0d]       & SLOW_SLEW);

        for(i=0; i<5; i++)
        {
            eeprom->cbus_function[2*i  ] =  buf[0x18+i] & 0x0f;
            eeprom->cbus_function[2*i+1] = (buf[0x18+i] >> 4) & 0x0f;
        }
        eeprom->chip = buf[0x1e];
        /*FIXME: Decipher more values*/
    }
    else if (ftdi->type == TYPE_230X)
    {
        for(i=0; i<4; i++)
        {
            eeprom->cbus_function[i] =  buf[0x1a + i] & 0xFF;
        }
        eeprom->group0_drive   = buf[0x0c]       & DRIVE_16MA;              /* not a bitflag */
        eeprom->group0_schmitt = !!(buf[0x0c]       & IS_SCHMITT);
        eeprom->group0_slew    = !!(buf[0x0c]       & SLOW_SLEW);
        eeprom->group1_drive   = (buf[0x0c] >> 4) & DRIVE_16MA;             /* not a bitflag */
        eeprom->group1_schmitt = !!((buf[0x0c] >> 4) & IS_SCHMITT);
        eeprom->group1_slew    = !!((buf[0x0c] >> 4) & SLOW_SLEW);

        eeprom->invert = buf[0xb];                                          /* not a bitflag */
    }

    if (verbose)
    {
        const char *channel_mode[] = {"UART", "FIFO", "CPU", "OPTO", "FT1284"};
        fprintf(stdout, "VID:     0x%04x\n",eeprom->vendor_id);
        fprintf(stdout, "PID:     0x%04x\n",eeprom->product_id);
        fprintf(stdout, "Release: 0x%04x\n",eeprom->release_number);

        if (eeprom->self_powered)
            fprintf(stdout, "Self-Powered%s", (eeprom->remote_wakeup)?", USB Remote Wake Up\n":"\n");
        else
            fprintf(stdout, "Bus Powered: %3d mA%s", eeprom->max_power,
                    (eeprom->remote_wakeup)?" USB Remote Wake Up\n":"\n");
        if (eeprom->manufacturer)
            fprintf(stdout, "Manufacturer: %s\n",eeprom->manufacturer);
        if (eeprom->product)
            fprintf(stdout, "Product:      %s\n",eeprom->product);
        if (eeprom->serial)
            fprintf(stdout, "Serial:       %s\n",eeprom->serial);
        fprintf(stdout,     "Checksum      : %04x\n", checksum);
        if (ftdi->type == TYPE_R) {
            fprintf(stdout,     "Internal EEPROM\n");
            fprintf(stdout,"Oscillator: %s\n", eeprom->external_oscillator?"External":"Internal");
        }
        else if (eeprom->chip >= 0x46)
            fprintf(stdout,     "Attached EEPROM: 93x%02x\n", eeprom->chip);
        if (eeprom->suspend_dbus7)
            fprintf(stdout, "Suspend on DBUS7\n");
        if (eeprom->suspend_pull_downs)
            fprintf(stdout, "Pull IO pins low during suspend\n");
        if(eeprom->powersave)
        {
            if(ftdi->type >= TYPE_232H)
                fprintf(stdout,"Enter low power state on ACBUS7\n");
        }
        if (eeprom->remote_wakeup)
            fprintf(stdout, "Enable Remote Wake Up\n");
        fprintf(stdout, "PNP: %d\n",(eeprom->is_not_pnp)?0:1);
        if (ftdi->type >= TYPE_2232C)
            fprintf(stdout,"Channel A has Mode %s%s%s\n",
                    channel_mode[eeprom->channel_a_type],
                    (eeprom->channel_a_driver)?" VCP":"",
                    (eeprom->high_current_a)?" High Current IO":"");
        if (ftdi->type == TYPE_232H)
        {
            fprintf(stdout,"FT1284 Mode Clock is idle %s, %s first, %sFlow Control\n",
                    (eeprom->clock_polarity)?"HIGH":"LOW",
                    (eeprom->data_order)?"LSB":"MSB",
                    (eeprom->flow_control)?"":"No ");
        }
        if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H))
            fprintf(stdout,"Channel B has Mode %s%s%s\n",
                    channel_mode[eeprom->channel_b_type],
                    (eeprom->channel_b_driver)?" VCP":"",
                    (eeprom->high_current_b)?" High Current IO":"");
        if (((ftdi->type == TYPE_BM) || (ftdi->type == TYPE_2232C)) &&
                eeprom->use_usb_version)
            fprintf(stdout,"Use explicit USB Version %04x\n",eeprom->usb_version);

        if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H))
        {
            fprintf(stdout,"%s has %d mA drive%s%s\n",
                    (ftdi->type == TYPE_2232H)?"AL":"A",
                    (eeprom->group0_drive+1) *4,
                    (eeprom->group0_schmitt)?" Schmitt Input":"",
                    (eeprom->group0_slew)?" Slow Slew":"");
            fprintf(stdout,"%s has %d mA drive%s%s\n",
                    (ftdi->type == TYPE_2232H)?"AH":"B",
                    (eeprom->group1_drive+1) *4,
                    (eeprom->group1_schmitt)?" Schmitt Input":"",
                    (eeprom->group1_slew)?" Slow Slew":"");
            fprintf(stdout,"%s has %d mA drive%s%s\n",
                    (ftdi->type == TYPE_2232H)?"BL":"C",
                    (eeprom->group2_drive+1) *4,
                    (eeprom->group2_schmitt)?" Schmitt Input":"",
                    (eeprom->group2_slew)?" Slow Slew":"");
            fprintf(stdout,"%s has %d mA drive%s%s\n",
                    (ftdi->type == TYPE_2232H)?"BH":"D",
                    (eeprom->group3_drive+1) *4,
                    (eeprom->group3_schmitt)?" Schmitt Input":"",
                    (eeprom->group3_slew)?" Slow Slew":"");
        }
        else if (ftdi->type == TYPE_232H)
        {
            const char *cbush_mux[] = {"TRISTATE","TXLED","RXLED", "TXRXLED","PWREN",
                                 "SLEEP","DRIVE_0","DRIVE_1","IOMODE","TXDEN",
                                 "CLK30","CLK15","CLK7_5"
                                };
            fprintf(stdout,"ACBUS has %d mA drive%s%s\n",
                    (eeprom->group0_drive+1) *4,
                    (eeprom->group0_schmitt)?" Schmitt Input":"",
                    (eeprom->group0_slew)?" Slow Slew":"");
            fprintf(stdout,"ADBUS has %d mA drive%s%s\n",
                    (eeprom->group1_drive+1) *4,
                    (eeprom->group1_schmitt)?" Schmitt Input":"",
                    (eeprom->group1_slew)?" Slow Slew":"");
            for (i=0; i<10; i++)
            {
                if (eeprom->cbus_function[i]<= CBUSH_CLK7_5 )
                    fprintf(stdout,"C%d Function: %s\n", i,
                            cbush_mux[eeprom->cbus_function[i]]);
            }
        }
        else if (ftdi->type == TYPE_230X)
        {
            const char *cbusx_mux[] = {"TRISTATE","TXLED","RXLED", "TXRXLED","PWREN",
                                 "SLEEP","DRIVE_0","DRIVE_1","IOMODE","TXDEN",
                                 "CLK24","CLK12","CLK6","BAT_DETECT","BAT_DETECT#",
                                 "I2C_TXE#", "I2C_RXF#", "VBUS_SENSE", "BB_WR#",
                                 "BBRD#", "TIME_STAMP", "AWAKE#",
                                };
            fprintf(stdout,"DBUS has %d mA drive%s%s\n",
                    (eeprom->group0_drive+1) *4,
                    (eeprom->group0_schmitt)?" Schmitt Input":"",
                    (eeprom->group0_slew)?" Slow Slew":"");
            fprintf(stdout,"CBUS has %d mA drive%s%s\n",
                    (eeprom->group1_drive+1) *4,
                    (eeprom->group1_schmitt)?" Schmitt Input":"",
                    (eeprom->group1_slew)?" Slow Slew":"");
            for (i=0; i<4; i++)
            {
                if (eeprom->cbus_function[i]<= CBUSX_AWAKE)
                    fprintf(stdout,"CBUS%d Function: %s\n", i, cbusx_mux[eeprom->cbus_function[i]]);
            }

            if (eeprom->invert)
                print_inverted_bits(eeprom->invert);
        }

        if (ftdi->type == TYPE_R)
        {
            const char *cbus_mux[] = {"TXDEN","PWREN","RXLED", "TXLED","TX+RXLED",
                                "SLEEP","CLK48","CLK24","CLK12","CLK6",
                                "IOMODE","BB_WR","BB_RD"
                               };
            const char *cbus_BB[] = {"RXF","TXE","RD", "WR"};

            if (eeprom->invert)
                print_inverted_bits(eeprom->invert);

            for (i=0; i<5; i++)
            {
                if (eeprom->cbus_function[i]<=CBUS_BB_RD)
                    fprintf(stdout,"C%d Function: %s\n", i,
                            cbus_mux[eeprom->cbus_function[i]]);
                else
                {
                    if (i < 4)
                        /* Running MPROG show that C0..3 have fixed function Synchronous
                           Bit Bang mode */
                        fprintf(stdout,"C%d BB Function: %s\n", i,
                                cbus_BB[i]);
                    else
                        fprintf(stdout, "Unknown CBUS mode. Might be special mode?\n");
                }
            }
        }
    }
    return 0;
}

/**
   Get a value from the decoded EEPROM structure

   \param ftdi pointer to ftdi_context
   \param value_name Enum of the value to query
   \param value Pointer to store read value

   \retval 0: all fine
   \retval -1: Value doesn't exist
*/
int ftdi_get_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int* value)
{
    switch (value_name)
    {
        case VENDOR_ID:
            *value = ftdi->eeprom->vendor_id;
            break;
        case PRODUCT_ID:
            *value = ftdi->eeprom->product_id;
            break;
        case RELEASE_NUMBER:
            *value = ftdi->eeprom->release_number;
            break;
        case SELF_POWERED:
            *value = ftdi->eeprom->self_powered;
            break;
        case REMOTE_WAKEUP:
            *value = ftdi->eeprom->remote_wakeup;
            break;
        case IS_NOT_PNP:
            *value = ftdi->eeprom->is_not_pnp;
            break;
        case SUSPEND_DBUS7:
            *value = ftdi->eeprom->suspend_dbus7;
            break;
        case IN_IS_ISOCHRONOUS:
            *value = ftdi->eeprom->in_is_isochronous;
            break;
        case OUT_IS_ISOCHRONOUS:
            *value = ftdi->eeprom->out_is_isochronous;
            break;
        case SUSPEND_PULL_DOWNS:
            *value = ftdi->eeprom->suspend_pull_downs;
            break;
        case USE_SERIAL:
            *value = ftdi->eeprom->use_serial;
            break;
        case USB_VERSION:
            *value = ftdi->eeprom->usb_version;
            break;
        case USE_USB_VERSION:
            *value = ftdi->eeprom->use_usb_version;
            break;
        case MAX_POWER:
            *value = ftdi->eeprom->max_power;
            break;
        case CHANNEL_A_TYPE:
            *value = ftdi->eeprom->channel_a_type;
            break;
        case CHANNEL_B_TYPE:
            *value = ftdi->eeprom->channel_b_type;
            break;
        case CHANNEL_A_DRIVER:
            *value = ftdi->eeprom->channel_a_driver;
            break;
        case CHANNEL_B_DRIVER:
            *value = ftdi->eeprom->channel_b_driver;
            break;
        case CHANNEL_C_DRIVER:
            *value = ftdi->eeprom->channel_c_driver;
            break;
        case CHANNEL_D_DRIVER:
            *value = ftdi->eeprom->channel_d_driver;
            break;
        case CHANNEL_A_RS485:
            *value = ftdi->eeprom->channel_a_rs485enable;
            break;
        case CHANNEL_B_RS485:
            *value = ftdi->eeprom->channel_b_rs485enable;
            break;
        case CHANNEL_C_RS485:
            *value = ftdi->eeprom->channel_c_rs485enable;
            break;
        case CHANNEL_D_RS485:
            *value = ftdi->eeprom->channel_d_rs485enable;
            break;
        case CBUS_FUNCTION_0:
            *value = ftdi->eeprom->cbus_function[0];
            break;
        case CBUS_FUNCTION_1:
            *value = ftdi->eeprom->cbus_function[1];
            break;
        case CBUS_FUNCTION_2:
            *value = ftdi->eeprom->cbus_function[2];
            break;
        case CBUS_FUNCTION_3:
            *value = ftdi->eeprom->cbus_function[3];
            break;
        case CBUS_FUNCTION_4:
            *value = ftdi->eeprom->cbus_function[4];
            break;
        case CBUS_FUNCTION_5:
            *value = ftdi->eeprom->cbus_function[5];
            break;
        case CBUS_FUNCTION_6:
            *value = ftdi->eeprom->cbus_function[6];
            break;
        case CBUS_FUNCTION_7:
            *value = ftdi->eeprom->cbus_function[7];
            break;
        case CBUS_FUNCTION_8:
            *value = ftdi->eeprom->cbus_function[8];
            break;
        case CBUS_FUNCTION_9:
            *value = ftdi->eeprom->cbus_function[9];
            break;
        case HIGH_CURRENT:
            *value = ftdi->eeprom->high_current;
            break;
        case HIGH_CURRENT_A:
            *value = ftdi->eeprom->high_current_a;
            break;
        case HIGH_CURRENT_B:
            *value = ftdi->eeprom->high_current_b;
            break;
        case INVERT:
            *value = ftdi->eeprom->invert;
            break;
        case GROUP0_DRIVE:
            *value = ftdi->eeprom->group0_drive;
            break;
        case GROUP0_SCHMITT:
            *value = ftdi->eeprom->group0_schmitt;
            break;
        case GROUP0_SLEW:
            *value = ftdi->eeprom->group0_slew;
            break;
        case GROUP1_DRIVE:
            *value = ftdi->eeprom->group1_drive;
            break;
        case GROUP1_SCHMITT:
            *value = ftdi->eeprom->group1_schmitt;
            break;
        case GROUP1_SLEW:
            *value = ftdi->eeprom->group1_slew;
            break;
        case GROUP2_DRIVE:
            *value = ftdi->eeprom->group2_drive;
            break;
        case GROUP2_SCHMITT:
            *value = ftdi->eeprom->group2_schmitt;
            break;
        case GROUP2_SLEW:
            *value = ftdi->eeprom->group2_slew;
            break;
        case GROUP3_DRIVE:
            *value = ftdi->eeprom->group3_drive;
            break;
        case GROUP3_SCHMITT:
            *value = ftdi->eeprom->group3_schmitt;
            break;
        case GROUP3_SLEW:
            *value = ftdi->eeprom->group3_slew;
            break;
        case POWER_SAVE:
            *value = ftdi->eeprom->powersave;
            break;
        case CLOCK_POLARITY:
            *value = ftdi->eeprom->clock_polarity;
            break;
        case DATA_ORDER:
            *value = ftdi->eeprom->data_order;
            break;
        case FLOW_CONTROL:
            *value = ftdi->eeprom->flow_control;
            break;
        case CHIP_TYPE:
            *value = ftdi->eeprom->chip;
            break;
        case CHIP_SIZE:
            *value = ftdi->eeprom->size;
            break;
        case EXTERNAL_OSCILLATOR:
            *value = ftdi->eeprom->external_oscillator;
            break;
        default:
            ftdi_error_return(-1, "Request for unknown EEPROM value");
    }
    return 0;
}

/**
   Set a value in the decoded EEPROM Structure
   No parameter checking is performed

   \param ftdi pointer to ftdi_context
   \param value_name Enum of the value to set
   \param value to set

   \retval 0: all fine
   \retval -1: Value doesn't exist
   \retval -2: Value not user settable
*/
int ftdi_set_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int value)
{
    switch (value_name)
    {
        case VENDOR_ID:
            ftdi->eeprom->vendor_id = value;
            break;
        case PRODUCT_ID:
            ftdi->eeprom->product_id = value;
            break;
        case RELEASE_NUMBER:
            ftdi->eeprom->release_number = value;
            break;
        case SELF_POWERED:
            ftdi->eeprom->self_powered = value;
            break;
        case REMOTE_WAKEUP:
            ftdi->eeprom->remote_wakeup = value;
            break;
        case IS_NOT_PNP:
            ftdi->eeprom->is_not_pnp = value;
            break;
        case SUSPEND_DBUS7:
            ftdi->eeprom->suspend_dbus7 = value;
            break;
        case IN_IS_ISOCHRONOUS:
            ftdi->eeprom->in_is_isochronous = value;
            break;
        case OUT_IS_ISOCHRONOUS:
            ftdi->eeprom->out_is_isochronous = value;
            break;
        case SUSPEND_PULL_DOWNS:
            ftdi->eeprom->suspend_pull_downs = value;
            break;
        case USE_SERIAL:
            ftdi->eeprom->use_serial = value;
            break;
        case USB_VERSION:
            ftdi->eeprom->usb_version = value;
            break;
        case USE_USB_VERSION:
            ftdi->eeprom->use_usb_version = value;
            break;
        case MAX_POWER:
            ftdi->eeprom->max_power = value;
            break;
        case CHANNEL_A_TYPE:
            ftdi->eeprom->channel_a_type = value;
            break;
        case CHANNEL_B_TYPE:
            ftdi->eeprom->channel_b_type = value;
            break;
        case CHANNEL_A_DRIVER:
            ftdi->eeprom->channel_a_driver = value;
            break;
        case CHANNEL_B_DRIVER:
            ftdi->eeprom->channel_b_driver = value;
            break;
        case CHANNEL_C_DRIVER:
            ftdi->eeprom->channel_c_driver = value;
            break;
        case CHANNEL_D_DRIVER:
            ftdi->eeprom->channel_d_driver = value;
            break;
        case CHANNEL_A_RS485:
            ftdi->eeprom->channel_a_rs485enable = value;
            break;
        case CHANNEL_B_RS485:
            ftdi->eeprom->channel_b_rs485enable = value;
            break;
        case CHANNEL_C_RS485:
            ftdi->eeprom->channel_c_rs485enable = value;
            break;
        case CHANNEL_D_RS485:
            ftdi->eeprom->channel_d_rs485enable = value;
            break;
        case CBUS_FUNCTION_0:
            ftdi->eeprom->cbus_function[0] = value;
            break;
        case CBUS_FUNCTION_1:
            ftdi->eeprom->cbus_function[1] = value;
            break;
        case CBUS_FUNCTION_2:
            ftdi->eeprom->cbus_function[2] = value;
            break;
        case CBUS_FUNCTION_3:
            ftdi->eeprom->cbus_function[3] = value;
            break;
        case CBUS_FUNCTION_4:
            ftdi->eeprom->cbus_function[4] = value;
            break;
        case CBUS_FUNCTION_5:
            ftdi->eeprom->cbus_function[5] = value;
            break;
        case CBUS_FUNCTION_6:
            ftdi->eeprom->cbus_function[6] = value;
            break;
        case CBUS_FUNCTION_7:
            ftdi->eeprom->cbus_function[7] = value;
            break;
        case CBUS_FUNCTION_8:
            ftdi->eeprom->cbus_function[8] = value;
            break;
        case CBUS_FUNCTION_9:
            ftdi->eeprom->cbus_function[9] = value;
            break;
        case HIGH_CURRENT:
            ftdi->eeprom->high_current = value;
            break;
        case HIGH_CURRENT_A:
            ftdi->eeprom->high_current_a = value;
            break;
        case HIGH_CURRENT_B:
            ftdi->eeprom->high_current_b = value;
            break;
        case INVERT:
            ftdi->eeprom->invert = value;
            break;
        case GROUP0_DRIVE:
            ftdi->eeprom->group0_drive = value;
            break;
        case GROUP0_SCHMITT:
            ftdi->eeprom->group0_schmitt = value;
            break;
        case GROUP0_SLEW:
            ftdi->eeprom->group0_slew = value;
            break;
        case GROUP1_DRIVE:
            ftdi->eeprom->group1_drive = value;
            break;
        case GROUP1_SCHMITT:
            ftdi->eeprom->group1_schmitt = value;
            break;
        case GROUP1_SLEW:
            ftdi->eeprom->group1_slew = value;
            break;
        case GROUP2_DRIVE:
            ftdi->eeprom->group2_drive = value;
            break;
        case GROUP2_SCHMITT:
            ftdi->eeprom->group2_schmitt = value;
            break;
        case GROUP2_SLEW:
            ftdi->eeprom->group2_slew = value;
            break;
        case GROUP3_DRIVE:
            ftdi->eeprom->group3_drive = value;
            break;
        case GROUP3_SCHMITT:
            ftdi->eeprom->group3_schmitt = value;
            break;
        case GROUP3_SLEW:
            ftdi->eeprom->group3_slew = value;
            break;
        case CHIP_TYPE:
            ftdi->eeprom->chip = value;
            break;
        case POWER_SAVE:
            ftdi->eeprom->powersave = value;
            break;
        case CLOCK_POLARITY:
            ftdi->eeprom->clock_polarity = value;
            break;
        case DATA_ORDER:
            ftdi->eeprom->data_order = value;
            break;
        case FLOW_CONTROL:
            ftdi->eeprom->flow_control = value;
            break;
        case CHIP_SIZE:
            ftdi_error_return(-2, "EEPROM Value can't be changed");
            break;
        case EXTERNAL_OSCILLATOR:
            ftdi->eeprom->external_oscillator = value;
            break;
        case USER_DATA_ADDR:
            ftdi->eeprom->user_data_addr = value;
            break;

        default :
            ftdi_error_return(-1, "Request to unknown EEPROM value");
    }
    ftdi->eeprom->initialized_for_connected_device = 0;
    return 0;
}

/** Get the read-only buffer to the binary EEPROM content

    \param ftdi pointer to ftdi_context
    \param buf buffer to receive EEPROM content
    \param size Size of receiving buffer

    \retval 0: All fine
    \retval -1: struct ftdi_contxt or ftdi_eeprom missing
    \retval -2: Not enough room to store eeprom
*/
int ftdi_get_eeprom_buf(struct ftdi_context *ftdi, unsigned char * buf, int size)
{
    if (!ftdi || !(ftdi->eeprom))
        ftdi_error_return(-1, "No appropriate structure");

    if (!buf || size < ftdi->eeprom->size)
        ftdi_error_return(-1, "Not enough room to store eeprom");

    // Only copy up to FTDI_MAX_EEPROM_SIZE bytes
    if (size > FTDI_MAX_EEPROM_SIZE)
        size = FTDI_MAX_EEPROM_SIZE;

    memcpy(buf, ftdi->eeprom->buf, size);

    return 0;
}

/** Set the EEPROM content from the user-supplied prefilled buffer

    \param ftdi pointer to ftdi_context
    \param buf buffer to read EEPROM content
    \param size Size of buffer

    \retval 0: All fine
    \retval -1: struct ftdi_context or ftdi_eeprom or buf missing
*/
int ftdi_set_eeprom_buf(struct ftdi_context *ftdi, const unsigned char * buf, int size)
{
    if (!ftdi || !(ftdi->eeprom) || !buf)
        ftdi_error_return(-1, "No appropriate structure");

    // Only copy up to FTDI_MAX_EEPROM_SIZE bytes
    if (size > FTDI_MAX_EEPROM_SIZE)
        size = FTDI_MAX_EEPROM_SIZE;

    memcpy(ftdi->eeprom->buf, buf, size);

    return 0;
}

/** Set the EEPROM user data content from the user-supplied prefilled buffer

    \param ftdi pointer to ftdi_context
    \param buf buffer to read EEPROM user data content
    \param size Size of buffer

    \retval 0: All fine
    \retval -1: struct ftdi_context or ftdi_eeprom or buf missing
*/
int ftdi_set_eeprom_user_data(struct ftdi_context *ftdi, const char * buf, int size)
{
    if (!ftdi || !(ftdi->eeprom) || !buf)
        ftdi_error_return(-1, "No appropriate structure");

    ftdi->eeprom->user_data_size = size;
    ftdi->eeprom->user_data = buf;
    return 0;
}

/**
    Read eeprom location

    \param ftdi pointer to ftdi_context
    \param eeprom_addr Address of eeprom location to be read
    \param eeprom_val Pointer to store read eeprom location

    \retval  0: all fine
    \retval -1: read failed
    \retval -2: USB device unavailable
*/
int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
{
    unsigned char buf[2];

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, eeprom_addr, buf, 2, ftdi->usb_read_timeout) != 2)
        ftdi_error_return(-1, "reading eeprom failed");

    *eeprom_val = (0xff & buf[0]) | (buf[1] << 8);

    return 0;
}

/**
    Read eeprom

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: read failed
    \retval -2: USB device unavailable
*/
int ftdi_read_eeprom(struct ftdi_context *ftdi)
{
    int i;
    unsigned char *buf;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");
    buf = ftdi->eeprom->buf;

    for (i = 0; i < FTDI_MAX_EEPROM_SIZE/2; i++)
    {
        if (libusb_control_transfer(
                    ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,SIO_READ_EEPROM_REQUEST, 0, i,
                    buf+(i*2), 2, ftdi->usb_read_timeout) != 2)
            ftdi_error_return(-1, "reading eeprom failed");
    }

    if (ftdi->type == TYPE_R)
        ftdi->eeprom->size = 0x80;
    /*    Guesses size of eeprom by comparing halves
          - will not work with blank eeprom */
    else if (strrchr((const char *)buf, 0xff) == ((const char *)buf +FTDI_MAX_EEPROM_SIZE -1))
        ftdi->eeprom->size = -1;
    else if (memcmp(buf,&buf[0x80],0x80) == 0)
        ftdi->eeprom->size = 0x80;
    else if (memcmp(buf,&buf[0x40],0x40) == 0)
        ftdi->eeprom->size = 0x40;
    else
        ftdi->eeprom->size = 0x100;
    return 0;
}

/*
    ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
    Function is only used internally
    \internal
*/
static unsigned char ftdi_read_chipid_shift(unsigned char value)
{
    return ((value & 1) << 1) |
           ((value & 2) << 5) |
           ((value & 4) >> 2) |
           ((value & 8) << 4) |
           ((value & 16) >> 1) |
           ((value & 32) >> 1) |
           ((value & 64) >> 4) |
           ((value & 128) >> 2);
}

/**
    Read the FTDIChip-ID from R-type devices

    \param ftdi pointer to ftdi_context
    \param chipid Pointer to store FTDIChip-ID

    \retval  0: all fine
    \retval -1: read failed
    \retval -2: USB device unavailable
*/
int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
{
    unsigned int a = 0, b = 0;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x43, (unsigned char *)&a, 2, ftdi->usb_read_timeout) == 2)
    {
        a = a << 8 | a >> 8;
        if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x44, (unsigned char *)&b, 2, ftdi->usb_read_timeout) == 2)
        {
            b = b << 8 | b >> 8;
            a = (a << 16) | (b & 0xFFFF);
            a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
                | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
            *chipid = a ^ 0xa5f0f7d1;
            return 0;
        }
    }

    ftdi_error_return(-1, "read of FTDIChip-ID failed");
}

/**
    Write eeprom location

    \param ftdi pointer to ftdi_context
    \param eeprom_addr Address of eeprom location to be written
    \param eeprom_val Value to be written

    \retval  0: all fine
    \retval -1: write failed
    \retval -2: USB device unavailable
    \retval -3: Invalid access to checksum protected area below 0x80
    \retval -4: Device can't access unprotected area
    \retval -5: Reading chip type failed
*/
int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr,
                               unsigned short eeprom_val)
{
    int chip_type_location;
    unsigned short chip_type;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if (eeprom_addr <0x80)
        ftdi_error_return(-2, "Invalid access to checksum protected area  below 0x80");


    switch (ftdi->type)
    {
        case TYPE_BM:
        case  TYPE_2232C:
            chip_type_location = 0x14;
            break;
        case TYPE_2232H:
        case TYPE_4232H:
            chip_type_location = 0x18;
            break;
        case TYPE_232H:
            chip_type_location = 0x1e;
            break;
        default:
            ftdi_error_return(-4, "Device can't access unprotected area");
    }

    if (ftdi_read_eeprom_location( ftdi, chip_type_location>>1, &chip_type))
        ftdi_error_return(-5, "Reading failed");
    fprintf(stderr," loc 0x%04x val 0x%04x\n", chip_type_location,chip_type);
    if ((chip_type & 0xff) != 0x66)
    {
        ftdi_error_return(-6, "EEPROM is not of 93x66");
    }

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
                                NULL, 0, ftdi->usb_write_timeout) != 0)
        ftdi_error_return(-1, "unable to write eeprom");

    return 0;
}

/**
    Write eeprom

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: read failed
    \retval -2: USB device unavailable
    \retval -3: EEPROM not initialized for the connected device;
*/
int ftdi_write_eeprom(struct ftdi_context *ftdi)
{
    unsigned short usb_val, status;
    int i, ret;
    unsigned char *eeprom;

    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if(ftdi->eeprom->initialized_for_connected_device == 0)
        ftdi_error_return(-3, "EEPROM not initialized for the connected device");

    eeprom = ftdi->eeprom->buf;

    /* These commands were traced while running MProg */
    if ((ret = ftdi_usb_reset(ftdi)) != 0)
        return ret;
    if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
        return ret;
    if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
        return ret;

    for (i = 0; i < ftdi->eeprom->size/2; i++)
    {
        /* Do not try to write to reserved area */
        if ((ftdi->type == TYPE_230X) && (i == 0x40))
        {
            i = 0x50;
        }
        usb_val = eeprom[i*2];
        usb_val += eeprom[(i*2)+1] << 8;
        if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                    SIO_WRITE_EEPROM_REQUEST, usb_val, i,
                                    NULL, 0, ftdi->usb_write_timeout) < 0)
            ftdi_error_return(-1, "unable to write eeprom");
    }

    return 0;
}

/**
    Erase eeprom

    This is not supported on FT232R/FT245R according to the MProg manual from FTDI.

    \param ftdi pointer to ftdi_context

    \retval  0: all fine
    \retval -1: erase failed
    \retval -2: USB device unavailable
    \retval -3: Writing magic failed
    \retval -4: Read EEPROM failed
    \retval -5: Unexpected EEPROM value
*/
#define MAGIC 0x55aa
int ftdi_erase_eeprom(struct ftdi_context *ftdi)
{
    unsigned short eeprom_value;
    if (ftdi == NULL || ftdi->usb_dev == NULL)
        ftdi_error_return(-2, "USB device unavailable");

    if ((ftdi->type == TYPE_R) || (ftdi->type == TYPE_230X))
    {
        ftdi->eeprom->chip = 0;
        return 0;
    }

    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
                                0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "unable to erase eeprom");


    /* detect chip type by writing 0x55AA as magic at word position 0xc0
       Chip is 93x46 if magic is read at word position 0x00, as wraparound happens around 0x40
       Chip is 93x56 if magic is read at word position 0x40, as wraparound happens around 0x80
       Chip is 93x66 if magic is only read at word position 0xc0*/
    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
                                SIO_WRITE_EEPROM_REQUEST, MAGIC, 0xc0,
                                NULL, 0, ftdi->usb_write_timeout) != 0)
        ftdi_error_return(-3, "Writing magic failed");
    if (ftdi_read_eeprom_location( ftdi, 0x00, &eeprom_value))
        ftdi_error_return(-4, "Reading failed");
    if (eeprom_value == MAGIC)
    {
        ftdi->eeprom->chip = 0x46;
    }
    else
    {
        if (ftdi_read_eeprom_location( ftdi, 0x40, &eeprom_value))
            ftdi_error_return(-4, "Reading failed");
        if (eeprom_value == MAGIC)
            ftdi->eeprom->chip = 0x56;
        else
        {
            if (ftdi_read_eeprom_location( ftdi, 0xc0, &eeprom_value))
                ftdi_error_return(-4, "Reading failed");
            if (eeprom_value == MAGIC)
                ftdi->eeprom->chip = 0x66;
            else
            {
                ftdi->eeprom->chip = -1;
            }
        }
    }
    if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
                                0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
        ftdi_error_return(-1, "unable to erase eeprom");
    return 0;
}

/**
    Get string representation for last error code

    \param ftdi pointer to ftdi_context

    \retval Pointer to error string
*/
const char *ftdi_get_error_string (struct ftdi_context *ftdi)
{
    if (ftdi == NULL)
        return "";

    return ftdi->error_str;
}

/* @} end of doxygen libftdi group */
0707010000004E000081A400000000000000000000000160917B8300005C4D000000000000000000000000000000000000002700000000libftdi1-1.5.12+git.0684c1b/src/ftdi.h/***************************************************************************
                          ftdi.h  -  description
                             -------------------
    begin                : Fri Apr 4 2003
    copyright            : (C) 2003-2020 by Intra2net AG and the libftdi developers
    email                : opensource@intra2net.com
    SPDX-License-Identifier: LGPL-2.1-only
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License           *
 *   version 2.1 as published by the Free Software Foundation;             *
 *                                                                         *
 ***************************************************************************/

#ifndef __libftdi_h__
#define __libftdi_h__

#include <stdint.h>
#ifndef _WIN32
#include <sys/time.h>
#endif

/* Define _FTDI_DISABLE_DEPRECATED to disable deprecated messages. */
#ifdef _FTDI_DISABLE_DEPRECATED
#define _Ftdi_Pragma(_msg)
#else
#define _Ftdi_Pragma(_msg) _Pragma(_msg)
#endif

/* 'interface' might be defined as a macro on Windows, so we need to
 * undefine it so as not to break the current libftdi API, because
 * struct ftdi_context has an 'interface' member
 * As this can be problematic if you include windows.h after ftdi.h
 * in your sources, we force windows.h to be included first. */
#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
#include <windows.h>
#if defined(interface)
#undef interface
#endif
#endif

/** FTDI chip type */
enum ftdi_chip_type
{
    TYPE_AM=0,
    TYPE_BM=1,
    TYPE_2232C=2,
    TYPE_R=3,
    TYPE_2232H=4,
    TYPE_4232H=5,
    TYPE_232H=6,
    TYPE_230X=7,
};
/** Parity mode for ftdi_set_line_property() */
enum ftdi_parity_type { NONE=0, ODD=1, EVEN=2, MARK=3, SPACE=4 };
/** Number of stop bits for ftdi_set_line_property() */
enum ftdi_stopbits_type { STOP_BIT_1=0, STOP_BIT_15=1, STOP_BIT_2=2 };
/** Number of bits for ftdi_set_line_property() */
enum ftdi_bits_type { BITS_7=7, BITS_8=8 };
/** Break type for ftdi_set_line_property2() */
enum ftdi_break_type { BREAK_OFF=0, BREAK_ON=1 };

/** MPSSE bitbang modes */
enum ftdi_mpsse_mode
{
    BITMODE_RESET  = 0x00,    /**< switch off bitbang mode, back to regular serial/FIFO */
    BITMODE_BITBANG= 0x01,    /**< classical asynchronous bitbang mode, introduced with B-type chips */
    BITMODE_MPSSE  = 0x02,    /**< MPSSE mode, available on 2232x chips */
    BITMODE_SYNCBB = 0x04,    /**< synchronous bitbang mode, available on 2232x and R-type chips  */
    BITMODE_MCU    = 0x08,    /**< MCU Host Bus Emulation mode, available on 2232x chips */
    /* CPU-style fifo mode gets set via EEPROM */
    BITMODE_OPTO   = 0x10,    /**< Fast Opto-Isolated Serial Interface Mode, available on 2232x chips  */
    BITMODE_CBUS   = 0x20,    /**< Bitbang on CBUS pins of R-type chips, configure in EEPROM before */
    BITMODE_SYNCFF = 0x40,    /**< Single Channel Synchronous FIFO mode, available on 2232H chips */
    BITMODE_FT1284 = 0x80,    /**< FT1284 mode, available on 232H chips */
};

/** Port interface for chips with multiple interfaces */
enum ftdi_interface
{
    INTERFACE_ANY = 0,
    INTERFACE_A   = 1,
    INTERFACE_B   = 2,
    INTERFACE_C   = 3,
    INTERFACE_D   = 4
};

/** Automatic loading / unloading of kernel modules */
enum ftdi_module_detach_mode
{
    AUTO_DETACH_SIO_MODULE = 0,
    DONT_DETACH_SIO_MODULE = 1,
    AUTO_DETACH_REATACH_SIO_MODULE = 2
};

/* Shifting commands IN MPSSE Mode*/
#define MPSSE_WRITE_NEG 0x01   /* Write TDI/DO on negative TCK/SK edge*/
#define MPSSE_BITMODE   0x02   /* Write bits, not bytes */
#define MPSSE_READ_NEG  0x04   /* Sample TDO/DI on negative TCK/SK edge */
#define MPSSE_LSB       0x08   /* LSB first */
#define MPSSE_DO_WRITE  0x10   /* Write TDI/DO */
#define MPSSE_DO_READ   0x20   /* Read TDO/DI */
#define MPSSE_WRITE_TMS 0x40   /* Write TMS/CS */

/* FTDI MPSSE commands */
#define SET_BITS_LOW   0x80
/*BYTE DATA*/
/*BYTE Direction*/
#define SET_BITS_HIGH  0x82
/*BYTE DATA*/
/*BYTE Direction*/
#define GET_BITS_LOW   0x81
#define GET_BITS_HIGH  0x83
#define LOOPBACK_START 0x84
#define LOOPBACK_END   0x85
#define TCK_DIVISOR    0x86
/* H Type specific commands */
#define DIS_DIV_5       0x8a
#define EN_DIV_5        0x8b
#define EN_3_PHASE      0x8c
#define DIS_3_PHASE     0x8d
#define CLK_BITS        0x8e
#define CLK_BYTES       0x8f
#define CLK_WAIT_HIGH   0x94
#define CLK_WAIT_LOW    0x95
#define EN_ADAPTIVE     0x96
#define DIS_ADAPTIVE    0x97
#define CLK_BYTES_OR_HIGH 0x9c
#define CLK_BYTES_OR_LOW  0x9d
/*FT232H specific commands */
#define DRIVE_OPEN_COLLECTOR 0x9e
/* Value Low */
/* Value HIGH */ /*rate is 12000000/((1+value)*2) */
#define DIV_VALUE(rate) (rate > 6000000)?0:((6000000/rate -1) > 0xffff)? 0xffff: (6000000/rate -1)

/* Commands in MPSSE and Host Emulation Mode */
#define SEND_IMMEDIATE 0x87
#define WAIT_ON_HIGH   0x88
#define WAIT_ON_LOW    0x89

/* Commands in Host Emulation Mode */
#define READ_SHORT     0x90
/* Address_Low */
#define READ_EXTENDED  0x91
/* Address High */
/* Address Low  */
#define WRITE_SHORT    0x92
/* Address_Low */
#define WRITE_EXTENDED 0x93
/* Address High */
/* Address Low  */

/* Definitions for flow control */
#define SIO_RESET          0 /* Reset the port */
#define SIO_MODEM_CTRL     1 /* Set the modem control register */
#define SIO_SET_FLOW_CTRL  2 /* Set flow control register */
#define SIO_SET_BAUD_RATE  3 /* Set baud rate */
#define SIO_SET_DATA       4 /* Set the data characteristics of the port */

#define FTDI_DEVICE_OUT_REQTYPE (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_OUT)
#define FTDI_DEVICE_IN_REQTYPE (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN)

/* Requests */
#define SIO_RESET_REQUEST             SIO_RESET
#define SIO_SET_BAUDRATE_REQUEST      SIO_SET_BAUD_RATE
#define SIO_SET_DATA_REQUEST          SIO_SET_DATA
#define SIO_SET_FLOW_CTRL_REQUEST     SIO_SET_FLOW_CTRL
#define SIO_SET_MODEM_CTRL_REQUEST    SIO_MODEM_CTRL
#define SIO_POLL_MODEM_STATUS_REQUEST 0x05
#define SIO_SET_EVENT_CHAR_REQUEST    0x06
#define SIO_SET_ERROR_CHAR_REQUEST    0x07
#define SIO_SET_LATENCY_TIMER_REQUEST 0x09
#define SIO_GET_LATENCY_TIMER_REQUEST 0x0A
#define SIO_SET_BITMODE_REQUEST       0x0B
#define SIO_READ_PINS_REQUEST         0x0C
#define SIO_READ_EEPROM_REQUEST       0x90
#define SIO_WRITE_EEPROM_REQUEST      0x91
#define SIO_ERASE_EEPROM_REQUEST      0x92


#define SIO_RESET_SIO 0

/* ** WARNING ** SIO_RESET_PURGE_RX or SIO_RESET_PURGE_TX are values used
 * internally by libftdi to purge the RX and/or TX FIFOs (buffers).
 * APPLICATION PROGRAMS SHOULD NOT BE USING THESE VALUES. Application
 * programs should use one of the ftdi_tciflush, ftdi_tcoflush, or
 * ftdi_tcioflush functions which emulate the Linux serial port tcflush(3)
 * function.
 *
 * History:
 *
 * The definitions for these values are with respect to the FTDI chip, not the
 * CPU. That is, when the FTDI chip receives a USB control transfer request
 * with the command SIO_RESET_PURGE_RX, the FTDI chip empties the FIFO
 * containing data received from the CPU awaiting transfer out the serial
 * port to the connected serial device (e.g., a modem). Likewise, upon
 * reception of the SIO_RESET_PURGE_TX command, the FTDI chip empties the
 * FIFO of data received from the attached serial device destined to be
 * transmitted to the CPU.
 *
 * Unfortunately the coding of the previous releases of libfti assumed these
 * commands had the opposite effect. This resulted in the function
 * ftdi_usb_purge_tx_buffer clearing data received from the attached serial
 * device.  Similarly, the function ftdi_usb_purge_rx_buffer cleared the
 * FTDI FIFO containing data to be transmitted to the attached serial
 * device.  More seriously, this latter function clear the libftid's
 * internal buffer of data received from the serial device, destined
 * to the application program.
 */
#ifdef __GNUC__
#define SIO_RESET_PURGE_RX _Ftdi_Pragma("GCC warning \"SIO_RESET_PURGE_RX\" deprecated: - use tciflush() method") 1
#define SIO_RESET_PURGE_TX _Ftdi_Pragma("GCC warning \"SIO_RESET_PURGE_RX\" deprecated: - use tcoflush() method") 2
#else
#pragma message("WARNING: You need to implement deprecated #define for this compiler")
#define SIO_RESET_PURGE_RX 1
#define SIO_RESET_PURGE_TX 2
#endif
/* New names for the values used internally to flush (purge). */
#define SIO_TCIFLUSH 2
#define SIO_TCOFLUSH 1

#define SIO_DISABLE_FLOW_CTRL 0x0
#define SIO_RTS_CTS_HS (0x1 << 8)
#define SIO_DTR_DSR_HS (0x2 << 8)
#define SIO_XON_XOFF_HS (0x4 << 8)

#define SIO_SET_DTR_MASK 0x1
#define SIO_SET_DTR_HIGH ( 1 | ( SIO_SET_DTR_MASK  << 8))
#define SIO_SET_DTR_LOW  ( 0 | ( SIO_SET_DTR_MASK  << 8))
#define SIO_SET_RTS_MASK 0x2
#define SIO_SET_RTS_HIGH ( 2 | ( SIO_SET_RTS_MASK << 8 ))
#define SIO_SET_RTS_LOW ( 0 | ( SIO_SET_RTS_MASK << 8 ))

#define SIO_RTS_CTS_HS (0x1 << 8)

/* marker for unused usb urb structures
   (taken from libusb) */
#define FTDI_URB_USERCONTEXT_COOKIE ((void *)0x1)

#ifdef _FTDI_DISABLE_DEPRECATED
#define DEPRECATED(func) func
#else
#ifdef __GNUC__
#define DEPRECATED(func) __attribute__ ((deprecated)) func
#elif defined(_MSC_VER)
#define DEPRECATED(func) __declspec(deprecated) func
#else
#pragma message("WARNING: You need to implement DEPRECATED for this compiler")
#define DEPRECATED(func) func
#endif
#endif

struct ftdi_transfer_control
{
    int completed;
    unsigned char *buf;
    int size;
    int offset;
    struct ftdi_context *ftdi;
    struct libusb_transfer *transfer;
};

/**
    \brief Main context structure for all libftdi functions.

    Do not access directly if possible.
*/
struct ftdi_context
{
    /* USB specific */
    /** libusb's context */
    struct libusb_context *usb_ctx;
    /** libusb's usb_dev_handle */
    struct libusb_device_handle *usb_dev;
    /** usb read timeout */
    int usb_read_timeout;
    /** usb write timeout */
    int usb_write_timeout;

    /* FTDI specific */
    /** FTDI chip type */
    enum ftdi_chip_type type;
    /** baudrate */
    int baudrate;
    /** bitbang mode state */
    unsigned char bitbang_enabled;
    /** pointer to read buffer for ftdi_read_data */
    unsigned char *readbuffer;
    /** read buffer offset */
    unsigned int readbuffer_offset;
    /** number of remaining data in internal read buffer */
    unsigned int readbuffer_remaining;
    /** read buffer chunk size */
    unsigned int readbuffer_chunksize;
    /** write buffer chunk size */
    unsigned int writebuffer_chunksize;
    /** maximum packet size. Needed for filtering modem status bytes every n packets. */
    unsigned int max_packet_size;

    /* FTDI FT2232C requirecments */
    /** FT2232C interface number: 0 or 1 */
    int interface;   /* 0 or 1 */
    /** FT2232C index number: 1 or 2 */
    int index;       /* 1 or 2 */
    /* Endpoints */
    /** FT2232C end points: 1 or 2 */
    int in_ep;
    int out_ep;      /* 1 or 2 */

    /** Bitbang mode. 1: (default) Normal bitbang mode, 2: FT2232C SPI bitbang mode */
    unsigned char bitbang_mode;

    /** Decoded eeprom structure */
    struct ftdi_eeprom *eeprom;

    /** String representation of last error */
    const char *error_str;

    /** Defines behavior in case a kernel module is already attached to the device */
    enum ftdi_module_detach_mode module_detach_mode;
};

/**
 List all handled EEPROM values.
   Append future new values only at the end to provide API/ABI stability*/
enum ftdi_eeprom_value
{
    VENDOR_ID          = 0,
    PRODUCT_ID         = 1,
    SELF_POWERED       = 2,
    REMOTE_WAKEUP      = 3,
    IS_NOT_PNP         = 4,
    SUSPEND_DBUS7      = 5,
    IN_IS_ISOCHRONOUS  = 6,
    OUT_IS_ISOCHRONOUS = 7,
    SUSPEND_PULL_DOWNS = 8,
    USE_SERIAL         = 9,
    USB_VERSION        = 10,
    USE_USB_VERSION    = 11,
    MAX_POWER          = 12,
    CHANNEL_A_TYPE     = 13,
    CHANNEL_B_TYPE     = 14,
    CHANNEL_A_DRIVER   = 15,
    CHANNEL_B_DRIVER   = 16,
    CBUS_FUNCTION_0    = 17,
    CBUS_FUNCTION_1    = 18,
    CBUS_FUNCTION_2    = 19,
    CBUS_FUNCTION_3    = 20,
    CBUS_FUNCTION_4    = 21,
    CBUS_FUNCTION_5    = 22,
    CBUS_FUNCTION_6    = 23,
    CBUS_FUNCTION_7    = 24,
    CBUS_FUNCTION_8    = 25,
    CBUS_FUNCTION_9    = 26,
    HIGH_CURRENT       = 27,
    HIGH_CURRENT_A     = 28,
    HIGH_CURRENT_B     = 29,
    INVERT             = 30,
    GROUP0_DRIVE       = 31,
    GROUP0_SCHMITT     = 32,
    GROUP0_SLEW        = 33,
    GROUP1_DRIVE       = 34,
    GROUP1_SCHMITT     = 35,
    GROUP1_SLEW        = 36,
    GROUP2_DRIVE       = 37,
    GROUP2_SCHMITT     = 38,
    GROUP2_SLEW        = 39,
    GROUP3_DRIVE       = 40,
    GROUP3_SCHMITT     = 41,
    GROUP3_SLEW        = 42,
    CHIP_SIZE          = 43,
    CHIP_TYPE          = 44,
    POWER_SAVE         = 45,
    CLOCK_POLARITY     = 46,
    DATA_ORDER         = 47,
    FLOW_CONTROL       = 48,
    CHANNEL_C_DRIVER   = 49,
    CHANNEL_D_DRIVER   = 50,
    CHANNEL_A_RS485    = 51,
    CHANNEL_B_RS485    = 52,
    CHANNEL_C_RS485    = 53,
    CHANNEL_D_RS485    = 54,
    RELEASE_NUMBER     = 55,
    EXTERNAL_OSCILLATOR= 56,
    USER_DATA_ADDR     = 57,
};

/**
    \brief list of usb devices created by ftdi_usb_find_all()
*/
struct ftdi_device_list
{
    /** pointer to next entry */
    struct ftdi_device_list *next;
    /** pointer to libusb's usb_device */
    struct libusb_device *dev;
};
#define FT1284_CLK_IDLE_STATE 0x01
#define FT1284_DATA_LSB       0x02 /* DS_FT232H 1.3 amd ftd2xx.h 1.0.4 disagree here*/
#define FT1284_FLOW_CONTROL   0x04
#define POWER_SAVE_DISABLE_H 0x80

#define USE_SERIAL_NUM 0x08
enum ftdi_cbus_func
{
    CBUS_TXDEN = 0, CBUS_PWREN = 1, CBUS_RXLED = 2, CBUS_TXLED = 3, CBUS_TXRXLED = 4,
    CBUS_SLEEP = 5, CBUS_CLK48 = 6, CBUS_CLK24 = 7, CBUS_CLK12 = 8, CBUS_CLK6 =  9,
    CBUS_IOMODE = 0xa, CBUS_BB_WR = 0xb, CBUS_BB_RD = 0xc
};

enum ftdi_cbush_func
{
    CBUSH_TRISTATE = 0, CBUSH_TXLED = 1, CBUSH_RXLED = 2, CBUSH_TXRXLED = 3, CBUSH_PWREN = 4,
    CBUSH_SLEEP = 5, CBUSH_DRIVE_0 = 6, CBUSH_DRIVE1 = 7, CBUSH_IOMODE = 8, CBUSH_TXDEN =  9,
    CBUSH_CLK30 = 10, CBUSH_CLK15 = 11, CBUSH_CLK7_5 = 12
};

enum ftdi_cbusx_func
{
    CBUSX_TRISTATE = 0, CBUSX_TXLED = 1, CBUSX_RXLED = 2, CBUSX_TXRXLED = 3, CBUSX_PWREN = 4,
    CBUSX_SLEEP = 5, CBUSX_DRIVE_0 = 6, CBUSX_DRIVE1 = 7, CBUSX_IOMODE = 8, CBUSX_TXDEN =  9,
    CBUSX_CLK24 = 10, CBUSX_CLK12 = 11, CBUSX_CLK6 = 12, CBUSX_BAT_DETECT = 13,
    CBUSX_BAT_DETECT_NEG = 14, CBUSX_I2C_TXE = 15, CBUSX_I2C_RXF = 16, CBUSX_VBUS_SENSE = 17,
    CBUSX_BB_WR = 18, CBUSX_BB_RD = 19, CBUSX_TIME_STAMP = 20, CBUSX_AWAKE = 21
};

/** Invert TXD# */
#define INVERT_TXD 0x01
/** Invert RXD# */
#define INVERT_RXD 0x02
/** Invert RTS# */
#define INVERT_RTS 0x04
/** Invert CTS# */
#define INVERT_CTS 0x08
/** Invert DTR# */
#define INVERT_DTR 0x10
/** Invert DSR# */
#define INVERT_DSR 0x20
/** Invert DCD# */
#define INVERT_DCD 0x40
/** Invert RI# */
#define INVERT_RI  0x80

/** Interface Mode. */
#define CHANNEL_IS_UART 0x0
#define CHANNEL_IS_FIFO 0x1
#define CHANNEL_IS_OPTO 0x2
#define CHANNEL_IS_CPU  0x4
#define CHANNEL_IS_FT1284 0x8

#define CHANNEL_IS_RS485 0x10

#define DRIVE_4MA  0
#define DRIVE_8MA  1
#define DRIVE_12MA 2
#define DRIVE_16MA 3
#define SLOW_SLEW  4
#define IS_SCHMITT 8

/** Driver Type. */
#define DRIVER_VCP 0x08
#define DRIVER_VCPH 0x10 /* FT232H has moved the VCP bit */

#define USE_USB_VERSION_BIT 0x10

#define SUSPEND_DBUS7_BIT 0x80

/** High current drive. */
#define HIGH_CURRENT_DRIVE   0x10
#define HIGH_CURRENT_DRIVE_R 0x04

/**
    \brief Progress Info for streaming read
*/
struct size_and_time
{
    uint64_t totalBytes;
    struct timeval time;
};

typedef struct
{
    struct size_and_time first;
    struct size_and_time prev;
    struct size_and_time current;
    double totalTime;
    double totalRate;
    double currentRate;
} FTDIProgressInfo;

typedef int (FTDIStreamCallback)(uint8_t *buffer, int length,
                                 FTDIProgressInfo *progress, void *userdata);

/**
 * Provide libftdi version information
 * major: Library major version
 * minor: Library minor version
 * micro: Currently unused, ight get used for hotfixes.
 * version_str: Version as (static) string
 * snapshot_str: Git snapshot version if known. Otherwise "unknown" or empty string.
*/
struct ftdi_version_info
{
    int major;
    int minor;
    int micro;
    const char *version_str;
    const char *snapshot_str;
};


#ifdef __cplusplus
extern "C"
{
#endif

    int ftdi_init(struct ftdi_context *ftdi);
    struct ftdi_context *ftdi_new(void);
    int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface);

    void ftdi_deinit(struct ftdi_context *ftdi);
    void ftdi_free(struct ftdi_context *ftdi);
    void ftdi_set_usbdev (struct ftdi_context *ftdi, struct libusb_device_handle *usbdev);

    struct ftdi_version_info ftdi_get_library_version(void);

    int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist,
                          int vendor, int product);
    void ftdi_list_free(struct ftdi_device_list **devlist);
    void ftdi_list_free2(struct ftdi_device_list *devlist);
    int ftdi_usb_get_strings(struct ftdi_context *ftdi, struct libusb_device *dev,
                             char *manufacturer, int mnf_len,
                             char *description, int desc_len,
                             char *serial, int serial_len);
    int ftdi_usb_get_strings2(struct ftdi_context *ftdi, struct libusb_device *dev,
                              char *manufacturer, int mnf_len,
                              char *description, int desc_len,
                              char *serial, int serial_len);

    int ftdi_eeprom_get_strings(struct ftdi_context *ftdi,
                                char *manufacturer, int mnf_len,
                                char *product, int prod_len,
                                char *serial, int serial_len);
    int ftdi_eeprom_set_strings(struct ftdi_context *ftdi, const char * manufacturer,
                                const char * product, const char * serial);

    int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product);
    int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
                           const char* description, const char* serial);
    int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
                                 const char* description, const char* serial, unsigned int index);
    int ftdi_usb_open_bus_addr(struct ftdi_context *ftdi, uint8_t bus, uint8_t addr);
    int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct libusb_device *dev);
    int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description);

    int ftdi_usb_close(struct ftdi_context *ftdi);
    int ftdi_usb_reset(struct ftdi_context *ftdi);
    int ftdi_tciflush(struct ftdi_context *ftdi);
    int ftdi_tcoflush(struct ftdi_context *ftdi);
    int ftdi_tcioflush(struct ftdi_context *ftdi);
    int DEPRECATED(ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi));
    int DEPRECATED(ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi));
    int DEPRECATED(ftdi_usb_purge_buffers(struct ftdi_context *ftdi));

    int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate);
    int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
                               enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity);
    int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
                                enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
                                enum ftdi_break_type break_type);

    int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size);
    int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize);
    int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize);

    int ftdi_write_data(struct ftdi_context *ftdi, const unsigned char *buf, int size);
    int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize);
    int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize);

    int ftdi_readstream(struct ftdi_context *ftdi, FTDIStreamCallback *callback,
                        void *userdata, int packetsPerTransfer, int numTransfers);
    struct ftdi_transfer_control *ftdi_write_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size);

    struct ftdi_transfer_control *ftdi_read_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size);
    int ftdi_transfer_data_done(struct ftdi_transfer_control *tc);
    void ftdi_transfer_data_cancel(struct ftdi_transfer_control *tc, struct timeval * to);

    int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode);
    int ftdi_disable_bitbang(struct ftdi_context *ftdi);
    int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins);

    int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency);
    int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency);

    int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status);

    /* flow control */
    int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl);
    int ftdi_setflowctrl_xonxoff(struct ftdi_context *ftdi, unsigned char xon, unsigned char xoff);
    int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts);
    int ftdi_setdtr(struct ftdi_context *ftdi, int state);
    int ftdi_setrts(struct ftdi_context *ftdi, int state);

    int ftdi_set_event_char(struct ftdi_context *ftdi, unsigned char eventch, unsigned char enable);
    int ftdi_set_error_char(struct ftdi_context *ftdi, unsigned char errorch, unsigned char enable);

    /* init eeprom for the given FTDI type */
    int ftdi_eeprom_initdefaults(struct ftdi_context *ftdi,
                                 const char * manufacturer, const char *product,
                                 const char * serial);
    int ftdi_eeprom_build(struct ftdi_context *ftdi);
    int ftdi_eeprom_decode(struct ftdi_context *ftdi, int verbose);

    int ftdi_get_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int* value);
    int ftdi_set_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int  value);

    int ftdi_get_eeprom_buf(struct ftdi_context *ftdi, unsigned char * buf, int size);
    int ftdi_set_eeprom_buf(struct ftdi_context *ftdi, const unsigned char * buf, int size);

    int ftdi_set_eeprom_user_data(struct ftdi_context *ftdi, const char * buf, int size);

    int ftdi_read_eeprom(struct ftdi_context *ftdi);
    int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid);
    int ftdi_write_eeprom(struct ftdi_context *ftdi);
    int ftdi_erase_eeprom(struct ftdi_context *ftdi);

    int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val);
    int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val);

    const char *ftdi_get_error_string(struct ftdi_context *ftdi);

#ifdef __cplusplus
}
#endif

#endif /* __libftdi_h__ */
0707010000004F000081A400000000000000000000000160917B830000107A000000000000000000000000000000000000002900000000libftdi1-1.5.12+git.0684c1b/src/ftdi_i.h/***************************************************************************
                          ftdi_i.h  -  description
                             -------------------
    begin                : Don Sep 9 2011
    copyright            : (C) 2003-2020 by Intra2net AG and the libftdi developers
    email                : opensource@intra2net.com
    SPDX-License-Identifier: LGPL-2.1-only
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License           *
 *   version 2.1 as published by the Free Software Foundation;             *
 *                                                                         *
 ***************************************************************************

 Non public definitions here

*/

/* Even on 93xx66 at max 256 bytes are used (AN_121)*/
#define FTDI_MAX_EEPROM_SIZE 256

/** Max Power adjustment factor. */
#define MAX_POWER_MILLIAMP_PER_UNIT 2

/**
    \brief FTDI eeprom structure
*/
struct ftdi_eeprom
{
    /** vendor id */
    int vendor_id;
    /** product id */
    int product_id;

    /** Was the eeprom structure initialized for the actual
        connected device? **/
    int initialized_for_connected_device;

    /** self powered */
    int self_powered;
    /** remote wakeup */
    int remote_wakeup;

    int is_not_pnp;

    /* Suspend on DBUS7 Low */
    int suspend_dbus7;

    /** input in isochronous transfer mode */
    int in_is_isochronous;
    /** output in isochronous transfer mode */
    int out_is_isochronous;
    /** suspend pull downs */
    int suspend_pull_downs;

    /** use serial */
    int use_serial;
    /** usb version */
    int usb_version;
    /** Use usb version on FT2232 devices*/
    int use_usb_version;
    /** maximum power */
    int max_power;

    /** manufacturer name */
    char *manufacturer;
    /** product name */
    char *product;
    /** serial number */
    char *serial;

    /* 2232D/H specific */
    /* Hardware type, 0 = RS232 Uart, 1 = 245 FIFO, 2 = CPU FIFO,
       4 = OPTO Isolate */
    int channel_a_type;
    int channel_b_type;
    /*  Driver Type, 1 = VCP */
    int channel_a_driver;
    int channel_b_driver;
    int channel_c_driver;
    int channel_d_driver;
    /* 4232H specific */
    int channel_a_rs485enable;
    int channel_b_rs485enable;
    int channel_c_rs485enable;
    int channel_d_rs485enable;

    /* Special function of FT232R/FT232H devices (and possibly others as well) */
    /** CBUS pin function. See CBUS_xxx defines. */
    int cbus_function[10];
    /** Select high current drive on R devices. */
    int high_current;
    /** Select high current drive on A channel (2232C). */
    int high_current_a;
    /** Select high current drive on B channel (2232C). */
    int high_current_b;
    /** Select inversion of data lines (bitmask). */
    int invert;
    /** Enable external oscillator. */
    int external_oscillator;

    /*2232H/4432H Group specific values */
    /* Group0 is AL on 2322H and A on 4232H
       Group1 is AH on 2232H and B on 4232H
       Group2 is BL on 2322H and C on 4232H
       Group3 is BH on 2232H and C on 4232H*/
    int group0_drive;
    int group0_schmitt;
    int group0_slew;
    int group1_drive;
    int group1_schmitt;
    int group1_slew;
    int group2_drive;
    int group2_schmitt;
    int group2_slew;
    int group3_drive;
    int group3_schmitt;
    int group3_slew;

    int powersave;

    int clock_polarity;
    int data_order;
    int flow_control;

    /** user data **/
    int user_data_addr;
    int user_data_size;
    const char *user_data;

    /** eeprom size in bytes. This doesn't get stored in the eeprom
        but is the only way to pass it to ftdi_eeprom_build. */
    int size;
    /* EEPROM Type 0x46 for 93xx46, 0x56 for 93xx56 and 0x66 for 93xx66*/
    int chip;
    unsigned char buf[FTDI_MAX_EEPROM_SIZE];

    /** device release number */
    int release_number;
};

07070100000050000081A400000000000000000000000160917B8300002542000000000000000000000000000000000000002E00000000libftdi1-1.5.12+git.0684c1b/src/ftdi_stream.c/***************************************************************************
                          ftdi_stream.c  -  description
                             -------------------
    copyright            : (C) 2009 Micah Dowty 2010 Uwe Bonnes
    email                : opensource@intra2net.com
    SPDX-License-Identifier: (LGPL-2.1-only AND MIT)
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License           *
 *   version 2.1 as published by the Free Software Foundation;             *
 *                                                                         *
 ***************************************************************************/

/* Adapted from
 * fastftdi.c - A minimal FTDI FT232H interface for which supports bit-bang
 *              mode, but focuses on very high-performance support for
 *              synchronous FIFO mode. Requires libusb-1.0
 *
 * Copyright (C) 2009 Micah Dowty
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <stdlib.h>
#include <stdio.h>
#ifndef _WIN32
#include <sys/time.h>
#endif
#include <libusb.h>

#include "ftdi.h"

typedef struct
{
    FTDIStreamCallback *callback;
    void *userdata;
    int packetsize;
    int activity;
    int result;
    FTDIProgressInfo progress;
} FTDIStreamState;

/* Handle callbacks
 *
 * With Exit request, free memory and release the transfer
 *
 * state->result is only set when some error happens
 */
static void LIBUSB_CALL
ftdi_readstream_cb(struct libusb_transfer *transfer)
{
    FTDIStreamState *state = transfer->user_data;
    int packet_size = state->packetsize;

    state->activity++;
    if (transfer->status == LIBUSB_TRANSFER_COMPLETED)
    {
        int i;
        uint8_t *ptr = transfer->buffer;
        int length = transfer->actual_length;
        int numPackets = (length + packet_size - 1) / packet_size;
        int res = 0;

        for (i = 0; i < numPackets; i++)
        {
            int payloadLen;
            int packetLen = length;

            if (packetLen > packet_size)
                packetLen = packet_size;

            payloadLen = packetLen - 2;
            state->progress.current.totalBytes += payloadLen;

            res = state->callback(ptr + 2, payloadLen,
                                  NULL, state->userdata);

            ptr += packetLen;
            length -= packetLen;
        }
        if (res)
        {
            free(transfer->buffer);
            libusb_free_transfer(transfer);
        }
        else
        {
            transfer->status = -1;
            state->result = libusb_submit_transfer(transfer);
        }
    }
    else
    {
        fprintf(stderr, "unknown status %d\n",transfer->status);
        state->result = LIBUSB_ERROR_IO;
    }
}

/**
   Helper function to calculate (unix) time differences

   \param a timeval
   \param b timeval
*/
static double
TimevalDiff(const struct timeval *a, const struct timeval *b)
{
    return (a->tv_sec - b->tv_sec) + 1e-6 * (a->tv_usec - b->tv_usec);
}

/**
    Streaming reading of data from the device

    Use asynchronous transfers in libusb-1.0 for high-performance
    streaming of data from a device interface back to the PC. This
    function continuously transfers data until either an error occurs
    or the callback returns a nonzero value. This function returns
    a libusb error code or the callback's return value.

    For every contiguous block of received data, the callback will
    be invoked.

    \param  ftdi pointer to ftdi_context
    \param  callback to user supplied function for one block of data
    \param  userdata
    \param  packetsPerTransfer number of packets per transfer
    \param  numTransfers Number of transfers per callback

*/

int
ftdi_readstream(struct ftdi_context *ftdi,
                FTDIStreamCallback *callback, void *userdata,
                int packetsPerTransfer, int numTransfers)
{
    struct libusb_transfer **transfers;
    FTDIStreamState state = { callback, userdata, ftdi->max_packet_size, 1 };
    int bufferSize = packetsPerTransfer * ftdi->max_packet_size;
    int xferIndex;
    int err = 0;

    /* Only FT2232H and FT232H know about the synchronous FIFO Mode*/
    if ((ftdi->type != TYPE_2232H) && (ftdi->type != TYPE_232H))
    {
        fprintf(stderr,"Device doesn't support synchronous FIFO mode\n");
        return 1;
    }

    /* We don't know in what state we are, switch to reset*/
    if (ftdi_set_bitmode(ftdi,  0xff, BITMODE_RESET) < 0)
    {
        fprintf(stderr,"Can't reset mode\n");
        return 1;
    }

    /* Purge anything remaining in the buffers*/
    if (ftdi_tcioflush(ftdi) < 0)
    {
        fprintf(stderr,"Can't flush FIFOs & buffers\n");
        return 1;
    }

    /*
     * Set up all transfers
     */

    transfers = calloc(numTransfers, sizeof *transfers);
    if (!transfers)
    {
        err = LIBUSB_ERROR_NO_MEM;
        goto cleanup;
    }

    for (xferIndex = 0; xferIndex < numTransfers; xferIndex++)
    {
        struct libusb_transfer *transfer;

        transfer = libusb_alloc_transfer(0);
        transfers[xferIndex] = transfer;
        if (!transfer)
        {
            err = LIBUSB_ERROR_NO_MEM;
            goto cleanup;
        }

        libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->out_ep,
                                  malloc(bufferSize), bufferSize,
                                  ftdi_readstream_cb,
                                  &state, 0);

        if (!transfer->buffer)
        {
            err = LIBUSB_ERROR_NO_MEM;
            goto cleanup;
        }

        transfer->status = -1;
        err = libusb_submit_transfer(transfer);
        if (err)
            goto cleanup;
    }

    /* Start the transfers only when everything has been set up.
     * Otherwise the transfers start stuttering and the PC not
     * fetching data for several to several ten milliseconds
     * and we skip blocks
     */
    if (ftdi_set_bitmode(ftdi,  0xff, BITMODE_SYNCFF) < 0)
    {
        fprintf(stderr,"Can't set synchronous fifo mode: %s\n",
                ftdi_get_error_string(ftdi));
        goto cleanup;
    }

    /*
     * Run the transfers, and periodically assess progress.
     */

    gettimeofday(&state.progress.first.time, NULL);

    do
    {
        FTDIProgressInfo  *progress = &state.progress;
        const double progressInterval = 1.0;
        struct timeval timeout = { 0, ftdi->usb_read_timeout * 1000};
        struct timeval now;

        int err = libusb_handle_events_timeout(ftdi->usb_ctx, &timeout);
        if (err ==  LIBUSB_ERROR_INTERRUPTED)
            /* restart interrupted events */
            err = libusb_handle_events_timeout(ftdi->usb_ctx, &timeout);
        if (!state.result)
        {
            state.result = err;
        }
        if (state.activity == 0)
            state.result = 1;
        else
            state.activity = 0;

        // If enough time has elapsed, update the progress
        gettimeofday(&now, NULL);
        if (TimevalDiff(&now, &progress->current.time) >= progressInterval)
        {
            progress->current.time = now;
            progress->totalTime = TimevalDiff(&progress->current.time,
                                              &progress->first.time);

            if (progress->prev.totalBytes)
            {
                // We have enough information to calculate rates

                double currentTime;

                currentTime = TimevalDiff(&progress->current.time,
                                          &progress->prev.time);

                progress->totalRate =
                    progress->current.totalBytes /progress->totalTime;
                progress->currentRate =
                    (progress->current.totalBytes -
                     progress->prev.totalBytes) / currentTime;
            }

            state.callback(NULL, 0, progress, state.userdata);
            progress->prev = progress->current;

        }
    } while (!state.result);

    /*
     * Cancel any outstanding transfers, and free memory.
     */

cleanup:
    fprintf(stderr, "cleanup\n");
    if (transfers)
        free(transfers);
    if (err)
        return err;
    else
        return state.result;
}

07070100000051000081A400000000000000000000000160917B830000012F000000000000000000000000000000000000003400000000libftdi1-1.5.12+git.0684c1b/src/ftdi_version_i.h.in#ifndef FTDI_VERSION_INTERNAL_H
#define FTDI_VERSION_INTERNAL_H

#define FTDI_MAJOR_VERSION @MAJOR_VERSION@
#define FTDI_MINOR_VERSION @MINOR_VERSION@
#define FTDI_MICRO_VERSION 0

const char FTDI_VERSION_STRING[] = "@VERSION_STRING@";
const char FTDI_SNAPSHOT_VERSION[] = "@SNAPSHOT_VERSION@";

#endif
07070100000052000041ED00000000000000000000000260917B8300000000000000000000000000000000000000000000002100000000libftdi1-1.5.12+git.0684c1b/test07070100000053000081A400000000000000000000000160917B83000001EA000000000000000000000000000000000000003000000000libftdi1-1.5.12+git.0684c1b/test/CMakeLists.txtfind_package(Boost COMPONENTS unit_test_framework REQUIRED)

enable_testing()

INCLUDE_DIRECTORIES(BEFORE ${CMAKE_SOURCE_DIR}/src ${Boost_INCLUDE_DIRS})

set(cpp_tests basic.cpp baudrate.cpp)

add_executable(test_libftdi1 ${cpp_tests})
target_link_libraries(test_libftdi1 ftdi1 ${Boost_UNIT_TEST_FRAMEWORK_LIBRARIES})

add_test(test_libftdi1 test_libftdi1)

# Add custom target so we run easily run "make check"
add_custom_target(check COMMAND ${CMAKE_CTEST_COMMAND} DEPENDS test_libftdi1)
07070100000054000081A400000000000000000000000160917B83000003AF000000000000000000000000000000000000002B00000000libftdi1-1.5.12+git.0684c1b/test/basic.cpp/**@file
@brief Test basic FTDI functionality

@author Thomas Jarosch
*/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License           *
 *   version 2.1 as published by the Free Software Foundation;             *
 *                                                                         *
 ***************************************************************************/

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

#include <ftdi.h>

BOOST_AUTO_TEST_SUITE(Basic)

BOOST_AUTO_TEST_CASE(SimpleInit)
{
    ftdi_context ftdi;

    int rtn_init = ftdi_init(&ftdi);
    BOOST_REQUIRE_EQUAL(0, rtn_init);

    ftdi_deinit(&ftdi);
}

BOOST_AUTO_TEST_SUITE_END()
07070100000055000081A400000000000000000000000160917B8300002CBF000000000000000000000000000000000000002E00000000libftdi1-1.5.12+git.0684c1b/test/baudrate.cpp/**@file
@brief Test baudrate calculator code

@author Thomas Jarosch and Uwe Bonnes
*/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License           *
 *   version 2.1 as published by the Free Software Foundation;             *
 *                                                                         *
 ***************************************************************************/

#include <ftdi.h>

#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include <vector>
#include <map>
#include <math.h>

using namespace std;

extern "C" int convert_baudrate_UT_export(int baudrate, struct ftdi_context *ftdi,
                                 unsigned short *value, unsigned short *index);

/// Basic initialization of libftdi for every test
class BaseFTDIFixture
{
protected:
    ftdi_context *ftdi;

public:
    BaseFTDIFixture()
        : ftdi(NULL)
    {
        ftdi = ftdi_new();
    }

    virtual ~BaseFTDIFixture()
    {
        delete ftdi;
        ftdi = NULL;
    }
};

BOOST_FIXTURE_TEST_SUITE(Baudrate, BaseFTDIFixture)

/// Helper class to store the convert_baudrate_UT_export result
struct calc_result
{
    int actual_baudrate;
    unsigned short divisor;
    unsigned short fractional_bits;
    unsigned short clock;

    calc_result(int actual, unsigned short my_divisor, unsigned short my_fractional_bits, unsigned short my_clock)
        : actual_baudrate(actual)
        , divisor(my_divisor)
        , fractional_bits(my_fractional_bits)
        , clock(my_clock)
    {
    }

    calc_result()
        : actual_baudrate(0)
        , divisor(0)
        , fractional_bits(0)
        , clock(0)
    {
    }
};

/**
 * @brief Test convert_baudrate code against a list of baud rates
 *
 * @param baudrates Baudrates to check
 **/
static void test_baudrates(ftdi_context *ftdi, const map<int, calc_result> &baudrates)
{
    typedef std::pair<int, calc_result> baudrate_type;
    BOOST_FOREACH(const baudrate_type &baudrate, baudrates)
    {
        unsigned short calc_value = 0, calc_index = 0;
        int calc_baudrate = convert_baudrate_UT_export(baudrate.first, ftdi, &calc_value, &calc_index);

        const calc_result *res = &baudrate.second;

        unsigned short divisor = calc_value & 0x3fff;
        unsigned short fractional_bits = (calc_value >> 14);
        unsigned short clock = (calc_index & 0x200) ? 120 : 48;

        switch (ftdi->type)
        {
        case TYPE_232H:
        case TYPE_2232H:
        case TYPE_4232H:
            fractional_bits |= (calc_index & 0x100) ? 4 : 0;
            break;
        case TYPE_R:
        case TYPE_2232C:
        case TYPE_BM:
        case TYPE_230X:
            fractional_bits |= (calc_index & 0x001) ? 4 : 0;
            break;
        default:;
        }

        // Aid debugging since this test is a generic function
        BOOST_CHECK_MESSAGE(res->actual_baudrate == calc_baudrate && res->divisor == divisor && res->fractional_bits == fractional_bits
                            && res->clock == clock,
                            "\n\nERROR: baudrate calculation failed for --" << baudrate.first << " baud--. Details below: ");

        BOOST_CHECK_EQUAL(res->actual_baudrate, calc_baudrate);
        BOOST_CHECK_EQUAL(res->divisor, divisor);
        BOOST_CHECK_EQUAL(res->fractional_bits, fractional_bits);
        BOOST_CHECK_EQUAL(res->clock, clock);
    }
}

BOOST_AUTO_TEST_CASE(TypeAMFixedBaudrates)
{
    ftdi->type = TYPE_AM;

    map<int, calc_result> baudrates;
    baudrates[183] = calc_result(183, 16383, 0, 48);
    baudrates[300] = calc_result(300, 10000, 0, 48);
    baudrates[600] = calc_result(600,  5000, 0, 48);
    baudrates[1200] = calc_result(1200, 2500, 0, 48);
    baudrates[2400] = calc_result(2400, 1250, 0, 48);
    baudrates[4800] = calc_result(4800, 625, 0, 48);
    baudrates[9600] = calc_result(9600, 312, 1, 48);
    baudrates[19200] = calc_result(19200, 156, 2, 48);
    baudrates[38400] = calc_result(38400, 78, 3, 48);
    baudrates[57600] = calc_result(57554, 52, 3, 48);
    baudrates[115200] = calc_result(115385, 26, 0, 48);
    baudrates[230400] = calc_result(230769, 13, 0, 48);
    baudrates[460800] = calc_result(461538,  6, 1, 48);
    baudrates[921600] = calc_result(923077,  3, 2, 48);
    baudrates[1000000] = calc_result(1000000, 3, 0, 48);
    baudrates[1090512] = calc_result(1000000, 3, 0, 48);
    baudrates[1090909] = calc_result(1000000, 3, 0, 48);
    baudrates[1090910] = calc_result(1000000, 3, 0, 48);
    baudrates[1200000] = calc_result(1200000, 2, 1, 48);
    baudrates[1333333] = calc_result(1333333, 2, 2, 48);
    baudrates[1411764] = calc_result(1411765, 2, 3, 48);
    baudrates[1500000] = calc_result(1500000, 2, 0, 48);
    baudrates[2000000] = calc_result(1500000, 2, 0, 48);
    baudrates[3000000] = calc_result(3000000, 0, 0, 48);

    test_baudrates(ftdi, baudrates);
}

BOOST_AUTO_TEST_CASE(TypeBMFixedBaudrates)
{
    // Unify testing of chips behaving the same
    std::vector<enum ftdi_chip_type> test_types;
    test_types.push_back(TYPE_BM);
    test_types.push_back(TYPE_2232C);
    test_types.push_back(TYPE_R);
    test_types.push_back(TYPE_230X);

    map<int, calc_result> baudrates;
    baudrates[183] = calc_result(183, 16383, 7, 48);
    baudrates[184] = calc_result(184, 16304, 4, 48);
    baudrates[300] = calc_result(300, 10000, 0, 48);
    baudrates[600] = calc_result(600,  5000, 0, 48);
    baudrates[1200] = calc_result(1200, 2500, 0, 48);
    baudrates[2400] = calc_result(2400, 1250, 0, 48);
    baudrates[4800] = calc_result(4800, 625, 0, 48);
    baudrates[9600] = calc_result(9600, 312, 1, 48);
    baudrates[19200] = calc_result(19200, 156, 2, 48);
    baudrates[38400] = calc_result(38400, 78, 3, 48);
    baudrates[57600] = calc_result(57554, 52, 3, 48);
    baudrates[115200] = calc_result(115385, 26, 0, 48);
    baudrates[230400] = calc_result(230769, 13, 0, 48);
    baudrates[460800] = calc_result(461538,  6, 1, 48);
    baudrates[921600] = calc_result(923077,  3, 2, 48);
    baudrates[1000000] = calc_result(1000000, 3, 0, 48);
    baudrates[1050000] = calc_result(1043478, 2, 7, 48);
    baudrates[1400000] = calc_result(1411765, 2, 3, 48);
    baudrates[1500000] = calc_result(1500000, 2, 0, 48);
    baudrates[2000000] = calc_result(2000000, 1, 0, 48);
    baudrates[3000000] = calc_result(3000000, 0, 0, 48);

    baudrates[(3000000*16/(2*16+15))-1] = calc_result(round(3000000/3.000), 3, 0, 48);
    baudrates[ 3000000*16/(2*16+15)   ] = calc_result(round(3000000/3.000), 3, 0, 48);
    baudrates[(3000000*16/(2*16+15))+1] = calc_result(round(3000000/2.875), 2, 7, 48);
    baudrates[ 3000000*16/(2*16+13)   ] = calc_result(round(3000000/2.875), 2, 7, 48);
    baudrates[(3000000*16/(2*16+13))+1] = calc_result(round(3000000/2.750), 2, 6, 48);
    baudrates[ 3000000*16/(2*16+11)   ] = calc_result(round(3000000/2.750), 2, 6, 48);
    baudrates[(3000000*16/(2*16+11))+1] = calc_result(round(3000000/2.625), 2, 5, 48);
    baudrates[ 3000000*16/(2*16+ 9)   ] = calc_result(round(3000000/2.625), 2, 5, 48);
    baudrates[(3000000*16/(2*16+ 9))+1] = calc_result(round(3000000/2.500), 2, 1, 48);
    baudrates[ 3000000*16/(2*16+ 7)   ] = calc_result(round(3000000/2.500), 2, 1, 48);
    baudrates[(3000000*16/(2*16+ 7))+1] = calc_result(round(3000000/2.375), 2, 4, 48);
    baudrates[ 3000000*16/(2*16+ 5)   ] = calc_result(round(3000000/2.375), 2, 4, 48);
    baudrates[(3000000*16/(2*16+ 5))+1] = calc_result(round(3000000/2.250), 2, 2, 48);
    baudrates[ 3000000*16/(2*16+ 3)   ] = calc_result(round(3000000/2.250), 2, 2, 48);
    baudrates[(3000000*16/(2*16+ 3))+1] = calc_result(round(3000000/2.125), 2, 3, 48);
    baudrates[ 3000000*16/(2*16+ 1)   ] = calc_result(round(3000000/2.125), 2, 3, 48);
    baudrates[(3000000*16/(2*16+ 1))+1] = calc_result(round(3000000/2.000), 2, 0, 48);

    BOOST_FOREACH(const enum ftdi_chip_type &test_chip_type, test_types)
    {
        ftdi->type = test_chip_type;
        test_baudrates(ftdi, baudrates);
    }
}

BOOST_AUTO_TEST_CASE(TypeHFixedBaudrates)
{
    // Unify testing of chips behaving the same
    std::vector<enum ftdi_chip_type> test_types;
    test_types.push_back(TYPE_2232H);
    test_types.push_back(TYPE_4232H);
    test_types.push_back(TYPE_232H);

    map<int, calc_result> baudrates;
    baudrates[183] = calc_result(183, 16383, 7, 48);
    baudrates[184] = calc_result(184, 16304, 4, 48);
    baudrates[300] = calc_result(300, 10000, 0, 48);
    baudrates[600] = calc_result(600,  5000, 0, 48);
    baudrates[1200] = calc_result(1200, 10000, 0, 120);
    baudrates[2400] = calc_result(2400,  5000, 0, 120);
    baudrates[4800] = calc_result(4800,  2500, 0, 120);
    baudrates[9600] = calc_result(9600,  1250, 0, 120);
    baudrates[19200] = calc_result(19200, 625, 0, 120);
    baudrates[38400] = calc_result(38400, 312, 1, 120);
    baudrates[57600] = calc_result(57588, 208, 4, 120);
    baudrates[115200] = calc_result(115246, 104, 3, 120);
    baudrates[230400] = calc_result(230216, 52, 3, 120);
    baudrates[460800] = calc_result(461538, 26, 0, 120);
    baudrates[921600] = calc_result(923077, 13, 0, 120);
    baudrates[1000000] = calc_result(1000000, 12, 0, 120);
    baudrates[1000000] = calc_result(1000000, 12, 0, 120);
    baudrates[6000000] = calc_result(6000000, 2, 0, 120);
    baudrates[4173913] = calc_result(4173913, 2, 7, 120);
    baudrates[8000000] = calc_result(8000000, 1, 0, 120);
    baudrates[12000000] = calc_result(12000000, 0, 0, 120);

    baudrates[(12000000*16/(2*16+15))-1] = calc_result(round(12000000/3.000), 3, 0, 120);
    baudrates[ 12000000*16/(2*16+15)   ] = calc_result(round(12000000/3.000), 3, 0, 120);
    baudrates[(12000000*16/(2*16+15))+1] = calc_result(round(12000000/2.875), 2, 7, 120);
    baudrates[ 12000000*16/(2*16+13)   ] = calc_result(round(12000000/2.875), 2, 7, 120);
    baudrates[(12000000*16/(2*16+13))+1] = calc_result(round(12000000/2.750), 2, 6, 120);
    baudrates[ 12000000*16/(2*16+11)   ] = calc_result(round(12000000/2.750), 2, 6, 120);
    baudrates[(12000000*16/(2*16+11))+1] = calc_result(round(12000000/2.625), 2, 5, 120);
    baudrates[ 12000000*16/(2*16+ 9)   ] = calc_result(round(12000000/2.625), 2, 5, 120);
    baudrates[(12000000*16/(2*16+ 9))+1] = calc_result(round(12000000/2.500), 2, 1, 120);
    baudrates[ 12000000*16/(2*16+ 7)   ] = calc_result(round(12000000/2.500), 2, 1, 120);
    baudrates[(12000000*16/(2*16+ 7))+1] = calc_result(round(12000000/2.375), 2, 4, 120);
    baudrates[ 12000000*16/(2*16+ 5)   ] = calc_result(round(12000000/2.375), 2, 4, 120);
    baudrates[(12000000*16/(2*16+ 5))+1] = calc_result(round(12000000/2.250), 2, 2, 120);
    baudrates[ 12000000*16/(2*16+ 3)   ] = calc_result(round(12000000/2.250), 2, 2, 120);
    baudrates[(12000000*16/(2*16+ 3))+1] = calc_result(round(12000000/2.125), 2, 3, 120);
    baudrates[ 12000000*16/(2*16+ 1)   ] = calc_result(round(12000000/2.125), 2, 3, 120);
    baudrates[(12000000*16/(2*16+ 1))+1] = calc_result(round(12000000/2.000), 2, 0, 120);

    BOOST_FOREACH(const enum ftdi_chip_type &test_chip_type, test_types)
    {
        ftdi->type = test_chip_type;
        test_baudrates(ftdi, baudrates);
    }
}

BOOST_AUTO_TEST_SUITE_END()
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!1154 blocks
openSUSE Build Service is sponsored by