]> rtime.felk.cvut.cz Git - sysless.git/commitdiff
Added newer version (1.64) of lpc21isp
authorMichal Sojka <sojkam1@fel.cvut.cz>
Wed, 18 Mar 2009 17:34:32 +0000 (18:34 +0100)
committerMichal Sojka <sojkam1@fel.cvut.cz>
Wed, 18 Mar 2009 17:38:18 +0000 (18:38 +0100)
12 files changed:
arch/arm/mach-lpc21xx/tools/lpc21isp/Makefile.omk
arch/arm/mach-lpc21xx/tools/lpc21isp/README [new file with mode: 0644]
arch/arm/mach-lpc21xx/tools/lpc21isp/adprog.c [new file with mode: 0644]
arch/arm/mach-lpc21xx/tools/lpc21isp/adprog.h [new file with mode: 0644]
arch/arm/mach-lpc21xx/tools/lpc21isp/gpl.txt [new file with mode: 0644]
arch/arm/mach-lpc21xx/tools/lpc21isp/lgpl-3.0.txt [new file with mode: 0644]
arch/arm/mach-lpc21xx/tools/lpc21isp/lpc21isp.c
arch/arm/mach-lpc21xx/tools/lpc21isp/lpc21isp.h [new file with mode: 0644]
arch/arm/mach-lpc21xx/tools/lpc21isp/lpcprog.c [new file with mode: 0644]
arch/arm/mach-lpc21xx/tools/lpc21isp/lpcprog.h [new file with mode: 0644]
arch/arm/mach-lpc21xx/tools/lpc21isp/lpcterm.c [new file with mode: 0644]
arch/arm/mach-lpc21xx/tools/lpc21isp/lpcterm.h [new file with mode: 0644]

index a66460c7c0acb4e90770aae613984d024df815bb..6d64bee20e4a3729e42947aff43b83e35287c3dc 100644 (file)
@@ -2,7 +2,7 @@
 
 utils_PROGRAMS = lpc21isp
 
-lpc21isp_SOURCES = lpc21isp.c
+lpc21isp_SOURCES = lpc21isp.c adprog.c lpcprog.c lpcterm.c
 
 # Override LOADLIBES from config.target (if specified)
 LOADLIBES=
diff --git a/arch/arm/mach-lpc21xx/tools/lpc21isp/README b/arch/arm/mach-lpc21xx/tools/lpc21isp/README
new file mode 100644 (file)
index 0000000..ba0a819
--- /dev/null
@@ -0,0 +1,45 @@
+/******************************************************************************\r
+\r
+Project:           Portable command line ISP for Philips LPC2000 family\r
+                   and Analog Devices ADUC70xx\r
+\r
+Filename:          README\r
+\r
+Compiler:          Microsoft VC 6/7, GCC Cygwin, GCC Linux, GCC ARM ELF\r
+\r
+Author:            Martin Maurer (Martin.Maurer@clibb.de)\r
+\r
+Copyright:         (c) Martin Maurer 2003-2008, All rights reserved\r
+Portions Copyright (c) by Aeolus Development 2004 http://www.aeolusdevelopment.com\r
+\r
+    This file is part of lpc21isp.\r
+\r
+    lpc21isp is free software: you can redistribute it and/or modify\r
+    it under the terms of the GNU Lesser General Public License as published by\r
+    the Free Software Foundation, either version 3 of the License, or\r
+    any later version.\r
+\r
+    lpc21isp is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+    GNU Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public License\r
+    and GNU General Public License along with lpc21isp.\r
+    If not, see <http://www.gnu.org/licenses/>.\r
+*/\r
+\r
+\r
+To compile with microsoft visual studio:\r
+- Open console. Execute bat file from your installation, e.g.\r
+  "c:\Program Files\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat"\r
+- Go to directory where you unpacked the source.\r
+- Run\r
+  nmake /f Makefile.vc clean all\r
+\r
+To compile with gcc (linux, cygwin, ...)\r
+- Open shell / terminal windows\r
+- Run (if you want to use make and gcc)\r
+  make -f Makefile.gnu clean all\r
+- Run (if you want to use gmake and gcc)\r
+  gmake -f Makefile.gnu clean all\r
diff --git a/arch/arm/mach-lpc21xx/tools/lpc21isp/adprog.c b/arch/arm/mach-lpc21xx/tools/lpc21isp/adprog.c
new file mode 100644 (file)
index 0000000..f449cd6
--- /dev/null
@@ -0,0 +1,324 @@
+/******************************************************************************\r
+\r
+Project:           Portable command line ISP for Philips LPC2000 family\r
+                   and Analog Devices ADUC70xx\r
+\r
+Filename:          adprog.c\r
+\r
+Compiler:          Microsoft VC 6/7, GCC Cygwin, GCC Linux, GCC ARM ELF\r
+\r
+Author:            Martin Maurer (Martin.Maurer@clibb.de)\r
+\r
+Copyright:         (c) Martin Maurer 2003-2008, All rights reserved\r
+Portions Copyright (c) by Aeolus Development 2004 http://www.aeolusdevelopment.com\r
+\r
+    This file is part of lpc21isp.\r
+\r
+    lpc21isp is free software: you can redistribute it and/or modify\r
+    it under the terms of the GNU Lesser General Public License as published by\r
+    the Free Software Foundation, either version 3 of the License, or\r
+    any later version.\r
+\r
+    lpc21isp is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+    GNU Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public License\r
+    and GNU General Public License along with lpc21isp.\r
+    If not, see <http://www.gnu.org/licenses/>.\r
+*/\r
+\r
+#if defined(_WIN32)\r
+#if !defined __BORLANDC__\r
+#include "StdAfx.h"\r
+#endif\r
+#endif // defined(_WIN32)\r
+#include "lpc21isp.h"\r
+\r
+#ifdef AD_SUPPORT\r
+#include "adprog.h"\r
+\r
+/***************************** AnalogDevicesSync ************************/\r
+/**  Attempt to synchronize with an Analog Device ARM micro.  Sends a\r
+backspace and reads back the microcontrollers response.  Performs\r
+multiple retries. Exits the program on error, returns to caller in the\r
+case of success.\r
+*/\r
+static void AnalogDevicesSync(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    BINARY sync;                        /* Holds sync command.          */\r
+    AD_SYNC_RESPONSE response;          /* Response from micro.         */\r
+    int sync_attempts;                  /* Number of retries.           */\r
+\r
+    /*  Make sure we don't read garbage later instead of the        */\r
+    /* response we expect from the micro.                           */\r
+    ClearSerialPortBuffers(IspEnvironment);\r
+\r
+    DebugPrintf(2, "Synchronizing\n"); /* Progress report.             */\r
+\r
+    sync = ANALOG_DEVICES_SYNC_CHAR;    /* Build up sync command.       */\r
+\r
+    /*  Perform the actual sync attempt.  First send the sync       */\r
+    /* character, the attempt to read back the response.  For the   */\r
+    /* AD ARM micro this is a fixed length block.  If response is   */\r
+    /* received attempt to validate it by comparing the first       */\r
+    /* characters to those expected.  If the received block does    */\r
+    /* not validate or is incomplete empty the serial buffer and    */\r
+    /* retry.                                                       */\r
+    for (sync_attempts = 0; sync_attempts < 5; sync_attempts++)\r
+    {\r
+        SendComPortBlock(IspEnvironment, &sync, 1);\r
+\r
+        if (ReceiveComPortBlockComplete(IspEnvironment, &response, sizeof(response),\r
+            500) == 0)\r
+        {\r
+\r
+            if (memcmp(response.product_id, ANALOG_DEVICES_SYNC_RESPONSE,\r
+                ANALOG_DEVICES_SYNC_SIZE) == 0)\r
+            {\r
+                return;\r
+            }\r
+            else\r
+            {\r
+                DumpString(3, &response, sizeof(response),\r
+                    "Unexpected response to sync attempt ");\r
+            }\r
+        }\r
+        else\r
+        {\r
+            DebugPrintf(3, "No (or incomplete) answer on sync attempt\n");\r
+        }\r
+\r
+        ClearSerialPortBuffers(IspEnvironment);\r
+    }\r
+\r
+    DebugPrintf(1, "No (or unacceptable) answer on sync attempt\n");\r
+    exit(4);\r
+}\r
+\r
+typedef struct {\r
+    char start1;\r
+    char start2;\r
+    BINARY bytes;\r
+    char cmd;\r
+    BINARY address_h;\r
+    BINARY address_u;\r
+    BINARY address_m;\r
+    BINARY address_l;\r
+    BINARY data[251];\r
+} AD_PACKET;\r
+\r
+/***************************** AnalogDevicesFormPacket ******************/\r
+/**  Create an Analog Devices communication packet from the constituent\r
+elements.\r
+\param [in] cmd The command being sent, one of 'E' for erase, 'W' for\r
+write, 'V' for verify or 'R' for run..\r
+\param [in] no_bytes the number of data bytes to send with the command in\r
+the packet.\r
+\param [in] address the address to apply the command to.\r
+\param [in] data the data to send with the packet, may be null if no_bytes\r
+is zero.\r
+\param[out] packet that will be filled.\r
+*/\r
+static void AnalogDevicesFormPacket(ISP_ENVIRONMENT *IspEnvironment,\r
+                                                char cmd, int no_bytes, unsigned int address,\r
+                                                const void *data, AD_PACKET *packet)\r
+{\r
+    BINARY checksum;\r
+    const BINARY *data_in;\r
+    int i;\r
+\r
+    (void)IspEnvironment; /* never used in this function */\r
+\r
+    /*  Some sanity checking on the arguments.  These should only   */\r
+    /* fail if there is a bug in the caller.                        */\r
+    /*  Check 1) that the number of data bytes is in an acceptable  */\r
+    /* range, 2) that we have a non-null pointer if data is being   */\r
+    /* put in the packet and 3) that we have a non-null pointer to  */\r
+    /* the packet to be filled. We just exit with an error message  */\r
+    /* if any of these tests fail.                                  */\r
+    if ((no_bytes < 0) || (no_bytes > 250))\r
+    {\r
+        DebugPrintf(1,\r
+            "The number of bytes (%d) passed to FormPacket is invalid.\n",\r
+            no_bytes);\r
+        exit(-1);\r
+    }\r
+    if ((data == 0) && (no_bytes != 0))\r
+    {\r
+        DebugPrintf(1,\r
+            "A null pointer to data paased to FormPacket when data was expected.\n");\r
+        exit(-1);\r
+    }\r
+    if (packet == 0)\r
+    {\r
+        DebugPrintf(1,\r
+            "A null packet pointer was passed to FormPacket.\n");\r
+        exit(-1);\r
+    }\r
+\r
+    checksum = 0;               /*  Checksum starts at zero.            */\r
+\r
+    data_in = (BINARY*) data;             /*  Pointer pun so we can walk through  */\r
+    /* the data.                            */\r
+\r
+    packet->start1 = 0x7;       /*  The start of the packet is constant.*/\r
+    packet->start2 = 0xE;\r
+\r
+    /*  Fill in the rest of the packet and calculate the checksum   */\r
+    /* as we go.                                                    */\r
+\r
+    /* The number of bytes is the number of data bytes + the        */\r
+    /* address bytes + the command byte.                            */\r
+    packet->bytes = (BINARY)(no_bytes + 5);\r
+\r
+    checksum += packet->bytes;\r
+\r
+    /*  The command for the packet being sent.  No error checking   */\r
+    /* done on this.                                                */\r
+    packet->cmd = cmd;\r
+\r
+    checksum += cmd;\r
+\r
+    /*  Now break up the address and place in the proper packet     */\r
+    /* locations.                                                   */\r
+    packet->address_l = (BINARY)(address & 0xFF);\r
+    packet->address_m = (BINARY)((address >> 8) & 0xFF);\r
+    packet->address_u = (BINARY)((address >> 16) & 0xFF);\r
+    packet->address_h = (BINARY)((address >> 24) & 0xFF);\r
+\r
+    checksum += packet->address_l;\r
+    checksum += packet->address_m;\r
+    checksum += packet->address_u;\r
+    checksum += packet->address_h;\r
+\r
+    /*  Copy the data bytes into the packet.  We could use memcpy   */\r
+    /* but we have to calculate the checksum anyway.                */\r
+    for (i = 0; i < no_bytes; i++)\r
+    {\r
+        packet->data[i] = data_in[i];\r
+        checksum += data_in[i];\r
+    }\r
+\r
+    /*  Finally, add the checksum to the end of the packet.         */\r
+    packet->data[i] = (BINARY)-checksum;\r
+}\r
+\r
+/***************************** AnalogDevicesSendPacket ******************/\r
+/**  Send a previously form Analog Devices communication.  Retry a\r
+couple of times if needed but fail by exiting the program if no ACK is\r
+forthcoming.\r
+\param [in] packet the packet to send.\r
+*/\r
+static void AnalogDevicesSendPacket(ISP_ENVIRONMENT *IspEnvironment,\r
+                                                const AD_PACKET * packet)\r
+{\r
+    BINARY response;\r
+    int retry = 0;\r
+\r
+    do {\r
+        retry++;\r
+\r
+        /*  Make sure we don't read garbage later instead of    */\r
+        /* the response we expect from the micro.               */\r
+        ClearSerialPortBuffers(IspEnvironment);\r
+\r
+        /*  Send the packet, the size is the number of data     */\r
+        /* bytes in the packet plus 3 bytes worth of header     */\r
+        /* plus checksum.                                       */\r
+        SendComPortBlock(IspEnvironment, packet, packet->bytes + 4);\r
+\r
+        /*  Receive the response and check, return to caller    */\r
+        /* if successful.                                       */\r
+        if (ReceiveComPortBlockComplete(IspEnvironment, &response, 1, 5000) == 0)\r
+        {\r
+            if (response == ANALOG_DEVICES_ACK)\r
+            {\r
+                DebugPrintf(3, "Packet Sent\n");\r
+                return;\r
+            }\r
+            if (response != ANALOG_DEVICES_NAK)\r
+            {\r
+                DebugPrintf(3, "Unexpected response to packet (%x)\n", (int)response);\r
+            }\r
+            DebugPrintf(2, "*");\r
+        }\r
+    } while (retry < 3);\r
+\r
+    DebugPrintf(1, "Send packet failed\n");\r
+    exit(-1);\r
+}\r
+\r
+/***************************** AnalogDevicesErase ***********************/\r
+/**  Erase the Analog Devices micro.  We take the simple way out and\r
+just erase the whole thing.\r
+*/\r
+static void AnalogDevicesErase(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    BINARY pages;\r
+    AD_PACKET packet;\r
+\r
+    pages = 0;\r
+    DebugPrintf(2, "Erasing .. ");\r
+    AnalogDevicesFormPacket(IspEnvironment, 'E', 1, 0, &pages, &packet);\r
+    AnalogDevicesSendPacket(IspEnvironment, &packet);\r
+    DebugPrintf(2, "Erased\n");\r
+}\r
+\r
+#define AD_PACKET_SIZE (250)\r
+\r
+/***************************** AnalogDevicesWrite ***********************/\r
+/**  Write the program.\r
+\param [in] data the program to download to the micro.\r
+\param [in] address where to start placing the program.\r
+\param [in] bytes the size of the progrm to download.\r
+*/\r
+static void AnalogDevicesWrite(ISP_ENVIRONMENT *IspEnvironment,\r
+                                         const void *data, long address, size_t bytes)\r
+{\r
+    AD_PACKET packet;\r
+    const BINARY *prog_data;\r
+\r
+    DebugPrintf(2, "Writing %d bytes ", bytes);\r
+    prog_data = (const BINARY*) data;\r
+    while (bytes > AD_PACKET_SIZE)\r
+    {\r
+        AnalogDevicesFormPacket(IspEnvironment, 'W', AD_PACKET_SIZE, address, prog_data, &packet);\r
+        AnalogDevicesSendPacket(IspEnvironment, &packet);\r
+        address += AD_PACKET_SIZE;\r
+        prog_data += AD_PACKET_SIZE;\r
+        bytes -= AD_PACKET_SIZE;\r
+        DebugPrintf(2, ".");\r
+    }\r
+    if (bytes > 0)\r
+    {\r
+        AnalogDevicesFormPacket(IspEnvironment, 'W', bytes, address, prog_data, &packet);\r
+        AnalogDevicesSendPacket(IspEnvironment, &packet);\r
+        DebugPrintf(2, ".");\r
+    }\r
+}\r
+\r
+/***************************** AnalogDevicesDownload ********************/\r
+/**  Perform the download into an Analog Devices micro.  As a quick and\r
+* dirty hack against flash relocations at 0x80000\r
+* \return 0 if ok, error code else\r
+* \ToDo: possible to implement the return value instead of calling\r
+* exit() in sub-functions\r
+*/\r
+int AnalogDevicesDownload(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    AnalogDevicesSync(IspEnvironment);\r
+    AnalogDevicesErase(IspEnvironment);\r
+    if (IspEnvironment->BinaryLength > 0x80000)\r
+    {\r
+        DebugPrintf(2, "Note:  Flash remapped 0x80000 to 0.\n");\r
+        AnalogDevicesWrite(IspEnvironment, IspEnvironment->BinaryContent + 0x80000, 0, IspEnvironment->BinaryLength-0x80000);\r
+    }\r
+    else\r
+    {\r
+        AnalogDevicesWrite(IspEnvironment, IspEnvironment->BinaryContent, 0, IspEnvironment->BinaryLength);\r
+    }\r
+    return (0);\r
+}\r
+#endif // AD_SUPPORT\r
diff --git a/arch/arm/mach-lpc21xx/tools/lpc21isp/adprog.h b/arch/arm/mach-lpc21xx/tools/lpc21isp/adprog.h
new file mode 100644 (file)
index 0000000..1cee9e6
--- /dev/null
@@ -0,0 +1,46 @@
+/******************************************************************************\r
+\r
+Project:           Portable command line ISP for Philips LPC2000 family\r
+                   and Analog Devices ADUC70xx\r
+\r
+Filename:          adprog.h\r
+\r
+Compiler:          Microsoft VC 6/7, GCC Cygwin, GCC Linux, GCC ARM ELF\r
+\r
+Author:            Martin Maurer (Martin.Maurer@clibb.de)\r
+\r
+Copyright:         (c) Martin Maurer 2003-2008, All rights reserved\r
+Portions Copyright (c) by Aeolus Development 2004 http://www.aeolusdevelopment.com\r
+\r
+    This file is part of lpc21isp.\r
+\r
+    lpc21isp is free software: you can redistribute it and/or modify\r
+    it under the terms of the GNU Lesser General Public License as published by\r
+    the Free Software Foundation, either version 3 of the License, or\r
+    any later version.\r
+\r
+    lpc21isp is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+    GNU Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public License\r
+    and GNU General Public License along with lpc21isp.\r
+    If not, see <http://www.gnu.org/licenses/>.\r
+*/\r
+\r
+#define ANALOG_DEVICES_SYNC_CHAR                ((BINARY)0x08)\r
+#define ANALOG_DEVICES_SYNC_RESPONSE        ("ADuC")\r
+#define ANALOG_DEVICES_SYNC_SIZE                (strlen(ANALOG_DEVICES_SYNC_RESPONSE))\r
+#define ANALOG_DEVICES_ACK                        0x6\r
+#define ANALOG_DEVICES_NAK                        0x7\r
+\r
+typedef struct\r
+{\r
+    BINARY product_id[15];\r
+    BINARY version[3];\r
+    BINARY reserved[4];\r
+    BINARY terminator[2];\r
+} AD_SYNC_RESPONSE;\r
+\r
+int AnalogDevicesDownload(ISP_ENVIRONMENT *IspEnvironment);\r
diff --git a/arch/arm/mach-lpc21xx/tools/lpc21isp/gpl.txt b/arch/arm/mach-lpc21xx/tools/lpc21isp/gpl.txt
new file mode 100644 (file)
index 0000000..94a9ed0
--- /dev/null
@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/arch/arm/mach-lpc21xx/tools/lpc21isp/lgpl-3.0.txt b/arch/arm/mach-lpc21xx/tools/lpc21isp/lgpl-3.0.txt
new file mode 100644 (file)
index 0000000..fc8a5de
--- /dev/null
@@ -0,0 +1,165 @@
+                  GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions. 
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version. 
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  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 that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser 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 as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
index 154d98c4372c68e6686eda65eef2f7a8e6394c29..976836ebcf539c0cef5701a9766c7cf3e2d8568c 100644 (file)
-/******************************************************************************
-
-Project:           Portable command line ISP for Philips LPC2000 family
-                   and Analog Devices ADUC70xx
-
-Filename:          lpc21isp.c
-
-Compiler:          Microsoft VC 6/7, GCC Cygwin, GCC Linux
-
-Autor:             Martin Maurer (Martin.Maurer@clibb.de)
-
-Copyright:         (c) Martin Maurer 2003-2005, All rights reserved
-Portions Copyright (c) by Aeolus Development 2004 http://www.aeolusdevelopment.com
-
-Version:           1.27
-
-Change-History:
-
- 1.00  2004-01-08  Initial Version, tested for MSVC6/7 and GCC under Cygwin
- 1.01  2004-01-10  Porting to Linux (at least compiling must work)
- 1.02  2004-01-10  Implemented conversion intel hex format -> binary
- 1.03  2004-01-25  Preparation to upload to public website
- 1.04  2004-02-12  Merged in bugfixes by Soeren Gust
- 1.05  2004-03-14  Implement printing of error codes as text / strings
- 1.06  2004-03-09  Merged in bugfixes by Charles Manning:
-                   The '?' sychronisation does not reliably respond to the first '?'.
-                   I added some retries.
-                   The LPC2106 sometimes responds to the '?' by echoing them back.
-                   This sometimes causes an attempt to match "?Synchonized".
-                   Added code to strip off any leading '?'s.
-                   Timeouts were too long.
-                   Change from RTS/CTS to no flow control.
-                   Done because many/most people will use only 3-wire comms.
-                   Added some progress tracing.
- 1.07  2004-03-14  Implement handling of control lines for easier booting
- 1.08  2004-04-01  Bugfix for upload problem
- 1.09  2004-04-03  Redesign of upload routine
-                   Now always 180 byte blocks are uploaded, to prevent
-                   small junks in uuencoding
- 1.10  2004-04-03  Clear buffers before sending commands to LPC21xx,
-                   this prevents synchronizing errors when previously loaded
-                   program does a lot of output, so FIFO of PC runs full
- 1.11  2004-04-03  Small optimization for controlling reset line
-                   otherwise termonly starts LPC twice, free PC buffers
- 1.12  2004-04-04  Add switch to enable logging terminal output to lpc21isp.log
- 1.13  2004-05-19  Merged in improvement by Charles Manning:
-                   Instead of exiting the wrong hex file size is corrected
- 1.14  2004-07-07  Merged in improvement by Alex Holden:
-                   Remove little/big endian dependancy
- 1.15  2004-09-27  Temporary improvement by Cyril Holweck:
-                   Removed test (data echoed = data transmited) on the main
-                   data transfert, since this was the biggest failure
-                   reason and is covered by checksome anyway.
-                   Added COMPILE_FOR_LPC21, to have target dump it's own
-                   memory to stdout.
- 1.16  2004-10-09  Merged in bugfix / improvement by Sinelnikov Evgeny
-                   I found out that Linux and Windows serial port initialization
-                   are different with pinouts states. My board don't get
-                   reset signal at first cycle of DTR pinout moving.
-                   And I add this moving to initalization cycle.
- 1.17  2004-10-21  Changes by Cyril Holweck
-                   Divide main, take out the real programming function, that can
-                   also be used by a target to copy its own code to another.
- 1.18  2004-10-26  Changes by Cyril Holweck
-                   Added a "G 0 A\r\n" at end of programming to run code.
- 1.19  2004-11-03  Changes by Robert Adsett
-                   Add support for Analog Devices.
-                   Separate file load from programming.
-                   Change from a debug on/off flag to debug level
-                   Remove if(debug) tests and replace with DebugPrintf
-                   statements.
-                   Change serial I/O and timing so that the system
-                   dependancies are isolated to a few portability functions.
-                   Add support for binary serial I/O.
-                   Add doxygen support.
- 1.20  2004-11-07  Preparation for multiport booting (factory support)
- 1.21  2004-11-08  Bugfix from Robert Adsett
-                   BinaryLength was not initialized
- 1.22  2004-11-08  Changes from Cyril Holweck / Evgeny Sinelnikov
-                   Forgotten IspEnvironment-> and bugfixes if COMPILE_FOR_LINUX
-                   If COMPILE_FOR_LPC21, PhilipsDownload() 'acts as' main():
-                   - it should not be static and should return int.
-                   - no sub-function can use exit() but only return()
-                   Use 'char' instead of 'byte' ;)
- 1.23  2005-01-16  Build in automatic detection of LPC chiptype
-                   (needed for 256 KByte support)
- 1.24B 2005-06-02  Changes by Thiadmer Riemersma: completed support for other
-                   chip types (LPC213x series and others).
- 1.24C 2005-06-11  Changes by Thiadmer Riemersma: added the device ID codes for
-                   chip types LPC2131 and LPC2132.
- 1.25  2005-06-19  Martin Maurer: Setup more parameters in DCB,
-                   otherwise wrong code is downloaded (only Windows and Cygwin)
-                   when a previous program has changed these parameters
-                   Check exact string of "G 0 A\r\n0\r\n" instead of whole received buffer,
-                   to prevent checking of already received by program start
-                   (error on running program, but reports CMD_SUCCESS)
-                   Add ifdefs for all baudrates (needed only for high baudrate,
-                   which seem to be not available on Macs...)
- 1.26  2005-06-26  Martin Maurer:
-                   Correct check again: "G 0 A\r\n0\r\n" is cutted, because of reboot
-                   (error on running program, but reports CMD_SUCCESS)
- 1.27  2005-06-29  Martin Maurer:
-                   Add LPC chip ID's (thanks to Robert from Philips) for
-                   missing LPC213x and upcoming new LPC214x chips
-                   (currently untested, because i don't have access to these chips,
-                    please give me feedback !)
-
-******************************************************************************/
-
-#define VERSION_STR    "1.27"
-
-#if defined(_WIN32) && !defined(__CYGWIN__)
-    #define COMPILE_FOR_WINDOWS
-    #define COMPILED_FOR ("Windows")
-#elif defined(__CYGWIN__)
-    #define COMPILE_FOR_CYGWIN
-    #define COMPILED_FOR ("Cygwin")
-#elif defined(__arm__) || defined(__thumb__)
-    #define COMPILE_FOR_LPC21
-    #define COMPILED_FOR ("ARM")
-    #define printf iprintf
-#else
-    #define COMPILE_FOR_LINUX
-    #define COMPILED_FOR ("Linux")
-#endif
-
-#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-#include <windows.h>
-#include <io.h>
-#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-#if defined COMPILE_FOR_WINDOWS
-#include <conio.h>
-#endif // defined COMPILE_FOR_WINDOWS
-
-#if defined COMPILE_FOR_LINUX
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <stdlib.h>
-#include <string.h>
-#include <strings.h>
-#include <sys/ioctl.h>
-#endif // defined COMPILE_FOR_LINUX
-
-#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
-#include <termios.h>
-#include <unistd.h>     // for read and return value of lseek
-#include <sys/time.h>   // for select_time
-#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
-
-#include <ctype.h>      // isdigit()
-#include <stdio.h>      // stdout
-#include <stdarg.h>
-#include <time.h>
-
-#if defined COMPILE_FOR_LPC21
-#include <stdlib.h>
-#include <string.h>
-#include "lpc_ioctl.h"
-#endif
-
-#if !defined COMPILE_FOR_LPC21
-#include <fcntl.h>
-#endif
-
-#ifndef O_BINARY
-#define O_BINARY 0
-#endif // O_BINARY
-
-#ifndef DWORD
-#define DWORD unsigned long
-#endif // DWORD
-
-#if defined COMPILE_FOR_LINUX
-#define stricmp strcasecmp
-#endif // defined COMPILE_FOR_LINUX
-
-typedef unsigned char BINARY;   /**< data type used for microcontroller
-                                *  memory image.                        */
-
-/*
-debug levels
-0 - very quiet          - Nothing gets printed at this level
-1 - quiet               - Only error messages should be printed
-2 - indicate progress   - Add progress messages
-3 - first level debug   - Major level tracing
-4 - second level debug  - Add detailed debugging
-5 - log comm's          - log serial I/O
-*/
-
-typedef enum
-{
-    PHILIPS_ARM,
-    ANALOG_DEVICES_ARM
-} TARGET;
-
-typedef struct
-{
-    unsigned long id;
-    unsigned Product;
-    unsigned FlashSize;     /* in kiB, for informational purposes only */
-    unsigned RAMSize;       /* in kiB, for informational purposes only */
-    unsigned FlashSectors;  /* total number of sectors */
-    unsigned MaxCopySize;   /* maximum size that can be copied to Flash in a single command */
-    int *SectorTable;       /* pointer to a sector table with the sector sizes */
-} LPC_DEVICE_TYPE;
-
-typedef struct
-{
-
-#if !defined COMPILE_FOR_LPC21
-    TARGET micro;                      /**< The type of micro that will be
-                                         * programmed.                           */
-    int debug_level;
-    unsigned char TerminalAfterUpload;
-    unsigned char TerminalOnly;
-    unsigned char DetectOnly;
-    int           DetectedDevice;       /* index in LPCtypes[] array */
-    unsigned char FormatHex;
-    unsigned char ControlLines;
-    unsigned char LogFile;
-    char *input_file;                   /**< Name of the file to get input from. */
-    char *serial_port;                  /**< Name of the serial port to use to
-                                         * communicate with the microcontroller.
-                                         * Read from the command line.          */
-    char *baud_rate;                    /**< Baud rate to use on the serial
-                                         * port communicating with the
-                                         * microcontroller. Read from the
-                                         * command line.                        */
-#endif // !defined COMPILE_FOR_LPC21
-
-    char *StringOscillator;             /**< Holds representation of oscillator
-                                          * speed from the command line.         */
-    BINARY *BinaryContent;              /**< Binary image of the                 */
-                                        /* microcontroller's memory.             */
-    unsigned long BinaryLength;
-
-#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-    HANDLE hCom;
-#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21
-    int fdCom;
-#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21
-
-#if defined COMPILE_FOR_LINUX
-    struct termios oldtio, newtio;
-#endif // defined COMPILE_FOR_LINUX
-
-    unsigned serial_timeout_count;   /**< Local used to track
-                                      * timeouts on serial port read. */
-
-} ISP_ENVIRONMENT;
-
-static int debug_level = 2;
-
-static void DumpString(int level, const void *s, size_t size, const char *fmt, ...);
-static void SendComPort(ISP_ENVIRONMENT *IspEnvironment, const char *s);
-static void ReceiveComPort(ISP_ENVIRONMENT *IspEnvironment, void *Answer, unsigned long MaxSize, unsigned long *RealSize, unsigned long WantedNr0x0A,unsigned timeOutMilliseconds);
-static void DebugPrintf( int level, const char *fmt, ...);
-static void PhilipsOutputErrorMessage(unsigned char ErrorNumber);
-static unsigned char GetErrorNumber(const char *Answer);
-static void SerialTimeoutSet(ISP_ENVIRONMENT *IspEnvironment, unsigned timeout_milliseconds);
-static void SerialTimeoutTick(ISP_ENVIRONMENT *IspEnvironment);
-static int SerialTimeoutCheck(ISP_ENVIRONMENT *IspEnvironment);
-
-#if !defined COMPILE_FOR_LPC21
-static void ClearSerialPortBuffers(ISP_ENVIRONMENT *IspEnvironment);
-static void ControlModemLines(ISP_ENVIRONMENT *IspEnvironment, unsigned char DTR, unsigned char RTS);
-static unsigned char Ascii2Hex(unsigned char c);
-#endif
-
-static int SectorTable_210x[] = { 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192,
-                                  8192, 8192, 8192, 8192, 8192, 8192, 8192 };
-static int SectorTable_211x[] = { 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192,
-                                  8192, 8192, 8192, 8192, 8192, 8192, 8192, };
-static int SectorTable_212x[] = { 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192,
-                                  65536, 65536, 8192, 8192, 8192, 8192, 8192, 8192,
-                                  8192 };
-static int SectorTable_213x[] = { 4096, 4096, 4096, 4096, 4096, 4096, 4096, 4096,
-                                  32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768,
-                                  32768, 32768, 32768, 32768, 32768, 32768, 4096, 4096,
-                                  4096, 4096, 4096 };
-static LPC_DEVICE_TYPE LPCtypes[] =
-{
-  { 0, 0, 0 },  /* unknown */
-  { 0xFFF0FF12, 2104, 128, 16, 15, 8192, SectorTable_210x },
-  { 0xFFF0FF22, 2105, 128, 32, 15, 8192, SectorTable_210x },
-  { 0xFFF0FF32, 2106, 128, 64, 15, 8192, SectorTable_210x },
-  { 0x0101FF12, 2114, 128, 16, 15, 8192, SectorTable_211x },
-  { 0x0201FF12, 2119, 128, 16, 15, 8192, SectorTable_211x },
-  { 0x0101FF13, 2124, 256, 16, 17, 8192, SectorTable_212x },
-  { 0x0201FF13, 2129, 256, 16, 17, 8192, SectorTable_212x },
-  { 0x0002FF01, 2131,  32,  8,  8, 4096, SectorTable_213x },
-  { 0x0002FF11, 2132,  64, 16,  9, 4096, SectorTable_213x },
-  { 0x0002FF12, 2134, 128, 16, 11, 4096, SectorTable_213x },
-  { 0x0002FF23, 2136, 256, 32, 15, 4096, SectorTable_213x },
-  { 0x0002FF25, 2138, 512, 32, 27, 4096, SectorTable_213x },
-  { 0x0402FF01, 2141,  32,  8,  8, 4096, SectorTable_213x },
-  { 0x0402FF11, 2142,  64, 16,  9, 4096, SectorTable_213x },
-  { 0x0402FF12, 2144, 128, 16, 11, 4096, SectorTable_213x },
-  { 0x0402FF23, 2146, 256, 40, 15, 4096, SectorTable_213x },
-  { 0x0402FF25, 2148, 512, 40, 27, 4096, SectorTable_213x },
-  { 0x0301FF13, 2194, 256, 16,  0, 8192, SectorTable_212x },
-  { 0x0301FF12, 2210,   0, 16,  0, 8192, SectorTable_211x }, /* table is a "don't care" */
-  { 0x0401FF12, 2212, 128, 16, 15, 8192, SectorTable_211x },
-  { 0x0601FF13, 2214, 256, 16, 17, 8192, SectorTable_212x },
-  /*            2290; same id as the LPC2210 */
-  { 0x0401FF13, 2292, 256, 16,  0, 8192, SectorTable_212x },
-  { 0x0501FF13, 2294, 256, 16,  0, 8192, SectorTable_212x },
-};
-
-/************* Portability layer. Serial and console I/O differences    */
-/* are taken care of here.                                              */
-
-#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
-static int kbhit( void);
-static int getch( void);
-#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
-
-#if defined COMPILE_FOR_LINUX
-static void Sleep(unsigned long MilliSeconds);
-#endif // defined COMPILE_FOR_LINUX
-
-
-
-#if !defined COMPILE_FOR_LPC21
-static void OpenSerialPort(ISP_ENVIRONMENT *IspEnvironment)
-{
-    // Open COM-Port (different between Windows and Linux)
-
-#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-    DCB    dcb;
-    COMMTIMEOUTS commtimeouts;
-
-    IspEnvironment->hCom = CreateFile(IspEnvironment->serial_port, GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
-
-    if(IspEnvironment->hCom == INVALID_HANDLE_VALUE)
-    {
-        DebugPrintf( 1, "Can't open COM-Port %s ! - Error: %ld\n", IspEnvironment->serial_port, GetLastError());
-        exit(2);
-    }
-
-    DebugPrintf( 3, "COM-Port %s opened...\n", IspEnvironment->serial_port);
-
-    GetCommState(IspEnvironment->hCom, &dcb);
-    dcb.BaudRate    = atol(IspEnvironment->baud_rate);
-    dcb.ByteSize    = 8;
-    dcb.StopBits    = ONESTOPBIT;
-    dcb.Parity      = NOPARITY;
-    dcb.fDtrControl = DTR_CONTROL_DISABLE;
-    dcb.fOutX       = FALSE;
-    dcb.fInX        = FALSE;
-    dcb.fNull       = FALSE;
-    dcb.fRtsControl = RTS_CONTROL_DISABLE;
-    if(SetCommState(IspEnvironment->hCom, &dcb) == 0)
-    {
-        DebugPrintf( 1, "Can't set baudrate %s ! - Error: %ld", IspEnvironment->baud_rate, GetLastError());
-        exit(3);
-    }
-
-    SetCommMask(IspEnvironment->hCom,EV_RXCHAR | EV_TXEMPTY);
-
-    commtimeouts.ReadIntervalTimeout         = MAXDWORD;
-    commtimeouts.ReadTotalTimeoutMultiplier  =    0;
-    commtimeouts.ReadTotalTimeoutConstant    =    1;
-    commtimeouts.WriteTotalTimeoutMultiplier =    0;
-    commtimeouts.WriteTotalTimeoutConstant   =    0;
-    SetCommTimeouts(IspEnvironment->hCom, &commtimeouts);
-
-#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-#if defined COMPILE_FOR_LINUX
-
-    IspEnvironment->fdCom = open(IspEnvironment->serial_port, O_RDWR | O_NOCTTY | O_NONBLOCK );
-
-    if(IspEnvironment->fdCom < 0)
-    {
-        DebugPrintf( 1, "Can't open COM-Port %s !\n", IspEnvironment->serial_port);
-        exit(2);
-    }
-
-    DebugPrintf( 3, "COM-Port %s opened...\n", IspEnvironment->serial_port);
-
-       /* clear input & output buffers, then switch to "blocking mode" */
-       tcflush(IspEnvironment->fdCom, TCOFLUSH);
-       tcflush(IspEnvironment->fdCom, TCIFLUSH);
-       fcntl(IspEnvironment->fdCom, F_SETFL, fcntl(IspEnvironment->fdCom, F_GETFL) & ~O_NONBLOCK);
-
-    tcgetattr(IspEnvironment->fdCom, &IspEnvironment->oldtio); /* save current port settings */
-
-    bzero(&IspEnvironment->newtio, sizeof(IspEnvironment->newtio));
-    IspEnvironment->newtio.c_cflag = CS8 | CLOCAL | CREAD;
-
-    switch(atol(IspEnvironment->baud_rate))
-    {
-#ifdef B1152000
-        case 1152000: IspEnvironment->newtio.c_cflag |= B1152000; break;
-#endif // B1152000
-#ifdef B576000
-        case  576000: IspEnvironment->newtio.c_cflag |=  B576000; break;
-#endif // B576000
-#ifdef B230400
-        case  230400: IspEnvironment->newtio.c_cflag |=  B230400; break;
-#endif // B230400
-#ifdef B115200
-        case  115200: IspEnvironment->newtio.c_cflag |=  B115200; break;
-#endif // B115200
-#ifdef B57600
-        case   57600: IspEnvironment->newtio.c_cflag |=   B57600; break;
-#endif // B57600
-#ifdef B38400
-        case   38400: IspEnvironment->newtio.c_cflag |=   B38400; break;
-#endif // B38400
-#ifdef B19200
-        case   19200: IspEnvironment->newtio.c_cflag |=   B19200; break;
-#endif // B19200
-#ifdef B9600
-        case    9600: IspEnvironment->newtio.c_cflag |=    B9600; break;
-#endif // B9600
-#ifdef B4800
-        case    4800: IspEnvironment->newtio.c_cflag |=    B4800; break;
-#endif // B4800
-#ifdef B2400
-        case    2400: IspEnvironment->newtio.c_cflag |=    B2400; break;
-#endif // B2400
-#ifdef B1200
-        case    1200: IspEnvironment->newtio.c_cflag |=    B1200; break;
-#endif // B1200
-#ifdef B600
-        case    600: IspEnvironment->newtio.c_cflag |=    B600; break;
-#endif // B600
-#ifdef B300
-        case    300: IspEnvironment->newtio.c_cflag |=    B300; break;
-#endif // B300
-        default:
-        {
-            DebugPrintf( 1, "unknown baudrate %s\n", IspEnvironment->baud_rate);
-            exit(3);
-        }
-    }
-
-    IspEnvironment->newtio.c_iflag = IGNPAR | IGNBRK | IXON | IXOFF;
-    IspEnvironment->newtio.c_oflag = 0;
-
-    /* set input mode (non-canonical, no echo,...) */
-    IspEnvironment->newtio.c_lflag = 0;
-
-    cfmakeraw(&IspEnvironment->newtio);
-    IspEnvironment->newtio.c_cc[VTIME]    = 1;   /* inter-character timer used */
-    IspEnvironment->newtio.c_cc[VMIN]     = 0;   /* blocking read until 0 chars received */
-
-    tcflush(IspEnvironment->fdCom, TCIFLUSH);
-    tcsetattr(IspEnvironment->fdCom, TCSANOW, &IspEnvironment->newtio);
-
-#endif // defined COMPILE_FOR_LINUX
-}
-
-static void CloseSerialPort(ISP_ENVIRONMENT *IspEnvironment)
-{
-#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-    CloseHandle(IspEnvironment->hCom);
-
-#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-#if defined COMPILE_FOR_LINUX
-
-       tcflush(IspEnvironment->fdCom, TCOFLUSH);
-       tcflush(IspEnvironment->fdCom, TCIFLUSH);
-    tcsetattr(IspEnvironment->fdCom, TCSANOW, &IspEnvironment->oldtio);
-
-    close(IspEnvironment->fdCom);
-
-#endif // defined COMPILE_FOR_LINUX
-}
-
-#endif // !defined COMPILE_FOR_LPC21
-
-/***************************** SendComPortBlock *************************/
-/**  Sends a block of bytes out the opened com port.
-\param [in] s block to send.
-\param [in] n size of the block.
-*/
-static void SendComPortBlock(ISP_ENVIRONMENT *IspEnvironment, const void *s, size_t n)
-{
-#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-    unsigned long realsize;
-
-#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-    DumpString( 4, s, n, "Sending ");
-
-#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-    WriteFile(IspEnvironment->hCom, s, n, &realsize, NULL);
-
-#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21
-
-    write(IspEnvironment->fdCom, s, n);
-
-#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21
-}
-
-/***************************** SendComPort ******************************/
-/**  Sends a string out the opened com port.
-\param [in] s string to send.
-*/
-static void SendComPort(ISP_ENVIRONMENT *IspEnvironment, const char *s)
-{
-    SendComPortBlock( IspEnvironment, s, strlen(s));
-}
-
-
-/***************************** ReceiveComPortBlock **********************/
-/**  Receives a buffer from the open com port. Returns all the characters
-ready (waits for up to 'n' milliseconds before accepting that no more
-characters are ready) or when the buffer is full. 'n' is system dependant,
-see SerialTimeout routines.
-\param [out] answer buffer to hold the bytes read from the serial port.
-\param [in] max_size the size of buffer pointed to by answer.
-\param [out] real_size pointer to a long that returns the amout of the
-buffer that is actually used.
-*/
-static void ReceiveComPortBlock( ISP_ENVIRONMENT *IspEnvironment,
-                                 void *answer, unsigned long max_size,
-                                 unsigned long *real_size)
-{
-
-#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-    ReadFile(IspEnvironment->hCom, answer, max_size, real_size, NULL);
-
-#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21
-
-    *real_size = read(IspEnvironment->fdCom, answer, max_size);
-
-#endif // defined COMPILE_FOR_LINUX
-
-
-    DumpString( 5, answer, (*real_size), "Read(Length=%ld): ", (*real_size));
-
-    if( *real_size == 0)
-    {
-        SerialTimeoutTick( IspEnvironment );
-    }
-}
-
-
-/***************************** SerialTimeoutSet *************************/
-/**  Sets (or resets) the timeout to the timout period requested.  Starts
-counting to this period.  This timeout support is a little odd in that the
-timeout specifies the accumulated deadtime waiting to read not the total
-time waiting to read. They should be close enought to the same for this
-use. Used by the serial input routines, the actual counting takes place in
-ReceiveComPortBlock.
-\param [in] timeout_milliseconds the time in milliseconds to use for
-timeout.  Note that just because it is set in milliseconds doesn't mean
-that the granularity is that fine.  In many cases (particularly Linux) it
-will be coarser.
-*/
-static void SerialTimeoutSet(ISP_ENVIRONMENT *IspEnvironment, unsigned timeout_milliseconds)
-{
-
-#if defined COMPILE_FOR_LINUX
-    IspEnvironment->serial_timeout_count = timeout_milliseconds/100;
-#elif defined COMPILE_FOR_LPC21
-    IspEnvironment->serial_timeout_count = timeout_milliseconds*200;
-#else
-    IspEnvironment->serial_timeout_count = timeout_milliseconds;
-#endif
-}
-
-/***************************** SerialTimeoutTick ************************/
-/**  Performs a timer tick.  In this simple case all we do is count down
-with protection against underflow and wrapping at the low end.
-*/
-static void SerialTimeoutTick(ISP_ENVIRONMENT *IspEnvironment)
-{
-    if( IspEnvironment->serial_timeout_count <= 1)
-    {
-        IspEnvironment->serial_timeout_count = 0;
-    }
-    else
-    {
-        IspEnvironment->serial_timeout_count--;
-    }
-}
-
-/***************************** SerialTimeoutCheck ***********************/
-/**  Check to see if the serial timeout timer has run down.
-\retval 1 if timer has run out.
-\retval 0 if timer still has time left.
-*/
-static int SerialTimeoutCheck(ISP_ENVIRONMENT *IspEnvironment)
-{
-    if( IspEnvironment->serial_timeout_count == 0)
-    {
-        return 1;
-    }
-    return 0;
-}
-
-
-#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
-/***************************** getch ************************************/
-/** Replacement for the common dos function of the same name. Reads a
-single unbuffered character from the 'keyboard'.
-\return The character read from the keyboard.
-*/
-static int getch(void)
-{
-    char ch;
-    struct termios origtty, tty;
-
-    /* store the current tty settings */
-    tcgetattr(0, &origtty);
-
-    /* start with the current settings */
-    tty = origtty;
-    /* make modifications to put it in raw mode, turn off echo */
-    tty.c_lflag &= ~ICANON;
-    tty.c_lflag &= ~ECHO;
-    tty.c_lflag &= ~ISIG;
-    tty.c_cc[VMIN] = 1;
-    tty.c_cc[VTIME] = 0;
-
-    /* put the settings into effect */
-    tcsetattr(0, TCSADRAIN, &tty);
-
-    /* Read in one character */
-    read(0,&ch,1);
-
-    /* reset the tty to its original settings */
-    tcsetattr(0, TCSADRAIN, &origtty);
-
-    return ch;
-}
-#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
-
-#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
-/***************************** kbhit ************************************/
-/** Replacement for the common dos function of the same name. Indicates if
-there are characters to be read from the console.
-\retval 0 No characters ready.
-\retval 1 Characters from the console ready to be read.
-*/
-static int kbhit(void)
-{
-    /* return 0 for no key pressed, 1 for key pressed */
-    int return_value = 0;
-
-    /* variables to store the current tty state, create a new one */
-    struct termios origtty, tty;
-    /* time struct for the select() function, to only wait a little while */
-    struct timeval select_time;
-    /* file descriptor variable for the select() call */
-    fd_set readset;
-
-    /* we're only interested in STDIN */
-    FD_ZERO(&readset);
-    FD_SET(STDIN_FILENO, &readset);
-
-    /* store the current tty settings */
-    tcgetattr(0, &origtty);
-
-    /* start with the current settings */
-    tty = origtty;
-    /* make modifications to put it in raw mode, turn off echo */
-    tty.c_lflag &= ~ICANON;
-    tty.c_lflag &= ~ECHO;
-    tty.c_lflag &= ~ISIG;
-    tty.c_cc[VMIN] = 1;
-    tty.c_cc[VTIME] = 0;
-
-    /* put the settings into effect */
-    tcsetattr(0, TCSADRAIN, &tty);
-
-    /* how long to block for - this must be > 0.0, but could be changed
-       to some other setting. 10-18msec seems to work well and only
-       minimally load the system (0% CPU loading) */
-    select_time.tv_sec = 0;
-    select_time.tv_usec = 10;
-
-    /* is there a keystroke there? */
-    if (select(1, &readset, NULL, NULL, &select_time))
-    {
-        /* yes, remember it */
-        return_value = 1;
-    }
-
-    /* reset the tty to its original settings */
-    tcsetattr(0, TCSADRAIN, &origtty);
-
-    /* return with what we found out */
-    return return_value;
-}
-#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
-
-
-#if !defined COMPILE_FOR_LPC21
-/***************************** ControlModemLines ************************/
-/**  Controls the modem lines to place the microcontroller into various
-states during the programming process.
-error rather abruptly terminates the program.
-\param [in] DTR the state to set the DTR line to.
-\param [in] RTS the state to set the RTS line to.
-*/
-static void ControlModemLines(ISP_ENVIRONMENT *IspEnvironment, unsigned char DTR, unsigned char RTS)
-{
-#if defined COMPILE_FOR_LINUX
-    int status;
-
-    if(ioctl(IspEnvironment->fdCom, TIOCMGET, &status) == 0)
-    {
-        DebugPrintf( 1, "ioctl get ok, status = %X\n",status);
-    }
-    else
-    {
-        DebugPrintf( 1, "ioctl get failed\n");
-    }
-
-    if(DTR) status |=  TIOCM_DTR;
-    else    status &= ~TIOCM_DTR;
-
-    if(RTS) status |=  TIOCM_RTS;
-    else    status &= ~TIOCM_RTS;
-
-    if(ioctl(IspEnvironment->fdCom, TIOCMSET, &status) == 0)
-    {
-        DebugPrintf( 1, "ioctl set ok, status = %X\n",status);
-    }
-    else
-    {
-        DebugPrintf( 1, "ioctl set failed\n");
-    }
-
-    if(ioctl(IspEnvironment->fdCom, TIOCMGET, &status) == 0)
-    {
-        DebugPrintf( 1, "ioctl get ok, status = %X\n",status);
-    }
-    else
-    {
-        DebugPrintf( 1, "ioctl get failed\n");
-    }
-
-#endif // defined COMPILE_FOR_LINUX
-#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-    if(DTR) EscapeCommFunction(IspEnvironment->hCom, SETDTR);
-    else    EscapeCommFunction(IspEnvironment->hCom, CLRDTR);
-
-    if(RTS) EscapeCommFunction(IspEnvironment->hCom, SETRTS);
-    else    EscapeCommFunction(IspEnvironment->hCom, CLRRTS);
-
-#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-
-    DebugPrintf( 3, "DTR (%d), RTS (%d)\n", DTR, RTS);
-}
-
-
-/***************************** ClearSerialPortBuffers********************/
-/**  Empty the serial port buffers.  Cleans things to a known state.
-*/
-static void ClearSerialPortBuffers(ISP_ENVIRONMENT *IspEnvironment)
-{
-#if defined COMPILE_FOR_LINUX
-    /* variables to store the current tty state, create a new one */
-    struct termios origtty, tty;
-
-    /* store the current tty settings */
-    tcgetattr(IspEnvironment->fdCom, &origtty);
-
-    // Flush input and output buffers
-    tcsetattr(IspEnvironment->fdCom, TCSAFLUSH, &tty);
-
-    /* reset the tty to its original settings */
-    tcsetattr(IspEnvironment->fdCom, TCSADRAIN, &origtty);
-#endif // defined COMPILE_FOR_LINUX
-#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-    PurgeComm(IspEnvironment->hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
-#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
-}
-#endif // !defined COMPILE_FOR_LPC21
-
-
-#if defined COMPILE_FOR_LINUX
-/***************************** Sleep ************************************/
-/**  Provide linux replacement for windows function.
-\param [in] Milliseconds the time to wait for in milliseconds.
-*/
-static void Sleep(unsigned long MilliSeconds)
-{
-    usleep(MilliSeconds*1000); //convert to microseconds
-}
-#endif // defined COMPILE_FOR_LINUX
-
-
-/************* Applicationlayer.                                        */
-
-/***************************** DebugPrintf ******************************/
-/**  Prints a debug string depending the current debug level. The higher
-the debug level the more detail that will be printed.  Each print
-has an associated level, the higher the level the more detailed the
-debugging information being sent.
-\param [in] level the debug level of the print statement, if the level
- is less than or equal to the current debug level it will be printed.
-\param [in] fmt a standard printf style format string.
-\param [in] ... the usual printf parameters.
-*/
-static void DebugPrintf( int level, const char *fmt, ...)
-{
-    va_list ap;
-
-    if( level <= debug_level)
-    {
-        va_start( ap, fmt);
-        vprintf( fmt, ap);
-        va_end( ap);
-        fflush( stdout);
-    }
-}
-
-/***************************** ReceiveComPort ***************************/
-/**  Receives a buffer from the open com port. Returns when the buffer is
-filled, the numer of requested linefeeds has been received or the timeout
-period has passed
-\param [in] ISPEnvironment.
-\param [out] Answer buffer to hold the bytes read from the serial port.
-\param [in] MaxSize the size of buffer pointed to by Answer.
-\param [out] RealSize pointer to a long that returns the amout of the
-buffer that is actually used.
-\param [in] WantedNr0x0A the maximum number of linefeeds to accept before
-returning.
-\param [in] timeOutMilliseconds the maximum amount of time to wait before
-reading with an incomplete buffer.
-*/
-static void ReceiveComPort( ISP_ENVIRONMENT *IspEnvironment,
-                            void *Ans, unsigned long MaxSize,
-                            unsigned long *RealSize, unsigned long WantedNr0x0A,
-                            unsigned timeOutMilliseconds)
-{
-    unsigned long tmp_realsize;
-    unsigned long nr_of_0x0A = 0;
-    int eof = 0;
-    unsigned long p;
-    char *Answer;
-
-    Answer = Ans;
-
-    SerialTimeoutSet( IspEnvironment, timeOutMilliseconds);
-
-    (*RealSize) = 0;
-
-    do
-    {
-        ReceiveComPortBlock( IspEnvironment, Answer + (*RealSize), MaxSize - 1 - (*RealSize), &tmp_realsize);
-
-        if(tmp_realsize != 0)
-        {
-            for(p = (*RealSize); p < (*RealSize) + tmp_realsize; p++)
-            {
-                if(Answer[p] == 0x0a)
-                {
-                    nr_of_0x0A++;
-                }
-                else if(Answer[p] < 0)
-                {
-                    eof = 1;
-                }
-            }
-        }
-
-        (*RealSize) += tmp_realsize;
-
-    } while(((*RealSize) < MaxSize) && (SerialTimeoutCheck(IspEnvironment) == 0) && (nr_of_0x0A < WantedNr0x0A) && !eof);
-
-    Answer[(*RealSize)] = 0;
-
-    DumpString( 3, Answer, (*RealSize), "Answer(Length=%ld): ", (*RealSize));
-}
-
-
-#if !defined COMPILE_FOR_LPC21
-
-/***************************** ReceiveComPortBlockComplete **************/
-/**  Receives a fixed block from the open com port. Returns when the
-block is completely filled or the timeout period has passed
-\param [out] block buffer to hold the bytes read from the serial port.
-\param [in] size the size of the buffer pointed to by block.
-\param [in] timeOut the maximum amount of time to wait before guvung up on
-completing the read.
-\return 0 if successful, non-zero otherwise.
-*/
-static int ReceiveComPortBlockComplete( ISP_ENVIRONMENT *IspEnvironment,
-                                        void *block, size_t size, unsigned timeout)
-{
-    unsigned long realsize = 0, read;
-    char *result;
-
-    result = block;
-
-    SerialTimeoutSet( IspEnvironment, timeout);
-
-    do
-    {
-        ReceiveComPortBlock( IspEnvironment, result + realsize, size - realsize, &read);
-
-        realsize += read;
-
-    } while((realsize < size) && (SerialTimeoutCheck(IspEnvironment) == 0));
-
-    DumpString( 3, result, realsize, "Answer(Length=%ld): ", realsize);
-
-    if( realsize != size)
-    {
-        return 1;
-    }
-    return 0;
-}
-
-/***************************** ReadArguments ****************************/
-/**  Reads the command line arguments and parses it for the various
-options. Uses the same arguments as main.  Used to separate the command
-line parsing from main and improve its readability.  This should also make
-it easier to modify the command line parsing in the future.
-\param [in] argc the number of arguments.
-\param [in] argv an array of pointers to the arguments.
-*/
-static void ReadArguments(ISP_ENVIRONMENT *IspEnvironment, int argc, char *argv[])
-{
-    int i;
-
-    if(argc >= 5)
-    {
-        for(i = 1; i < argc - 4; i++)
-        {
-            if(stricmp(argv[i], "-bin") == 0)
-            {
-                 IspEnvironment->FormatHex = 0;
-                 DebugPrintf( 3, "Binary format file input.\n");
-            }
-            else if(stricmp(argv[i], "-hex") == 0)
-            {
-                 IspEnvironment->FormatHex = 1;
-                 DebugPrintf( 3, "Hex format file input.\n");
-            }
-            else if(stricmp(argv[i], "-term") == 0)
-            {
-                 IspEnvironment->TerminalAfterUpload = 1;
-                 DebugPrintf( 3, "Invoke terminal after upload.\n");
-            }
-            else if(stricmp(argv[i], "-termonly") == 0)
-            {
-                 IspEnvironment->TerminalOnly = 1;
-                 DebugPrintf( 3, "Only provide terminal.\n");
-            }
-            else if(stricmp(argv[i], "-detectonly") == 0)
-            {
-                 IspEnvironment->DetectOnly = 1;
-                 DebugPrintf( 3, "Only detect LPC chip part id.\n");
-            }
-            else if(stricmp(argv[i], "-debug") == 0)
-            {
-                 debug_level = 4;
-                 DebugPrintf( 3, "Turn on debug.\n");
-            }
-            else if(stricmp(argv[i], "-control") == 0)
-            {
-                 IspEnvironment->ControlLines = 1;
-                 DebugPrintf( 3, "Use RTS/DTS to control target state.\n");
-            }
-            else if(stricmp(argv[i], "-logfile") == 0)
-            {
-                 IspEnvironment->LogFile = 1;
-                 DebugPrintf( 3, "Log terminal output.\n");
-            }
-            else if( stricmp( argv[i], "-ADARM") == 0)
-            {
-                IspEnvironment->micro = ANALOG_DEVICES_ARM;
-                DebugPrintf( 2, "Target: Analog Devices.\n");
-            }
-            else if( stricmp( argv[i], "-PHILIPSARM") == 0)
-            {
-                IspEnvironment->micro = PHILIPS_ARM;
-                DebugPrintf( 2, "Target: Philips.\n");
-            }
-            else
-            {
-                DebugPrintf( 2, "Unknown command line option: \"%s\"\n", argv[i]);
-            }
-        }
-
-        IspEnvironment->input_file = argv[argc - 1];
-        IspEnvironment->StringOscillator = argv[argc - 2];
-        IspEnvironment->serial_port = argv[argc - 4];
-        IspEnvironment->baud_rate = argv[argc - 3];
-    }
-
-    if(argc < 5)
-    {
-        debug_level = (debug_level < 2) ? 2 : debug_level;
-    }
-
-    if(argc < 5)
-    {
-        DebugPrintf( 2, "\n");
-        DebugPrintf( 2, "Portable command line ISP for Philips LPC2000 family and \n");
-        DebugPrintf( 2, "Version " VERSION_STR "                 Analog Devices ADUC 70xx\n");
-        DebugPrintf( 2, "Compiled for %s: %s %s\n", COMPILED_FOR, __DATE__, __TIME__);
-        DebugPrintf( 2, "Copyright (c) by Martin Maurer, 2003-2005  Email: Martin.Maurer@clibb.de\n");
-        DebugPrintf( 2, "Portions Copyright (c) by Aeolus Development 2004\n");
-        DebugPrintf( 2, "                 http://www.aeolusdevelopment.com\n");
-        DebugPrintf( 2, "\n");
-
-        DebugPrintf( 1, "Syntax:  lpc21isp [Options] comport baudrate Oscillator_in_kHz file\n\n");
-        DebugPrintf( 1, "Example: lpc21isp test.hex com1 115200 14746\n\n");
-        DebugPrintf( 1, "Options: -bin           for uploading binary file\n");
-        DebugPrintf( 1, "         -hex           for uploading file in intel hex format (default)\n");
-        DebugPrintf( 1, "         -term          for starting terminal after upload\n");
-        DebugPrintf( 1, "         -termonly      for starting terminal without an upload\n");
-        DebugPrintf( 1, "         -detectonly    detect only used LPC chiptype (PHILIPSARM only)\n");
-        DebugPrintf( 1, "         -debug         for creating a lot of debug infos\n");
-        DebugPrintf( 1, "         -control       for controlling RS232 lines for easier booting\n");
-        DebugPrintf( 1, "                        (Reset = DTR, EnableBootLoader = RTS)\n");
-        DebugPrintf( 1, "         -logfile       for enabling logging of terminal output to lpc21isp.log\n");
-        DebugPrintf( 1, "         -ADARM         for downloading to an Analog Devices\n");
-        DebugPrintf( 1, "                        ARM microcontroller ADUC70xx\n");
-        DebugPrintf( 1, "         -PHILIPSARM    for downloading to a microcontroller from\n");
-        DebugPrintf( 1, "                        Philips LPC2000 family (default)\n");
-
-        exit(1);
-    }
-
-    if(IspEnvironment->micro == PHILIPS_ARM)
-    {
-        if (strlen(IspEnvironment->StringOscillator) > 5)
-        {
-            printf("Invalid crystal frequency %s",argv[argc - 1]);
-            exit(1);
-        }
-    }
-}
-
-typedef enum
-{
-    PROGRAM_MODE,
-    RUN_MODE
-} TARGET_MODE;
-
-/***************************** ResetTarget ******************************/
-/**  Resets the target leaving it in either download (program) mode or
-run mode.
-\param [in] mode the mode to leave the target in.
-*/
-static void ResetTarget( ISP_ENVIRONMENT *IspEnvironment, TARGET_MODE mode)
-{
-
-    if(IspEnvironment->ControlLines)
-    {
-
-        switch( mode)
-        {
-                /* Reset and jump to boot loader.                       */
-            case PROGRAM_MODE:
-                ControlModemLines(IspEnvironment, 1, 1);
-                Sleep(100);
-                ClearSerialPortBuffers(IspEnvironment);
-                Sleep(100);
-                ControlModemLines(IspEnvironment, 0, 1);
-                Sleep(100);
-                // Clear the RTS line after having reset the micro
-                // Needed for the "GO <Address> <Mode>" ISP command to work */
-                ControlModemLines(IspEnvironment, 0, 0);
-                break;
-
-                /* Reset and start uploaded program                     */
-            case RUN_MODE:
-                ControlModemLines(IspEnvironment, 1, 0);
-                Sleep(100);
-                ClearSerialPortBuffers(IspEnvironment);
-                Sleep(100);
-                ControlModemLines(IspEnvironment, 0, 0);
-                Sleep(100);
-                break;
-        }
-    }
-}
-
-/***************************** LoadFile *********************************/
-/**  Loads the requested file to download into memory.
-\param [in] IspEnvironment  structure containing input filename
-*/
-static void LoadFile(ISP_ENVIRONMENT *IspEnvironment)
-{
-    int fd;
-    int i;
-    unsigned long  Pos;
-    unsigned long  FileLength;
-    BINARY        *FileContent;              /**< Used to store the content of a hex */
-                                             /* file before converting to binary.    */
-    unsigned long BinaryMemSize;
-
-    fd = open(IspEnvironment->input_file, O_RDONLY | O_BINARY);
-    if(fd == -1)
-    {
-        DebugPrintf( 1, "Can't open file %s\n", IspEnvironment->input_file);
-        exit(1);
-    }
-
-    FileLength = lseek(fd, 0L, 2);      // Get file size
-
-    if(FileLength == (size_t)-1)
-    {
-        DebugPrintf( 1, "\nFileLength = -1 !?!\n");
-        exit(1);
-    }
-
-    lseek(fd, 0L, 0);
-
-    FileContent = malloc(FileLength);
-
-    BinaryMemSize = FileLength * 2;
-
-    IspEnvironment->BinaryLength = 0;   /* Increase length as needed.       */
-
-    IspEnvironment->BinaryContent = malloc(BinaryMemSize);
-
-    read(fd, FileContent, FileLength);
-
-    close(fd);
-
-    DebugPrintf( 2, "File %s:\n\tloaded...\n", IspEnvironment->input_file);
-
-        // Intel-Hex -> Binary Conversion
-
-    if(IspEnvironment->FormatHex != 0)
-    {
-        unsigned char  RecordLength;
-        unsigned short RecordAddress;
-        unsigned long  RealAddress = 0;
-        unsigned char  RecordType;
-        unsigned char  Hexvalue;
-
-        DebugPrintf( 3, "Converting file %s to binary format...\n", IspEnvironment->input_file);
-
-        Pos = 0;
-        while(Pos < FileLength)
-        {
-            if(FileContent[Pos] == '\r')
-            {
-                Pos++;
-                continue;
-            }
-
-            if(FileContent[Pos] == '\n')
-            {
-                Pos++;
-                continue;
-            }
-
-            if(FileContent[Pos] != ':')
-            {
-                DebugPrintf( 1, "Missing start of record (':') wrong byte %c / %02X\n", FileContent[Pos], FileContent[Pos]);
-                exit(1);
-            }
-
-            Pos++;
-
-            RecordLength   = Ascii2Hex(FileContent[Pos++]);
-            RecordLength <<= 4;
-            RecordLength  |= Ascii2Hex(FileContent[Pos++]);
-
-            DebugPrintf( 4, "RecordLength = %02X\n", RecordLength);
-
-            RecordAddress   = Ascii2Hex(FileContent[Pos++]);
-            RecordAddress <<= 4;
-            RecordAddress  |= Ascii2Hex(FileContent[Pos++]);
-            RecordAddress <<= 4;
-            RecordAddress  |= Ascii2Hex(FileContent[Pos++]);
-            RecordAddress <<= 4;
-            RecordAddress  |= Ascii2Hex(FileContent[Pos++]);
-
-            DebugPrintf( 4, "RecordAddress = %04X\n", RecordAddress);
-
-            RealAddress = RealAddress - (RealAddress & 0xffff) + RecordAddress;
-
-            DebugPrintf( 4, "RealAddress = %08lX\n", RealAddress);
-
-            RecordType      = Ascii2Hex(FileContent[Pos++]);
-            RecordType    <<= 4;
-            RecordType     |= Ascii2Hex(FileContent[Pos++]);
-
-            DebugPrintf( 4, "RecordType = %02X\n", RecordType);
-
-            if(RecordType == 0x00)          // 00 - Data record
-            {
-                    // Memory for binary file big enough ?
-                while(RealAddress + RecordLength > BinaryMemSize)
-                {
-                    BinaryMemSize <<= 1;
-                    IspEnvironment->BinaryContent = realloc(IspEnvironment->BinaryContent, BinaryMemSize);
-                }
-
-                    // We need to know, what the highest address is,
-                    // how many bytes / sectors we must flash
-                if(RealAddress + RecordLength > IspEnvironment->BinaryLength)
-                {
-                    IspEnvironment->BinaryLength = RealAddress + RecordLength;
-                    DebugPrintf( 3, "Image size now: %ld\n", IspEnvironment->BinaryLength);
-                }
-
-                for(i = 0; i < RecordLength; i++)
-                {
-                    Hexvalue        = Ascii2Hex(FileContent[Pos++]);
-                    Hexvalue      <<= 4;
-                    Hexvalue       |= Ascii2Hex(FileContent[Pos++]);
-                    IspEnvironment->BinaryContent[RealAddress + i] = Hexvalue;
-                }
-            }
-            else if(RecordType == 0x01)     // 01 - End of file record
-            {
-                break;
-            }
-            else if(RecordType == 0x02)     // 02 - Extended segment address record
-            {
-                for(i = 0; i < RecordLength * 2; i++)   // double amount of nibbles
-                {
-                    RealAddress <<= 4;
-                    if(i == 0)
-                    {
-                        RealAddress  = Ascii2Hex(FileContent[Pos++]);
-                    }
-                    else
-                    {
-                        RealAddress |= Ascii2Hex(FileContent[Pos++]);
-                    }
-                }
-                RealAddress <<= 4;
-            }
-            else if(RecordType == 0x03)     // 03 - Start segment address record
-            {
-                for(i = 0; i < RecordLength * 2; i++)   // double amount of nibbles
-                {
-                    RealAddress <<= 4;
-                    if(i == 0)
-                    {
-                        RealAddress  = Ascii2Hex(FileContent[Pos++]);
-                    }
-                    else
-                    {
-                        RealAddress |= Ascii2Hex(FileContent[Pos++]);
-                    }
-                }
-                RealAddress <<= 8;
-            }
-            else if(RecordType == 0x04)     // 04 - Extended linear address record, used by IAR
-            {
-                DebugPrintf( 1, "RecordType %02X not yet implemented - ignore ?\n", RecordType);
-                // exit(1);
-            }
-            else if(RecordType == 0x05)     // 05 - Start linear address record
-            {
-                DebugPrintf( 1, "RecordType %02X not yet implemented\n", RecordType);
-                exit(1);
-            }
-
-            while(FileContent[Pos++] != 0x0a)      // Search till line end
-            {
-            }
-        }
-
-        DebugPrintf( 2, "\tconverted to binary format...\n");
-
-            // When debugging is switched on, output result of conversion to file debugout.bin
-        if(debug_level >= 4)
-        {
-            int fdout;
-            fdout = open("debugout.bin", O_RDWR | O_BINARY | O_CREAT | O_TRUNC, 0777);
-            write(fdout, IspEnvironment->BinaryContent, IspEnvironment->BinaryLength);
-            close(fdout);
-        }
-    }
-    else
-    {
-        memcpy(IspEnvironment->BinaryContent, FileContent, FileLength);
-
-        IspEnvironment->BinaryLength = FileLength;
-    }
-
-    DebugPrintf( 2, "\timage size : %ld\n", IspEnvironment->BinaryLength);
-
-        // check length to flash for correct alignment, can happen with broken ld-scripts
-    if (IspEnvironment->BinaryLength % 4 != 0)
-    {
-        unsigned long NewBinaryLength = ((IspEnvironment->BinaryLength + 3)/4) * 4;
-
-        DebugPrintf( 2, "Warning:  data not aligned to 32 bits, padded (length was %lX, now %lX)\n", IspEnvironment->BinaryLength, NewBinaryLength);
-
-        IspEnvironment->BinaryLength = NewBinaryLength;
-    }
-
-}
-
-
-#define ANALOG_DEVICES_SYNC_CHAR        ((BINARY)0x08)
-#define ANALOG_DEVICES_SYNC_RESPONSE    ("ADuC")
-#define ANALOG_DEVICES_SYNC_SIZE        (strlen( ANALOG_DEVICES_SYNC_RESPONSE))
-
-typedef struct {
-    BINARY product_id[15];
-    BINARY version[3];
-    BINARY reserved[4];
-    BINARY terminator[2];
-    } AD_SYNC_RESPONSE;
-
-/***************************** AnalogDevicesSync ************************/
-/**  Attempt to synchronize with an Analog Device ARM micro.  Sends a
-backspace and reads back the microcontrollers response.  Performs
-multiple retries. Exits the program on error, returns to caller in the
-case of success.
-*/
-static void AnalogDevicesSync(ISP_ENVIRONMENT *IspEnvironment)
-{
-    BINARY sync;                        /* Holds sync command.          */
-    AD_SYNC_RESPONSE response;          /* Response from micro.         */
-    int sync_attempts;                  /* Number of retries.           */
-
-        /*  Make sure we don't read garbage later instead of the        */
-        /* response we expect from the micro.                           */
-    ClearSerialPortBuffers(IspEnvironment);
-
-    DebugPrintf( 2, "Synchronizing\n"); /* Progress report.             */
-
-    sync = ANALOG_DEVICES_SYNC_CHAR;    /* Build up sync command.       */
-
-        /*  Perform the actual sync attempt.  First send the sync       */
-        /* character, the attempt to read back the response.  For the   */
-        /* AD ARM micro this is a fixed length block.  If response is   */
-        /* received attempt to validate it by comparing the first       */
-        /* characters to those expected.  If the received block does    */
-        /* not validate or is incomplete empty the serial buffer and    */
-        /* retry.                                                       */
-    for(sync_attempts = 0; sync_attempts < 5; sync_attempts++)
-    {
-        SendComPortBlock( IspEnvironment, &sync, 1);
-
-        if( ReceiveComPortBlockComplete( IspEnvironment, &response, sizeof( response),
-            500) == 0)
-        {
-
-            if( memcmp( response.product_id, ANALOG_DEVICES_SYNC_RESPONSE,
-                ANALOG_DEVICES_SYNC_SIZE) == 0)
-            {
-                return;
-            }
-            else
-            {
-                DumpString( 3, &response, sizeof(response),
-                    "Unexpected response to sync attempt ");
-            }
-        }
-        else
-        {
-            DebugPrintf( 3, "No (or incomplete) answer on sync attempt\n");
-        }
-
-        ClearSerialPortBuffers(IspEnvironment);
-    }
-
-    DebugPrintf( 1, "No (or unacceptable) answer on sync attempt\n");
-    exit(4);
-}
-
-typedef struct {
-    char start1;
-    char start2;
-    BINARY bytes;
-    char cmd;
-    BINARY address_h;
-    BINARY address_u;
-    BINARY address_m;
-    BINARY address_l;
-    BINARY data[251];
-    } AD_PACKET;
-
-/***************************** AnalogDevicesFormPacket ******************/
-/**  Create an Analog Devices communication packet from the constituent
-elements.
-\param [in] cmd The command being sent, one of 'E' for erase, 'W' for
-write, 'V' for verify or 'R' for run..
-\param [in] no_bytes the number of data bytes to send with the command in
-the packet.
-\param [in] address the address to apply the command to.
-\param [in] data the data to send with the packet, may be null if no_bytes
-is zero.
-\param[out] packet that will be filled.
-*/
-static void AnalogDevicesFormPacket( ISP_ENVIRONMENT *IspEnvironment,
-                                     char cmd, int no_bytes, unsigned int address,
-                                     const void *data, AD_PACKET *packet)
-{
-    BINARY checksum;
-    const BINARY *data_in;
-    int i;
-
-    (void)IspEnvironment; /* never used in this function */
-
-        /*  Some sanity checking on the arguments.  These should only   */
-        /* fail if there is a bug in the caller.                        */
-        /*  Check 1) that the number of data bytes is in an acceptable  */
-        /* range, 2) that we have a non-null pointer if data is being   */
-        /* put in the packet and 3) that we have a non-null pointer to  */
-        /* the packet to be filled. We just exit with an error message  */
-        /* if any of these tests fail.                                  */
-    if( (no_bytes < 0) || (no_bytes > 250))
-    {
-        DebugPrintf( 1,
-            "The number of bytes (%d) passed to FormPacket is invalid.\n",
-            no_bytes);
-        exit( -1);
-    }
-    if( (data == 0) && (no_bytes != 0))
-    {
-        DebugPrintf( 1,
-            "A null pointer to data paased to FormPacket when data was expected.\n");
-        exit( -1);
-    }
-    if( packet == 0)
-    {
-        DebugPrintf( 1,
-            "A null packet pointer was passed to FormPacket.\n");
-        exit( -1);
-    }
-
-    checksum = 0;               /*  Checksum starts at zero.            */
-
-    data_in = data;             /*  Pointer pun so we can walk through  */
-                                /* the data.                            */
-
-    packet->start1 = 0x7;       /*  The start of the packet is constant.*/
-    packet->start2 = 0xE;
-
-        /*  Fill in the rest of the packet and calculate the checksum   */
-        /* as we go.                                                    */
-
-        /* The number of bytes is the number of data bytes + the        */
-        /* address bytes + the command byte.                            */
-    packet->bytes = (BINARY)(no_bytes + 5);
-
-    checksum += packet->bytes;
-
-        /*  The command for the packet being sent.  No error checking   */
-        /* done on this.                                                */
-    packet->cmd = cmd;
-
-    checksum += cmd;
-
-        /*  Now break up the address and place in the proper packet     */
-        /* locations.                                                   */
-    packet->address_l = (BINARY)(address & 0xFF);
-    packet->address_m = (BINARY)((address >> 8) & 0xFF);
-    packet->address_u = (BINARY)((address >> 16) & 0xFF);
-    packet->address_h = (BINARY)((address >> 24) & 0xFF);
-
-    checksum += packet->address_l;
-    checksum += packet->address_m;
-    checksum += packet->address_u;
-    checksum += packet->address_h;
-
-        /*  Copy the data bytes into the packet.  We could use memcpy   */
-        /* but we have to calculate the checksum anyway.                */
-    for( i = 0; i < no_bytes; i++)
-    {
-        packet->data[i] = data_in[i];
-        checksum += data_in[i];
-    }
-
-        /*  Finally, add the checksum to the end of the packet.         */
-    packet->data[i] = (BINARY)-checksum;
-}
-
-#define ANALOG_DEVICES_ACK      0x6
-#define ANALOG_DEVICES_NAK      0x7
-
-/***************************** AnalogDevicesSendPacket ******************/
-/**  Send a previously form Analog Devices communication.  Retry a
-couple of times if needed but fail by exiting the program if no ACK is
-forthcoming.
-\param [in] packet the packet to send.
-*/
-static void AnalogDevicesSendPacket( ISP_ENVIRONMENT *IspEnvironment,
-                                     const AD_PACKET * packet)
-{
-    BINARY response;
-    int retry = 0;
-
-    do {
-        retry++;
-
-                /*  Make sure we don't read garbage later instead of    */
-                /* the response we expect from the micro.               */
-        ClearSerialPortBuffers(IspEnvironment);
-
-                /*  Send the packet, the size is the number of data     */
-                /* bytes in the packet plus 3 bytes worth of header     */
-                /* plus checksum.                                       */
-        SendComPortBlock( IspEnvironment, packet, packet->bytes + 4);
-
-                /*  Receive the response and check, return to caller    */
-                /* if successful.                                       */
-        if( ReceiveComPortBlockComplete( IspEnvironment, &response, 1, 500) == 0)
-        {
-            if( response == ANALOG_DEVICES_ACK)
-            {
-                DebugPrintf( 3, "Packet Sent\n");
-                return;
-            }
-            if( response != ANALOG_DEVICES_NAK)
-            {
-                DebugPrintf( 3, "Unexpected response to packet (%x)\n", (int)response);
-            }
-            DebugPrintf( 2, "*");
-        }
-    } while( retry < 3);
-
-    DebugPrintf( 1, "Send packet failed\n");
-    exit( -1);
-}
-
-/***************************** AnalogDevicesErase ***********************/
-/**  Erase the Analog Devices micro.  We take the simple way out and
-just erase the whole thing.
-*/
-static void AnalogDevicesErase(ISP_ENVIRONMENT *IspEnvironment)
-{
-    BINARY pages;
-    AD_PACKET packet;
-
-    pages = 0;
-    DebugPrintf( 2, "Erasing .. ");
-    AnalogDevicesFormPacket( IspEnvironment, 'E', 1, 0, &pages, &packet);
-    AnalogDevicesSendPacket( IspEnvironment, &packet);
-    DebugPrintf( 2, "Erased\n");
-}
-
-#define AD_PACKET_SIZE (250)
-
-/***************************** AnalogDevicesWrite ***********************/
-/**  Write the program.
-\param [in] data the program to download to the micro.
-\param [in] address where to start placing the program.
-\param [in] bytes the size of the progrm to download.
-*/
-static void AnalogDevicesWrite( ISP_ENVIRONMENT *IspEnvironment,
-                                const void *data, long address, size_t bytes)
-{
-    AD_PACKET packet;
-    const BINARY *prog_data;
-
-    DebugPrintf( 2, "Writing %d bytes ", bytes);
-    prog_data = data;
-    while( bytes > AD_PACKET_SIZE)
-    {
-        AnalogDevicesFormPacket( IspEnvironment, 'W', AD_PACKET_SIZE, address, prog_data, &packet);
-        AnalogDevicesSendPacket( IspEnvironment, &packet);
-        address += AD_PACKET_SIZE;
-        prog_data += AD_PACKET_SIZE;
-        bytes -= AD_PACKET_SIZE;
-        DebugPrintf( 2, ".");
-    }
-    if( bytes > 0)
-    {
-        AnalogDevicesFormPacket( IspEnvironment, 'W', bytes, address, prog_data, &packet);
-        AnalogDevicesSendPacket( IspEnvironment, &packet);
-        DebugPrintf( 2, ".");
-    }
-}
-
-/***************************** AnalogDevicesDownload ********************/
-/**  Perform the download into an Analog Devices micro.  As a quick and
- * dirty hack against flash relocations at 0x80000
- * \return 0 if ok, error code else
- * \ToDo: possible to implement the return value instead of calling
- * exit() in sub-functions
- */
-static int AnalogDevicesDownload(ISP_ENVIRONMENT *IspEnvironment)
-{
-    AnalogDevicesSync(IspEnvironment);
-    AnalogDevicesErase(IspEnvironment);
-    if( IspEnvironment->BinaryLength > 0x80000)
-    {
-        DebugPrintf( 2, "Note:  Flash remapped 0x80000 to 0.\n");
-        AnalogDevicesWrite( IspEnvironment, IspEnvironment->BinaryContent + 0x80000, 0, IspEnvironment->BinaryLength-0x80000);
-    }
-    else
-    {
-        AnalogDevicesWrite( IspEnvironment, IspEnvironment->BinaryContent, 0, IspEnvironment->BinaryLength);
-    }
-    return(0);
-}
-
-/* note -- need to rationalize timeouts, use define?
-similarly for the number of sync attempts
-*/
-
-#endif // !defined COMPILE_FOR_LPC21
-
-
-static int SendAndVerify(ISP_ENVIRONMENT *IspEnvironment, const char *Command,
-                         char *AnswerBuffer, int AnswerLength)
-{
-    unsigned long realsize;
-    int cmdlen;
-
-    SendComPort( IspEnvironment, Command);
-    ReceiveComPort( IspEnvironment, AnswerBuffer, AnswerLength-1, &realsize, 2, 5000);
-    cmdlen = strlen(Command);
-    return (strncmp(AnswerBuffer, Command, cmdlen) == 0
-            && strcmp(AnswerBuffer + cmdlen, "0\r\n") == 0);
-}
-
-/***************************** Download *********************************/
-/**  Download the file from the internal memory image to the philips microcontroller.
- *   This function is visible from outside if COMPILE_FOR_LPC21
- */
-#define LPC_RAMBASE     0x40000200L
-#if !defined COMPILE_FOR_LPC21
-static
-#endif
-int PhilipsDownload(ISP_ENVIRONMENT *IspEnvironment)
-{
-    unsigned long realsize;
-    char Answer[128];
-    char temp[128];
-    char *strippedAnswer, *endPtr;
-    int  strippedsize;
-    int nQuestionMarks;
-    int found;
-    unsigned long Sector;
-    unsigned long SectorLength;
-    unsigned long SectorStart, SectorOffset, SectorChunk;
-    char tmpString[128];
-    char uuencode_table[64];
-    int Line;
-    unsigned long tmpStringPos;
-    unsigned long BlockOffset;
-    unsigned long Block;
-    unsigned long Pos;
-    unsigned long CopyLength;
-    int c,k=0,i;
-    unsigned long ivt_CRC;          // CRC over interrupt vector table
-    unsigned long block_CRC;
-    time_t tStartUpload, tDoneUpload;
-    long WatchDogSeconds = 0;
-    int WaitForWatchDog = 0;
-
-    if(!IspEnvironment->DetectOnly)
-    {
-            // Build up uuencode table
-        uuencode_table[0] = 0x60;           // 0x20 is translated to 0x60 !
-
-        for(i = 1; i <= 64; i++)
-        {
-            uuencode_table[i] = (char)(0x20 + i);
-        }
-
-            // Patch 0x14, otherwise it is not running and jumps to boot mode
-
-        ivt_CRC = 0;
-
-            /* Clear the vector at 0x14 so it doesn't affect the checksum: */
-        for(i = 0; i < 4; i++)
-        {
-            IspEnvironment->BinaryContent[i + 0x14] = 0;
-        }
-            /* Calculate a native checksum of the little endian vector table: */
-        for(i = 0; i < (4 * 8);) {
-            ivt_CRC += IspEnvironment->BinaryContent[i++];
-            ivt_CRC += IspEnvironment->BinaryContent[i++] << 8;
-            ivt_CRC += IspEnvironment->BinaryContent[i++] << 16;
-            ivt_CRC += IspEnvironment->BinaryContent[i++] << 24;
-        }
-
-            /* Negate the result and place in the vector at 0x14 as little endian
-             * again. The resulting vector table should checksum to 0. */
-        ivt_CRC = (unsigned long)-ivt_CRC;
-        for(i = 0; i < 4; i++)
-        {
-            IspEnvironment->BinaryContent[i + 0x14] = (unsigned char)(ivt_CRC >> (8 * i));
-        }
-
-        DebugPrintf( 3, "Position 0x14 patched: ivt_CRC = 0x%08lX\n", ivt_CRC);
-    }
-
-    DebugPrintf( 2, "Synchronizing");
-
-    for(nQuestionMarks = found = 0; !found && nQuestionMarks < 100; nQuestionMarks++)
-    {
-               DebugPrintf( 2, ".");
-        SendComPort( IspEnvironment, "?");
-
-        memset(Answer,0,sizeof(Answer));
-        ReceiveComPort( IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 1,100);
-
-        strippedAnswer = Answer;
-        strippedsize = realsize;
-        while((strippedsize > 0) && ((*strippedAnswer == '?') || (*strippedAnswer == 0)))
-        {
-            strippedAnswer++;
-            strippedsize--;
-        }
-
-        DumpString( 3, strippedAnswer, strippedsize, "StrippedAnswer(Length=%ld): '", strippedsize);
-
-        if(strcmp(strippedAnswer, "Bootloader\r\n") == 0 && IspEnvironment->TerminalOnly == 0)
-        {
-            long chars, xtal;
-            unsigned long ticks;
-            chars = (17 * IspEnvironment->BinaryLength + 1) / 10;
-            WatchDogSeconds = (10 * chars + 5) / atol(IspEnvironment->baud_rate) + 10;
-            xtal = atol(IspEnvironment->StringOscillator) * 1000;
-            ticks = (unsigned long)WatchDogSeconds * ((xtal + 15) / 16);
-            DebugPrintf( 2, "Entering ISP; re-synchronizing (watchdog = %ld seconds)\n", WatchDogSeconds);
-            sprintf(temp, "T %lu\r\n", ticks);
-            SendComPort( IspEnvironment, temp);
-            ReceiveComPort( IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 1,100);
-            if(strcmp(Answer, "OK\r\n") != 0)
-            {
-                printf("No answer on 'watchdog timer set'\n");
-                return(4);
-            }
-            SendComPort( IspEnvironment, "G 10356\r\n");
-            Sleep(200);
-            nQuestionMarks = 0;
-            WaitForWatchDog = 1;
-            continue;
-        }
-
-        tStartUpload = time(NULL);
-        if(strcmp(strippedAnswer, "Synchronized\r\n") == 0)
-        {
-            found = 1;
-        }
-#if !defined COMPILE_FOR_LPC21
-        else
-        {
-            ResetTarget(IspEnvironment, PROGRAM_MODE );
-        }
-#endif
-    }
-
-    if(!found)
-    {
-        DebugPrintf( 1, " no answer on '?'\n");
-        return(4);
-    }
-
-    DebugPrintf( 2, " OK\n");
-
-    SendComPort( IspEnvironment, "Synchronized\r\n");
-
-    ReceiveComPort( IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 2,1000);
-
-    if(strcmp(Answer, "Synchronized\r\nOK\r\n") != 0)
-    {
-        DebugPrintf( 1, "No answer on 'Synchronized'\n");
-        return(4);
-    }
-
-    DebugPrintf( 3, "Synchronized 1\n");
-
-    DebugPrintf( 3, "Setting oscillator\n");
-
-    sprintf( temp, "%s\r\n", IspEnvironment->StringOscillator);
-    SendComPort( IspEnvironment, temp);
-
-    ReceiveComPort( IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 2,1000);
-
-    sprintf( temp, "%s\r\nOK\r\n", IspEnvironment->StringOscillator);
-
-    if(strcmp(Answer, temp) != 0)
-    {
-        DebugPrintf( 1, "No answer on Oscillator-Command\n");
-        return(4);
-    }
-
-    DebugPrintf( 3, "Unlock\n");
-
-    if (!SendAndVerify(IspEnvironment, "U 23130\r\n", Answer, sizeof Answer))
-    {
-        DebugPrintf( 1, "Unlock-Command:\n");
-        PhilipsOutputErrorMessage(GetErrorNumber(Answer));
-        return(4);
-    }
-
-    DebugPrintf( 2, "Read bootcode version: ");
-
-    SendComPort( IspEnvironment, "K\r\n");
-
-    ReceiveComPort( IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 4,5000);
-
-    if(strncmp(Answer, "K\r\n", 3) != 0)
-    {
-        DebugPrintf( 1, "no answer on Read Boot Code Version\n");
-        return(4);
-    }
-
-    if(strncmp(Answer, "K\r\n0\r\n", 6) == 0)
-    {
-        int maj, min, build;
-        strippedAnswer = Answer + 6;
-        if (sscanf(strippedAnswer, "%d %d %d", &build, &min, &maj) == 2) {
-            maj = min;
-            min = build;
-            build = 0;
-        } /* if */
-        DebugPrintf( 2, "%d.%d.%d\n", maj, min, build);
-    }
-    else
-    {
-        DebugPrintf( 2, "unknown\n");
-    }
-
-    DebugPrintf( 2, "Read part ID: ");
-    SendComPort( IspEnvironment, "J\r\n");
-
-    ReceiveComPort( IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 3,5000);
-
-    if(strncmp(Answer, "J\r\n", 3) != 0)
-    {
-        DebugPrintf( 1, "no answer on Read Part Id\n");
-        return(4);
-    }
-
-    strippedAnswer = (strncmp(Answer, "J\r\n0\r\n", 6) == 0) ? Answer + 6 : Answer;
-    Pos = strtoul(strippedAnswer, &endPtr, 10);
-    *endPtr = '\0'; /* delete \r\n */
-    for (i = sizeof LPCtypes / sizeof LPCtypes[0] - 1; i > 0 && LPCtypes[i].id != Pos; i--)
-        /* nothing */;
-    IspEnvironment->DetectedDevice = i;
-    if (IspEnvironment->DetectedDevice == 0)
-        DebugPrintf( 2, "unknown");
-    else
-        DebugPrintf( 2, "LPC%d, %d kiB ROM / %d kiB SRAM",
-                        LPCtypes[IspEnvironment->DetectedDevice].Product,
-                        LPCtypes[IspEnvironment->DetectedDevice].FlashSize,
-                        LPCtypes[IspEnvironment->DetectedDevice].RAMSize);
-    DebugPrintf( 2, " (%s)\n", strippedAnswer);
-
-    if (IspEnvironment->DetectOnly)
-        return(0);
-
-    for(SectorStart = Sector = 0; ; SectorStart += LPCtypes[IspEnvironment->DetectedDevice].SectorTable[Sector++])
-    {
-        if (Sector >= LPCtypes[IspEnvironment->DetectedDevice].FlashSectors)
-        {
-            DebugPrintf( 1, "Programm too large; running out of Flash sectors.\n");
-            return(4);
-        }
-
-        DebugPrintf(2, "Sector %ld: ", Sector);
-        fflush(stdout);
-
-        sprintf(tmpString, "P %ld %ld\r\n", Sector, Sector);
-        if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))
-        {
-            DebugPrintf( 1, "Wrong answer on Prepare-Command (1) (Sector %ld)\n", Sector);
-            PhilipsOutputErrorMessage(GetErrorNumber(Answer));
-            return(4);
-        }
-
-        DebugPrintf( 2, ".");
-        fflush(stdout);
-
-        sprintf(tmpString, "E %ld %ld\r\n", Sector, Sector);
-        if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))
-        {
-            DebugPrintf( 1, "Wrong answer on Erase-Command (Sector %ld)\n", Sector);
-            PhilipsOutputErrorMessage(GetErrorNumber(Answer));
-            return(4);
-        }
-
-        DebugPrintf( 2, ".");
-        fflush(stdout);
-
-        SectorLength = LPCtypes[IspEnvironment->DetectedDevice].SectorTable[Sector];
-        if(SectorLength > IspEnvironment->BinaryLength - SectorStart)
-        {
-            SectorLength = IspEnvironment->BinaryLength - SectorStart;
-        }
-
-        for(SectorOffset = 0; SectorOffset < SectorLength; SectorOffset += SectorChunk)
-        {
-                       if (SectorOffset > 0)
-                       {
-                               // Add a visible marker between segments in a sector
-                DebugPrintf(2, "|");  /* means: partial segment copied */
-                fflush(stdout);
-                       }
-
-                // If the Flash ROM sector size is bigger than the number of bytes
-                // we can copy from RAM to Flash, we must "chop up" the sector and
-                // copy these individually.
-                // This is especially needed in the case where a Flash sector is
-                // bigger than the amount of SRAM.
-            SectorChunk = SectorLength - SectorOffset;
-            if(SectorChunk > (unsigned)LPCtypes[IspEnvironment->DetectedDevice].MaxCopySize)
-            {
-                SectorChunk = LPCtypes[IspEnvironment->DetectedDevice].MaxCopySize;
-            }
-
-                // Write multiple of 45 * 4 Byte blocks to RAM, but copy maximum of on sector to Flash
-                // In worst case we transfer up to 180 byte to much to RAM
-                // but then we can always use full 45 byte blocks and length is multiple of 4
-            CopyLength = SectorChunk;
-            if((CopyLength % (45 * 4)) != 0)
-            {
-                CopyLength += ((45 * 4) - (CopyLength % (45 * 4)));
-            }
-            sprintf(tmpString, "W %ld %ld\r\n", LPC_RAMBASE, CopyLength);
-            if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))
-            {
-                DebugPrintf( 1, "Wrong answer on Write-Command\n");
-                PhilipsOutputErrorMessage(GetErrorNumber(Answer));
-                return(4);
-            }
-
-            DebugPrintf( 2, ".");
-            fflush(stdout);
-
-            block_CRC = 0;
-            Line = 0;
-
-                // Transfer blocks of 45 * 4 bytes to RAM
-            for(Pos = SectorStart + SectorOffset; (Pos < SectorStart + SectorOffset + CopyLength) && (Pos < IspEnvironment->BinaryLength); Pos += (45 * 4))
-            {
-                for(Block = 0; Block < 4; Block++)  // Each block 45 bytes
-                {
-                    DebugPrintf( 2, ".");
-                    fflush(stdout);
-
-                        // Uuencode one 45 byte block
-                    tmpStringPos = 0;
-
-                    tmpString[tmpStringPos++] = (char)(' ' + 45);  // Encode Length of block
-
-                    for(BlockOffset = 0; BlockOffset < 45; BlockOffset++)
-                    {
-                        c = IspEnvironment->BinaryContent[Pos + Block * 45 + BlockOffset];
-
-                        block_CRC += c;
-
-                        k = (k << 8) + (c & 255);
-
-                        if((BlockOffset % 3) == 2)   // Collecting always 3 Bytes, then do processing in 4 Bytes
-                        {
-                            tmpString[tmpStringPos++] = uuencode_table[(k >> 18) & 63];
-                            tmpString[tmpStringPos++] = uuencode_table[(k >> 12) & 63];
-                            tmpString[tmpStringPos++] = uuencode_table[(k >>  6) & 63];
-                            tmpString[tmpStringPos++] = uuencode_table[ k        & 63];
-                        }
-                    }
-
-                    tmpString[tmpStringPos++] = '\r';
-                    tmpString[tmpStringPos++] = '\n';
-                    tmpString[tmpStringPos++] = 0;
-
-                    SendComPort( IspEnvironment, tmpString);
-
-                    ReceiveComPort( IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 1,5000);
-
-                    if(strncmp(Answer, tmpString, tmpStringPos) != 0)
-                    {
-                        DebugPrintf( 1, "Error on writing data (1)\n");
-                        return(4);
-                    }
-
-                    Line++;
-
-                    DebugPrintf( 3, "Line = %d\n", Line);
-
-                    if(Line == 20)
-                    {
-                            // printf("block_CRC = %ld\n", block_CRC);
-
-                        sprintf(tmpString, "%ld\r\n", block_CRC);
-                        SendComPort( IspEnvironment, tmpString);
-
-                        ReceiveComPort( IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 2,5000);
-
-                        sprintf(tmpString, "%ld\r\nOK\r\n", block_CRC);
-                        if(strcmp(Answer, tmpString) != 0)
-                        {
-                            DebugPrintf( 1, "Error on writing block_CRC (1)\n");
-                            return(4);
-                        }
-
-                        Line = 0;
-                        block_CRC = 0;
-                    }
-                }
-            }
-
-            if(Line != 0)
-            {
-                sprintf(tmpString, "%ld\r\n", block_CRC);
-                SendComPort( IspEnvironment, tmpString);
-
-                ReceiveComPort( IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 2,5000);
-
-                sprintf(tmpString, "%ld\r\nOK\r\n", block_CRC);
-                if(strcmp(Answer, tmpString) != 0)
-                {
-                    DebugPrintf( 1, "Error on writing block_CRC (2)\n");
-                    return(4);
-                }
-            }
-
-                // Prepare command must be repeated before every write
-            sprintf(tmpString, "P %ld %ld\r\n", Sector, Sector);
-            if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))
-            {
-                DebugPrintf( 1, "Wrong answer on Prepare-Command (2) (Sector %ld)\n", Sector);
-                PhilipsOutputErrorMessage(GetErrorNumber(Answer));
-                return(4);
-            }
-
-               // Round CopyLength up to one of the following values: 512, 1024,
-               // 4096, 8192; but do not exceed the maximum copy size (usually
-               // 8192, but chip-dependent)
-            if(CopyLength < 512)
-            {
-                CopyLength = 512;
-            }
-            else if(SectorLength < 1024)
-            {
-                CopyLength = 1024;
-            }
-            else if(SectorLength < 4096)
-            {
-                CopyLength = 4096;
-            }
-            else
-            {
-                CopyLength = 8192;
-            }
-            if(CopyLength > (unsigned)LPCtypes[IspEnvironment->DetectedDevice].MaxCopySize)
-            {
-                CopyLength = LPCtypes[IspEnvironment->DetectedDevice].MaxCopySize;
-            }
-
-            sprintf(tmpString, "C %ld %ld %ld\r\n", SectorStart + SectorOffset, LPC_RAMBASE, CopyLength);
-            if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))
-            {
-                DebugPrintf( 1, "Wrong answer on Write-Command\n");
-                PhilipsOutputErrorMessage(GetErrorNumber(Answer));
-                return(4);
-            }
-
-        }
-
-        DebugPrintf(2, "\n");
-        fflush(stdout);
-
-        if((SectorStart + SectorLength) >= IspEnvironment->BinaryLength)
-        {
-            break;
-        }
-    }
-
-    tDoneUpload = time(NULL);
-    DebugPrintf( 2, "Download Finished... taking %d seconds\n", tDoneUpload - tStartUpload);
-
-    if (WaitForWatchDog)
-    {
-        DebugPrintf( 2, "Wait for restart, in %d seconds from now\n", WatchDogSeconds - (tDoneUpload - tStartUpload));
-    }
-    else
-    {
-        DebugPrintf( 2, "Now launching the brand new code\n" );
-        fflush(stdout);
-
-        SendComPort(IspEnvironment, "G 0 A\r\n"); //goto 0 : run this fresh new downloaded code code
-        ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 2, 5000);
-        /* the reply string is frequently terminated with a -1 (EOF) because the
-         * connection gets broken; zero-terminate the string ourselves
-         */
-        while (realsize > 0 && Answer[(int)realsize - 1] < 0)
-            realsize--;
-        Answer[(int)realsize] = '\0';
-        /* Better to check only the first 9 chars instead of complete receive buffer,
-         * because the answer can contain the output by the started programm
-         */
-        if(realsize == 0 || strncmp((const char *)Answer, "G 0 A\r\n0\r", 9) != 0)
-        {
-            DebugPrintf( 2, "Failed to run the new downloaded code: ");
-            PhilipsOutputErrorMessage(GetErrorNumber(Answer));
-            return(4);
-        }
-        fflush(stdout);
-    }
-    return(0);
-}
-
-
-#if !defined COMPILE_FOR_LPC21
-/***************************** Terminal *********************************/
-/**  Acts as a simple dumb terminal. Press 'ESC' to exit.
-*/
-static void Terminal( ISP_ENVIRONMENT *IspEnvironment)
-{
-    int           ch = 0;
-    char buffer[128];
-    int           fdlogfile = -1;
-    unsigned long realsize;
-
-        // When logging is switched on, output terminal output to lpc21isp.log
-    if(IspEnvironment->LogFile)
-    {
-        fdlogfile = open("lpc21isp.log", O_RDWR | O_BINARY | O_CREAT | O_TRUNC, 0777);
-    }
-
-    printf("Terminal started (press Escape to abort)\n\n");
-    fflush(stdout);
-
-    do
-    {
-            // Check for received characters
-
-        ReceiveComPort( IspEnvironment, buffer, sizeof(buffer) - 1, &realsize, 0,200);
-
-        if( realsize )
-        {
-            write(1, buffer, realsize);
-            fflush(stdout);
-            if(IspEnvironment->LogFile)     // When logging is turned on, then copy output to logfile
-            {
-                write(fdlogfile, buffer, realsize);
-            }
-        }
-
-            // check for keypress, and write any out the port.
-        if ( kbhit() )
-        {
-            ch = getch();
-            if(ch == 0x1b)
-            {
-                break;
-            }
-
-            buffer[0] = (unsigned char)ch;
-            buffer[1] = 0;
-
-            SendComPort( IspEnvironment, buffer);
-        }
-    } while(ch != 0x1b);
-
-    printf("\n\nTerminal stopped\n\n");
-    fflush(stdout);
-
-    if(IspEnvironment->LogFile)
-    {
-        close(fdlogfile);
-    }
-
-}
-
-#endif // !defined COMPILE_FOR_LPC21
-
-/***************************** main *************************************/
-/**  main. Everything starts from here.
-\param [in] argc the number of arguments.
-\param [in] argv an array of pointers to the arguments.
-*/
-
-#if !defined COMPILE_FOR_LPC21
-
-int main(int argc, char *argv[])
-{
-    ISP_ENVIRONMENT IspEnvironment;
-    int downloadResult = -1;
-
-        // Initialize debug level
-    debug_level = 2;
-
-        // Initialize ISP Environment
-    IspEnvironment.micro = PHILIPS_ARM;          /**< The type of micro that will be */
-                                                 /* programmed.                      */
-    IspEnvironment.TerminalAfterUpload = 0;
-    IspEnvironment.TerminalOnly = 0;
-    IspEnvironment.DetectOnly = 0;
-    IspEnvironment.DetectedDevice = 0;          /* index in LPCtypes[] */
-    IspEnvironment.FormatHex = 1;
-    IspEnvironment.ControlLines = 0;
-    IspEnvironment.LogFile = 0;
-
-        /* Read and parse the command line.                             */
-    ReadArguments( &IspEnvironment, argc, argv);
-       DebugPrintf( 2, "lpc21isp version " VERSION_STR "\n");
-
-        /* Download requested, read in the input file.                  */
-    if(!IspEnvironment.TerminalOnly && !IspEnvironment.DetectOnly)
-    {
-        LoadFile(&IspEnvironment);
-    }
-
-    OpenSerialPort(&IspEnvironment);   /* Open the serial port to the microcontroller. */
-
-    ResetTarget(&IspEnvironment, PROGRAM_MODE);
-
-    ClearSerialPortBuffers(&IspEnvironment);
-
-
-        /* Perform the requested download.                              */
-    if(!IspEnvironment.TerminalOnly)
-    {
-        switch( IspEnvironment.micro)
-        {
-            case PHILIPS_ARM:
-                downloadResult = PhilipsDownload(&IspEnvironment);
-                break;
-
-            case ANALOG_DEVICES_ARM:
-                downloadResult = AnalogDevicesDownload(&IspEnvironment);
-                break;
-        }
-        if( downloadResult != 0 )
-        {
-            CloseSerialPort(&IspEnvironment);
-            exit(downloadResult);
-        }
-    }
-
-    ResetTarget(&IspEnvironment, RUN_MODE);
-
-    IspEnvironment.debug_level = 1;    /* From now on there is no more debug output !! */
-                                       /* Therefore switch it off...                   */
-
-        /* User asked for terminal emulation, provide a really dumb     */
-        /* terminal.                                                    */
-    if(IspEnvironment.TerminalAfterUpload || IspEnvironment.TerminalOnly)
-    {
-        Terminal(&IspEnvironment);
-    }
-
-    CloseSerialPort(&IspEnvironment);  /*  All done, close the serial port to the      */
-    return(0);                         /* microcontroller and exit.                    */
-}
-
-#endif // !defined COMPILE_FOR_LPC21
-
-/***************************** DumpString ******************************/
-/**  Prints an area of memory to stdout. Converts non-printables to hex.
-\param [in] level the debug level of the block to be dumped.  If this is
-less than or equal to the current debug level than the dump will happen
-otherwise this just returns.
-\param [in] b pointer to an area of memory.
-\param [in] size the length of the memory block to print.
-\param [in] fmt a printf style format string used to produce a prefix to
-the block of dumped memory.
-\param [in] ... the arguments referenced by the fmt string.
-*/
-static void DumpString(int level, const void *b, size_t size, const char *fmt, ...)
-{
-    size_t i;
-    const char *s;
-    va_list ap;
-
-    if( level <= debug_level)
-    {
-        va_start( ap, fmt);
-        vprintf( fmt, ap);
-        va_end( ap);
-
-        s = b;
-
-        printf("'");
-        for( i = 0; i < size; i++)
-            {
-            if(s[i] >= 0x20 && s[i] <= 0x7e) /*isprint?*/
-            {
-                putchar(s[i]);
-            }
-            else
-            {
-                printf("(%02X)", s[i]);
-            }
-        }
-        printf("'\n");
-    }
-
-}
-
-
-#if !defined COMPILE_FOR_LPC21
-/***************************** Ascii2Hex ********************************/
-/**  Converts a hex character to its equivalent number value. In case of an
-error rather abruptly terminates the program.
-\param [in] c the hex digit to convert.
-\return the value of the hex digit.
-*/
-static unsigned char Ascii2Hex(unsigned char c)
-{
-    if(c >= '0' && c <= '9')
-    {
-        return(unsigned char)(c - '0');
-    }
-    if(c >= 'A' && c <= 'F')
-    {
-        return(unsigned char)(c - 'A' + 10);
-    }
-    if(c >= 'a' && c <= 'f')
-    {
-        return(unsigned char)(c - 'a' + 10);
-    }
-    printf("Wrong Hex-Nibble %c (%02X)\n", c, c);
-    exit(1);
-    return(0);  // this "return" will never be reached, but some compilers give a warning if it is not present
-}
-#endif // !defined COMPILE_FOR_LPC21
-
-
-/***************************** PhilipsOutputErrorMessage ***********************/
-/**  Given an error number find and print the appropriate error message.
-\param [in] ErrorNumber The number of the error.
-*/
-static void PhilipsOutputErrorMessage(unsigned char ErrorNumber)
-{
-//#if !defined COMPILE_FOR_LPC21
-    switch(ErrorNumber)
-    {
-        case   0:
-            DebugPrintf( 1, "CMD_SUCCESS");
-            break;
-
-        case   1:
-            DebugPrintf( 1, "INVALID_COMMAND");
-            break;
-
-        case   2:
-            DebugPrintf( 1, "SRC_ADDR_ERROR: Source address is not on word boundary.");
-            break;
-        case   3:
-            DebugPrintf( 1, "DST_ADDR_ERROR: Destination address is not on a correct boundary.");
-            break;
-
-        case   4:
-            DebugPrintf( 1, "SRC_ADDR_NOT_MAPPED: Source address is not mapped in the memory map.\n");
-            DebugPrintf( 1, "                     Count value is taken into consideration where applicable.");
-            break;
-
-        case   5:
-            DebugPrintf( 1, "DST_ADDR_NOT_MAPPED: Destination address is not mapped in the memory map.\n");
-            DebugPrintf( 1, "                     Count value is taken into consideration where applicable.");
-            break;
-
-        case   6:
-            DebugPrintf( 1, "COUNT_ERROR: Byte count is not multiple of 4 or is not a permitted value.");
-            break;
-
-        case   7:
-            DebugPrintf( 1, "INVALID_SECTOR: Sector number is invalid or end sector number is\n");
-            DebugPrintf( 1, "                greater than start sector number.");
-            break;
-
-        case   8:
-            DebugPrintf( 1, "SECTOR_NOT_BLANK");
-            break;
-
-        case   9:
-            DebugPrintf( 1, "SECTOR_NOT_PREPARED_FOR_WRITE_OPERATION:\n");
-            DebugPrintf( 1, "Command to prepare sector for write operation was not executed.");
-            break;
-
-        case  10:
-            DebugPrintf( 1, "COMPARE_ERROR: Source and destination data not equal.");
-            break;
-
-        case  11:
-            DebugPrintf( 1, "BUSY: Flash programming hardware interface is busy.");
-            break;
-
-        case  12:
-            DebugPrintf( 1, "PARAM_ERROR: Insufficient number of parameters or invalid parameter.");
-            break;
-
-        case  13:
-            DebugPrintf( 1, "ADDR_ERROR: Address is not on word boundary.");
-            break;
-
-        case  14:
-            DebugPrintf( 1, "ADDR_NOT_MAPPED: Address is not mapped in the memory map.\n");
-            DebugPrintf( 1, "                 Count value is taken in to consideration where applicable.");
-            break;
-
-        case  15:
-            DebugPrintf( 1, "CMD_LOCKED");
-            break;
-
-        case  16:
-            DebugPrintf( 1, "INVALID_CODE: Unlock code is invalid.");
-            break;
-
-        case  17:
-            DebugPrintf( 1, "INVALID_BAUD_RATE: Invalid baud rate setting.");
-            break;
-
-        case  18:
-            DebugPrintf( 1, "INVALID_STOP_BIT: Invalid stop bit setting.");
-            break;
-
-        case 255:                                                                                            break;
-        default:
-            DebugPrintf( 1, "unknown error %u", ErrorNumber);
-            break;
-    }
-//#else // !defined COMPILE_FOR_LPC21
-//    printf("error %u", ErrorNumber);
-//#endif // !defined COMPILE_FOR_LPC21
-}
-
-
-/***************************** GetErrorNumber ***************************/
-/**  Find error number in string.  This will normally be the string
-returned from the microcontroller.
-\param [in] Answer the buffer to search for the error number.
-\return the error number found, if no linefeed found before the end of the
-string an error value of 255 is returned. If a non-numeric value is found
-then it is printed to stdout and an error value of 255 is returned.
-*/
-static unsigned char GetErrorNumber(const char *Answer)
-{
-    unsigned int i = 0;
-
-    while(1)
-    {
-        if(Answer[i] == 0x00) return(255);
-        if(Answer[i] == 0x0a) break;
-        i++;
-    }
-
-    i++;
-
-    if(Answer[i] < '0' || Answer[i] > '9')
-    {
-        DebugPrintf( 1, "ErrorString: %s", &Answer[i]);
-        return(255);
-    }
-
-    return (unsigned char)(atoi(&Answer[i]));
-}
+/******************************************************************************\r
+\r
+Project:           Portable command line ISP for Philips LPC2000 family\r
+                   and Analog Devices ADUC70xx\r
+\r
+Filename:          lpc21isp.c\r
+\r
+Compiler:          Microsoft VC 6/7, GCC Cygwin, GCC Linux, GCC ARM ELF\r
+\r
+Author:            Martin Maurer (Martin.Maurer@clibb.de)\r
+\r
+Copyright:         (c) Martin Maurer 2003-2008, All rights reserved\r
+Portions Copyright (c) by Aeolus Development 2004 http://www.aeolusdevelopment.com\r
+\r
+    This file is part of lpc21isp.\r
+\r
+    lpc21isp is free software: you can redistribute it and/or modify\r
+    it under the terms of the GNU Lesser General Public License as published by\r
+    the Free Software Foundation, either version 3 of the License, or\r
+    any later version.\r
+\r
+    lpc21isp is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+    GNU Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public License\r
+    and GNU General Public License along with lpc21isp.\r
+    If not, see <http://www.gnu.org/licenses/>.\r
+*/\r
+\r
+#if defined(_WIN32)\r
+#if !defined __BORLANDC__\r
+#include "StdAfx.h"        // Precompiled Header for WIN32\r
+#endif\r
+#endif // defined(_WIN32)\r
+#include "lpc21isp.h"   // if using propriatory serial port communication (customize attached lpc21isp.h)\r
+#include "adprog.h"\r
+#include "lpcprog.h"\r
+#include "lpcterm.h"\r
+\r
+/*\r
+Change-History:\r
+\r
+1.00  2004-01-08  Initial Version, tested for MSVC6/7 and GCC under Cygwin\r
+1.01  2004-01-10  Porting to Linux (at least compiling must work)\r
+1.02  2004-01-10  Implemented conversion intel hex format -> binary\r
+1.03  2004-01-25  Preparation to upload to public website\r
+1.04  2004-02-12  Merged in bugfixes by Soeren Gust\r
+1.05  2004-03-14  Implement printing of error codes as text / strings\r
+1.06  2004-03-09  Merged in bugfixes by Charles Manning:\r
+                  The '?' sychronisation does not reliably respond to the first '?'.\r
+                  I added some retries.\r
+                  The LPC2106 sometimes responds to the '?' by echoing them back.\r
+                  This sometimes causes an attempt to match "?Synchonized".\r
+                  Added code to strip off any leading '?'s.\r
+                  Timeouts were too long.\r
+                  Change from RTS/CTS to no flow control.\r
+                  Done because many/most people will use only 3-wire comms.\r
+                  Added some progress tracing.\r
+1.07  2004-03-14  Implement handling of control lines for easier booting\r
+1.08  2004-04-01  Bugfix for upload problem\r
+1.09  2004-04-03  Redesign of upload routine\r
+                  Now always 180 byte blocks are uploaded, to prevent\r
+                  small junks in uuencoding\r
+1.10  2004-04-03  Clear buffers before sending commands to LPC21xx,\r
+                  this prevents synchronizing errors when previously loaded\r
+                  program does a lot of output, so FIFO of PC runs full\r
+1.11  2004-04-03  Small optimization for controlling reset line\r
+                  otherwise termonly starts LPC twice, free PC buffers\r
+1.12  2004-04-04  Add switch to enable logging terminal output to lpc21isp.log\r
+1.13  2004-05-19  Merged in improvement by Charles Manning:\r
+                  Instead of exiting the wrong hex file size is corrected\r
+1.14  2004-07-07  Merged in improvement by Alex Holden:\r
+                  Remove little/big endian dependancy\r
+1.15  2004-09-27  Temporary improvement by Cyril Holweck:\r
+                  Removed test (data echoed = data transmited) on the main\r
+                  data transfert, since this was the biggest failure\r
+                  reason and is covered by checksome anyway.\r
+                  Added COMPILE_FOR_LPC21, to have target dump it's own\r
+                  memory to stdout.\r
+1.16  2004-10-09  Merged in bugfix / improvement by Sinelnikov Evgeny\r
+                  I found out that Linux and Windows serial port initialization\r
+                  are different with pinouts states. My board don't get\r
+                  reset signal at first cycle of DTR pinout moving.\r
+                  And I add this moving to initalization cycle.\r
+1.17  2004-10-21  Changes by Cyril Holweck\r
+                  Divide main, take out the real programming function, that can\r
+                  also be used by a target to copy its own code to another.\r
+1.18  2004-10-26  Changes by Cyril Holweck\r
+                  Added a "G 0 A\r\n" at end of programming to run code.\r
+1.19  2004-11-03  Changes by Robert Adsett\r
+                  Add support for Analog Devices.\r
+                  Separate file load from programming.\r
+                  Change from a debug on/off flag to debug level\r
+                  Remove if (debug) tests and replace with DebugPrintf\r
+                  statements.\r
+                  Change serial I/O and timing so that the system\r
+                  dependancies are isolated to a few portability functions.\r
+                  Add support for binary serial I/O.\r
+                  Add doxygen support.\r
+1.20  2004-11-07  Preparation for multiport booting (factory support)\r
+1.21  2004-11-08  Bugfix from Robert Adsett\r
+                  BinaryLength was not initialized\r
+1.22  2004-11-08  Changes from Cyril Holweck / Evgeny Sinelnikov\r
+                  Forgotten IspEnvironment-> and bugfixes if COMPILE_FOR_LINUX\r
+                  If COMPILE_FOR_LPC21, PhilipsDownload() 'acts as' main():\r
+                  - it should not be static and should return int.\r
+                  - no sub-function can use exit() but only return ()\r
+                  Use 'char' instead of 'byte' ;)\r
+1.23  2005-01-16  Build in automatic detection of LPC chiptype\r
+                  (needed for 256 KByte support)\r
+1.24B 2005-06-02  Changes by Thiadmer Riemersma: completed support for other\r
+                  chip types (LPC213x series and others).\r
+1.24C 2005-06-11  Changes by Thiadmer Riemersma: added the device ID codes for\r
+                  chip types LPC2131 and LPC2132.\r
+1.25  2005-06-19  Martin Maurer: Setup more parameters in DCB,\r
+                  otherwise wrong code is downloaded (only Windows and Cygwin)\r
+                  when a previous program has changed these parameters\r
+                  Check exact string of "G 0 A\r\n0\r\n" instead of whole received buffer,\r
+                  to prevent checking of already received by program start\r
+                  (error on running program, but reports CMD_SUCCESS)\r
+                  Add ifdefs for all baudrates (needed only for high baudrate,\r
+                  which seem to be not available on Macs...)\r
+1.26  2005-06-26  Martin Maurer:\r
+                  Correct check again: "G 0 A\r\n0\r\n" is cutted, because of reboot\r
+                  (error on running program, but reports CMD_SUCCESS)\r
+1.27  2005-06-29  Martin Maurer:\r
+                  Add LPC chip ID's (thanks to Robert from Philips) for\r
+                  missing LPC213x and upcoming new LPC214x chips\r
+                  (currently untested, because i don't have access to these chips,\r
+                  please give me feedback !)\r
+1.28  2005-07-27  Anders Rosvall / Embedded Artists AB:\r
+                  Changed the reset timeout to 500 ms when entering the bootloader.\r
+                  Some external reset controllers have quite long timeout periods,\r
+                  so extening the timeout delay would be a good thing.\r
+1.29  2005-09-14  Rob Jansen:\r
+                  Added functionality to download to RAM and run from there.\r
+                  In LoadFile() added record types 04 (Extended Linear Address Record)\r
+                  and 05 (Start Linear Address Record), added address offset\r
+                  (IspEnvironment->BinaryOffset) and start address (...->StartAddress).\r
+                  Changed PhilipsDownload to skip all Flash prepare/erase/copy commands.\r
+                  Note: Tested with VC7 only\r
+1.30   2005-10-04 Rob Jansen:\r
+                  - forgot to change the version string in 1.29\r
+                  - Wrong text in LoadFile corrected (printed text mentions record type 05,\r
+                    this should be 04\r
+                  - Changed LoadFile to accept multiple record types 04\r
+                  - Changed LoadFile to check on memory size, will not load more than x MB\r
+                    if linear extended address records are used\r
+1.31   2005-11-13 Martin Maurer: Thanks to Frank Gutmann\r
+                  Updated number of sectors in device table\r
+                  for LPC2194, LPC2292 and LPC2294\r
+1.32   2005-12-02 Martin Maurer: Corrected missing control of RTS/DTR\r
+                  in case user selected -termonly and -control\r
+                  Small correction (typo in debug)\r
+1.33   2006-10-01 Jean-Marc Koller:\r
+                  Added support for MacOS X (difference on how to set termios baudrate).\r
+1.34   2006-10-01  Cyril Holweck:\r
+                  Made it compile again for lpc21isp\r
+                  Added const keyword to constant variables to make it better\r
+                  code for embeded target. (decrease RAM usage)\r
+                  Replaced all regular call to printf() by DebugPrintf()\r
+                  Removed call to scanf() (not much usefull and cost a lot to my target)\r
+1.35   2006-22-01 Cyril Holweck\r
+                  Added feature for LPC21: will start downloading at Sector 1 and upward,\r
+                  to finish with Sector 0, the one containing the checksum controling BSL entry\r
+1.36   2006-25-01 Cyril Holweck\r
+                  PhilipsDownload() will now return a unique error code for each error\r
+1.37   2006-10-03 Jeroen Domburg\r
+                  Added LPC2103 (and only the 2103, I can't find the IDs for 2101/2102)\r
+                  Corrected a loop which occured if the program completely fits in sector 0\r
+1.38   2007-01-05 Ray Molenkamp\r
+                  Added feature for LPC21: Wipe entire device before programming to enable\r
+                  reflashing of chips with the lpc codeprotection feature enabled.\r
+1.39   2007-01-12 Martin Maurer\r
+                  Added initial support for new processors LPC23xx and LPC24xx\r
+1.40   2007-01-22 Martin Maurer\r
+                  Correction of chip id of LPC2458\r
+1.41   2007-01-28 Jean-Marc Koller\r
+                  Modified Terminal() to disable ECHO with termios only once, instead of\r
+                  modifying and restoring termios in each getch and kbhit call (which caused\r
+                  a strange echo behaviour in MacOS X).\r
+1.42   2007-01-28 Rob Probin\r
+                  Added -localecho command to allow local echoing in terminal mode for use\r
+                  where target does not echo back keystrokes.\r
+1.43   2007-01-29 Martin Maurer\r
+                  Moved keyboard handling routines to own subroutines,\r
+                  so they can be used during aborting synchronisation.\r
+                  Newest cygwin made problems, StringOscillator always contained '\0x0d'\r
+                  at the end, when calling lpc21isp from batch file\r
+1.44   2007-02-23 Yang Yang\r
+                  Added feature for LPC21: Verify the data in Flash after every writes\r
+                  to sector. To detect errors in writing to Flash ROM.\r
+1.45   2007-02-25 Martin Maurer\r
+                  Replace printf syntax of DumpString by a simple pointer to a string\r
+                  printf syntax is a nice thing, but it is not working :-(\r
+                  and therefore makes debugging much more difficult...\r
+                  Moved VERSION_STR to top of file to avoid possible cosmetical errors\r
+1.46   2007-02-25 Martin Maurer\r
+                  Again corrected debug output: should solve output of\r
+                  (FFFFFFB5) instead of (B5)\r
+1.47   2007-02-27 Robert Adsett\r
+                  Raised timeout on AD send packet function.\r
+1.48   2007-04-20 Martin Maurer\r
+                  Thanks to Josef Wolf for preventing to overwrite over end of array\r
+1.49   2007-10-16 New Option -halfduplex allow single wire using.\r
+                  Implemented and tested only for Windows. Data Resend implemented.\r
+1.50   2007-10-31 Changes by Simon Ellwood\r
+                  Formated the code for readablity\r
+                  Fixed some c++ compiler issues\r
+1.51   2007-11-20 Changes by Simon Ellwood\r
+                  Split into seperate files\r
+                  Made more modular so when used in an embedded mode only the required code is built\r
+1.52   2008-01-22 Changes by Manuel Koeppen\r
+                  Made compileable again for linux and windows\r
+                  Fixed bug in ClearSerialPortBuffers (linux)\r
+1.53   2008-02-25 Changes by Michael Roth\r
+                  Get priority of debug messages wih -control right\r
+1.54   2008-03-03 Martin Maurer\r
+                  Try to bring lpc21isp back to a useable state in Windows, Cygwin, Linux and Mac OS.\r
+                  Merged in changes by Erika Stefanini, which were done only for old version 1.49:\r
+                  Added device ids for revision B chips\r
+1.55   2008-03-03 Martin Maurer\r
+                  Thanks to Fausto Marzoli, bugfix for compiling latest version under Linux\r
+1.56   2008-04-01 Steve Franks\r
+                  Integrate FreeBSD patch.\r
+                  Add support for swapping and/or inverting RTS & DTR\r
+1.57   2008-04-06 Mauricio Scaff\r
+                  Changed OpenSerialPort to work with MacOS\r
+                  Corrected the number of sectors in some 512K devices (28 instead of 27)\r
+                  Added support for LPC2387 and LPC2388\r
+                  Defined BL error 19 (Code Protected)\r
+1.58   2008-05-10 Herbert Demmel dh2@demmel.com\r
+                  I had the special requirement to integrate the program into my own Windows\r
+                  software compiled with Borland C++ Builder 5. I had to do some minor changes\r
+                  for Borland (see defined __BORLANDC__) and modified to code slightly to have\r
+                  some simple callbacks for screen i/o (see define INTEGRATED_IN_WIN_APP).\r
+                  Please notet that I don *not* check / modify the part for AnalogDevices !!\r
+                  Besides that I fixed some minor issues:\r
+                  added dcb.fOutxCtsFlow = FALSE and dcb.fOutxDsrFlow = FALSE (sometimes required)\r
+                  Now comparing one character less of answer to "Now launching ... code" command\r
+1.59   2008-07-07 Peter Hayward\r
+                  Fixed freeze under Windows XP SP2 by removing redundant call to SetCommMask.\r
+1.60   2008-07-21 Martin Maurer\r
+                  Added uptodate part ids for LPC2458, LPC2468 and LPC2478\r
+                  Add comment "obsolete" for older part ids for LPC2458 and LPC2468\r
+                  Add ", " between compile date and time\r
+1.61   2008-10-21 Fausto Marzoli (thanks to Geoffrey Wossum for the patches)\r
+                  Fix for compiling latest version under Linux and "ControlLinesSwapped" issue\r
+1.62   2008-11-19 Martin Maurer\r
+                  Added (untested) support for LPC2109\r
+                  Added (untested) support for LPC2361 / LPC2362\r
+                  Heavy update of part identification number of LPC23xx and LPC24xx\r
+                  Correct bug, that hex file must exist, when "-detectonly" is used\r
+                  Correct Makefile.vc: use /Fe instead of -o\r
+1.63   2008-11-23 Martin Maurer\r
+                  Changed to GNU Lesser General Public License\r
+1.64   2009-01-19 Steve Franks\r
+               __FREEBSD__ changed to __FreeBSD__ at some point, plus other com port fixes\r
+*/\r
+\r
+// Don't forget to update the version string that is on the next line\r
+#define VERSION_STR "1.64"\r
+\r
+#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+static char RxTmpBuf[256];        // save received data to this buffer for half-duplex\r
+char * pRxTmpBuf = RxTmpBuf;\r
+#endif\r
+\r
+#if !defined COMPILE_FOR_LPC21\r
+int debug_level = 2;\r
+#endif\r
+\r
+/************* Portability layer. Serial and console I/O differences    */\r
+/* are taken care of here.                                              */\r
+\r
+#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+static void OpenSerialPort(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    DCB    dcb;\r
+    COMMTIMEOUTS commtimeouts;\r
+\r
+    IspEnvironment->hCom = CreateFile(IspEnvironment->serial_port, GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);\r
+\r
+    if (IspEnvironment->hCom == INVALID_HANDLE_VALUE)\r
+    {\r
+        DebugPrintf(1, "Can't open COM-Port %s ! - Error: %ld\n", IspEnvironment->serial_port, GetLastError());\r
+        exit(2);\r
+    }\r
+\r
+    DebugPrintf(3, "COM-Port %s opened...\n", IspEnvironment->serial_port);\r
+\r
+    GetCommState(IspEnvironment->hCom, &dcb);\r
+    dcb.BaudRate    = atol(IspEnvironment->baud_rate);\r
+    dcb.ByteSize    = 8;\r
+    dcb.StopBits    = ONESTOPBIT;\r
+    dcb.Parity      = NOPARITY;\r
+    dcb.fDtrControl = DTR_CONTROL_DISABLE;\r
+    dcb.fOutX       = FALSE;\r
+    dcb.fInX        = FALSE;\r
+    dcb.fNull       = FALSE;\r
+    dcb.fRtsControl = RTS_CONTROL_DISABLE;\r
+\r
+    // added by Herbert Demmel - iF CTS line has the wrong state, we would never send anything!\r
+    dcb.fOutxCtsFlow = FALSE;\r
+    dcb.fOutxDsrFlow = FALSE;\r
+\r
+    if (SetCommState(IspEnvironment->hCom, &dcb) == 0)\r
+    {\r
+        DebugPrintf(1, "Can't set baudrate %s ! - Error: %ld", IspEnvironment->baud_rate, GetLastError());\r
+        exit(3);\r
+    }\r
+\r
+   /*\r
+    *  Peter Hayward 02 July 2008\r
+    *\r
+    *  The following call is only needed if the WaitCommEvent\r
+    *  or possibly the GetCommMask functions are used.  They are\r
+    *  *not* in this implimentation.  However, under Windows XP SP2\r
+    *  on my laptop the use of this call causes XP to freeze (crash) while\r
+    *  this program is running, e.g. in section 5/6/7 ... of a largish\r
+    *  download.  Removing this *unnecessary* call fixed the problem.\r
+    *  At the same time I've added a call to SetupComm to request\r
+    *  (not necessarity honoured) the operating system to provide\r
+    *  large I/O buffers for high speed I/O without handshaking.\r
+    *\r
+    *   SetCommMask(IspEnvironment->hCom,EV_RXCHAR | EV_TXEMPTY);\r
+    */\r
+    SetupComm(IspEnvironment->hCom, 32000, 32000);\r
+\r
+    SetCommMask(IspEnvironment->hCom, EV_RXCHAR | EV_TXEMPTY);\r
+\r
+    commtimeouts.ReadIntervalTimeout         = MAXDWORD;\r
+    commtimeouts.ReadTotalTimeoutMultiplier  =    0;\r
+    commtimeouts.ReadTotalTimeoutConstant    =    1;\r
+    commtimeouts.WriteTotalTimeoutMultiplier =    0;\r
+    commtimeouts.WriteTotalTimeoutConstant   =    0;\r
+    SetCommTimeouts(IspEnvironment->hCom, &commtimeouts);\r
+}\r
+#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+#if defined COMPILE_FOR_LINUX\r
+static void OpenSerialPort(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    IspEnvironment->fdCom = open(IspEnvironment->serial_port, O_RDWR | O_NOCTTY | O_NONBLOCK);\r
+\r
+    if (IspEnvironment->fdCom < 0)\r
+    {\r
+        int err = errno;\r
+        DebugPrintf(1, "Can't open COM-Port %s ! (Error: %dd (0x%X))\n", IspEnvironment->serial_port, err, err);\r
+        exit(2);\r
+    }\r
+\r
+    DebugPrintf(3, "COM-Port %s opened...\n", IspEnvironment->serial_port);\r
+\r
+    /* clear input & output buffers, then switch to "blocking mode" */\r
+    tcflush(IspEnvironment->fdCom, TCOFLUSH);\r
+    tcflush(IspEnvironment->fdCom, TCIFLUSH);\r
+    fcntl(IspEnvironment->fdCom, F_SETFL, fcntl(IspEnvironment->fdCom, F_GETFL) & ~O_NONBLOCK);\r
+\r
+    tcgetattr(IspEnvironment->fdCom, &IspEnvironment->oldtio); /* save current port settings */\r
+\r
+    bzero(&IspEnvironment->newtio, sizeof(IspEnvironment->newtio));\r
+    IspEnvironment->newtio.c_cflag = CS8 | CLOCAL | CREAD;\r
+\r
+#ifdef __APPLE__\r
+#define NEWTERMIOS_SETBAUDARTE(bps) IspEnvironment->newtio.c_ispeed = IspEnvironment->newtio.c_ospeed = bps;\r
+\r
+#elif __FreeBSD__\r
+\r
+       if(cfsetspeed(&IspEnvironment->newtio,(speed_t) strtol(IspEnvironment->baud_rate,NULL,10))) {\r
+                  DebugPrintf(1, "baudrate %s not supported\n", IspEnvironment->baud_rate);\r
+                  exit(3);\r
+              };\r
+#else\r
+#define NEWTERMIOS_SETBAUDARTE(bps) IspEnvironment->newtio.c_cflag |= bps;\r
+\r
+    switch (atol(IspEnvironment->baud_rate))\r
+    {\r
+#ifdef B1152000\r
+          case 1152000: NEWTERMIOS_SETBAUDARTE(B1152000); break;\r
+#endif // B1152000\r
+#ifdef B576000\r
+          case  576000: NEWTERMIOS_SETBAUDARTE(B576000); break;\r
+#endif // B576000\r
+#ifdef B230400\r
+          case  230400: NEWTERMIOS_SETBAUDARTE(B230400); break;\r
+#endif // B230400\r
+#ifdef B115200\r
+          case  115200: NEWTERMIOS_SETBAUDARTE(B115200); break;\r
+#endif // B115200\r
+#ifdef B57600\r
+          case   57600: NEWTERMIOS_SETBAUDARTE(B57600); break;\r
+#endif // B57600\r
+#ifdef B38400\r
+          case   38400: NEWTERMIOS_SETBAUDARTE(B38400); break;\r
+#endif // B38400\r
+#ifdef B19200\r
+          case   19200: NEWTERMIOS_SETBAUDARTE(B19200); break;\r
+#endif // B19200\r
+#ifdef B9600\r
+          case    9600: NEWTERMIOS_SETBAUDARTE(B9600); break;\r
+#endif // B9600\r
+          default:\r
+              {\r
+                  DebugPrintf(1, "unknown baudrate %s\n", IspEnvironment->baud_rate);\r
+                  exit(3);\r
+              }\r
+    }\r
+\r
+#endif\r
+\r
+    IspEnvironment->newtio.c_iflag = IGNPAR | IGNBRK | IXON | IXOFF;\r
+    IspEnvironment->newtio.c_oflag = 0;\r
+\r
+    /* set input mode (non-canonical, no echo,...) */\r
+    IspEnvironment->newtio.c_lflag = 0;\r
+\r
+    cfmakeraw(&IspEnvironment->newtio);\r
+    IspEnvironment->newtio.c_cc[VTIME]    = 1;   /* inter-character timer used */\r
+    IspEnvironment->newtio.c_cc[VMIN]     = 0;   /* blocking read until 0 chars received */\r
+\r
+    tcflush(IspEnvironment->fdCom, TCIFLUSH);\r
+    if(tcsetattr(IspEnvironment->fdCom, TCSANOW, &IspEnvironment->newtio))\r
+    {\r
+       DebugPrintf(1, "Could not change serial port behaviour (wrong baudrate?)\n");\r
+       exit(3);\r
+    }\r
+\r
+}\r
+#endif // defined COMPILE_FOR_LINUX\r
+\r
+#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+static void CloseSerialPort(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    CloseHandle(IspEnvironment->hCom);\r
+}\r
+\r
+#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+#if defined COMPILE_FOR_LINUX\r
+static void CloseSerialPort(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    tcflush(IspEnvironment->fdCom, TCOFLUSH);\r
+    tcflush(IspEnvironment->fdCom, TCIFLUSH);\r
+    tcsetattr(IspEnvironment->fdCom, TCSANOW, &IspEnvironment->oldtio);\r
+\r
+    close(IspEnvironment->fdCom);\r
+}\r
+#endif // defined COMPILE_FOR_LINUX\r
+\r
+\r
+/***************************** SendComPortBlock *************************/\r
+/**  Sends a block of bytes out the opened com port.\r
+\param [in] s block to send.\r
+\param [in] n size of the block.\r
+*/\r
+void SendComPortBlock(ISP_ENVIRONMENT *IspEnvironment, const void *s, size_t n)\r
+{\r
+#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+    unsigned long realsize;\r
+    size_t m;\r
+    unsigned long rxsize;\r
+    char * pch;\r
+    char * rxpch;\r
+#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+    DumpString(4, s, n, "Sending ");\r
+\r
+#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+    if (IspEnvironment->HalfDuplex == 0)\r
+        WriteFile(IspEnvironment->hCom, s, n, &realsize, NULL);\r
+    else\r
+    {\r
+        pch = (char *)s;\r
+        rxpch = RxTmpBuf;\r
+        pRxTmpBuf = RxTmpBuf;\r
+\r
+        // avoid buffer otherflow\r
+        if (n > sizeof (RxTmpBuf))\r
+            n = sizeof (RxTmpBuf);\r
+\r
+        for (m = 0; m < n; m++)\r
+        {\r
+            WriteFile(IspEnvironment->hCom, pch, 1, &realsize, NULL);\r
+\r
+            if ((*pch != '?') || (n != 1))\r
+            {\r
+                do\r
+                {\r
+                    ReadFile(IspEnvironment->hCom, rxpch, 1, &rxsize, NULL);\r
+                }while (rxsize == 0);\r
+            }\r
+            pch++;\r
+            rxpch++;\r
+        }\r
+        *rxpch = 0;        // terminate echo string\r
+    }\r
+#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21\r
+\r
+    write(IspEnvironment->fdCom, s, n);\r
+\r
+#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21\r
+}\r
+\r
+/***************************** SendComPort ******************************/\r
+/**  Sends a string out the opened com port.\r
+\param [in] s string to send.\r
+*/\r
+void SendComPort(ISP_ENVIRONMENT *IspEnvironment, const char *s)\r
+{\r
+    SendComPortBlock(IspEnvironment, s, strlen(s));\r
+}\r
+\r
+/***************************** SerialTimeoutTick ************************/\r
+/**  Performs a timer tick.  In this simple case all we do is count down\r
+with protection against underflow and wrapping at the low end.\r
+*/\r
+static void SerialTimeoutTick(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    if (IspEnvironment->serial_timeout_count <= 1)\r
+    {\r
+        IspEnvironment->serial_timeout_count = 0;\r
+    }\r
+    else\r
+    {\r
+        IspEnvironment->serial_timeout_count--;\r
+    }\r
+}\r
+\r
+\r
+/***************************** ReceiveComPortBlock **********************/\r
+/**  Receives a buffer from the open com port. Returns all the characters\r
+ready (waits for up to 'n' milliseconds before accepting that no more\r
+characters are ready) or when the buffer is full. 'n' is system dependant,\r
+see SerialTimeout routines.\r
+\param [out] answer buffer to hold the bytes read from the serial port.\r
+\param [in] max_size the size of buffer pointed to by answer.\r
+\param [out] real_size pointer to a long that returns the amout of the\r
+buffer that is actually used.\r
+*/\r
+static void ReceiveComPortBlock(ISP_ENVIRONMENT *IspEnvironment,\r
+                                          void *answer, unsigned long max_size,\r
+                                          unsigned long *real_size)\r
+{\r
+    char tmp_string[32];\r
+\r
+#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+    if (IspEnvironment->HalfDuplex == 0)\r
+        ReadFile(IspEnvironment->hCom, answer, max_size, real_size, NULL);\r
+    else\r
+    {\r
+        *real_size = strlen (pRxTmpBuf);\r
+        if (*real_size)\r
+        {\r
+            if (max_size >= *real_size)\r
+            {\r
+                strncpy((char*) answer, pRxTmpBuf, *real_size);\r
+                RxTmpBuf[0] = 0;\r
+                pRxTmpBuf = RxTmpBuf;\r
+            }\r
+            else\r
+            {\r
+                strncpy((char*) answer, pRxTmpBuf, max_size);\r
+                *real_size = max_size;\r
+                pRxTmpBuf += max_size;\r
+            }\r
+        }\r
+        else\r
+            ReadFile(IspEnvironment->hCom, answer, max_size, real_size, NULL);\r
+    }\r
+\r
+#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21\r
+\r
+    *real_size = read(IspEnvironment->fdCom, answer, max_size);\r
+\r
+#endif // defined COMPILE_FOR_LINUX\r
+\r
+    sprintf(tmp_string, "Read(Length=%ld): ", (*real_size));\r
+    DumpString(5, answer, (*real_size), tmp_string);\r
+\r
+    if (*real_size == 0)\r
+    {\r
+        SerialTimeoutTick(IspEnvironment);\r
+    }\r
+}\r
+\r
+\r
+/***************************** SerialTimeoutSet *************************/\r
+/**  Sets (or resets) the timeout to the timout period requested.  Starts\r
+counting to this period.  This timeout support is a little odd in that the\r
+timeout specifies the accumulated deadtime waiting to read not the total\r
+time waiting to read. They should be close enought to the same for this\r
+use. Used by the serial input routines, the actual counting takes place in\r
+ReceiveComPortBlock.\r
+\param [in] timeout_milliseconds the time in milliseconds to use for\r
+timeout.  Note that just because it is set in milliseconds doesn't mean\r
+that the granularity is that fine.  In many cases (particularly Linux) it\r
+will be coarser.\r
+*/\r
+static void SerialTimeoutSet(ISP_ENVIRONMENT *IspEnvironment, unsigned timeout_milliseconds)\r
+{\r
+#if defined COMPILE_FOR_LINUX\r
+    IspEnvironment->serial_timeout_count = timeout_milliseconds / 100;\r
+#elif defined COMPILE_FOR_LPC21\r
+    IspEnvironment->serial_timeout_count = timeout_milliseconds * 200;\r
+#else\r
+    IspEnvironment->serial_timeout_count = timeout_milliseconds;\r
+#endif\r
+}\r
+\r
+\r
+\r
+/***************************** SerialTimeoutCheck ***********************/\r
+/**  Check to see if the serial timeout timer has run down.\r
+\retval 1 if timer has run out.\r
+\retval 0 if timer still has time left.\r
+*/\r
+static int SerialTimeoutCheck(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    if (IspEnvironment->serial_timeout_count == 0)\r
+    {\r
+        return 1;\r
+    }\r
+    return 0;\r
+}\r
+\r
+\r
+#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN\r
+/***************************** getch ************************************/\r
+/** Replacement for the common dos function of the same name. Reads a\r
+single unbuffered character from the 'keyboard'.\r
+\return The character read from the keyboard.\r
+*/\r
+int getch(void)\r
+{\r
+    char ch;\r
+\r
+    /* Read in one character */\r
+    read(0,&ch,1);\r
+\r
+    return ch;\r
+}\r
+#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN\r
+\r
+#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN\r
+/***************************** kbhit ************************************/\r
+/** Replacement for the common dos function of the same name. Indicates if\r
+there are characters to be read from the console.\r
+\retval 0 No characters ready.\r
+\retval 1 Characters from the console ready to be read.\r
+*/\r
+int kbhit(void)\r
+{\r
+    /* return 0 for no key pressed, 1 for key pressed */\r
+    int return_value = 0;\r
+\r
+    /* time struct for the select() function, to only wait a little while */\r
+    struct timeval select_time;\r
+    /* file descriptor variable for the select() call */\r
+    fd_set readset;\r
+\r
+    /* we're only interested in STDIN */\r
+    FD_ZERO(&readset);\r
+    FD_SET(STDIN_FILENO, &readset);\r
+\r
+    /* how long to block for - this must be > 0.0, but could be changed\r
+    to some other setting. 10-18msec seems to work well and only\r
+    minimally load the system (0% CPU loading) */\r
+    select_time.tv_sec = 0;\r
+    select_time.tv_usec = 10;\r
+\r
+    /* is there a keystroke there? */\r
+    if (select(1, &readset, NULL, NULL, &select_time))\r
+    {\r
+        /* yes, remember it */\r
+        return_value = 1;\r
+    }\r
+\r
+\r
+    /* return with what we found out */\r
+    return return_value;\r
+}\r
+struct termios keyboard_origtty;\r
+#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN\r
+\r
+\r
+/***************************** PrepareKeyboardTtySettings ***************/\r
+/** Set the keyboard tty to be able to check for new characters via kbhit\r
+getting them via getch\r
+*/\r
+\r
+void PrepareKeyboardTtySettings(void)\r
+{\r
+#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN\r
+    /* store the current tty settings */\r
+    if (!tcgetattr(0, &keyboard_origtty))\r
+    {\r
+        struct termios tty;\r
+        /* start with the current settings */\r
+        tty = keyboard_origtty;\r
+        /* make modifications to put it in raw mode, turn off echo */\r
+        tty.c_lflag &= ~ICANON;\r
+        tty.c_lflag &= ~ECHO;\r
+        tty.c_lflag &= ~ISIG;\r
+        tty.c_cc[VMIN] = 1;\r
+        tty.c_cc[VTIME] = 0;\r
+\r
+        /* put the settings into effect */\r
+        tcsetattr(0, TCSADRAIN, &tty);\r
+    }\r
+#endif\r
+}\r
+\r
+\r
+/***************************** ResetKeyboardTtySettings *****************/\r
+/** Reset the keyboard tty to original settings\r
+*/\r
+void ResetKeyboardTtySettings(void)\r
+{\r
+#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN\r
+    /* reset the tty to its original settings */\r
+    tcsetattr(0, TCSADRAIN, &keyboard_origtty);\r
+#endif\r
+}\r
+\r
+\r
+#if !defined COMPILE_FOR_LPC21\r
+/***************************** ControlModemLines ************************/\r
+/**  Controls the modem lines to place the microcontroller into various\r
+states during the programming process.\r
+error rather abruptly terminates the program.\r
+\param [in] DTR the state to set the DTR line to.\r
+\param [in] RTS the state to set the RTS line to.\r
+*/\r
+static void ControlModemLines(ISP_ENVIRONMENT *IspEnvironment, unsigned char DTR, unsigned char RTS)\r
+{\r
+    //handle wether to invert the control lines:\r
+    DTR ^= IspEnvironment->ControlLinesInverted;\r
+    RTS ^= IspEnvironment->ControlLinesInverted;\r
+\r
+    //handle wether to swap the control lines\r
+    if (IspEnvironment->ControlLinesSwapped)\r
+    {\r
+        unsigned char tempRTS;\r
+        tempRTS = RTS;\r
+        RTS = DTR;\r
+        DTR = tempRTS;\r
+    }\r
+\r
+#if defined COMPILE_FOR_LINUX\r
+    int status;\r
+\r
+    if (ioctl(IspEnvironment->fdCom, TIOCMGET, &status) == 0)\r
+    {\r
+        DebugPrintf(3, "ioctl get ok, status = %X\n",status);\r
+    }\r
+    else\r
+    {\r
+        DebugPrintf(1, "ioctl get failed\n");\r
+    }\r
+\r
+    if (DTR) status |=  TIOCM_DTR;\r
+    else    status &= ~TIOCM_DTR;\r
+\r
+    if (RTS) status |=  TIOCM_RTS;\r
+    else    status &= ~TIOCM_RTS;\r
+\r
+    if (ioctl(IspEnvironment->fdCom, TIOCMSET, &status) == 0)\r
+    {\r
+        DebugPrintf(3, "ioctl set ok, status = %X\n",status);\r
+    }\r
+    else\r
+    {\r
+        DebugPrintf(1, "ioctl set failed\n");\r
+    }\r
+\r
+    if (ioctl(IspEnvironment->fdCom, TIOCMGET, &status) == 0)\r
+    {\r
+        DebugPrintf(3, "ioctl get ok, status = %X\n",status);\r
+    }\r
+    else\r
+    {\r
+        DebugPrintf(1, "ioctl get failed\n");\r
+    }\r
+\r
+#endif // defined COMPILE_FOR_LINUX\r
+#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+    if (DTR) EscapeCommFunction(IspEnvironment->hCom, SETDTR);\r
+    else    EscapeCommFunction(IspEnvironment->hCom, CLRDTR);\r
+\r
+    if (RTS) EscapeCommFunction(IspEnvironment->hCom, SETRTS);\r
+    else    EscapeCommFunction(IspEnvironment->hCom, CLRRTS);\r
+\r
+#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+#if defined COMPILE_FOR_LPC21\r
+    LPC_RESET(DTR);\r
+    LPC_BSL(RTS);\r
+#endif\r
+\r
+    DebugPrintf(3, "DTR (%d), RTS (%d)\n", DTR, RTS);\r
+}\r
+\r
+\r
+/***************************** ClearSerialPortBuffers********************/\r
+/**  Empty the serial port buffers.  Cleans things to a known state.\r
+*/\r
+void ClearSerialPortBuffers(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+#if defined COMPILE_FOR_LINUX\r
+    /* variables to store the current tty state, create a new one */\r
+    struct termios origtty, tty;\r
+\r
+    /* store the current tty settings */\r
+    tcgetattr(IspEnvironment->fdCom, &origtty);\r
+\r
+    // Flush input and output buffers\r
+    tty=origtty;\r
+    tcsetattr(IspEnvironment->fdCom, TCSAFLUSH, &tty);\r
+\r
+    /* reset the tty to its original settings */\r
+    tcsetattr(IspEnvironment->fdCom, TCSADRAIN, &origtty);\r
+#endif // defined COMPILE_FOR_LINUX\r
+#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+    PurgeComm(IspEnvironment->hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);\r
+#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+}\r
+#endif // !defined COMPILE_FOR_LPC21\r
+\r
+\r
+#if defined COMPILE_FOR_LINUX\r
+/***************************** Sleep ************************************/\r
+/**  Provide linux replacement for windows function.\r
+\param [in] Milliseconds the time to wait for in milliseconds.\r
+*/\r
+void Sleep(unsigned long MilliSeconds)\r
+{\r
+    usleep(MilliSeconds*1000); //convert to microseconds\r
+}\r
+#endif // defined COMPILE_FOR_LINUX\r
+\r
+\r
+#if defined COMPILE_FOR_LPC21\r
+/**  Provide linux replacement for windows function.\r
+\note I implement that one in my private header file today...\r
+\param [in] Milliseconds the time to wait for in milliseconds.\r
+*/\r
+/*static void Sleep(unsigned long MilliSeconds)\r
+{\r
+#   warning Sleep function not implemented\r
+}\r
+*/\r
+#endif // defined COMPILE_FOR_LPC21\r
+\r
+\r
+\r
+/************* Applicationlayer.                                        */\r
+\r
+#if !defined COMPILE_FOR_LPC21\r
+/***************************** DebugPrintf ******************************/\r
+/**  Prints a debug string depending the current debug level. The higher\r
+the debug level the more detail that will be printed.  Each print\r
+has an associated level, the higher the level the more detailed the\r
+debugging information being sent.\r
+\param [in] level the debug level of the print statement, if the level\r
+is less than or equal to the current debug level it will be printed.\r
+\param [in] fmt a standard printf style format string.\r
+\param [in] ... the usual printf parameters.\r
+*/\r
+#if !defined INTEGRATED_IN_WIN_APP\r
+void DebugPrintf(int level, const char *fmt, ...)\r
+{\r
+    va_list ap;\r
+\r
+    if (level <= debug_level)\r
+    {\r
+        char pTemp[2000];\r
+        va_start(ap, fmt);\r
+        //vprintf(fmt, ap);\r
+        vsprintf(pTemp, fmt, ap);\r
+        TRACE(pTemp);\r
+        va_end(ap);\r
+        fflush(stdout);\r
+    }\r
+}\r
+#endif\r
+#endif // !defined COMPILE_FOR_LPC21\r
+\r
+\r
+/***************************** ReceiveComPort ***************************/\r
+/**  Receives a buffer from the open com port. Returns when the buffer is\r
+filled, the numer of requested linefeeds has been received or the timeout\r
+period has passed\r
+\param [in] ISPEnvironment.\r
+\param [out] Answer buffer to hold the bytes read from the serial port.\r
+\param [in] MaxSize the size of buffer pointed to by Answer.\r
+\param [out] RealSize pointer to a long that returns the amout of the\r
+buffer that is actually used.\r
+\param [in] WantedNr0x0A the maximum number of linefeeds to accept before\r
+returning.\r
+\param [in] timeOutMilliseconds the maximum amount of time to wait before\r
+reading with an incomplete buffer.\r
+*/\r
+void ReceiveComPort(ISP_ENVIRONMENT *IspEnvironment,\r
+                                    const char *Ans, unsigned long MaxSize,\r
+                                    unsigned long *RealSize, unsigned long WantedNr0x0A,\r
+                                    unsigned timeOutMilliseconds)\r
+{\r
+    unsigned long tmp_realsize;\r
+    unsigned long nr_of_0x0A = 0;\r
+    int eof = 0;\r
+    unsigned long p;\r
+    unsigned char *Answer;\r
+    char tmp_string[32];\r
+\r
+    Answer = (unsigned char*) Ans;\r
+\r
+    SerialTimeoutSet(IspEnvironment, timeOutMilliseconds);\r
+\r
+    (*RealSize) = 0;\r
+\r
+    do\r
+    {\r
+        ReceiveComPortBlock(IspEnvironment, Answer + (*RealSize), MaxSize - 1 - (*RealSize), &tmp_realsize);\r
+\r
+        if (tmp_realsize != 0)\r
+        {\r
+            for (p = (*RealSize); p < (*RealSize) + tmp_realsize; p++)\r
+            {\r
+                if (Answer[p] == 0x0a)\r
+                {\r
+                    nr_of_0x0A++;\r
+                }\r
+                else if (((signed char) Answer[p]) < 0)\r
+                {\r
+                    eof = 1;\r
+                }\r
+            }\r
+        }\r
+\r
+        (*RealSize) += tmp_realsize;\r
+\r
+    } while (((*RealSize) < MaxSize) && (SerialTimeoutCheck(IspEnvironment) == 0) && (nr_of_0x0A < WantedNr0x0A) && !eof);\r
+\r
+    Answer[(*RealSize)] = 0;\r
+\r
+    sprintf(tmp_string, "Answer(Length=%ld): ", (*RealSize));\r
+    DumpString(3, Answer, (*RealSize), tmp_string);\r
+}\r
+\r
+\r
+#if !defined COMPILE_FOR_LPC21\r
+\r
+/***************************** ReceiveComPortBlockComplete **************/\r
+/**  Receives a fixed block from the open com port. Returns when the\r
+block is completely filled or the timeout period has passed\r
+\param [out] block buffer to hold the bytes read from the serial port.\r
+\param [in] size the size of the buffer pointed to by block.\r
+\param [in] timeOut the maximum amount of time to wait before guvung up on\r
+completing the read.\r
+\return 0 if successful, non-zero otherwise.\r
+*/\r
+int ReceiveComPortBlockComplete(ISP_ENVIRONMENT *IspEnvironment,\r
+                                                    void *block, size_t size, unsigned timeout)\r
+{\r
+    unsigned long realsize = 0, read;\r
+    char *result;\r
+    char tmp_string[32];\r
+\r
+    result = (char*) block;\r
+\r
+    SerialTimeoutSet(IspEnvironment, timeout);\r
+\r
+    do\r
+    {\r
+        ReceiveComPortBlock(IspEnvironment, result + realsize, size - realsize, &read);\r
+\r
+        realsize += read;\r
+\r
+    } while ((realsize < size) && (SerialTimeoutCheck(IspEnvironment) == 0));\r
+\r
+    sprintf(tmp_string, "Answer(Length=%ld): ", realsize);\r
+    DumpString(3, result, realsize, tmp_string);\r
+\r
+    if (realsize != size)\r
+    {\r
+        return 1;\r
+    }\r
+    return 0;\r
+}\r
+\r
+/***************************** ReadArguments ****************************/\r
+/**  Reads the command line arguments and parses it for the various\r
+options. Uses the same arguments as main.  Used to separate the command\r
+line parsing from main and improve its readability.  This should also make\r
+it easier to modify the command line parsing in the future.\r
+\param [in] argc the number of arguments.\r
+\param [in] argv an array of pointers to the arguments.\r
+*/\r
+static void ReadArguments(ISP_ENVIRONMENT *IspEnvironment, unsigned int argc, char *argv[])\r
+{\r
+    unsigned int i;\r
+\r
+    if (argc >= 5)\r
+    {\r
+        for (i = 1; i < argc - 4; i++)\r
+        {\r
+            if (stricmp(argv[i], "-wipe") == 0)\r
+            {\r
+                IspEnvironment->WipeDevice = 1;\r
+                DebugPrintf(3, "Wipe entire device before writing.\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-bin") == 0)\r
+            {\r
+                IspEnvironment->FileFormat = FORMAT_BINARY;\r
+                DebugPrintf(3, "Binary format file input.\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-hex") == 0)\r
+            {\r
+                IspEnvironment->FileFormat = FORMAT_HEX;\r
+                DebugPrintf(3, "Hex format file input.\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-logfile") == 0)\r
+            {\r
+                IspEnvironment->LogFile = 1;\r
+                DebugPrintf(3, "Log terminal output.\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-detectonly") == 0)\r
+            {\r
+                IspEnvironment->DetectOnly  = 1;\r
+                IspEnvironment->ProgramChip = 0;\r
+                DebugPrintf(3, "Only detect LPC chip part id.\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-debug") == 0)\r
+            {\r
+                debug_level = 4;\r
+                DebugPrintf(3, "Turn on debug.\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-control") == 0)\r
+            {\r
+                IspEnvironment->ControlLines = 1;\r
+                DebugPrintf(3, "Use RTS/DTR to control target state.\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-controlswap") == 0)\r
+            {\r
+                IspEnvironment->ControlLinesSwapped = 1;\r
+                DebugPrintf(3, "Use RTS to control reset, and DTR to control P0.14(ISP).\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-controlinv") == 0)\r
+            {\r
+                IspEnvironment->ControlLinesInverted = 1;\r
+                DebugPrintf(3, "Invert state of RTS & DTR (0=true/assert/set, 1=false/deassert/clear).\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-halfduplex") == 0)\r
+            {\r
+                IspEnvironment->HalfDuplex = 1;\r
+                DebugPrintf(3, "halfduplex serial communication.\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-ADARM") == 0)\r
+            {\r
+                IspEnvironment->micro = ANALOG_DEVICES_ARM;\r
+                DebugPrintf(2, "Target: Analog Devices.\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-PHILIPSARM") == 0)\r
+            {\r
+                IspEnvironment->micro = PHILIPS_ARM;\r
+                DebugPrintf(2, "Target: Philips.\n");\r
+                continue;\r
+            }\r
+\r
+            if (stricmp(argv[i], "-Verify") == 0)\r
+            {\r
+                IspEnvironment->Verify = 1;\r
+                DebugPrintf(2, "Verify after copy RAM to Flash.\n");\r
+                continue;\r
+            }\r
+\r
+#ifdef INTEGRATED_IN_WIN_APP\r
+            if (stricmp(argv[i], "-nosync") == 0)\r
+            {\r
+                IspEnvironment->NoSync = 1;\r
+                DebugPrintf(2, "Performing no syncing, already done.\n");\r
+                continue;\r
+            }\r
+#endif\r
+\r
+#ifdef TERMINAL_SUPPORT\r
+            if (CheckTerminalParameters(IspEnvironment, argv[i]))\r
+            {\r
+                continue;\r
+            }\r
+#endif\r
+\r
+            DebugPrintf(2, "Unknown command line option: \"%s\"\n", argv[i]);\r
+        }\r
+\r
+        IspEnvironment->input_file = argv[argc - 4];\r
+\r
+        // Newest cygwin delivers a '\x0d' at the end of argument\r
+        // when calling lpc21isp from batch file\r
+        for (i = 0; i < strlen(argv[argc - 1]) && i < (sizeof(IspEnvironment->StringOscillator) - 1) &&\r
+            argv[argc - 1][i] >= '0' && argv[argc - 1][i] <= '9'; i++)\r
+        {\r
+            IspEnvironment->StringOscillator[i] = argv[argc - 1][i];\r
+        }\r
+        IspEnvironment->StringOscillator[i] = 0;\r
+\r
+        IspEnvironment->serial_port = argv[argc - 3];\r
+        IspEnvironment->baud_rate = argv[argc - 2];\r
+    }\r
+\r
+    if (argc < 5)\r
+    {\r
+        debug_level = (debug_level < 2) ? 2 : debug_level;\r
+    }\r
+\r
+    if (argc < 5)\r
+    {\r
+        DebugPrintf(2, "\n"\r
+                       "Portable command line ISP for NXP LPC2000 family and Analog Devices ADUC 70xx\n"\r
+                       "Version " VERSION_STR " compiled for " COMPILED_FOR ": " __DATE__ ", " __TIME__ "\n"\r
+                       "Copyright (c) by Martin Maurer, 2003-2008, Email: Martin.Maurer@clibb.de\n"\r
+                       "Portions Copyright (c) by Aeolus Development 2004, www.aeolusdevelopment.com\n"\r
+                       "\n");\r
+\r
+        DebugPrintf(1, "Syntax:  lpc21isp [Options] file comport baudrate Oscillator_in_kHz\n\n"\r
+                       "Example: lpc21isp test.hex com1 115200 14746\n\n"\r
+                       "Options: -bin         for uploading binary file\n"\r
+                       "         -hex         for uploading file in intel hex format (default)\n"\r
+                       "         -term        for starting terminal after upload\n"\r
+                       "         -termonly    for starting terminal without an upload\n"\r
+                       "         -localecho   for local echo in terminal\n"\r
+                       "         -detectonly  detect only used LPC chiptype (PHILIPSARM only)\n"\r
+                       "         -debug       for creating a lot of debug infos\n"\r
+                       "         -wipe        Erase entire device before upload\n"\r
+                       "         -control     for controlling RS232 lines for easier booting\n"\r
+                       "                      (Reset = DTR, EnableBootLoader = RTS)\n"\r
+#ifdef INTEGRATED_IN_WIN_APP\r
+                       "         -nosync      Do not synchronize device via '?'\n"\r
+#endif\r
+                       "         -controlswap swap RS232 control lines\n"\r
+                       "                      (Reset = RTS, EnableBootLoader = DTR)\n"\r
+                       "         -controlinv  Invert state of RTS & DTR \n"\r
+                       "                      (0=true/assert/set, 1=false/deassert/clear).\n"\r
+                       "         -verify      Verify the data in Flash after every writes to\n"\r
+                       "                      sector. To detect errors in writing to Flash ROM\n"\r
+                       "         -logfile     for enabling logging of terminal output to lpc21isp.log\n"\r
+                       "         -halfduplex  use halfduplex serial communication (i.e. with K-Line)\n"\r
+                       "         -ADARM       for downloading to an Analog Devices\n"\r
+                       "                      ARM microcontroller ADUC70xx\n"\r
+                       "         -PHILIPSARM  for downloading to a microcontroller from\n"\r
+                       "                      Philips LPC2000 family (default)\n");\r
+\r
+        exit(1);\r
+    }\r
+\r
+    if (IspEnvironment->micro == PHILIPS_ARM)\r
+    {\r
+        // If StringOscillator is bigger than 100 MHz, there seems to be something wrong\r
+        if (strlen(IspEnvironment->StringOscillator) > 5)\r
+        {\r
+            DebugPrintf(1, "Invalid crystal frequency %s\n", IspEnvironment->StringOscillator);\r
+            exit(1);\r
+        }\r
+    }\r
+}\r
+\r
+/***************************** ResetTarget ******************************/\r
+/**  Resets the target leaving it in either download (program) mode or\r
+run mode.\r
+\param [in] mode the mode to leave the target in.\r
+*/\r
+void ResetTarget(ISP_ENVIRONMENT *IspEnvironment, TARGET_MODE mode)\r
+{\r
+    if (IspEnvironment->ControlLines)\r
+    {\r
+        switch (mode)\r
+        {\r
+        /* Reset and jump to boot loader.                       */\r
+        case PROGRAM_MODE:\r
+            ControlModemLines(IspEnvironment, 1, 1);\r
+            Sleep(100);\r
+            ClearSerialPortBuffers(IspEnvironment);\r
+            Sleep(100);\r
+            ControlModemLines(IspEnvironment, 0, 1);\r
+            //Longer delay is the Reset signal is conected to an external rest controller\r
+            Sleep(500);\r
+            // Clear the RTS line after having reset the micro\r
+            // Needed for the "GO <Address> <Mode>" ISP command to work */\r
+            ControlModemLines(IspEnvironment, 0, 0);\r
+            break;\r
+\r
+        /* Reset and start uploaded program                     */\r
+        case RUN_MODE:\r
+            ControlModemLines(IspEnvironment, 1, 0);\r
+            Sleep(100);\r
+            ClearSerialPortBuffers(IspEnvironment);\r
+            Sleep(100);\r
+            ControlModemLines(IspEnvironment, 0, 0);\r
+            Sleep(100);\r
+            break;\r
+        }\r
+    }\r
+}\r
+\r
+\r
+/***************************** Ascii2Hex ********************************/\r
+/**  Converts a hex character to its equivalent number value. In case of an\r
+error rather abruptly terminates the program.\r
+\param [in] c the hex digit to convert.\r
+\return the value of the hex digit.\r
+*/\r
+static unsigned char Ascii2Hex(unsigned char c)\r
+{\r
+    if (c >= '0' && c <= '9')\r
+    {\r
+        return (unsigned char)(c - '0');\r
+    }\r
+\r
+    if (c >= 'A' && c <= 'F')\r
+    {\r
+        return (unsigned char)(c - 'A' + 10);\r
+    }\r
+\r
+    if (c >= 'a' && c <= 'f')\r
+    {\r
+        return (unsigned char)(c - 'a' + 10);\r
+    }\r
+\r
+    DebugPrintf(1, "Wrong Hex-Nibble %c (%02X)\n", c, c);\r
+    exit(1);\r
+\r
+    return 0;  // this "return" will never be reached, but some compilers give a warning if it is not present\r
+}\r
+\r
+void ReadHexFile(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    LoadFile(IspEnvironment);\r
+\r
+    if (IspEnvironment->BinaryLength)\r
+    {\r
+        BINARY* FileContent = IspEnvironment->FileContent;\r
+\r
+        unsigned long  Pos;\r
+        unsigned char  RecordLength;\r
+        unsigned short RecordAddress;\r
+        unsigned long  RealAddress = 0;\r
+        unsigned char  RecordType;\r
+        unsigned char  Hexvalue;\r
+        unsigned long  StartAddress;\r
+        int            BinaryOffsetDefined = 0;\r
+        unsigned char  i;\r
+\r
+\r
+        DebugPrintf(3, "Converting file %s to binary format...\n", IspEnvironment->input_file);\r
+\r
+        Pos = 0;\r
+        while (Pos < IspEnvironment->BinaryLength)\r
+        {\r
+            if (FileContent[Pos] == '\r')\r
+            {\r
+                Pos++;\r
+                continue;\r
+            }\r
+\r
+            if (FileContent[Pos] == '\n')\r
+            {\r
+                Pos++;\r
+                continue;\r
+            }\r
+\r
+            if (FileContent[Pos] != ':')\r
+            {\r
+                DebugPrintf(1, "Missing start of record (':') wrong byte %c / %02X\n", FileContent[Pos], FileContent[Pos]);\r
+                exit(1);\r
+            }\r
+\r
+            Pos++;\r
+\r
+            RecordLength   = Ascii2Hex(FileContent[Pos++]);\r
+            RecordLength <<= 4;\r
+            RecordLength  |= Ascii2Hex(FileContent[Pos++]);\r
+\r
+            DebugPrintf(4, "RecordLength = %02X\n", RecordLength);\r
+\r
+            RecordAddress   = Ascii2Hex(FileContent[Pos++]);\r
+            RecordAddress <<= 4;\r
+            RecordAddress  |= Ascii2Hex(FileContent[Pos++]);\r
+            RecordAddress <<= 4;\r
+            RecordAddress  |= Ascii2Hex(FileContent[Pos++]);\r
+            RecordAddress <<= 4;\r
+            RecordAddress  |= Ascii2Hex(FileContent[Pos++]);\r
+\r
+            DebugPrintf(4, "RecordAddress = %04X\n", RecordAddress);\r
+\r
+            RealAddress = RealAddress - (RealAddress & 0xffff) + RecordAddress;\r
+\r
+            DebugPrintf(4, "RealAddress = %08lX\n", RealAddress);\r
+\r
+            RecordType      = Ascii2Hex(FileContent[Pos++]);\r
+            RecordType    <<= 4;\r
+            RecordType     |= Ascii2Hex(FileContent[Pos++]);\r
+\r
+            DebugPrintf(4, "RecordType = %02X\n", RecordType);\r
+\r
+            if (RecordType == 0x00)          // 00 - Data record\r
+            {\r
+                /*\r
+                * Binary Offset is defined as soon as first data record read\r
+                */\r
+\r
+                //BinaryOffsetDefined = 1;\r
+\r
+                // Memory for binary file big enough ?\r
+                while ((RealAddress + RecordLength - IspEnvironment->BinaryOffset) > IspEnvironment->BinaryMemSize)\r
+                {\r
+                    IspEnvironment->BinaryMemSize <<= 1;    // Double the size allocated !!!\r
+                    IspEnvironment->BinaryContent = (BINARY*) realloc(IspEnvironment->BinaryContent, IspEnvironment->BinaryMemSize);\r
+                }\r
+\r
+                // We need to know, what the highest address is,\r
+                // how many bytes / sectors we must flash\r
+                if (RealAddress + RecordLength - IspEnvironment->BinaryOffset > IspEnvironment->BinaryLength)\r
+                {\r
+                    IspEnvironment->BinaryLength = RealAddress + RecordLength - IspEnvironment->BinaryOffset;\r
+                    DebugPrintf(3, "Image size now: %ld\n", IspEnvironment->BinaryLength);\r
+                }\r
+\r
+                for (i = 0; i < RecordLength; i++)\r
+                {\r
+                    Hexvalue        = Ascii2Hex(FileContent[Pos++]);\r
+                    Hexvalue      <<= 4;\r
+                    Hexvalue       |= Ascii2Hex(FileContent[Pos++]);\r
+                    IspEnvironment->BinaryContent[RealAddress + i - IspEnvironment->BinaryOffset] = Hexvalue;\r
+                }\r
+            }\r
+            else if (RecordType == 0x01)     // 01 - End of file record\r
+            {\r
+                break;\r
+            }\r
+            else if (RecordType == 0x02)     // 02 - Extended segment address record\r
+            {\r
+                for (i = 0; i < RecordLength * 2; i++)   // double amount of nibbles\r
+                {\r
+                    RealAddress <<= 4;\r
+                    if (i == 0)\r
+                    {\r
+                        RealAddress  = Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                    else\r
+                    {\r
+                        RealAddress |= Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                }\r
+                RealAddress <<= 4;\r
+            }\r
+            else if (RecordType == 0x03)     // 03 - Start segment address record\r
+            {\r
+                for (i = 0; i < RecordLength * 2; i++)   // double amount of nibbles\r
+                {\r
+                    RealAddress <<= 4;\r
+                    if (i == 0)\r
+                    {\r
+                        RealAddress  = Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                    else\r
+                    {\r
+                        RealAddress |= Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                }\r
+                RealAddress <<= 8;\r
+            }\r
+            else if (RecordType == 0x04)     // 04 - Extended linear address record, used by IAR\r
+            {\r
+                for (i = 0; i < RecordLength * 2; i++)   // double amount of nibbles\r
+                {\r
+                    RealAddress <<= 4;\r
+                    if (i == 0)\r
+                    {\r
+                        RealAddress  = Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                    else\r
+                    {\r
+                        RealAddress |= Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                }\r
+                RealAddress <<= 16;\r
+                if (!BinaryOffsetDefined)\r
+                {\r
+                    // set startaddress of BinaryContent\r
+                    // use of LPC_FLASHMASK to allow a memory range, not taking the first\r
+                    // [04] record as actual start-address.\r
+                    IspEnvironment->BinaryOffset = RealAddress & LPC_FLASHMASK;\r
+                }\r
+                else\r
+                {\r
+                    if ((RealAddress & LPC_FLASHMASK) != IspEnvironment->BinaryOffset)\r
+                    {\r
+                        DebugPrintf(1, "New Extended Linear Address Record [04] out of memory range\n"\r
+                                       "Current Memory starts at: 0x%08X, new Address is: 0x%08X",\r
+                                       IspEnvironment->BinaryOffset, RealAddress);\r
+                        exit(1);\r
+                    }\r
+                }\r
+            }\r
+            else if (RecordType == 0x05)     // 05 - Start linear address record\r
+            {\r
+                StartAddress = 0;\r
+                for (i = 0; i < RecordLength * 2; i++)   // double amount of nibbles\r
+                {\r
+                    StartAddress <<= 4;\r
+                    if (i == 0)\r
+                    {\r
+                        StartAddress  = Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                    else\r
+                    {\r
+                        StartAddress |= Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                }\r
+                DebugPrintf(1,"Start Address = 0x%8X\n", StartAddress);\r
+                IspEnvironment->StartAddress = StartAddress;\r
+            }\r
+\r
+            while (FileContent[Pos++] != 0x0a)      // Search till line end\r
+            {\r
+            }\r
+        }\r
+\r
+        DebugPrintf(2, "\tconverted to binary format...\n");\r
+\r
+        // When debugging is switched on, output result of conversion to file debugout.bin\r
+        if (debug_level >= 4)\r
+        {\r
+            int fdout;\r
+            fdout = open("debugout.bin", O_RDWR | O_BINARY | O_CREAT | O_TRUNC, 0777);\r
+            write(fdout, IspEnvironment->BinaryContent, IspEnvironment->BinaryLength);\r
+            close(fdout);\r
+        }\r
+    }\r
+}\r
+\r
+\r
+/***************************** LoadFile *********************************/\r
+/**  Loads the requested file to download into memory.\r
+\param [in] IspEnvironment  structure containing input filename\r
+*/\r
+static void LoadFile(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    int            fd;\r
+    int            i;\r
+    int            BinaryOffsetDefined;\r
+    unsigned long  Pos;\r
+    unsigned long  FileLength;\r
+    BINARY        *FileContent;              /**< Used to store the content of a hex */\r
+                                             /*   file before converting to binary.  */\r
+    unsigned long  BinaryMemSize;\r
+\r
+    fd = open(IspEnvironment->input_file, O_RDONLY | O_BINARY);\r
+    if (fd == -1)\r
+    {\r
+        DebugPrintf(1, "Can't open file %s\n", IspEnvironment->input_file);\r
+        exit(1);\r
+    }\r
+\r
+    FileLength = lseek(fd, 0L, 2);      // Get file size\r
+\r
+    if (FileLength == (size_t)-1)\r
+    {\r
+        DebugPrintf(1, "\nFileLength = -1 !?!\n");\r
+        exit(1);\r
+    }\r
+\r
+    lseek(fd, 0L, 0);\r
+\r
+    FileContent = (BINARY*) malloc(FileLength);\r
+\r
+    BinaryMemSize = FileLength * 2;\r
+\r
+    IspEnvironment->BinaryLength = 0;   /* Increase length as needed.       */\r
+    IspEnvironment->BinaryOffset = 0;\r
+    IspEnvironment->StartAddress = 0;\r
+    BinaryOffsetDefined = 0;\r
+\r
+    IspEnvironment->BinaryContent = (BINARY*) malloc(BinaryMemSize);\r
+\r
+    read(fd, FileContent, FileLength);\r
+\r
+    close(fd);\r
+\r
+    DebugPrintf(2, "File %s:\n\tloaded...\n", IspEnvironment->input_file);\r
+\r
+    // Intel-Hex -> Binary Conversion\r
+\r
+    if (IspEnvironment->FileFormat == FORMAT_HEX)\r
+    {\r
+        unsigned char  RecordLength;\r
+        unsigned short RecordAddress;\r
+        unsigned long  RealAddress = 0;\r
+        unsigned char  RecordType;\r
+        unsigned char  Hexvalue;\r
+        unsigned long  StartAddress;\r
+\r
+        DebugPrintf(3, "Converting file %s to binary format...\n", IspEnvironment->input_file);\r
+\r
+        Pos = 0;\r
+        while (Pos < FileLength)\r
+        {\r
+            if (FileContent[Pos] == '\r')\r
+            {\r
+                Pos++;\r
+                continue;\r
+            }\r
+\r
+            if (FileContent[Pos] == '\n')\r
+            {\r
+                Pos++;\r
+                continue;\r
+            }\r
+\r
+            if (FileContent[Pos] != ':')\r
+            {\r
+                DebugPrintf(1, "Missing start of record (':') wrong byte %c / %02X\n", FileContent[Pos], FileContent[Pos]);\r
+                exit(1);\r
+            }\r
+\r
+            Pos++;\r
+\r
+            RecordLength   = Ascii2Hex(FileContent[Pos++]);\r
+            RecordLength <<= 4;\r
+            RecordLength  |= Ascii2Hex(FileContent[Pos++]);\r
+\r
+            DebugPrintf(4, "RecordLength = %02X\n", RecordLength);\r
+\r
+            RecordAddress   = Ascii2Hex(FileContent[Pos++]);\r
+            RecordAddress <<= 4;\r
+            RecordAddress  |= Ascii2Hex(FileContent[Pos++]);\r
+            RecordAddress <<= 4;\r
+            RecordAddress  |= Ascii2Hex(FileContent[Pos++]);\r
+            RecordAddress <<= 4;\r
+            RecordAddress  |= Ascii2Hex(FileContent[Pos++]);\r
+\r
+            DebugPrintf(4, "RecordAddress = %04X\n", RecordAddress);\r
+\r
+            RealAddress = RealAddress - (RealAddress & 0xffff) + RecordAddress;\r
+\r
+            DebugPrintf(4, "RealAddress = %08lX\n", RealAddress);\r
+\r
+            RecordType      = Ascii2Hex(FileContent[Pos++]);\r
+            RecordType    <<= 4;\r
+            RecordType     |= Ascii2Hex(FileContent[Pos++]);\r
+\r
+            DebugPrintf(4, "RecordType = %02X\n", RecordType);\r
+\r
+            if (RecordType == 0x00)          // 00 - Data record\r
+            {\r
+                /*\r
+                * Binary Offset is defined as soon as first data record read\r
+                */\r
+                BinaryOffsetDefined = 1;\r
+                // Memory for binary file big enough ?\r
+                while (RealAddress + RecordLength - IspEnvironment->BinaryOffset > BinaryMemSize)\r
+                {\r
+                    BinaryMemSize <<= 1;\r
+                    IspEnvironment->BinaryContent = (BINARY*) realloc(IspEnvironment->BinaryContent, BinaryMemSize);\r
+                }\r
+\r
+                // We need to know, what the highest address is,\r
+                // how many bytes / sectors we must flash\r
+                if (RealAddress + RecordLength - IspEnvironment->BinaryOffset > IspEnvironment->BinaryLength)\r
+                {\r
+                    IspEnvironment->BinaryLength = RealAddress + RecordLength - IspEnvironment->BinaryOffset;\r
+                    DebugPrintf(3, "Image size now: %ld\n", IspEnvironment->BinaryLength);\r
+                }\r
+\r
+                for (i = 0; i < RecordLength; i++)\r
+                {\r
+                    Hexvalue        = Ascii2Hex(FileContent[Pos++]);\r
+                    Hexvalue      <<= 4;\r
+                    Hexvalue       |= Ascii2Hex(FileContent[Pos++]);\r
+                    IspEnvironment->BinaryContent[RealAddress + i - IspEnvironment->BinaryOffset] = Hexvalue;\r
+                }\r
+            }\r
+            else if (RecordType == 0x01)     // 01 - End of file record\r
+            {\r
+                break;\r
+            }\r
+            else if (RecordType == 0x02)     // 02 - Extended segment address record\r
+            {\r
+                for (i = 0; i < RecordLength * 2; i++)   // double amount of nibbles\r
+                {\r
+                    RealAddress <<= 4;\r
+                    if (i == 0)\r
+                    {\r
+                        RealAddress  = Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                    else\r
+                    {\r
+                        RealAddress |= Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                }\r
+                RealAddress <<= 4;\r
+            }\r
+            else if (RecordType == 0x03)     // 03 - Start segment address record\r
+            {\r
+                for (i = 0; i < RecordLength * 2; i++)   // double amount of nibbles\r
+                {\r
+                    RealAddress <<= 4;\r
+                    if (i == 0)\r
+                    {\r
+                        RealAddress  = Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                    else\r
+                    {\r
+                        RealAddress |= Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                }\r
+                RealAddress <<= 8;\r
+            }\r
+            else if (RecordType == 0x04)     // 04 - Extended linear address record, used by IAR\r
+            {\r
+                for (i = 0; i < RecordLength * 2; i++)   // double amount of nibbles\r
+                {\r
+                    RealAddress <<= 4;\r
+                    if (i == 0)\r
+                    {\r
+                        RealAddress  = Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                    else\r
+                    {\r
+                        RealAddress |= Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                }\r
+                RealAddress <<= 16;\r
+                if (!BinaryOffsetDefined)\r
+                {\r
+                    // set startaddress of BinaryContent\r
+                    // use of LPC_FLASHMASK to allow a memory range, not taking the first\r
+                    // [04] record as actual start-address.\r
+                    IspEnvironment->BinaryOffset = RealAddress & LPC_FLASHMASK;\r
+                }\r
+                else\r
+                {\r
+                    if ((RealAddress & LPC_FLASHMASK) != IspEnvironment->BinaryOffset)\r
+                    {\r
+                        DebugPrintf(1, "New Extended Linear Address Record [04] out of memory range\n");\r
+                        DebugPrintf(1, "Current Memory starts at: 0x%08X, new Address is: 0x%08X",\r
+                            IspEnvironment->BinaryOffset, RealAddress);\r
+                        exit(1);\r
+                    }\r
+                }\r
+            }\r
+            else if (RecordType == 0x05)     // 05 - Start linear address record\r
+            {\r
+                StartAddress = 0;\r
+                for (i = 0; i < RecordLength * 2; i++)   // double amount of nibbles\r
+                {\r
+                    StartAddress <<= 4;\r
+                    if (i == 0)\r
+                    {\r
+                        StartAddress  = Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                    else\r
+                    {\r
+                        StartAddress |= Ascii2Hex(FileContent[Pos++]);\r
+                    }\r
+                }\r
+                DebugPrintf(1,"Start Address = 0x%8X\n", StartAddress);\r
+                IspEnvironment->StartAddress = StartAddress;\r
+            }\r
+\r
+            while (FileContent[Pos++] != 0x0a)      // Search till line end\r
+            {\r
+            }\r
+        }\r
+\r
+        DebugPrintf(2, "\tconverted to binary format...\n");\r
+\r
+        // When debugging is switched on, output result of conversion to file debugout.bin\r
+        if (debug_level >= 4)\r
+        {\r
+            int fdout;\r
+            fdout = open("debugout.bin", O_RDWR | O_BINARY | O_CREAT | O_TRUNC, 0777);\r
+            write(fdout, IspEnvironment->BinaryContent, IspEnvironment->BinaryLength);\r
+            close(fdout);\r
+        }\r
+    }\r
+    else\r
+    {\r
+        memcpy(IspEnvironment->BinaryContent, FileContent, FileLength);\r
+\r
+        IspEnvironment->BinaryLength = FileLength;\r
+    }\r
+\r
+    DebugPrintf(2, "\timage size : %ld\n", IspEnvironment->BinaryLength);\r
+\r
+    // check length to flash for correct alignment, can happen with broken ld-scripts\r
+    if (IspEnvironment->BinaryLength % 4 != 0)\r
+    {\r
+        unsigned long NewBinaryLength = ((IspEnvironment->BinaryLength + 3)/4) * 4;\r
+\r
+        DebugPrintf(2, "Warning:  data not aligned to 32 bits, padded (length was %lX, now %lX)\n", IspEnvironment->BinaryLength, NewBinaryLength);\r
+\r
+        IspEnvironment->BinaryLength = NewBinaryLength;\r
+    }\r
+}\r
+#endif // !defined COMPILE_FOR_LPC21\r
+\r
+#ifndef COMPILE_FOR_LPC21\r
+int PerformActions(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    int downloadResult = -1;\r
+\r
+    DebugPrintf(2, "lpc21isp version " VERSION_STR "\n");\r
+\r
+    /* Download requested, read in the input file.                  */\r
+    if (IspEnvironment->ProgramChip)\r
+    {\r
+        LoadFile(IspEnvironment);\r
+    }\r
+\r
+    OpenSerialPort(IspEnvironment);   /* Open the serial port to the microcontroller. */\r
+\r
+    ResetTarget(IspEnvironment, PROGRAM_MODE);\r
+\r
+    ClearSerialPortBuffers(IspEnvironment);\r
+\r
+    /* Perform the requested download.                              */\r
+    if (IspEnvironment->ProgramChip || IspEnvironment->DetectOnly)\r
+    {\r
+        switch (IspEnvironment->micro)\r
+        {\r
+#ifdef LPC_SUPPORT\r
+        case PHILIPS_ARM:\r
+            downloadResult = PhilipsDownload(IspEnvironment);\r
+            break;\r
+#endif\r
+\r
+#ifdef AD_SUPPORT\r
+        case ANALOG_DEVICES_ARM:\r
+            downloadResult = AnalogDevicesDownload(IspEnvironment);\r
+            break;\r
+#endif\r
+        }\r
+\r
+        if (downloadResult != 0)\r
+        {\r
+            CloseSerialPort(IspEnvironment);\r
+            exit(downloadResult);\r
+        }\r
+    }\r
+\r
+    if (IspEnvironment->StartAddress == 0 || IspEnvironment->TerminalOnly)\r
+    {\r
+        /* Only reset target if startaddress = 0\r
+        * Otherwise stay with the running program as started in Download()\r
+        */\r
+        ResetTarget(IspEnvironment, RUN_MODE);\r
+    }\r
+\r
+    IspEnvironment->debug_level = 1;    /* From now on there is no more debug output !! */\r
+                                        /* Therefore switch it off...                   */\r
+\r
+#ifdef TERMINAL_SUPPORT\r
+    // Pass control to Terminal which will provide a terminal if one was asked for\r
+    // User asked for terminal emulation, provide a really dumb terminal.\r
+    Terminal(IspEnvironment);\r
+#endif\r
+\r
+    CloseSerialPort(IspEnvironment);  /*  All done, close the serial port to the      */\r
+\r
+    return 0;\r
+}\r
+#endif\r
+\r
+/***************************** main *************************************/\r
+/**  main. Everything starts from here.\r
+\param [in] argc the number of arguments.\r
+\param [in] argv an array of pointers to the arguments.\r
+*/\r
+\r
+#if !defined COMPILE_FOR_LPC21\r
+\r
+#if defined INTEGRATED_IN_WIN_APP\r
+int AppDoProgram(int argc, char *argv[])\r
+#else\r
+int main(int argc, char *argv[])\r
+#endif\r
+{\r
+    ISP_ENVIRONMENT IspEnvironment;\r
+\r
+    // Initialize debug level\r
+    debug_level = 2;\r
+\r
+    // Initialize ISP Environment\r
+    memset(&IspEnvironment, 0, sizeof(IspEnvironment));       // Clear the IspEnviroment to a known value\r
+    IspEnvironment.micro       = PHILIPS_ARM;                 // Default Micro\r
+    IspEnvironment.FileFormat  = FORMAT_HEX;                  // Default File Format\r
+    IspEnvironment.ProgramChip = TRUE;                        // Default to Programming the chip\r
+    ReadArguments(&IspEnvironment, argc, argv);               // Read and parse the command line\r
+\r
+    return PerformActions(&IspEnvironment);                   // Do as requested !\r
+}\r
+\r
+#endif // !defined COMPILE_FOR_LPC21\r
+\r
+/***************************** DumpString ******************************/\r
+/**  Prints an area of memory to stdout. Converts non-printables to hex.\r
+\param [in] level the debug level of the block to be dumped.  If this is\r
+less than or equal to the current debug level than the dump will happen\r
+otherwise this just returns.\r
+\param [in] b pointer to an area of memory.\r
+\param [in] size the length of the memory block to print.\r
+\param [in] prefix string is a pointer to a prefix string.\r
+*/\r
+void DumpString(int level, const void *b, size_t size, const char *prefix_string)\r
+{\r
+    size_t i;\r
+    const char * s = (const char*) b;\r
+    unsigned char c;\r
+\r
+    DebugPrintf(level, prefix_string);\r
+\r
+    DebugPrintf(level, "'");\r
+    for (i = 0; i < size; i++)\r
+    {\r
+        c = s[i];\r
+        if (c >= 0x20 && c <= 0x7e) /*isprint?*/\r
+        {\r
+            DebugPrintf(level, "%c", c);\r
+        }\r
+        else\r
+        {\r
+            DebugPrintf(level, "(%02X)", c);\r
+        }\r
+    }\r
+    DebugPrintf(level, "'\n");\r
+}\r
+\r
+#if !defined COMPILE_FOR_LPC21\r
+int lpctest(char* FileName)\r
+{\r
+    ISP_ENVIRONMENT IspEnvironment;\r
+\r
+    // Initialize debug level\r
+    debug_level = 2;\r
+\r
+    // Initialize ISP Environment\r
+    memset(&IspEnvironment, 0, sizeof(IspEnvironment));        // Clear the IspEnviroment to a known value\r
+    IspEnvironment.micro        = PHILIPS_ARM;                 // Default Micro\r
+    IspEnvironment.FileFormat   = FORMAT_HEX;                  // Default File Format\r
+    IspEnvironment.ProgramChip  = TRUE;                        // Default to Programming the chip\r
+    IspEnvironment.input_file   = FileName;\r
+    IspEnvironment.ControlLines = TRUE;\r
+    IspEnvironment.serial_port  = "COM2";\r
+    IspEnvironment.baud_rate    = "19200";\r
+    strcpy(IspEnvironment.StringOscillator, "25000");\r
+\r
+    return PerformActions(&IspEnvironment);                    // Do as requested !\r
+}\r
+#endif\r
diff --git a/arch/arm/mach-lpc21xx/tools/lpc21isp/lpc21isp.h b/arch/arm/mach-lpc21xx/tools/lpc21isp/lpc21isp.h
new file mode 100644 (file)
index 0000000..5f5dc2a
--- /dev/null
@@ -0,0 +1,277 @@
+/******************************************************************************\r
+\r
+Project:           Portable command line ISP for Philips LPC2000 family\r
+                   and Analog Devices ADUC70xx\r
+\r
+Filename:          lsp21isp.h\r
+\r
+Compiler:          Microsoft VC 6/7, GCC Cygwin, GCC Linux, GCC ARM ELF\r
+\r
+Author:            Martin Maurer (Martin.Maurer@clibb.de)\r
+\r
+Copyright:         (c) Martin Maurer 2003-2008, All rights reserved\r
+Portions Copyright (c) by Aeolus Development 2004 http://www.aeolusdevelopment.com\r
+\r
+    This file is part of lpc21isp.\r
+\r
+    lpc21isp is free software: you can redistribute it and/or modify\r
+    it under the terms of the GNU Lesser General Public License as published by\r
+    the Free Software Foundation, either version 3 of the License, or\r
+    any later version.\r
+\r
+    lpc21isp is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+    GNU Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public License\r
+    and GNU General Public License along with lpc21isp.\r
+    If not, see <http://www.gnu.org/licenses/>.\r
+*/\r
+\r
+// #define INTEGRATED_IN_WIN_APP\r
+\r
+#if defined(_WIN32) && !defined(__CYGWIN__)\r
+#define COMPILE_FOR_WINDOWS\r
+#define COMPILED_FOR "Windows"\r
+#elif defined(__CYGWIN__)\r
+#define COMPILE_FOR_CYGWIN\r
+#define COMPILED_FOR "Cygwin"\r
+#elif defined(__arm__) || defined(__thumb__)\r
+#define COMPILE_FOR_LPC21\r
+#define COMPILED_FOR "ARM"\r
+#define printf iprintf\r
+#elif defined(__APPLE__)\r
+#define COMPILE_FOR_LINUX\r
+#define COMPILED_FOR "Apple MacOS X"\r
+#elif defined(__FreeBSD__)\r
+#define COMPILE_FOR_LINUX\r
+#define COMPILED_FOR "FreeBSD"\r
+#else\r
+#define COMPILE_FOR_LINUX\r
+#define COMPILED_FOR "Linux"\r
+#endif\r
+\r
+// The Required features can be enabled / disabled here\r
+#define LPC_SUPPORT\r
+\r
+#ifndef COMPILE_FOR_LPC21\r
+#define AD_SUPPORT\r
+#define TERMINAL_SUPPORT\r
+#endif\r
+\r
+#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+#include <windows.h>\r
+#include <io.h>\r
+#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+#if defined COMPILE_FOR_WINDOWS\r
+#include <conio.h>\r
+//#define TRACE(x) OutputDebugString(x)\r
+#define TRACE(x) printf("%s",x)\r
+#endif // defined COMPILE_FOR_WINDOWS\r
+\r
+#if defined COMPILE_FOR_CYGWIN\r
+//#define TRACE(x) OutputDebugString(x)\r
+#define TRACE(x) printf("%s",x)\r
+#endif // defined COMPILE_FOR_WINDOWS\r
+\r
+#if defined COMPILE_FOR_LINUX\r
+#include <sys/types.h>\r
+#include <sys/stat.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+#include <strings.h>\r
+#include <sys/ioctl.h>\r
+extern void Sleep(unsigned long MilliSeconds);\r
+#define TRACE(x) printf("%s",x)\r
+#endif // defined COMPILE_FOR_LINUX\r
+\r
+#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN\r
+#include <termios.h>\r
+#include <unistd.h>     // for read and return value of lseek\r
+#include <sys/time.h>   // for select_time\r
+extern int kbhit(void);\r
+extern int getch(void);\r
+extern struct termios keyboard_origtty;\r
+#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN\r
+\r
+#include <ctype.h>      // isdigit()\r
+#include <stdio.h>      // stdout\r
+#include <stdarg.h>\r
+#include <time.h>\r
+#if defined (COMPILE_FOR_LINUX)\r
+#include <sys/errno.h>\r
+#endif\r
+\r
+#if defined COMPILE_FOR_LPC21\r
+#include <stdlib.h>\r
+#include <string.h>\r
+//#include <lpc_ioctl.h>  // if using libc serial port communication\r
+#else\r
+#include <fcntl.h>\r
+#endif\r
+\r
+typedef enum\r
+{\r
+    PHILIPS_ARM,\r
+    ANALOG_DEVICES_ARM\r
+} TARGET;\r
+\r
+typedef enum\r
+{\r
+    PROGRAM_MODE,\r
+    RUN_MODE\r
+} TARGET_MODE;\r
+\r
+typedef enum\r
+{\r
+    FORMAT_BINARY,\r
+    FORMAT_HEX\r
+} FILE_FORMAT_TYPE;\r
+\r
+typedef unsigned char BINARY;               // Data type used for microcontroller\r
+\r
+typedef struct\r
+{\r
+#if !defined COMPILE_FOR_LPC21\r
+    TARGET micro;                                // The type of micro that will be programmed.\r
+    FILE_FORMAT_TYPE FileFormat;\r
+    unsigned char ProgramChip;                // Normally set\r
+\r
+    int debug_level;\r
+    unsigned char ControlLines;\r
+    unsigned char ControlLinesSwapped;\r
+    unsigned char ControlLinesInverted;\r
+    unsigned char LogFile;\r
+    char *input_file;                   // The name of the file to get input from.\r
+    char *serial_port;                  // Name of the serial port to use to\r
+                                        // communicate with the microcontroller.\r
+                                        // Read from the command line.\r
+#endif // !defined COMPILE_FOR_LPC21\r
+\r
+    unsigned char TerminalOnly;         // Declared here for lazyness saves ifdef's\r
+#ifdef TERMINAL_SUPPORT\r
+    unsigned char TerminalAfterUpload;\r
+    unsigned char LocalEcho;\r
+#endif\r
+\r
+    unsigned char HalfDuplex;           // Only used for LPC Programming\r
+    unsigned char DetectOnly;\r
+    unsigned char WipeDevice;\r
+    unsigned char Verify;\r
+    int           DetectedDevice;       /* index in LPCtypes[] array */\r
+    char *baud_rate;                    /**< Baud rate to use on the serial\r
+                                           * port communicating with the\r
+                                           * microcontroller. Read from the\r
+                                           * command line.                        */\r
+\r
+    char StringOscillator[6];           /**< Holds representation of oscillator\r
+                                           * speed from the command line.         */\r
+\r
+    BINARY *FileContent;\r
+    BINARY *BinaryContent;              /**< Binary image of the                  */\r
+                                          /* microcontroller's memory.            */\r
+    unsigned long BinaryLength;\r
+    unsigned long BinaryOffset;\r
+    unsigned long StartAddress;\r
+    unsigned long BinaryMemSize;\r
+\r
+#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+    HANDLE hCom;\r
+#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN\r
+\r
+#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21\r
+    int fdCom;\r
+#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21\r
+\r
+#if defined COMPILE_FOR_LINUX\r
+    struct termios oldtio, newtio;\r
+#endif // defined COMPILE_FOR_LINUX\r
+\r
+#ifdef INTEGRATED_IN_WIN_APP\r
+    unsigned char NoSync;\r
+#endif\r
+\r
+    unsigned serial_timeout_count;   /**< Local used to track timeouts on serial port read. */\r
+\r
+} ISP_ENVIRONMENT;\r
+\r
+#if defined COMPILE_FOR_LPC21\r
+\r
+#define DebugPrintf(in, ...)\r
+\r
+#else\r
+extern int debug_level;\r
+\r
+#if defined INTEGRATED_IN_WIN_APP\r
+\r
+#define DebugPrintf AppDebugPrintf\r
+void AppDebugPrintf(int level, const char *fmt, ...);\r
+\r
+#define exit(val)   AppException(val)\r
+void AppException(int exception_level);\r
+\r
+int AppDoProgram(int argc, char *argv[]);\r
+\r
+#define Exclude_kbhit 1\r
+int AppSyncing(int trials);\r
+void AppWritten(int size);\r
+\r
+#else\r
+void DebugPrintf(int level, const char *fmt, ...);\r
+//#define DebugPrintf(level, ...) if (level <= debug_level) { TRACE( __VA_ARGS__ ); }\r
+#endif\r
+\r
+void ClearSerialPortBuffers(ISP_ENVIRONMENT *IspEnvironment);\r
+static void ControlModemLines(ISP_ENVIRONMENT *IspEnvironment, unsigned char DTR, unsigned char RTS);\r
+static unsigned char Ascii2Hex(unsigned char c);\r
+\r
+#endif\r
+\r
+\r
+#if defined COMPILE_FOR_LINUX\r
+#define stricmp strcasecmp\r
+#endif // defined COMPILE_FOR_LINUX\r
+\r
+#ifndef O_BINARY\r
+#define O_BINARY 0\r
+#endif // O_BINARY\r
+\r
+#ifndef DWORD\r
+#define DWORD unsigned long\r
+#endif // DWORD\r
+\r
+/*\r
+debug levels\r
+0 - very quiet          - Nothing gets printed at this level\r
+1 - quiet               - Only error messages should be printed\r
+2 - indicate progress   - Add progress messages\r
+3 - first level debug   - Major level tracing\r
+4 - second level debug  - Add detailed debugging\r
+5 - log comm's          - log serial I/O\r
+*/\r
+\r
+\r
+void ReceiveComPort(ISP_ENVIRONMENT *IspEnvironment,\r
+                    const char *Ans, unsigned long MaxSize,\r
+                    unsigned long *RealSize, unsigned long WantedNr0x0A,\r
+                    unsigned timeOutMilliseconds);\r
+void PrepareKeyboardTtySettings(void);\r
+void ResetKeyboardTtySettings(void);\r
+void ResetTarget(ISP_ENVIRONMENT *IspEnvironment, TARGET_MODE mode);\r
+\r
+void DumpString(int level, const void *s, size_t size, const char *prefix_string);\r
+void SendComPort(ISP_ENVIRONMENT *IspEnvironment, const char *s);\r
+void SendComPortBlock(ISP_ENVIRONMENT *IspEnvironment, const void *s, size_t n);\r
+int ReceiveComPortBlockComplete(ISP_ENVIRONMENT *IspEnvironment, void *block, size_t size, unsigned timeout);\r
+void ClearSerialPortBuffers(ISP_ENVIRONMENT *IspEnvironment);\r
+\r
+#ifdef COMPILE_FOR_WINDOWS\r
+static void SerialTimeoutSet(ISP_ENVIRONMENT *IspEnvironment, unsigned timeout_milliseconds);\r
+static int SerialTimeoutCheck(ISP_ENVIRONMENT *IspEnvironment);\r
+#endif // COMPILE_FOR_WINDOWS\r
+\r
+static void LoadFile(ISP_ENVIRONMENT *IspEnvironment);\r
+\r
+int lpctest(char* FileName);\r
diff --git a/arch/arm/mach-lpc21xx/tools/lpc21isp/lpcprog.c b/arch/arm/mach-lpc21xx/tools/lpc21isp/lpcprog.c
new file mode 100644 (file)
index 0000000..ef5f39e
--- /dev/null
@@ -0,0 +1,1148 @@
+/******************************************************************************\r
+\r
+Project:           Portable command line ISP for Philips LPC2000 family\r
+                   and Analog Devices ADUC70xx\r
+\r
+Filename:          lpcprog.c\r
+\r
+Compiler:          Microsoft VC 6/7, GCC Cygwin, GCC Linux, GCC ARM ELF\r
+\r
+Author:            Martin Maurer (Martin.Maurer@clibb.de)\r
+\r
+Copyright:         (c) Martin Maurer 2003-2008, All rights reserved\r
+Portions Copyright (c) by Aeolus Development 2004 http://www.aeolusdevelopment.com\r
+\r
+    This file is part of lpc21isp.\r
+\r
+    lpc21isp is free software: you can redistribute it and/or modify\r
+    it under the terms of the GNU Lesser General Public License as published by\r
+    the Free Software Foundation, either version 3 of the License, or\r
+    any later version.\r
+\r
+    lpc21isp is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+    GNU Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public License\r
+    and GNU General Public License along with lpc21isp.\r
+    If not, see <http://www.gnu.org/licenses/>.\r
+*/\r
+\r
+// This file is for the Actual Programming of the LPC Chips\r
+\r
+#if defined(_WIN32)\r
+#if !defined __BORLANDC__\r
+#include "StdAfx.h"\r
+#endif\r
+#endif // defined(_WIN32)\r
+#include "lpc21isp.h"\r
+\r
+#ifdef LPC_SUPPORT\r
+#include "lpcprog.h"\r
+\r
+static const unsigned int SectorTable_210x[] =\r
+{\r
+    8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192,\r
+    8192, 8192, 8192, 8192, 8192, 8192, 8192\r
+};\r
+\r
+static const unsigned int SectorTable_2103[] =\r
+{\r
+    4096, 4096, 4096, 4096, 4096, 4096, 4096, 4096\r
+};\r
+\r
+static const unsigned int SectorTable_2109[] =\r
+{\r
+    8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192\r
+};\r
+\r
+static const unsigned int SectorTable_211x[] =\r
+{\r
+    8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192,\r
+    8192, 8192, 8192, 8192, 8192, 8192, 8192,\r
+};\r
+\r
+static const unsigned int SectorTable_212x[] =\r
+{\r
+    8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192,\r
+    65536, 65536, 8192, 8192, 8192, 8192, 8192, 8192, 8192\r
+};\r
+\r
+// Used for devices with 500K (LPC2138 and LPC2148) and\r
+// for devices with 504K (1 extra 4k block at the end)\r
+static const unsigned int SectorTable_213x[] =\r
+{\r
+     4096,  4096,  4096,  4096,  4096,  4096,  4096,  4096,\r
+    32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768,\r
+    32768, 32768, 32768, 32768, 32768, 32768,  4096,  4096,\r
+     4096,  4096,  4096,  4096\r
+};\r
+\r
+static int unsigned SectorTable_RAM[]  = { 65000 };\r
+\r
+static LPC_DEVICE_TYPE LPCtypes[] =\r
+{\r
+    { 0, 0, 0 },  /* unknown */\r
+    { 0x0004FF11, 2103,  32,  8,  8, 4096, SectorTable_2103 },\r
+    { 0xFFF0FF12, 2104, 128, 16, 15, 8192, SectorTable_210x },\r
+    { 0xFFF0FF22, 2105, 128, 32, 15, 8192, SectorTable_210x },\r
+    { 0xFFF0FF32, 2106, 128, 64, 15, 8192, SectorTable_210x },\r
+    { 0x0201FF01, 2109,  64,  8,  8, 4096, SectorTable_2109 },\r
+    { 0x0101FF12, 2114, 128, 16, 15, 8192, SectorTable_211x },\r
+    { 0x0201FF12, 2119, 128, 16, 15, 8192, SectorTable_211x },\r
+    { 0x0101FF13, 2124, 256, 16, 17, 8192, SectorTable_212x },\r
+    { 0x0201FF13, 2129, 256, 16, 17, 8192, SectorTable_212x },\r
+    { 0x0002FF01, 2131,  32,  8,  8, 4096, SectorTable_213x },\r
+    { 0x0002FF11, 2132,  64, 16,  9, 4096, SectorTable_213x },\r
+    { 0x0002FF12, 2134, 128, 16, 11, 4096, SectorTable_213x },\r
+    { 0x0002FF23, 2136, 256, 32, 15, 4096, SectorTable_213x },\r
+    { 0x0002FF25, 2138, 512, 32, 27, 4096, SectorTable_213x },\r
+    { 0x0402FF01, 2141,  32,  8,  8, 4096, SectorTable_213x },\r
+    { 0x0402FF11, 2142,  64, 16,  9, 4096, SectorTable_213x },\r
+    { 0x0402FF12, 2144, 128, 16, 11, 4096, SectorTable_213x },\r
+    { 0x0402FF23, 2146, 256, 40, 15, 4096, SectorTable_213x },\r
+    { 0x0402FF25, 2148, 512, 40, 27, 4096, SectorTable_213x },\r
+    { 0x0301FF13, 2194, 256, 16, 17, 8192, SectorTable_212x },\r
+    { 0x0301FF12, 2210,   0, 16,  0, 8192, SectorTable_211x }, /* table is a "don't care" */\r
+    { 0x0401FF12, 2212, 128, 16, 15, 8192, SectorTable_211x },\r
+    { 0x0601FF13, 2214, 256, 16, 17, 8192, SectorTable_212x },\r
+    /*            2290; same id as the LPC2210 */\r
+    { 0x0401FF13, 2292, 256, 16, 17, 8192, SectorTable_212x },\r
+    { 0x0501FF13, 2294, 256, 16, 17, 8192, SectorTable_212x },\r
+    { 0x00000000, 2361, 128, 34, 11, 4096, SectorTable_213x },\r
+    { 0x00000000, 2362, 128, 34, 11, 4096, SectorTable_213x },\r
+    { 0x1600F902, 2364, 128, 34, 11, 4096, SectorTable_213x },\r
+    { 0x1600E823, 2365, 256, 58, 15, 4096, SectorTable_213x },\r
+    { 0x1600F923, 2366, 256, 58, 15, 4096, SectorTable_213x },\r
+    { 0x1600E825, 2367, 512, 58, 15, 4096, SectorTable_213x },\r
+    { 0x1600F925, 2368, 512, 58, 28, 4096, SectorTable_213x },\r
+    { 0x1700E825, 2377, 512, 58, 28, 4096, SectorTable_213x },\r
+    { 0x1700FD25, 2378, 512, 58, 28, 4096, SectorTable_213x },\r
+    { 0x1800F935, 2387, 512, 98, 28, 4096, SectorTable_213x },\r
+    { 0x1800FF35, 2388, 512, 98, 28, 4096, SectorTable_213x },\r
+    { 0x1500FF35, 2458, 512, 98, 28, 4096, SectorTable_213x },\r
+    { 0x1600FF30, 2460,   0, 98,  0, 4096, SectorTable_213x },\r
+    { 0x1600FF35, 2468, 512, 98, 28, 4096, SectorTable_213x },\r
+    { 0x1701FF30, 2470,   0, 98,  0, 4096, SectorTable_213x },\r
+    { 0x1701FF35, 2478, 512, 98, 28, 4096, SectorTable_213x }\r
+};\r
+\r
+/***************************** PHILIPS Download *********************************/\r
+/**  Download the file from the internal memory image to the philips microcontroller.\r
+*   This function is visible from outside if COMPILE_FOR_LPC21\r
+*/\r
+\r
+static int SendAndVerify(ISP_ENVIRONMENT *IspEnvironment, const char *Command,\r
+                                 char *AnswerBuffer, int AnswerLength)\r
+{\r
+    unsigned long realsize;\r
+    int cmdlen;\r
+\r
+    SendComPort(IspEnvironment, Command);\r
+    ReceiveComPort(IspEnvironment, AnswerBuffer, AnswerLength - 1, &realsize, 2, 5000);\r
+    cmdlen = strlen(Command);\r
+    return (strncmp(AnswerBuffer, Command, cmdlen) == 0\r
+        && strcmp(AnswerBuffer + cmdlen, "0\r\n") == 0);\r
+}\r
+\r
+\r
+\r
+/***************************** PhilipsOutputErrorMessage ***********************/\r
+/**  Given an error number find and print the appropriate error message.\r
+\param [in] ErrorNumber The number of the error.\r
+*/\r
+#if defined COMPILE_FOR_LPC21\r
+\r
+#define PhilipsOutputErrorMessage(in)        // Cleanly remove this feature from the embedded version !!\r
+\r
+#else\r
+\r
+static void PhilipsOutputErrorMessage(unsigned char ErrorNumber)\r
+{\r
+    switch (ErrorNumber)\r
+    {\r
+    case   0:\r
+        DebugPrintf(1, "CMD_SUCCESS\n");\r
+        break;\r
+\r
+    case   1:\r
+        DebugPrintf(1, "INVALID_COMMAND\n");\r
+        break;\r
+\r
+    case   2:\r
+        DebugPrintf(1, "SRC_ADDR_ERROR: Source address is not on word boundary.\n");\r
+        break;\r
+    case   3:\r
+        DebugPrintf(1, "DST_ADDR_ERROR: Destination address is not on a correct boundary.\n");\r
+        break;\r
+\r
+    case   4:\r
+        DebugPrintf(1, "SRC_ADDR_NOT_MAPPED: Source address is not mapped in the memory map.\n"\r
+                       "                     Count value is taken into consideration where applicable.\n");\r
+        break;\r
+\r
+    case   5:\r
+        DebugPrintf(1, "DST_ADDR_NOT_MAPPED: Destination address is not mapped in the memory map.\n"\r
+                       "                     Count value is taken into consideration where applicable.\n");\r
+        break;\r
+\r
+    case   6:\r
+        DebugPrintf(1, "COUNT_ERROR: Byte count is not multiple of 4 or is not a permitted value.\n");\r
+        break;\r
+\r
+    case   7:\r
+        DebugPrintf(1, "INVALID_SECTOR: Sector number is invalid or end sector number is\n"\r
+                       "                greater than start sector number.\n");\r
+        break;\r
+\r
+    case   8:\r
+        DebugPrintf(1, "SECTOR_NOT_BLANK\n");\r
+        break;\r
+\r
+    case   9:\r
+        DebugPrintf(1, "SECTOR_NOT_PREPARED_FOR_WRITE_OPERATION:\n"\r
+                       "Command to prepare sector for write operation was not executed.\n");\r
+        break;\r
+\r
+    case  10:\r
+        DebugPrintf(1, "COMPARE_ERROR: Source and destination data not equal.\n");\r
+        break;\r
+\r
+    case  11:\r
+        DebugPrintf(1, "BUSY: Flash programming hardware interface is busy.\n");\r
+        break;\r
+\r
+    case  12:\r
+        DebugPrintf(1, "PARAM_ERROR: Insufficient number of parameters or invalid parameter.\n");\r
+        break;\r
+\r
+    case  13:\r
+        DebugPrintf(1, "ADDR_ERROR: Address is not on word boundary.\n");\r
+        break;\r
+\r
+    case  14:\r
+        DebugPrintf(1, "ADDR_NOT_MAPPED: Address is not mapped in the memory map.\n"\r
+                       "                 Count value is taken in to consideration where applicable.\n");\r
+        break;\r
+\r
+    case  15:\r
+        DebugPrintf(1, "CMD_LOCKED\n");\r
+        break;\r
+\r
+    case  16:\r
+        DebugPrintf(1, "INVALID_CODE: Unlock code is invalid.\n");\r
+        break;\r
+\r
+    case  17:\r
+        DebugPrintf(1, "INVALID_BAUD_RATE: Invalid baud rate setting.\n");\r
+        break;\r
+\r
+    case  18:\r
+        DebugPrintf(1, "INVALID_STOP_BIT: Invalid stop bit setting.\n");\r
+        break;\r
+\r
+    case  19:\r
+        DebugPrintf( 1, "CODE READ PROTECTION ENABLED\n");\r
+        break;\r
+\r
+    case 255:\r
+        break;\r
+\r
+    default:\r
+        DebugPrintf(1, "unknown error %u\n", ErrorNumber);\r
+        break;\r
+    }\r
+\r
+    //DebugPrintf(1, "error (%u), see  PhilipsOutputErrorMessage() in lpc21isp.c for help \n\r", ErrorNumber);\r
+}\r
+#endif // !defined COMPILE_FOR_LPC21\r
+\r
+/***************************** GetAndReportErrorNumber ***************************/\r
+/**  Find error number in string.  This will normally be the string\r
+returned from the microcontroller.\r
+\param [in] Answer the buffer to search for the error number.\r
+\return the error number found, if no linefeed found before the end of the\r
+string an error value of 255 is returned. If a non-numeric value is found\r
+then it is printed to stdout and an error value of 255 is returned.\r
+*/\r
+static unsigned char GetAndReportErrorNumber(const char *Answer)\r
+{\r
+    unsigned char Result = 0xFF;                            // Error !!!\r
+    unsigned int i = 0;\r
+\r
+    while (1)\r
+    {\r
+        if (Answer[i] == 0x00)\r
+        {\r
+            break;\r
+        }\r
+\r
+        if (Answer[i] == 0x0a)\r
+        {\r
+            i++;\r
+\r
+            if (Answer[i] < '0' || Answer[i] > '9')\r
+            {\r
+                DebugPrintf(1, "ErrorString: %s", &Answer[i]);\r
+                break;\r
+            }\r
+\r
+            Result = (unsigned char) (atoi(&Answer[i]));\r
+            break;\r
+        }\r
+\r
+        i++;\r
+    }\r
+\r
+    PhilipsOutputErrorMessage(Result);\r
+\r
+    return Result;\r
+}\r
+\r
+\r
+int PhilipsDownload(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    unsigned long realsize;\r
+    char Answer[128];\r
+    char temp[128];\r
+    /*const*/ char *strippedAnswer, *endPtr;\r
+    int  strippedsize;\r
+    int nQuestionMarks;\r
+    int found;\r
+    unsigned long Sector;\r
+    unsigned long SectorLength;\r
+    unsigned long SectorStart, SectorOffset, SectorChunk;\r
+    char tmpString[128];\r
+    char uuencode_table[64];\r
+    int Line;\r
+    unsigned long tmpStringPos;\r
+    unsigned long BlockOffset;\r
+    unsigned long Block;\r
+    unsigned long Pos;\r
+    unsigned long CopyLength;\r
+    int c,k=0,i;\r
+    unsigned long ivt_CRC;          // CRC over interrupt vector table\r
+    unsigned long block_CRC;\r
+    time_t tStartUpload=0, tDoneUpload=0;\r
+    long WatchDogSeconds = 0;\r
+    int WaitForWatchDog = 0;\r
+    char tmp_string[64];\r
+    char * cmdstr;\r
+\r
+#if !defined COMPILE_FOR_LPC21\r
+\r
+#if defined __BORLANDC__\r
+#define local_static static\r
+#else\r
+#define local_static\r
+#endif\r
+\r
+//    char * cmdstr;\r
+    int repeat = 0;\r
+    // Puffer for data to resend after "RESEND\r\n" Target responce\r
+    local_static char sendbuf0[128];\r
+    local_static char sendbuf1[128];\r
+    local_static char sendbuf2[128];\r
+    local_static char sendbuf3[128];\r
+    local_static char sendbuf4[128];\r
+    local_static char sendbuf5[128];\r
+    local_static char sendbuf6[128];\r
+    local_static char sendbuf7[128];\r
+    local_static char sendbuf8[128];\r
+    local_static char sendbuf9[128];\r
+    local_static char sendbuf10[128];\r
+    local_static char sendbuf11[128];\r
+    local_static char sendbuf12[128];\r
+    local_static char sendbuf13[128];\r
+    local_static char sendbuf14[128];\r
+    local_static char sendbuf15[128];\r
+    local_static char sendbuf16[128];\r
+    local_static char sendbuf17[128];\r
+    local_static char sendbuf18[128];\r
+    local_static char sendbuf19[128];\r
+\r
+    char * sendbuf[20] = {    sendbuf0,  sendbuf1,  sendbuf2,  sendbuf3,  sendbuf4,\r
+                              sendbuf5,  sendbuf6,  sendbuf7,  sendbuf8,  sendbuf9,\r
+                              sendbuf10, sendbuf11, sendbuf12, sendbuf13, sendbuf14,\r
+                              sendbuf15, sendbuf16, sendbuf17, sendbuf18, sendbuf19};\r
+#endif\r
+\r
+    if (!IspEnvironment->DetectOnly)\r
+    {\r
+        // Build up uuencode table\r
+        uuencode_table[0] = 0x60;           // 0x20 is translated to 0x60 !\r
+\r
+        for (i = 1; i < 64; i++)\r
+        {\r
+            uuencode_table[i] = (char)(0x20 + i);\r
+        }\r
+\r
+        // Patch 0x14, otherwise it is not running and jumps to boot mode\r
+\r
+        ivt_CRC = 0;\r
+\r
+        // Clear the vector at 0x14 so it doesn't affect the checksum:\r
+        for (i = 0; i < 4; i++)\r
+        {\r
+            IspEnvironment->BinaryContent[i + 0x14] = 0;\r
+        }\r
+\r
+        // Calculate a native checksum of the little endian vector table:\r
+        for (i = 0; i < (4 * 8);) {\r
+            ivt_CRC += IspEnvironment->BinaryContent[i++];\r
+            ivt_CRC += IspEnvironment->BinaryContent[i++] << 8;\r
+            ivt_CRC += IspEnvironment->BinaryContent[i++] << 16;\r
+            ivt_CRC += IspEnvironment->BinaryContent[i++] << 24;\r
+        }\r
+\r
+        /* Negate the result and place in the vector at 0x14 as little endian\r
+        * again. The resulting vector table should checksum to 0. */\r
+        ivt_CRC = (unsigned long) (0 - ivt_CRC);\r
+        for (i = 0; i < 4; i++)\r
+        {\r
+            IspEnvironment->BinaryContent[i + 0x14] = (unsigned char)(ivt_CRC >> (8 * i));\r
+        }\r
+\r
+        DebugPrintf(3, "Position 0x14 patched: ivt_CRC = 0x%08lX\n", ivt_CRC);\r
+    }\r
+\r
+    DebugPrintf(2, "Synchronizing (ESC to abort)");\r
+\r
+    PrepareKeyboardTtySettings();\r
+\r
+#if defined INTEGRATED_IN_WIN_APP\r
+    if (IspEnvironment->NoSync)\r
+    {\r
+        found = 1;\r
+    }\r
+    else\r
+#endif\r
+    {\r
+        for (nQuestionMarks = found = 0; !found && nQuestionMarks < 100; nQuestionMarks++)\r
+        {\r
+#if defined INTEGRATED_IN_WIN_APP\r
+            // allow calling application to abort when syncing takes too long\r
+\r
+            if (!AppSyncing(nQuestionMarks))\r
+            {\r
+                return (USER_ABORT_SYNC);\r
+            }\r
+#else\r
+#ifndef Exclude_kbhit\r
+            if (kbhit())\r
+            {\r
+                if (getch() == 0x1b)\r
+                {\r
+                    ResetKeyboardTtySettings();\r
+                    DebugPrintf(2, "\nUser aborted during synchronisation\n");\r
+                    return (USER_ABORT_SYNC);\r
+                }\r
+            }\r
+#endif\r
+#endif\r
+\r
+            DebugPrintf(2, ".");\r
+            SendComPort(IspEnvironment, "?");\r
+\r
+            memset(Answer,0,sizeof(Answer));\r
+            ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 1,100);\r
+\r
+            strippedAnswer = Answer;\r
+            strippedsize = realsize;\r
+            while ((strippedsize > 0) && ((*strippedAnswer == '?') || (*strippedAnswer == 0)))\r
+            {\r
+                strippedAnswer++;\r
+                strippedsize--;\r
+            }\r
+\r
+            sprintf(tmp_string, "StrippedAnswer(Length=%ld): '", strippedsize);\r
+            DumpString(3, strippedAnswer, strippedsize, tmp_string);\r
+\r
+            if (strcmp(strippedAnswer, "Bootloader\r\n") == 0 && IspEnvironment->TerminalOnly == 0)\r
+            {\r
+                long chars, xtal;\r
+                unsigned long ticks;\r
+                chars = (17 * IspEnvironment->BinaryLength + 1) / 10;\r
+                WatchDogSeconds = (10 * chars + 5) / atol(IspEnvironment->baud_rate) + 10;\r
+                xtal = atol(IspEnvironment->StringOscillator) * 1000;\r
+                ticks = (unsigned long)WatchDogSeconds * ((xtal + 15) / 16);\r
+                DebugPrintf(2, "Entering ISP; re-synchronizing (watchdog = %ld seconds)\n", WatchDogSeconds);\r
+                sprintf(temp, "T %lu\r\n", ticks);\r
+                SendComPort(IspEnvironment, temp);\r
+                ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 1,100);\r
+                if (strcmp(Answer, "OK\r\n") != 0)\r
+                {\r
+                    ResetKeyboardTtySettings();\r
+                    DebugPrintf(2, "No answer on 'watchdog timer set'\n");\r
+                    return (NO_ANSWER_WDT);\r
+                }\r
+                SendComPort(IspEnvironment, "G 10356\r\n");\r
+                Sleep(200);\r
+                nQuestionMarks = 0;\r
+                WaitForWatchDog = 1;\r
+                continue;\r
+            }\r
+\r
+            tStartUpload = time(NULL);\r
+\r
+            if (strcmp(strippedAnswer, "Synchronized\r\n") == 0)\r
+            {\r
+                found = 1;\r
+            }\r
+#if !defined COMPILE_FOR_LPC21\r
+            else\r
+            {\r
+                ResetTarget(IspEnvironment, PROGRAM_MODE);\r
+            }\r
+#endif\r
+        }\r
+    }\r
+\r
+    ResetKeyboardTtySettings();\r
+\r
+    if (!found)\r
+    {\r
+        DebugPrintf(1, " no answer on '?'\n");\r
+        return (NO_ANSWER_QM);\r
+    }\r
+\r
+#if defined INTEGRATED_IN_WIN_APP\r
+    AppSyncing(-1);                         // flag syncing done\r
+#endif\r
+\r
+    DebugPrintf(2, " OK\n");\r
+\r
+    if (IspEnvironment->HalfDuplex == 0)\r
+    {\r
+        SendComPort(IspEnvironment, "Synchronized\r\n");\r
+    }\r
+    else\r
+    {\r
+        SendComPort(IspEnvironment, "Synchronized\n");\r
+    }\r
+\r
+    ReceiveComPort(IspEnvironment, Answer, sizeof(Answer) - 1, &realsize, 2, 1000);\r
+\r
+    if ((strcmp(Answer, "Synchronized\r\nOK\r\n") != 0) && (strcmp(Answer, "Synchronized\rOK\r\n") != 0) &&\r
+        (strcmp(Answer, "Synchronized\nOK\r\n") != 0))\r
+    {\r
+        DebugPrintf(1, "No answer on 'Synchronized'\n");\r
+        return (NO_ANSWER_SYNC);\r
+    }\r
+\r
+    DebugPrintf(3, "Synchronized 1\n");\r
+\r
+    DebugPrintf(3, "Setting oscillator\n");\r
+\r
+    if (IspEnvironment->HalfDuplex == 0)\r
+        sprintf(temp, "%s\r\n", IspEnvironment->StringOscillator);\r
+    else\r
+        sprintf(temp, "%s\n", IspEnvironment->StringOscillator);\r
+\r
+    SendComPort(IspEnvironment, temp);\r
+\r
+    ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 2, 1000);\r
+\r
+    if (IspEnvironment->HalfDuplex == 0)\r
+        sprintf(temp, "%s\r\nOK\r\n", IspEnvironment->StringOscillator);\r
+    else\r
+        sprintf(temp, "%s\nOK\r\n", IspEnvironment->StringOscillator);\r
+\r
+    if (strcmp(Answer, temp) != 0)\r
+    {\r
+        DebugPrintf(1, "No answer on Oscillator-Command\n");\r
+        return (NO_ANSWER_OSC);\r
+    }\r
+\r
+    DebugPrintf(3, "Unlock\n");\r
+\r
+    if (IspEnvironment->HalfDuplex == 0)\r
+        cmdstr = "U 23130\r\n";\r
+    else\r
+        cmdstr = "U 23130\n";\r
+\r
+    //if (!SendAndVerify(IspEnvironment, "U 23130\n", Answer, sizeof Answer))//if (!SendAndVerify(IspEnvironment, "U 23130\r\n", Answer, sizeof Answer))\r
+    if (!SendAndVerify(IspEnvironment, cmdstr, Answer, sizeof Answer))\r
+    {\r
+        DebugPrintf(1, "Unlock-Command:\n");\r
+        return (UNLOCK_ERROR + GetAndReportErrorNumber(Answer));\r
+    }\r
+\r
+    DebugPrintf(2, "Read bootcode version: ");\r
+\r
+    if (IspEnvironment->HalfDuplex == 0)\r
+        cmdstr = "K\r\n";\r
+    else\r
+        cmdstr = "K\n";\r
+\r
+    SendComPort(IspEnvironment, cmdstr);\r
+\r
+    ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 4,5000);\r
+\r
+\r
+    //if (strncmp(Answer, "K\n", 2) != 0)//if (strncmp(Answer, "K\r\n", 3) != 0)\r
+    if (strncmp(Answer, cmdstr, strlen(cmdstr)) != 0)\r
+    {\r
+        DebugPrintf(1, "no answer on Read Boot Code Version\n");\r
+        return (NO_ANSWER_RBV);\r
+    }\r
+\r
+    //if (strncmp(Answer, "K\n0\r\n", 5) == 0)//if (strncmp(Answer, "K\r\n0\r\n", 6) == 0)\r
+    if (strncmp(Answer + strlen(cmdstr), "0\r\n", 3) == 0)\r
+    {\r
+        strippedAnswer = Answer + strlen(cmdstr) + 3;\r
+        /*\r
+        int maj, min, build;\r
+        if (sscanf(strippedAnswer, "%d %d %d", &build, &min, &maj) == 2) {\r
+        maj = min;\r
+        min = build;\r
+        build = 0;\r
+        } // if\r
+        DebugPrintf(2, "%d.%d.%d\n", maj, min, build);\r
+        */\r
+        DebugPrintf(2, strippedAnswer);\r
+    }\r
+    else\r
+    {\r
+        DebugPrintf(2, "unknown\n");\r
+    }\r
+\r
+    DebugPrintf(2, "Read part ID: ");\r
+\r
+    if (IspEnvironment->HalfDuplex == 0)\r
+        cmdstr = "J\r\n";\r
+    else\r
+        cmdstr = "J\n";\r
+\r
+    SendComPort(IspEnvironment, cmdstr);\r
+\r
+    ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 3,5000);\r
+\r
+\r
+\r
+    //if (strncmp(Answer, "J\n", 2) != 0)//if (strncmp(Answer, "J\r\n", 3) != 0)\r
+    if (strncmp(Answer, cmdstr, strlen(cmdstr)) != 0)\r
+    {\r
+        DebugPrintf(1, "no answer on Read Part Id\n");\r
+        return (NO_ANSWER_RPID);\r
+    }\r
+\r
+    if (IspEnvironment->HalfDuplex == 0)\r
+        strippedAnswer = (strncmp(Answer, "J\r\n0\r\n", 6) == 0) ? Answer + 6 : Answer;\r
+    else\r
+        strippedAnswer = (strncmp(Answer, "J\n0\r\n", 5) == 0) ? Answer + 5 : Answer;\r
+\r
+    Pos = strtoul(strippedAnswer, &endPtr, 10);\r
+    *endPtr = '\0'; /* delete \r\n */\r
+    for (i = sizeof LPCtypes / sizeof LPCtypes[0] - 1; i > 0 && LPCtypes[i].id != Pos; i--)\r
+        /* nothing */;\r
+        IspEnvironment->DetectedDevice = i;\r
+    if (IspEnvironment->DetectedDevice == 0) {\r
+        DebugPrintf(2, "unknown");\r
+    }\r
+    else {\r
+        DebugPrintf(2, "LPC%d, %d kiB ROM / %d kiB SRAM",\r
+            LPCtypes[IspEnvironment->DetectedDevice].Product,\r
+            LPCtypes[IspEnvironment->DetectedDevice].FlashSize,\r
+            LPCtypes[IspEnvironment->DetectedDevice].RAMSize);\r
+    }\r
+    DebugPrintf(2, " (0x%X)\n", Pos);//strippedAnswer);\r
+\r
+    /* In case of a download to RAM, use full RAM for downloading\r
+    * set the flash parameters to full RAM also.\r
+    * This makes sure that all code is downloaded as one big sector\r
+    */\r
+\r
+    if (IspEnvironment->BinaryOffset >= LPC_RAMSTART)\r
+    {\r
+        LPCtypes[IspEnvironment->DetectedDevice].FlashSectors = 1;\r
+        LPCtypes[IspEnvironment->DetectedDevice].MaxCopySize  = LPCtypes[IspEnvironment->DetectedDevice].RAMSize*1024 - (LPC_RAMBASE - LPC_RAMSTART);\r
+        LPCtypes[IspEnvironment->DetectedDevice].SectorTable  = SectorTable_RAM;\r
+        SectorTable_RAM[0] = LPCtypes[IspEnvironment->DetectedDevice].MaxCopySize;\r
+    }\r
+    if (IspEnvironment->DetectOnly)\r
+        return (0);\r
+\r
+\r
+    // Start with sector 1 and go upward... Sector 0 containing the interrupt vectors\r
+    // will be loaded last, since it contains a checksum and device will re-enter\r
+    // bootloader mode as long as this checksum is invalid.\r
+    DebugPrintf(2, "Will start programming at Sector 1 if possible, and conclude with Sector 0 to ensure that checksum is written last.\n");\r
+    if (LPCtypes[IspEnvironment->DetectedDevice].SectorTable[0] >= IspEnvironment->BinaryLength)\r
+    {\r
+        Sector = 0;\r
+        SectorStart = 0;\r
+    }\r
+    else\r
+    {\r
+        SectorStart = LPCtypes[IspEnvironment->DetectedDevice].SectorTable[0];\r
+        Sector = 1;\r
+    }\r
+\r
+    if (IspEnvironment->WipeDevice == 1)\r
+    {\r
+        DebugPrintf(2, "Wiping Device. ");\r
+\r
+        if (IspEnvironment->HalfDuplex == 0)\r
+          sprintf(tmpString, "P %ld %ld\r\n", 0, LPCtypes[IspEnvironment->DetectedDevice].FlashSectors-1);\r
+        else\r
+            sprintf(tmpString, "P %ld %ld\n", 0, LPCtypes[IspEnvironment->DetectedDevice].FlashSectors-1);\r
+\r
+        if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))\r
+        {\r
+            DebugPrintf(1, "Wrong answer on Prepare-Command\n");\r
+            return (WRONG_ANSWER_PREP + GetAndReportErrorNumber(Answer));\r
+        }\r
+\r
+        if (IspEnvironment->HalfDuplex == 0)\r
+            sprintf(tmpString, "E %ld %ld\r\n", 0, LPCtypes[IspEnvironment->DetectedDevice].FlashSectors-1);\r
+        else\r
+            sprintf(tmpString, "E %ld %ld\n", 0, LPCtypes[IspEnvironment->DetectedDevice].FlashSectors-1);\r
+\r
+        if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))\r
+        {\r
+            DebugPrintf(1, "Wrong answer on Erase-Command\n");\r
+            return (WRONG_ANSWER_ERAS + GetAndReportErrorNumber(Answer));\r
+        }\r
+        DebugPrintf(2, "OK \n");\r
+    }\r
+    while (1)\r
+    {\r
+        if (Sector >= LPCtypes[IspEnvironment->DetectedDevice].FlashSectors)\r
+        {\r
+            DebugPrintf(1, "Program too large; running out of Flash sectors.\n");\r
+            return (PROGRAM_TOO_LARGE);\r
+        }\r
+\r
+        DebugPrintf(2, "Sector %ld: ", Sector);\r
+        fflush(stdout);\r
+\r
+        if (IspEnvironment->BinaryOffset < LPC_RAMSTART) // Skip Erase when running from RAM\r
+        {\r
+            if (IspEnvironment->HalfDuplex == 0)\r
+                sprintf(tmpString, "P %ld %ld\r\n", Sector, Sector);\r
+            else\r
+                sprintf(tmpString, "P %ld %ld\n", Sector, Sector);\r
+\r
+            if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))\r
+            {\r
+                DebugPrintf(1, "Wrong answer on Prepare-Command (1) (Sector %ld)\n", Sector);\r
+                return (WRONG_ANSWER_PREP + GetAndReportErrorNumber(Answer));\r
+            }\r
+\r
+            DebugPrintf(2, ".");\r
+            fflush(stdout);\r
+            if (IspEnvironment->WipeDevice == 0)\r
+            {\r
+                if (IspEnvironment->HalfDuplex == 0)\r
+                    sprintf(tmpString, "E %ld %ld\r\n", Sector, Sector);\r
+                else\r
+                    sprintf(tmpString, "E %ld %ld\n", Sector, Sector);\r
+\r
+                if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))\r
+                {\r
+                    DebugPrintf(1, "Wrong answer on Erase-Command (Sector %ld)\n", Sector);\r
+                    return (WRONG_ANSWER_ERAS + GetAndReportErrorNumber(Answer));\r
+                }\r
+\r
+                DebugPrintf(2, ".");\r
+                fflush(stdout);\r
+            }\r
+        }\r
+\r
+        SectorLength = LPCtypes[IspEnvironment->DetectedDevice].SectorTable[Sector];\r
+        if (SectorLength > IspEnvironment->BinaryLength - SectorStart)\r
+        {\r
+            SectorLength = IspEnvironment->BinaryLength - SectorStart;\r
+        }\r
+\r
+        for (SectorOffset = 0; SectorOffset < SectorLength; SectorOffset += SectorChunk)\r
+        {\r
+            if (SectorOffset > 0)\r
+            {\r
+                // Add a visible marker between segments in a sector\r
+                DebugPrintf(2, "|");  /* means: partial segment copied */\r
+                fflush(stdout);\r
+            }\r
+\r
+            // If the Flash ROM sector size is bigger than the number of bytes\r
+            // we can copy from RAM to Flash, we must "chop up" the sector and\r
+            // copy these individually.\r
+            // This is especially needed in the case where a Flash sector is\r
+            // bigger than the amount of SRAM.\r
+            SectorChunk = SectorLength - SectorOffset;\r
+            if (SectorChunk > (unsigned)LPCtypes[IspEnvironment->DetectedDevice].MaxCopySize)\r
+            {\r
+                SectorChunk = LPCtypes[IspEnvironment->DetectedDevice].MaxCopySize;\r
+            }\r
+\r
+            // Write multiple of 45 * 4 Byte blocks to RAM, but copy maximum of on sector to Flash\r
+            // In worst case we transfer up to 180 byte to much to RAM\r
+            // but then we can always use full 45 byte blocks and length is multiple of 4\r
+            CopyLength = SectorChunk;\r
+            if ((CopyLength % (45 * 4)) != 0)\r
+            {\r
+                CopyLength += ((45 * 4) - (CopyLength % (45 * 4)));\r
+            }\r
+\r
+            if (IspEnvironment->HalfDuplex == 0)\r
+                sprintf(tmpString, "W %ld %ld\r\n", LPC_RAMBASE, CopyLength);\r
+            else\r
+                sprintf(tmpString, "W %ld %ld\n", LPC_RAMBASE, CopyLength);\r
+\r
+            if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))\r
+            {\r
+                DebugPrintf(1, "Wrong answer on Write-Command\n");\r
+                return (WRONG_ANSWER_WRIT + GetAndReportErrorNumber(Answer));\r
+            }\r
+\r
+            DebugPrintf(2, ".");\r
+            fflush(stdout);\r
+\r
+            block_CRC = 0;\r
+            Line = 0;\r
+\r
+            // Transfer blocks of 45 * 4 bytes to RAM\r
+            for (Pos = SectorStart + SectorOffset; (Pos < SectorStart + SectorOffset + CopyLength) && (Pos < IspEnvironment->BinaryLength); Pos += (45 * 4))\r
+            {\r
+                for (Block = 0; Block < 4; Block++)  // Each block 45 bytes\r
+                {\r
+                    DebugPrintf(2, ".");\r
+                    fflush(stdout);\r
+\r
+#if defined INTEGRATED_IN_WIN_APP\r
+                    // inform the calling application about having written another chuck of data\r
+                    AppWritten(45);\r
+#endif\r
+\r
+                    // Uuencode one 45 byte block\r
+                    tmpStringPos = 0;\r
+\r
+#if !defined COMPILE_FOR_LPC21\r
+                    sendbuf[Line][tmpStringPos++] = (char)(' ' + 45);    // Encode Length of block\r
+#else\r
+                    tmpString[tmpStringPos++] = (char)(' ' + 45);        // Encode Length of block\r
+#endif\r
+\r
+                    for (BlockOffset = 0; BlockOffset < 45; BlockOffset++)\r
+                    {\r
+                        if (IspEnvironment->BinaryOffset < LPC_RAMSTART)\r
+                        { // Flash: use full memory\r
+                            c = IspEnvironment->BinaryContent[Pos + Block * 45 + BlockOffset];\r
+                        }\r
+                        else\r
+                        { // RAM: Skip first 0x200 bytes, these are used by the download program in LPC21xx\r
+                            c = IspEnvironment->BinaryContent[Pos + Block * 45 + BlockOffset + 0x200];\r
+                        }\r
+\r
+                        block_CRC += c;\r
+\r
+                        k = (k << 8) + (c & 255);\r
+\r
+                        if ((BlockOffset % 3) == 2)   // Collecting always 3 Bytes, then do processing in 4 Bytes\r
+                        {\r
+#if !defined COMPILE_FOR_LPC21\r
+                            sendbuf[Line][tmpStringPos++] = uuencode_table[(k >> 18) & 63];\r
+                            sendbuf[Line][tmpStringPos++] = uuencode_table[(k >> 12) & 63];\r
+                            sendbuf[Line][tmpStringPos++] = uuencode_table[(k >>  6) & 63];\r
+                            sendbuf[Line][tmpStringPos++] = uuencode_table[ k        & 63];\r
+#else\r
+                            tmpString[tmpStringPos++] = uuencode_table[(k >> 18) & 63];\r
+                            tmpString[tmpStringPos++] = uuencode_table[(k >> 12) & 63];\r
+                            tmpString[tmpStringPos++] = uuencode_table[(k >>  6) & 63];\r
+                            tmpString[tmpStringPos++] = uuencode_table[ k        & 63];\r
+#endif\r
+                        }\r
+                    }\r
+\r
+\r
+#if !defined COMPILE_FOR_LPC21\r
+                    sendbuf[Line][tmpStringPos++] = '\r';\r
+                    sendbuf[Line][tmpStringPos++] = '\n';\r
+                    sendbuf[Line][tmpStringPos++] = 0;\r
+\r
+                    SendComPort(IspEnvironment, sendbuf[Line]);\r
+                    // receive only for debug proposes\r
+                    ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 1,5000);\r
+#else\r
+                    tmpString[tmpStringPos++] = '\r';\r
+                    tmpString[tmpStringPos++] = '\n';\r
+                    tmpString[tmpStringPos++] = 0;\r
+\r
+                    SendComPort(IspEnvironment, tmpString);\r
+                    ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 1,5000);\r
+                    if (strncmp(Answer, tmpString, tmpStringPos) != 0)\r
+                    {\r
+                        DebugPrintf(1, "Error on writing data (1)\n");\r
+                        return (ERROR_WRITE_DATA);\r
+                    }\r
+#endif\r
+\r
+                    Line++;\r
+\r
+                    DebugPrintf(3, "Line = %d\n", Line);\r
+\r
+                    if (Line == 20)\r
+                    {\r
+#if !defined COMPILE_FOR_LPC21\r
+                        for (repeat = 0; repeat < 3; repeat++)\r
+                        {\r
+\r
+                            // printf("block_CRC = %ld\n", block_CRC);\r
+\r
+                            if (IspEnvironment->HalfDuplex == 0)\r
+                                sprintf(tmpString, "%ld\r\n", block_CRC);\r
+                            else\r
+                                sprintf(tmpString, "%ld\n", block_CRC);\r
+\r
+                            SendComPort(IspEnvironment, tmpString);\r
+\r
+                            ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 2,5000);\r
+\r
+                            if (IspEnvironment->HalfDuplex == 0)\r
+                                sprintf(tmpString, "%ld\r\nOK\r\n", block_CRC);\r
+                            else\r
+                                sprintf(tmpString, "%ld\nOK\r\n", block_CRC);\r
+\r
+                            if (strcmp(Answer, tmpString) != 0)\r
+                            {\r
+                                for (i = 0; i < Line; i++)\r
+                                {\r
+                                    SendComPort(IspEnvironment, sendbuf[i]);\r
+                                    ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 1,5000);\r
+                                }\r
+                            }\r
+                            else\r
+                                break;\r
+                        }\r
+\r
+                        if (repeat >= 3)\r
+                        {\r
+                            DebugPrintf(1, "Error on writing block_CRC (1)\n");\r
+                            return (ERROR_WRITE_CRC);\r
+                        }\r
+#else\r
+                        // printf("block_CRC = %ld\n", block_CRC);\r
+                        sprintf(tmpString, "%ld\r\n", block_CRC);\r
+                        SendComPort(IspEnvironment, tmpString);\r
+\r
+                        ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 2,5000);\r
+\r
+                        sprintf(tmpString, "%ld\r\nOK\r\n", block_CRC);\r
+                        if (strcmp(Answer, tmpString) != 0)\r
+                        {\r
+                            DebugPrintf(1, "Error on writing block_CRC (1)\n");\r
+                            return (ERROR_WRITE_CRC);\r
+                        }\r
+#endif\r
+                        Line = 0;\r
+                        block_CRC = 0;\r
+                    }\r
+                }\r
+            }\r
+\r
+            if (Line != 0)\r
+            {\r
+#if !defined COMPILE_FOR_LPC21\r
+                for (repeat = 0; repeat < 3; repeat++)\r
+                {\r
+                    if (IspEnvironment->HalfDuplex == 0)\r
+                        sprintf(tmpString, "%ld\r\n", block_CRC);\r
+                    else\r
+                        sprintf(tmpString, "%ld\n", block_CRC);\r
+\r
+                    SendComPort(IspEnvironment, tmpString);\r
+\r
+                    ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 2,5000);\r
+\r
+                    if (IspEnvironment->HalfDuplex == 0)\r
+                        sprintf(tmpString, "%ld\r\nOK\r\n", block_CRC);\r
+                    else\r
+                        sprintf(tmpString, "%ld\nOK\r\n", block_CRC);\r
+\r
+                    if (strcmp(Answer, tmpString) != 0)\r
+                    {\r
+                        for (i = 0; i < Line; i++)\r
+                        {\r
+                            SendComPort(IspEnvironment, sendbuf[i]);\r
+                            ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 1,5000);\r
+                        }\r
+                    }\r
+                    else\r
+                        break;\r
+                }\r
+\r
+                if (repeat >= 3)\r
+                {\r
+                    DebugPrintf(1, "Error on writing block_CRC (2)\n");\r
+                    return (ERROR_WRITE_CRC2);\r
+                }\r
+#else\r
+                sprintf(tmpString, "%ld\r\n", block_CRC);\r
+                SendComPort(IspEnvironment, tmpString);\r
+\r
+                ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 2,5000);\r
+\r
+                sprintf(tmpString, "%ld\r\nOK\r\n", block_CRC);\r
+                if (strcmp(Answer, tmpString) != 0)\r
+                {\r
+                    DebugPrintf(1, "Error on writing block_CRC (2)\n");\r
+                    return (ERROR_WRITE_CRC2);\r
+                }\r
+#endif\r
+            }\r
+\r
+            if (IspEnvironment->BinaryOffset < LPC_RAMSTART)\r
+            {\r
+                // Prepare command must be repeated before every write\r
+                if (IspEnvironment->HalfDuplex == 0)\r
+                    sprintf(tmpString, "P %ld %ld\r\n", Sector, Sector);\r
+                else\r
+                    sprintf(tmpString, "P %ld %ld\n", Sector, Sector);\r
+\r
+                if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))\r
+                {\r
+                    DebugPrintf(1, "Wrong answer on Prepare-Command (2) (Sector %ld)\n", Sector);\r
+                    return (WRONG_ANSWER_PREP2 + GetAndReportErrorNumber(Answer));\r
+                }\r
+\r
+                // Round CopyLength up to one of the following values: 512, 1024,\r
+                // 4096, 8192; but do not exceed the maximum copy size (usually\r
+                // 8192, but chip-dependent)\r
+                if (CopyLength < 512)\r
+                {\r
+                    CopyLength = 512;\r
+                }\r
+                else if (SectorLength < 1024)\r
+                {\r
+                    CopyLength = 1024;\r
+                }\r
+                else if (SectorLength < 4096)\r
+                {\r
+                    CopyLength = 4096;\r
+                }\r
+                else\r
+                {\r
+                    CopyLength = 8192;\r
+                }\r
+                if (CopyLength > (unsigned)LPCtypes[IspEnvironment->DetectedDevice].MaxCopySize)\r
+                {\r
+                    CopyLength = LPCtypes[IspEnvironment->DetectedDevice].MaxCopySize;\r
+                }\r
+\r
+                if (IspEnvironment->HalfDuplex == 0)\r
+                    sprintf(tmpString, "C %ld %ld %ld\r\n", SectorStart + SectorOffset, LPC_RAMBASE, CopyLength);\r
+                else\r
+                    sprintf(tmpString, "C %ld %ld %ld\n", SectorStart + SectorOffset, LPC_RAMBASE, CopyLength);\r
+\r
+                if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))\r
+                {\r
+                    DebugPrintf(1, "Wrong answer on Copy-Command\n");\r
+                    return (WRONG_ANSWER_COPY + GetAndReportErrorNumber(Answer));\r
+                }\r
+\r
+                if (IspEnvironment->Verify)\r
+                {\r
+\r
+                    //Avoid compare first 64 bytes.\r
+                    //Because first 64 bytes are re-mapped to flash boot sector,\r
+                    //and the compare result may not be correct.\r
+                    if (SectorStart + SectorOffset<64)\r
+                    {\r
+                        if (IspEnvironment->HalfDuplex == 0)\r
+                            sprintf(tmpString, "M %ld %ld %ld\r\n", 64, LPC_RAMBASE + (64 - SectorStart - SectorOffset), CopyLength-(64 - SectorStart - SectorOffset));\r
+                        else\r
+                            sprintf(tmpString, "M %ld %ld %ld\n", 64, LPC_RAMBASE + (64 - SectorStart - SectorOffset), CopyLength-(64 - SectorStart - SectorOffset));\r
+                    }\r
+                    else\r
+                    {\r
+                        if (IspEnvironment->HalfDuplex == 0)\r
+                            sprintf(tmpString, "M %ld %ld %ld\r\n", SectorStart + SectorOffset, LPC_RAMBASE, CopyLength);\r
+                        else\r
+                            sprintf(tmpString, "M %ld %ld %ld\n", SectorStart + SectorOffset, LPC_RAMBASE, CopyLength);\r
+                    }\r
+\r
+                    if (!SendAndVerify(IspEnvironment, tmpString, Answer, sizeof Answer))\r
+                    {\r
+                        DebugPrintf(1, "Wrong answer on Compare-Command\n");\r
+                        return (WRONG_ANSWER_COPY + GetAndReportErrorNumber(Answer));\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        DebugPrintf(2, "\n");\r
+        fflush(stdout);\r
+\r
+        if ((SectorStart + SectorLength) >= IspEnvironment->BinaryLength && Sector!=0)\r
+        {\r
+            Sector = 0;\r
+            SectorStart = 0;\r
+        }\r
+        else if (Sector == 0) {\r
+            break;\r
+        }\r
+        else {\r
+            SectorStart += LPCtypes[IspEnvironment->DetectedDevice].SectorTable[Sector];\r
+            Sector++;\r
+        }\r
+    }\r
+\r
+    tDoneUpload = time(NULL);\r
+    if (IspEnvironment->Verify)\r
+        DebugPrintf(2, "Download Finished and Verified correct... taking %d seconds\n", tDoneUpload - tStartUpload);\r
+    else\r
+        DebugPrintf(2, "Download Finished... taking %d seconds\n", tDoneUpload - tStartUpload);\r
+\r
+    if (WaitForWatchDog)\r
+    {\r
+        DebugPrintf(2, "Wait for restart, in %d seconds from now\n", WatchDogSeconds - (tDoneUpload - tStartUpload));\r
+    }\r
+    else\r
+    {\r
+        DebugPrintf(2, "Now launching the brand new code\n");\r
+        fflush(stdout);\r
+\r
+        if (IspEnvironment->HalfDuplex == 0)\r
+            sprintf(tmpString, "G %ld A\r\n", IspEnvironment->StartAddress);\r
+        else\r
+            sprintf(tmpString, "G %ld A\n", IspEnvironment->StartAddress);\r
+\r
+        SendComPort(IspEnvironment, tmpString); //goto 0 : run this fresh new downloaded code code\r
+        if (IspEnvironment->BinaryOffset < LPC_RAMSTART)\r
+        { // Skip response on G command - show response on Terminal instead\r
+            ReceiveComPort(IspEnvironment, Answer, sizeof(Answer)-1, &realsize, 2, 5000);\r
+            /* the reply string is frequently terminated with a -1 (EOF) because the\r
+            * connection gets broken; zero-terminate the string ourselves\r
+            */\r
+            while (realsize > 0 && ((signed char) Answer[(int)realsize - 1]) < 0)\r
+                realsize--;\r
+            Answer[(int)realsize] = '\0';\r
+            /* Better to check only the first 9 chars instead of complete receive buffer,\r
+            * because the answer can contain the output by the started programm\r
+            */\r
+            if (IspEnvironment->HalfDuplex == 0)\r
+            {\r
+                // This was not working with my LPC2214 most of the time - Herbert Demmel\r
+                // was: cmdstr = "G 0 A\r\n0\r";\r
+                cmdstr = "G 0 A\r\n0";\r
+            }\r
+            else\r
+            {\r
+                cmdstr = "G 0 A\n0\r";\r
+            }\r
+\r
+            //if (realsize == 0 || strncmp((const char *)Answer, "G 0 A\n0\r", 8) != 0)//if (realsize == 0 || strncmp((const char *)Answer, "G 0 A\r\n0\r", 9) != 0)\r
+            if (realsize == 0 || strncmp((const char *)Answer, cmdstr, strlen(cmdstr)) != 0)\r
+            {\r
+                DebugPrintf(2, "Failed to run the new downloaded code: ");\r
+                return (FAILED_RUN + GetAndReportErrorNumber(Answer));\r
+            }\r
+        }\r
+\r
+        fflush(stdout);\r
+    }\r
+    return (0);\r
+}\r
+#endif // LPC_SUPPORT\r
diff --git a/arch/arm/mach-lpc21xx/tools/lpc21isp/lpcprog.h b/arch/arm/mach-lpc21xx/tools/lpc21isp/lpcprog.h
new file mode 100644 (file)
index 0000000..19bbc56
--- /dev/null
@@ -0,0 +1,100 @@
+/******************************************************************************\r
+\r
+Project:           Portable command line ISP for Philips LPC2000 family\r
+                   and Analog Devices ADUC70xx\r
+\r
+Filename:          lpcprog.h\r
+\r
+Compiler:          Microsoft VC 6/7, GCC Cygwin, GCC Linux, GCC ARM ELF\r
+\r
+Author:            Martin Maurer (Martin.Maurer@clibb.de)\r
+\r
+Copyright:         (c) Martin Maurer 2003-2008, All rights reserved\r
+Portions Copyright (c) by Aeolus Development 2004 http://www.aeolusdevelopment.com\r
+\r
+    This file is part of lpc21isp.\r
+\r
+    lpc21isp is free software: you can redistribute it and/or modify\r
+    it under the terms of the GNU Lesser General Public License as published by\r
+    the Free Software Foundation, either version 3 of the License, or\r
+    any later version.\r
+\r
+    lpc21isp is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+    GNU Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public License\r
+    and GNU General Public License along with lpc21isp.\r
+    If not, see <http://www.gnu.org/licenses/>.\r
+*/\r
+\r
+/* LPC_RAMSTART, LPC_RAMBASE\r
+*\r
+* Used in PhilipsDownload() to decide whether to Flash code or just place in in RAM\r
+* (works for .hex files only)\r
+*\r
+* LPC_RAMSTART - the Physical start address of the SRAM\r
+* LPC_RAMBASE  - the base address where downloading starts.\r
+*                Note that any code in the .hex file that resides in 0x4000,0000 ~ 0x4000,0200\r
+*                will _not_ be written to the LPCs SRAM.\r
+*                This is due to the fact that 0x4000,0040 - 0x4000,0200 is used by the bootrom.\r
+*                Any interrupt vectors must be copied to 0x4000,0000 and remapped to 0x0000,0000\r
+*                by the startup code.\r
+*/\r
+#define LPC_RAMSTART    0x40000000L\r
+#define LPC_RAMBASE     0x40000200L\r
+\r
+/* Return values used by PhilipsDownload(): reserving all values from 0x1000 to 0x1FFF */\r
+\r
+#define NO_ANSWER_WDT       0x1000\r
+#define NO_ANSWER_QM        0x1001\r
+#define NO_ANSWER_SYNC      0x1002\r
+#define NO_ANSWER_OSC       0x1003\r
+#define NO_ANSWER_RBV       0x1004\r
+#define NO_ANSWER_RPID      0x1005\r
+#define ERROR_WRITE_DATA    0x1006\r
+#define ERROR_WRITE_CRC     0x1007\r
+#define ERROR_WRITE_CRC2    0x1008\r
+#define PROGRAM_TOO_LARGE   0x1009\r
+\r
+#define USER_ABORT_SYNC     0x100A   /* User aborted synchronisation process */\r
+\r
+#define UNLOCK_ERROR        0x1100   /* return value is 0x1100 + philips ISP returned value (0 to 255) */\r
+#define WRONG_ANSWER_PREP   0x1200   /* return value is 0x1200 + philips ISP returned value (0 to 255) */\r
+#define WRONG_ANSWER_ERAS   0x1300   /* return value is 0x1300 + philips ISP returned value (0 to 255) */\r
+#define WRONG_ANSWER_WRIT   0x1400   /* return value is 0x1400 + philips ISP returned value (0 to 255) */\r
+#define WRONG_ANSWER_PREP2  0x1500   /* return value is 0x1500 + philips ISP returned value (0 to 255) */\r
+#define WRONG_ANSWER_COPY   0x1600   /* return value is 0x1600 + philips ISP returned value (0 to 255) */\r
+#define FAILED_RUN          0x1700   /* return value is 0x1700 + philips ISP returned value (0 to 255) */\r
+\r
+#ifndef WIN32\r
+#define LPC_BSL_PIN        13\r
+#define LPC_RESET_PIN    47\r
+#define LPC_RESET(in)    NAsetGPIOpin(LPC_RESET_PIN, (in))\r
+#define LPC_BSL(in)        NAsetGPIOpin(LPC_BSL_PIN, (in))\r
+#endif\r
+\r
+\r
+/* LPC_FLASHMASK\r
+*\r
+* LPC_FLASHMASK - bitmask to define the maximum size of the Filesize to download.\r
+*                 LoadFile() will check any new segment address record (03) or extended linear\r
+*                 address record (04) to see if the addressed 64 kByte data block still falls\r
+*                 in the max. flash size.\r
+*                 LoadFile() will not load any files that are larger than this size.\r
+*/\r
+#define LPC_FLASHMASK  0xFFC00000 /* 22 bits = 4 MB */\r
+\r
+typedef struct\r
+{\r
+    unsigned long id;\r
+    unsigned Product;\r
+    unsigned FlashSize;     /* in kiB, for informational purposes only */\r
+    unsigned RAMSize;       /* in kiB, for informational purposes only */\r
+    unsigned FlashSectors;  /* total number of sectors */\r
+    unsigned MaxCopySize;   /* maximum size that can be copied to Flash in a single command */\r
+    const unsigned int *SectorTable; /* pointer to a sector table with constant the sector sizes */\r
+} LPC_DEVICE_TYPE;\r
+\r
+int PhilipsDownload(ISP_ENVIRONMENT *IspEnvironment);\r
diff --git a/arch/arm/mach-lpc21xx/tools/lpc21isp/lpcterm.c b/arch/arm/mach-lpc21xx/tools/lpc21isp/lpcterm.c
new file mode 100644 (file)
index 0000000..556d224
--- /dev/null
@@ -0,0 +1,137 @@
+/******************************************************************************\r
+\r
+Project:           Portable command line ISP for Philips LPC2000 family\r
+                   and Analog Devices ADUC70xx\r
+\r
+Filename:          lpcterm.c\r
+\r
+Compiler:          Microsoft VC 6/7, GCC Cygwin, GCC Linux, GCC ARM ELF\r
+\r
+Author:            Martin Maurer (Martin.Maurer@clibb.de)\r
+\r
+Copyright:         (c) Martin Maurer 2003-2008, All rights reserved\r
+Portions Copyright (c) by Aeolus Development 2004 http://www.aeolusdevelopment.com\r
+\r
+    This file is part of lpc21isp.\r
+\r
+    lpc21isp is free software: you can redistribute it and/or modify\r
+    it under the terms of the GNU Lesser General Public License as published by\r
+    the Free Software Foundation, either version 3 of the License, or\r
+    any later version.\r
+\r
+    lpc21isp is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+    GNU Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public License\r
+    and GNU General Public License along with lpc21isp.\r
+    If not, see <http://www.gnu.org/licenses/>.\r
+*/\r
+\r
+#if defined(_WIN32)\r
+#if !defined __BORLANDC__\r
+#include "StdAfx.h"\r
+#endif\r
+#endif // defined(_WIN32)\r
+#include "lpc21isp.h"\r
+#include "lpcterm.h"\r
+\r
+#ifdef TERMINAL_SUPPORT\r
+/***************************** Terminal *********************************/\r
+/**  Acts as a simple dumb terminal. Press 'ESC' to exit.\r
+*/\r
+BOOL CheckTerminalParameters(ISP_ENVIRONMENT *IspEnvironment, char* pstr)\r
+{\r
+    if (stricmp(pstr, "-localecho") == 0)\r
+    {\r
+        IspEnvironment->LocalEcho = 1;\r
+        DebugPrintf(3, "Local echo in terminal mode.\n");\r
+        return TRUE;\r
+    }\r
+\r
+    if (stricmp(pstr, "-term") == 0)\r
+    {\r
+        IspEnvironment->TerminalAfterUpload = 1;\r
+        DebugPrintf(3, "Invoke terminal after upload.\n");\r
+        return TRUE;\r
+    }\r
+\r
+    if (stricmp(pstr, "-termonly") == 0)\r
+    {\r
+        IspEnvironment->TerminalOnly    = 1;\r
+        IspEnvironment->ProgramChip    = 0;\r
+        DebugPrintf(3, "Only provide terminal.\n");\r
+        return TRUE;\r
+    }\r
+\r
+    return FALSE;\r
+}\r
+\r
+void Terminal(ISP_ENVIRONMENT *IspEnvironment)\r
+{\r
+    if (IspEnvironment->TerminalAfterUpload || IspEnvironment->TerminalOnly)\r
+    {\r
+        int           ch = 0;\r
+        char buffer[128];\r
+        int           fdlogfile = -1;\r
+        unsigned long realsize;\r
+\r
+        // When logging is switched on, output terminal output to lpc21isp.log\r
+        if (IspEnvironment->LogFile)\r
+        {\r
+            fdlogfile = open("lpc21isp.log", O_RDWR | O_BINARY | O_CREAT | O_TRUNC, 0777);\r
+        }\r
+\r
+        PrepareKeyboardTtySettings();\r
+\r
+        DebugPrintf(1, "Terminal started (press Escape to abort)\n\n");\r
+        fflush(stdout);\r
+\r
+        do\r
+        {\r
+            ReceiveComPort(IspEnvironment, buffer, sizeof(buffer) - 1, &realsize, 0,200);          // Check for received characters\r
+\r
+            if (realsize)\r
+            {\r
+                write(1, buffer, realsize);\r
+                fflush(stdout);\r
+                if (IspEnvironment->LogFile)     // When logging is turned on, then copy output to logfile\r
+                {\r
+                    write(fdlogfile, buffer, realsize);\r
+                }\r
+            }\r
+\r
+            // check for keypress, and write any out the port.\r
+            if (kbhit())\r
+            {\r
+                ch = getch();\r
+                if (ch == 0x1b)\r
+                {\r
+                    break;\r
+                }\r
+                buffer[0] = (unsigned char)ch;\r
+                buffer[1] = 0;\r
+\r
+                if (IspEnvironment->LocalEcho)\r
+                {\r
+                    write(1, buffer, 1);\r
+                }\r
+\r
+                SendComPort(IspEnvironment, buffer);\r
+            }\r
+        }\r
+        while (ch != 0x1b);\r
+\r
+        DebugPrintf(1, "\n\nTerminal stopped\n\n");\r
+        fflush(stdout);\r
+\r
+        ResetKeyboardTtySettings();\r
+\r
+        if (IspEnvironment->LogFile)\r
+        {\r
+            close(fdlogfile);\r
+        }\r
+    }\r
+}\r
+#endif\r
diff --git a/arch/arm/mach-lpc21xx/tools/lpc21isp/lpcterm.h b/arch/arm/mach-lpc21xx/tools/lpc21isp/lpcterm.h
new file mode 100644 (file)
index 0000000..85ef129
--- /dev/null
@@ -0,0 +1,42 @@
+/******************************************************************************\r
+\r
+Project:           Portable command line ISP for Philips LPC2000 family\r
+                   and Analog Devices ADUC70xx\r
+\r
+Filename:          lpcterm.h\r
+\r
+Compiler:          Microsoft VC 6/7, GCC Cygwin, GCC Linux, GCC ARM ELF\r
+\r
+Author:            Martin Maurer (Martin.Maurer@clibb.de)\r
+\r
+Copyright:         (c) Martin Maurer 2003-2008, All rights reserved\r
+Portions Copyright (c) by Aeolus Development 2004 http://www.aeolusdevelopment.com\r
+\r
+    This file is part of lpc21isp.\r
+\r
+    lpc21isp is free software: you can redistribute it and/or modify\r
+    it under the terms of the GNU Lesser General Public License as published by\r
+    the Free Software Foundation, either version 3 of the License, or\r
+    any later version.\r
+\r
+    lpc21isp is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+    GNU Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public License\r
+    and GNU General Public License along with lpc21isp.\r
+    If not, see <http://www.gnu.org/licenses/>.\r
+*/\r
+\r
+#ifndef TRUE\r
+#define TRUE (1)\r
+#endif\r
+#ifndef FALSE\r
+#define FALSE (0)\r
+#endif\r
+\r
+typedef int BOOL;\r
+\r
+void Terminal(ISP_ENVIRONMENT *IspEnvironment);\r
+BOOL CheckTerminalParameters(ISP_ENVIRONMENT *IspEnvironment, char* pstr);\r